
window.adsys.extend('banner_frontpage', {
    'afterLoad': function(ad) {
      use_page_block_replacement(ad);
    }
});

window.adsys.extend('netboard_frontpage', {
    'afterLoad': function(ad) {
      use_page_block_replacement(ad);
    }
});

window.adsys.extend('netboard_frontpage_2', {
    'afterLoad': function(ad) {
      use_page_block_replacement(ad);
    }
});

window.adsys.extend('netboard_article', {
  'afterLoad': function(ad) {
    /**
     * NOTE! When copying this function to other sites' adsys.collapse.js, make sure that
     * the area-name is correct:
     * -some have "netboard_article_1" and some have just "netboard_article"!!
     */
    if (!ad.hasCreative) {
      // Remove the adArea
      ad.$areaEl.remove();
      this.netBoardRemoved = true;
    } else {
      this.netBoardRemoved = false;
    }

    if (this.netBoardRemoved && window.textAdsProvider && $('area-text_ads_article_top')) {
      // Netboard is removed so adjust the textAds-area just below the byline
      if (window.textAdsProvider.isEniro) {
        // Adjust adjescent Eniro text ads
        this.adjustEniroAds();
      } else {
        // Adjust adjescent AdSense text ads
        this.adjustAds();
      }
      if (this.adAdjustmentDone) {
        /* On digi, we keep the byline "as is", because the "next-article" link-image
         * (the gray arrow) makes the floats stack unevenly at the top and the article-text
         * floats into the top-space left over by the uneven stacking */
      }
    }
  },

  _adjustRetries: 0, // <- Used to bail on the adjustment calbacks
  adjustEniroAds: function() {
    /**
     * Wait for the eniroads' data to get fetched before continuing to
     * apply the common adjustments.
     */
    console.debug('netboard_article_1:adjustEniroTextAds');
    if (!window.textAdsProvider.data && (window.textAdsProvider.failed || this._adjustRetries > 100)) {
      // No data and [fetching failed or limit reached]
      return;
    } else if (!window.textAdsProvider.data) {
      // Try again to see if data gets set
      setTimeout(this.adjustEniroAds.bind(this), 20);
      return;
    }
    // Apply the comon adjustments
    this.adjustAds();
  },

  adjustAds: function() {
    console.debug('netboard_article_1:adjustAd');
    try {
      if (this.netBoardRemoved) {
        // Float the ad-area to the right of the byline
        $('area-text_ads_article_top').setStyle({
          'width': '250px',
          'float': 'right',
          'margin': '13px 10px 10px'
        });
      }
      // Flag that the ad-area has been adjusted
      this.adAdjustmentDone = true;
    } catch(e) {
      console.error(e);
    }
  }
});

window.adsys.extend('buttonrow_frontpage', {
  'afterLoad': function(ad) {
      if (!ad.hasCreative) {
        ad.$adEl.remove();
      }

      var maxAdCount = 3;
      var $subBlock = ad.$areaEl.down('.sub-block');
      var adCount = $subBlock.childElements().length;

      if (!adCount) {
        // No ads in area
        ad.$areaEl.remove();
      } else if (adCount < maxAdCount){
        /* We're using the buttonrow_frontpage_1 area on multiple pages,
         * make sure we're supposed to center the remaining ads */
        if (ad.$areaEl.hasClassName('center_on_collapse')) {
          var pagePadding = 20;
          // Center remaining ads by left-padding subBlock around the ads
          var width = ad.$areaEl.getWidth() - pagePadding;
          var left_space = Math.floor( (width / maxAdCount) * (maxAdCount - adCount) / 2);
          $subBlock.setStyle({'paddingLeft': left_space+'px'});
        }
      }
  }
});

/*
 * Often-used collapse funtions
 */
function use_page_block_replacement(ad, $replacement_block) {
    /*
     * Used on the frontpage;
     * Replaces the ad block-parent with a sibling block.
     * If no replacement_block is passed, the replacement_block will sought by
     * the id of "<id of block to replace>-replacement".
     */
    if (!ad.hasCreative) {
        // Remove the ad element
        ad.$adEl.remove();
    }
    // If there are no more ad elements in the area, remove the area as well
    var replaced = false;
    if (ad.$areaEl.select('.ad-tag').length == 0) {
        // Find page block & replacement-block
        $block = ad.$areaEl.up('.block');
        if (!$replacement_block) {
          $replacement_block = $($block.id + '-replacement');
        }

        if ($block) {
          $block.hide();
        }

        if ($block && $replacement_block) {
          // Replace block
          if (ad.debug && !ad.debug['silent']) {
            /* Set a different background-color on the replacement elements
             * and don't hide the original block */
            try {
              console.debug('use_page_block_replacement replaced', $block, 'with', $replacement_block);
              $replacement_block.childElements().each(function($el) {
                $el.setStyle({backgroundColor: 'silver'});
              });
            } catch(e) {
              console.error(e);
            };
          }
          $replacement_block.show();
          // Mark that block was replaced
          replaced = true;
        }
    }
    return replaced;
}

