@britannica/ads
Advanced tools
Comparing version 1.0.0-beta.5 to 1.0.0-beta.6
@@ -0,3 +1,4 @@ | ||
import './AdsManager.scss'; | ||
import { IAd } from './common/types'; | ||
declare class _AdsManager { | ||
export declare class AdsManager { | ||
private static providerClasses; | ||
@@ -19,3 +20,1 @@ private providers; | ||
} | ||
export declare const AdsManager: _AdsManager; | ||
export {}; |
@@ -1,2 +0,2 @@ | ||
"use strict";var e;Object.defineProperty(exports,"__esModule",{value:!0}),function(e){e[e.Debug=0]="Debug",e[e.Info2=1]="Info2",e[e.Info=2]="Info",e[e.None=3]="None"}(e||(e={}));class t{static INFO_STYLE="font-weight:bold; background-color: #084466; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static INFO_STYLE2="font-weight:bold; background-color: rebeccapurple; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static ERR_STYLE="font-weight:bold; background-color: red; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static WARN_STYLE="font-weight:bold; background-color: orange; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static DEBUG_STYLE="font-weight:bold; background-color: #88A95B; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";error=console.error.bind(window.console,"%cAd Lib",t.ERR_STYLE);warning=console.warn.bind(window.console,"%cAd Lib",t.WARN_STYLE);debug;info;info2;level;constructor(){this.level=s.isDefined(__adLib)?e[__adLib.logLevel]:e.None,this.info=e.Info>=this.level?console.log.bind(window.console,"%cAd Lib",t.INFO_STYLE):()=>null,this.info2=e.Info2>=this.level?console.log.bind(window.console,"%cAd Lib",t.INFO_STYLE2):()=>null,this.debug=e.Debug>=this.level?console.debug.bind(window.console,"%cAd Lib",t.DEBUG_STYLE):()=>null}getLevel(){return this.level}}const i=new t;class s{static isDefined(e){return void 0!==e}static isFunction(e){return"function"==typeof e}}var r,a,n,o;!function(e){e.before="beforeBegin",e.after="afterEnd",e.prepend="afterBegin",e.append="beforeEnd"}(r||(r={}));class d{static insert(e,t,i){t.insertAdjacentHTML(e,i)}static remove(e){e&&e.parentNode.removeChild(e)}static loadScript(e,t={}){return new Promise(((s,r)=>{let a=document.createElement("script");a.src=e,a.onload=()=>s(),a.onerror=()=>r();for(const[e,i]of Object.entries(t))a.setAttribute(e,i);document.head.append(a),i.info(`Loaded: [${e}]`)}))}static css(e,t,i){e.style.setProperty(t,i)}static addClass(e,...t){t.forEach((t=>{t&&e.classList.add(t)}))}static removeClass(e,t){e.classList.remove(t)}static onDocumentReady(e){"loading"!=document.readyState?e():document.addEventListener("DOMContentLoaded",e)}static get(e,t=document.body){return t.querySelector(e)}static getAll(e,t=document.body){return t.querySelectorAll(e)}static setEventListener(e,t,i){e.addEventListener(t,i)}static removeEventListener(e,t,i){e.removeEventListener(t,i)}static onInViewPort(e,t){new IntersectionObserver(((i,s)=>{i.forEach((i=>{i.isIntersecting&&(t(e),s.disconnect(),s=null)}))}),{threshold:1}).observe(e)}static onScroll(e,t){window.addEventListener("scroll",function(e,t){var i=!1;return function(){i||(e(window.scrollY),i=!0,setTimeout((function(){i=!1}),t))}}(e,t))}static delayedCall(e,t){t?setTimeout(e,1e3*t):e()}}class l{static createCookieSession(e,t,i){document.cookie=`${e}=${t}; path=/${i?";domain="+i:""}`}static readCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(`${e}=`))).split("=")[1]}static isCookieExists(e){return document.cookie.split(";").some((t=>t.trim().startsWith(`${e}=`)))}}class c{static substringBefore(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(0,i)}static substringAfter(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(i+1)}static defaultIfBlank(e,t){return e&&0!=e.length?e:t}}class p{static getJsonFromScriptSnippet(e,t=document.body){const i=d.get(`script[type="application/json"].${e}`,t);return i?p.elementContentToJson(i):null}static elementContentToJson(e){var t=e.innerText;try{return JSON.parse(t)}catch(e){return i.error("JSON parsing error: ",e),null}}}!function(e){e.PAUSED="PAUSED",e.RUNNING="RUNNING",e.STOPPED="STOPPED"}(a||(a={}));class f{_id=(Date.now()+Math.floor(100*Math.random())).toString().slice(-5);_state=a.STOPPED;internalTimerId;restartTimerId;lastStart;remaining;callback;delay;constructor(e,t){this.callback=e,this.delay=t}get id(){return this._id}get state(){return this._state}callbackFn(){this.lastStart=Date.now(),this.remaining=this.delay,this.callback()}pause(){this.state==a.RUNNING&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining-=Date.now()-this.lastStart,this._state=a.PAUSED,i.debug(`Timer [${this._id}] Paused - Remaining [${this.remaining}ms]`))}resume(){this.state==a.PAUSED&&(this.restartTimerId=window.setTimeout((()=>{this.callback(),this.start()}),this.remaining),this.lastStart=Date.now(),this._state=a.RUNNING,i.debug(`Timer [${this._id}] Resumed in [${this.remaining}ms].`))}stop(){this.state!=a.STOPPED&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining=this.delay,this._state=a.STOPPED,i.debug(`Timer [${this._id}] - Internal id [${this.internalTimerId}] Stopped`))}start(){this.lastStart=Date.now(),this.remaining=this.delay,this.internalTimerId=window.setInterval((()=>this.callbackFn()),this.delay),this._state=a.RUNNING,i.debug(`Started Timer [${this._id}] - Internal id [${this.internalTimerId}]`)}restart(){this.stop(),this.start()}stopInternalTimer(){this.internalTimerId&&(window.clearInterval(this.internalTimerId),this.internalTimerId=null)}stopResumeTimer(){this.restartTimerId&&(window.clearTimeout(this.restartTimerId),this.restartTimerId=null)}}class u{static US_PrivacyCookieName="usprivacy";static US_PrivacyCookieDuration=365;static init(){i.info2("Init IAB: Insert iframe locator into body"),d.insert(r.append,document.body,'<iframe name="__uspapiLocator" style="display:none;height:0;opacity:0;visibility:hidden;border:0;width:0;"></iframe>'),i.info2("Install IAB message handler"),window.addEventListener("message",u.optOutMsgHandler,!1),i.info2("Install global __uspapi function"),window.__uspapi=(e,t,s)=>{if(i.info2(`IAB: __uspapi function called. Command: [${e}] `),"getuspdata"===e.toLowerCase()){let e={version:t,uspString:l.readCookie(u.US_PrivacyCookieName)};i.info2("IAB: getuspdata command. Response: ",e),s(e,null!=e.uspString)}},l.isCookieExists(u.US_PrivacyCookieName)||(__adLib.usPrivacyConsent?(i.info2("IAB: US privacy consent needed (CCPA), create default cookie [1YNY]"),u.createCookie(1,!0,!1,!0)):(i.info2("IAB: No US privacy consent needed, create default cookie [1---]"),u.createCookie()))}static createCookie(e=1,t,i,s){let r=e=>!0===e?"Y":!1===e?"N":"-",a=e.toString()+r(t)+r(i)+r(s),n=`${u.US_PrivacyCookieName}=${a}; `,o=new Date;o.setTime(o.getTime()+24*u.US_PrivacyCookieDuration*60*60*1e3);let d=`expires=${o.toUTCString()}; `;document.cookie=n+d+"path=/; SameSite=Lax; "}static optOutMsgHandler(e){let t,s="string"==typeof e.data;if(t=s?-1!==e.data.indexOf("__uspapiCall")?JSON.parse(e.data):{}:e.data,t.__uspapiCall){i.info2("Received __uspapiCall event. Will post message to sender with the cookie content");let r=t.__uspapiCall;window.__uspapi(r.command,r.version,(function(t,a){let n={__uspapiReturn:{returnValue:t,success:a,callId:r.callId}},o=e.source;i.info2("IAB: post message back ",n,o),o.postMessage(s?JSON.stringify(n):n,"*")}))}}}class g{static async init(){if(__adLib.requiresConsent){if(!s.isDefined(window.__tcfapi)){i.info2("__tcfapi not found -> Will load the oneTrust scripts");try{await d.loadScript("https://cdn.cookielaw.org/consent/cmp.stub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw i.error("Unable to load oneTrust cmp.stub.js script"),e}try{await d.loadScript("https://cdn.cookielaw.org/scripttemplates/otSDKStub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw i.error("Unable to load oneTrust otSDKStub.js script "),e}i.info2("oneTrust scripts loaded")}i.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{i.info2(`OptanonWrapper called. Defer Ads status is [${g.getDeferAdsStatus()}]`),g.getDeferAdsStatus()&&(i.info2("Defer Ads status is true -> Set Read TCData callback"),window.__tcfapi("getTCData",2,((e,t)=>{if(i.info2(`TCData read: success = [${t}] data = `,e),!t||g.statusOk(e))return i.info2("Error or status already OK -> send message to the app to load the ads immediately "),void g.setDeferAdsStatus(!1);const s=(e,t)=>{i.info2("Received __tcpapi status change Event: ",e),t&&g.statusOk(e)&&(i.info2("Status now OK, remove the event listener and send message to the app to load the ads immediately"),window.__tcfapi("removeEventListener",2,s),g.setDeferAdsStatus(!1))};i.info2("Status not OK yet. Set event listener to load the ads when it will be OK"),window.__tcfapi("addEventListener",2,s)})))},i.info2("Defer the ads loading by default"),g.setDeferAdsStatus(!0)}else i.info2("Not Consent Required")}static getDeferAdsStatus(){return __adLib.deferAds}static setDeferAdsStatus(e){__adLib.deferAds=e,e||document.dispatchEvent(new Event("endDeferAds"))}static statusOk(e){return"useractioncomplete"==e.eventStatus||"tcloaded"==e.eventStatus}static getPrebidConsentParameters(){return __adLib.usPrivacyConsent?__adLib.prebidCcpaConfiguration:__adLib.requiresConsent?__adLib.prebidGdprConfiguration:null}static onDNSMILinkClicked(){i.info2("CCPA consent called"),i.info2("create default IAB cookie [1YYY]"),u.createCookie(1,!0,!0,!0),i.info2("Modifies onetrust OptanonConsent cookies and ActiveGroups global variables");let e=[4],t=decodeURIComponent(l.readCookie("OptanonConsent "));i.info2("Current OptanonConsent cookie value = ",t);for(let i of e)t=t.replace(`,${i}:1,`,`,${i}:0,`),window.OptanonActiveGroups=window.OptanonActiveGroups.replace(`,${i},`,","),window.OnetrustActiveGroups=window.OnetrustActiveGroups.replace(`,${i},`,",");i.info2("New OptanonConsent cookie value = ",t),i.info2(`New OptanonActiveGroups = [${window.OptanonActiveGroups}]`),i.info2(`New OneTrustActiveGroups = [${window.OnetrustActiveGroups}]`),l.createCookieSession("OptanonConsent",encodeURI(t),__adLib.topDomain),l.createCookieSession("EbConsentClosed","true"),i.info2("created new OptanonConsent and EbConsentClosed cookies")}}class h{static async loadPrebidScript(){if(!__adLib.videoForPrebidLoaded&&!s.isDefined(window.pbjs)){i.info(`Loading [${__adLib.prebidScriptUrl}] prebid script now`),window.pbjs={que:[]};try{await d.loadScript(__adLib.prebidScriptUrl)}catch(e){return void i.error(`Unable to load [${__adLib.prebidScriptUrl}] prebid script -> skip ad`)}__adLib.videoForPrebidLoaded=!0}}}class b{static setJwplayerSetupWithPrebid(t,s,r,a=!1){a||__adLib.showPrerollAdInVideos?(h.loadPrebidScript(),pbjs.que.push((()=>{let a=__adLib.prebidConfiguration;a.debug=i.getLevel()==e.Debug,pbjs.setConfig(a),pbjs.addAdUnits(__adLib.prebidVideoAdUnit),i.info("Request Prebid bids with ad unit id: ",t),pbjs.requestBids({bidsBackHandler:()=>{let e={iu:`${`${__adLib.googleDfpId}/EB_${__adLib.leg}/${__adLib.dfpUnitPrefix}`}${t}`,output:"vast"};i.info("Prebid video url called. Params = ",e);let a=pbjs.adServers.dfp.buildVideoUrl({adUnit:__adLib.prebidVideoAdUnit,params:e});i.info(`Bidding completed. Set URL in jwplayer setup and call callback: [${a}]`),s.advertising={client:"googima",adschedule:[{offset:"pre",tag:a}]},r()}})}))):r()}static addJwPlayerAdSetup(e,t){t.advertising={client:"googima",adschedule:[{offset:"pre",tag:e}]}}}class _{static CONTAINER_CLASS="__alPrerollContainer";static WRAPPER_CLASS="__alPrerollWrapper";static JWPLAYER_CONTAINER_ID="__alPreroll";static async createPreRollAd(e,t,a=(()=>{})){if(__adLib.prerollAdIsRunning)return void i.info("Preroll Ad is already running. Ignore this one");if(!__adLib.showPrerollAd)return i.info("Preroll Ads not enabled -> return"),void a();if(class{static isAdBlockerActivated(){var e=d.get("#_MGS_");e||(d.insert(r.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=d.get("#_MGS_"));var t=d.get("div",e);return"none"===window.getComputedStyle(t).display}}.isAdBlockerActivated())return void a();if(__adLib.prerollAdIsRunning=!0,!s.isDefined(window.jwplayer)){i.info("jwplayer not found. Loading the script now");try{await d.loadScript(`https://content.jwplatform.com/libraries/${__adLib.jwplayerId}.js`)}catch(e){return i.error("Unable to load jwplayer script -> skip ad"),__adLib.prerollAdIsRunning=!1,void a()}}d.addClass(e,_.CONTAINER_CLASS),i.info(`Insert preroll [${t}] Ad into`,e),d.insert(r.prepend,e,`<div class="${_.WRAPPER_CLASS}"><div id="${_.JWPLAYER_CONTAINER_ID}"></div></div>`);let n=d.get(`.${_.WRAPPER_CLASS}`,e),o={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};b.setJwplayerSetupWithPrebid(t,o,(()=>{i.info("Prebid preroll completed. Init JWPlayer: ",o);let t=jwplayer(_.JWPLAYER_CONTAINER_ID);t.setup(o);const s=s=>{t&&(i.info(`Preroll Ended. Cause: [${s}]. Will remove the player and its container`),t.remove(),t=null,d.remove(n),d.removeClass(e,_.CONTAINER_CLASS),__adLib.prerollAdIsRunning=!1,a())};t.on("adComplete",(()=>{s("Ad completed")})),t.on("adSkipped",(()=>{s("Ad Skipped")})),t.on("adError",(()=>{s("Ad Error")})),t.on("adBlock",(()=>{s("Ad Blocked")})),t.on("complete",(()=>{s("Video completed")})),t.on("error",(()=>{s("Error")}))}),!0)}}!function(e){e.DFP="DFP"}(n||(n={}));!function(e){e.REGULAR="REGULAR",e.CATFISH="CATFISH"}(o||(o={}));class m extends class{type;ads;constructor(){this.ads=[],this.type=this.getType()}addAd(e){this.ads.push(e)}}{static PAGELOAD_TARGETING="PAGELOAD";index=1;getName(){return"Google DFP"}getType(){return n.DFP}constructor(){super()}async initProvider(){if(window.googletag={cmd:[]},!s.isDefined(googletag.defineSlot)){i.info("Googletag not found. Load the script");try{await d.loadScript("https://securepubads.g.doubleclick.net/tag/js/gpt.js")}catch(e){throw i.error("**** Unable to load gpt.js -> most ads and scripts will be broken ***"),e}}if(i.info("Googletag script loaded: ",googletag.defineSlot),h.loadPrebidScript(),!s.isDefined(window.headertag)&&__adLib.includeIndex)try{await d.loadScript(__adLib.indexScriptUrl)}catch(e){i.error(`Unable to load [${__adLib.indexScriptUrl}] Index script. We won't use it.`)}if(!s.isDefined(window.apstag)&&__adLib.includeA9)try{await d.loadScript("https://c.amazon-adsystem.com/aax2/apstag.js"),function(e,t){function i(i,s){t[e]._Q.push([i,s])}t[e]||(t[e]={init:function(){i("i",arguments)},fetchBids:function(){i("f",arguments)},setDisplayBids:function(){},targetingKeys:function(){return[]},_Q:[]})}("apstag",window)}catch(e){i.error("Unable to load A9 script. Will disable it"),__adLib.includeA9=!1}googletag.cmd.push((function(){if(googletag.pubads().setTargeting("dc_ref",__adLib.url),s.isDefined(Storage)){var e=localStorage.getItem("bcDFPTargetingParams");if(e)i.info("Setting Blueconic targeting parameters"),JSON.parse(e).forEach((e=>googletag.pubads().setTargeting(e.key,e.value)))}if(i.info(`targeting: ${googletag.pubads().getTargetingKeys()}`),googletag.pubads().disableInitialLoad(),googletag.pubads().enableSingleRequest(),googletag.pubads().enableAsyncRendering(),googletag.pubads().setTagForChildDirectedTreatment(0),googletag.pubads().setTagForUnderAgeOfConsent(0),__adLib.dfpLazyLoad&&googletag.pubads().enableLazyLoad(__adLib.dfpLazyLoadParameters),googletag.enableServices(),__adLib.includeA9){var t={pubID:__adLib.a9Id,adServer:"googletag",bidTimeout:1200};__uspapi&&__uspapi("getuspdata","1",((e,i)=>{i&&(t.params={us_privacy:e.uspString})})),i.info("Init A9 with ",t),apstag.init(t)}}))}createSlot(e,t){return this.initSlot(e,t)}initSlot(e,t){return new Promise((s=>{googletag.cmd.push((()=>{try{i.info("process DFP ad: ",e);var a=e.adParameters,n=a.size[0][0],l=a.size[0][1];i.info("Content container for this ad is ",t);var p="";if(e.displayType!=o.CATFISH)if(a.placeholderSize)p=`min-width:${c.substringBefore(a.placeholderSize,"x")}px;min-height:${c.substringAfter(a.placeholderSize,"x")}px;`;else if(1==a.size.length)p=`width:${n}px;height:${l}px;`;else{p=`min-height:${Math.round(a.size.map((e=>e[1])).reduce(((e,t)=>e+t))/a.size.length)}px;`}var f="DFP_"+this.index++;e.containerId=f,e.dfpSize=1==a.size.length?a.size[0]:a.size;var u=`style="${p}${c.defaultIfBlank(a.style,"")}"`,g=`<div data-type="${e.type}" class="__alAd ${c.defaultIfBlank(__adLib.adClass,"")} ${c.defaultIfBlank(a.cssClass,"")}" ${u} id="${f}"></div>`;i.info(`Inject DIV: [${g}] into `,t),d.insert(r[e.injector],t,g);var h=this.setDfpA9Slot(e);let b=d.get(`#${f}`);b.setAttribute("data-identifier",e.dfpSlot.getAdUnitPath()),b.setAttribute("data-qa-identifier",h),s(b)}catch(t){i.error("Init Slot Error: ",e,t),s(null)}}))}))}setDfpA9Slot=function(e){i.info("Initializes DFP slot and A9 slot for ",e);var t=e.adParameters,s=__adLib.dfpIdPrefix.replace("${LEG}",__adLib.leg),r=`${__adLib.isPhone?"MOBILE":"DESKTOP"}_${t.id}`,a=`/${__adLib.googleDfpId}/${s}${r}`;return i.info(`Define new slot: [${a}] with: size [${e.dfpSize}] id [${e.containerId}]`),e.dfpSlot=googletag.defineSlot(a,e.dfpSize,e.containerId),t.targeting&&Object.entries(t.targeting).forEach((([t,i])=>{e.dfpSlot.setTargeting(t,String(i))})),e.dfpSlot.addService(googletag.pubads()),__adLib.includeA9&&(e.a9Slot={slotID:e.containerId,slotName:a,sizes:t.size}),i.info("DFP/A9 slot defined for ",e),r};refreshAllAds(){i.info("Refresh all DFP ads."),googletag.cmd.push((()=>{m.setPageLoadTargeting(this.ads),this.refreshSlots()}))}requestBids(e){this.refreshAds(e)}refreshAds(e){i.info("Refresh ads: ",e),googletag.cmd.push((()=>{m.setPageLoadTargeting(e),this.refreshSlots(e)}))}static setPageLoadTargeting(e){for(let t of e){const e=`REFRESH${t.refreshCounter}`;i.info(`Update ${m.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(m.PAGELOAD_TARGETING,e)}}refreshSlots(t=this.ads){i.info("Refresh slots - ads : ",t);let s=!1,r=!1,a=!1,n=()=>{a||!r||!s&&__adLib.includeA9||(-1!=p&&window.clearTimeout(p),i.info("Prebid is completed and A9 completed or disabled -> call DFP"),o())},o=()=>{i.info("Refresh ads ",t);let e=t.map((e=>e.dfpSlot));i.info("Refresh DFP slots ",e),googletag.pubads().refresh(e)},d=[];for(let e of t)d.push({code:e.dfpSlot.getAdUnitPath(),mediaTypes:{banner:{sizes:e.adParameters.size}},bids:__adLib.prebidBannerBiddersConfiguration});i.info("Prebid ad unit configuration: ",d);let l={...__adLib.prebidConfiguration,debug:i.getLevel()==e.Debug,...g.getPrebidConsentParameters()};if(__adLib.includeA9){var c=t.map((e=>e.a9Slot));i.info("Calls A9 with these slots:",c),apstag.fetchBids({slots:c},(()=>{i.info("A9 bid request completed"),apstag.setDisplayBids(),s=!0,n()}))}pbjs.que.push((()=>{i.info("Set Prebid Config: ",l),pbjs.setConfig(l),pbjs.addAdUnits(d),i.info("Request Prebid bids"),pbjs.requestBids({timeout:__adLib.prebidTimeout,bidsBackHandler:()=>{i.info("Prebid request bid completed"),pbjs.setTargetingForGPTAsync(t.map((e=>e.dfpSlot.getAdUnitPath()))),r=!0,n()}})}));let p=-1;0!=__adLib.biddersFailsafeTimeout&&(i.info(`Bidders failsafe timeout set to [${__adLib.biddersFailsafeTimeout}] ms`),p=window.setTimeout((()=>{i.info("Bidding Timeout! -> calls DFP directly"),a=!0,o()}),__adLib.biddersFailsafeTimeout))}}class A{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,t){i.info("Create a catfish container");let s=`<div id="${A.CATFISH_ID}" class="__alCatfish" style=" ${e?`width:${e}px;`:""} ${t?`height:${t}px`:""}"></div>`;return d.insert(r.append,document.body,s),i.info("Static Catfish Inserted",A.getCurrentCatfishElement()),A.getCurrentCatfishElement()}static getCurrentCatfishElement(){return d.get(`#${A.CATFISH_ID}`)}}require("./AdsManager.scss");class S{static providerClasses=new Map([[n.DFP,m]]);providers=new Map;timers=[];constructor(){s.isDefined(typeof window.__adLib)&&d.onDocumentReady((()=>{i.info("Ad Library Loaded"),this.init()}))}isAdBlockerActivated(){var e=d.get("#_MGS_");e||(d.insert(r.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=d.get("#_MGS_"));var t=d.get("div",e);return"none"===window.getComputedStyle(t).display}async init(){i.info("Init Ads manager at page load"),u.init(),await g.init(),i.info("Set tab visibility event handler"),d.setEventListener(document,"visibilitychange",(()=>{let e="visible"===document.visibilityState;i.info(`Tab visibility changed to [${e}]`),e?this.resumeAllPausedTimers():this.pauseAllRunningTimers()})),__adLib.deferAds?(i.info("Ads need to be deferred. Will wait until the [endDeferAds] is fired"),d.setEventListener(document,"endDeferAds",(()=>{i.info("Deferred Ads event triggered. Will now initialize the ads"),this.contentLoadInit(document.body,__adLib.initialLoadAds)}))):(i.info("No deferred ads. Will initialize the ads now"),this.contentLoadInit(document.body,__adLib.initialLoadAds))}async contentLoadInit(e=document.body,t){let s;if(i.info(" ============================================================================================="),i.info("Initialize container with ads"),i.info(" ============================================================================================="),t)s=t,i.info("Ad definitions passed as parameter: ",s);else{i.info("Look for json ads definition in ",e);let t=p.getJsonFromScriptSnippet("ads-script",e);if(!t)return void i.info("Did not find ads definition.");if(s=t,!s)return;i.info("Found ad definitions: ",s)}let r=new Map;for(let t of s){if(i.info("Init this ad: ",t),!this.providers.has(t.type)){i.info(`Initializes Provider: [${t.type}]`);try{let e=new(S.providerClasses.get(t.type));await e.initProvider(),this.providers.set(t.type,e)}catch(e){i.error(`Unable to instantiate Ad Provider: [${t.type}]`,t,e);continue}}let s=this.providers.get(t.type);r.has(t.type)||r.set(t.type,[]),t.provider=s;let a=null;if(t.displayType==o.REGULAR)a=d.get(t.selector,e);else if(t.displayType==o.CATFISH){if(a=A.getCurrentCatfishElement(),a){let e=d.get(".__alAd",a).ad;e.provider.refreshAds([e]),i.info("Catfish already exists, just refresh its ad");continue}a=A.newCatfish(),t.injector="append"}a?(t.$container=await s.createSlot(t,a),t.$container?(t.$container.ad=t,t.refreshCounter=0,s.addAd(t),r.get(t.type).push(t),t.autoRefresh?(t.$container.isInViewPort=!1,t.refreshTimer=new f((()=>{S.timerCallback(t)}),1e3*__adLib.refreshTimer),this.timers.push(t.refreshTimer),i.info("This ad is autorefresh, added refresh timer: ",t.refreshTimer)):(t.refreshTimer=null,t.$container.isInViewPort=!0,i.info("This ad is not autorefresh -> no refresh timer")),t.displayType==o.CATFISH?(i.info("The ad is a catfish -> always in viewport and start refresh timer"),t.$container.isInViewPort=!0,t.refreshTimer&&t.refreshTimer.start()):t.autoRefresh&&(i.info("Add the ad container to the observer -> ",t.$container),this.isInViewPortObserver.observe(t.$container)),i.info("Ad initialized",t)):i.info("Slot creation failed -> skip this ad")):i.info("Error when initializing the ad/Existing ad -> skip it: ",t)}for(let[e,t]of r)0==t.length?i.info(`No ads for [${e}] provider`):(i.info(`Request Bids for [${e}] provider: `,t),this.providers.get(e).requestBids(t));if(__adLib.stickyContainerSelector){const t=d.getAll(`${__adLib.stickyContainerSelector} .__alAd`,e);let s=t.length;if(s>0){let e=t.item(s-1);i.info("Last ad is sticky",e),d.addClass(e,"__alSticky",__adLib.stickyAdClass)}}}isInViewPortObserver=new IntersectionObserver((e=>{e.forEach((e=>{let t=e.target;t.isInViewPort=e.intersectionRatio>=__adLib.viewportThreshold,t.isInViewPort?(i.info("Ad in viewport -> resume timer",t.ad),S.resumeRefreshTimer(t.ad)):(i.info("Ad out of viewport -> stop timer",t.ad),S.pauseRefreshTimer(t.ad))}))}),{threshold:__adLib.viewportThreshold});static timerCallback(e){i.info("Ad is refreshed.",e),e.refreshCounter++,e.provider.refreshAds([e])}static resumeRefreshTimer(e){i.info("Resume refresh timer for ",e),e.refreshTimer.state==a.PAUSED?e.refreshTimer.resume():e.refreshTimer.state==a.STOPPED&&e.refreshTimer.start()}static pauseRefreshTimer(e){i.info("Pause refresh timer for ",e),e.refreshTimer.pause()}pausedTimers=[];pauseAllRunningTimers(){this.pausedTimers=this.timers.filter((e=>e.state==a.RUNNING)),0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.pause())),i.info("Pause these timers: ",this.pausedTimers.map((e=>e.id))))}resumeAllPausedTimers(){0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.resume())),i.info("Resume these timers: ",this.pausedTimers.map((e=>e.id))))}refreshAllAds(){i.info("Refresh All ads"),this.providers.forEach((e=>{i.info(`will refresh ads for this provider: [${e.getName()}]`);for(let t of e.ads)t.refreshCounter++;e.refreshAllAds();for(let t of e.ads)t.refreshTimer&&t.refreshTimer.restart()}))}}const w=new S;exports.AdsManager=w,exports.ConsentManager=g,exports.PrebidForVideo=b,exports.PrerollAd=_; | ||
"use strict";var e,t,i;!function(e){e[e.Debug=0]="Debug",e[e.Info2=1]="Info2",e[e.Info=2]="Info",e[e.None=3]="None"}(e||(e={}));class o{static INFO_STYLE="font-weight:bold; background-color: #084466; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static INFO_STYLE2="font-weight:bold; background-color: rebeccapurple; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static ERR_STYLE="font-weight:bold; background-color: red; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static WARN_STYLE="font-weight:bold; background-color: orange; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static DEBUG_STYLE="font-weight:bold; background-color: #88A95B; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";error=console.error.bind(window.console,"%cAd Lib",o.ERR_STYLE);warning=console.warn.bind(window.console,"%cAd Lib",o.WARN_STYLE);debug;info;info2;level;constructor(t){this.level=t,this.info=e.Info>=this.level?console.log.bind(window.console,"%cAd Lib",o.INFO_STYLE):()=>null,this.info2=e.Info2>=this.level?console.log.bind(window.console,"%cAd Lib",o.INFO_STYLE2):()=>null,this.debug=e.Debug>=this.level?console.debug.bind(window.console,"%cAd Lib",o.DEBUG_STYLE):()=>null}getLevel(){return this.level}}class n{static isDefined(e){return void 0!==e}static isFunction(e){return"function"==typeof e}}!function(e){e.before="beforeBegin",e.after="afterEnd",e.prepend="afterBegin",e.append="beforeEnd"}(t||(t={}));class a{static insert(e,t,i){t.insertAdjacentHTML(e,i)}static remove(e){e&&e.parentNode.removeChild(e)}static loadScript(e,t={}){return new Promise(((i,o)=>{let n=document.createElement("script");n.src=e,n.onload=()=>i(),n.onerror=()=>o();for(const[e,i]of Object.entries(t))n.setAttribute(e,i);document.head.append(n),window.Log.info(`Loaded: [${e}]`)}))}static css(e,t,i){e.style.setProperty(t,i)}static addClass(e,...t){t.forEach((t=>{t&&e.classList.add(t)}))}static removeClass(e,t){e.classList.remove(t)}static onDocumentReady(e){"loading"!=document.readyState?e():document.addEventListener("DOMContentLoaded",e)}static get(e,t=document.body){return t.querySelector(e)}static getAll(e,t=document.body){return t.querySelectorAll(e)}static setEventListener(e,t,i){e.addEventListener(t,i)}static removeEventListener(e,t,i){e.removeEventListener(t,i)}static onInViewPort(e,t){new IntersectionObserver(((i,o)=>{i.forEach((i=>{i.isIntersecting&&(t(e),o.disconnect(),o=null)}))}),{threshold:1}).observe(e)}static onScroll(e,t){window.addEventListener("scroll",function(e,t){var i=!1;return function(){i||(e(window.scrollY),i=!0,setTimeout((function(){i=!1}),t))}}(e,t))}static delayedCall(e,t){t?setTimeout(e,1e3*t):e()}}class r{static createCookieSession(e,t,i){document.cookie=`${e}=${t}; path=/${i?";domain="+i:""}`}static readCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(`${e}=`))).split("=")[1]}static isCookieExists(e){return document.cookie.split(";").some((t=>t.trim().startsWith(`${e}=`)))}}class s{static substringBefore(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(0,i)}static substringAfter(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(i+1)}static defaultIfBlank(e,t){return e&&0!=e.length?e:t}}class d{static getJsonFromScriptSnippet(e,t=document.body){const i=a.get(`script[type="application/json"].${e}`,t);return i?d.elementContentToJson(i):null}static elementContentToJson(e){var t=e.innerText;try{return JSON.parse(t)}catch(e){return window.Log.error("JSON parsing error: ",e),null}}}!function(e){e.PAUSED="PAUSED",e.RUNNING="RUNNING",e.STOPPED="STOPPED"}(i||(i={}));class l{_id=(Date.now()+Math.floor(100*Math.random())).toString().slice(-5);_state=i.STOPPED;internalTimerId;restartTimerId;lastStart;remaining;callback;delay;constructor(e,t){this.callback=e,this.delay=t}get id(){return this._id}get state(){return this._state}callbackFn(){this.lastStart=Date.now(),this.remaining=this.delay,this.callback()}pause(){this.state==i.RUNNING&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining-=Date.now()-this.lastStart,this._state=i.PAUSED,window.Log.debug(`Timer [${this._id}] Paused - Remaining [${this.remaining}ms]`))}resume(){this.state==i.PAUSED&&(this.restartTimerId=window.setTimeout((()=>{this.callback(),this.start()}),this.remaining),this.lastStart=Date.now(),this._state=i.RUNNING,window.Log.debug(`Timer [${this._id}] Resumed in [${this.remaining}ms].`))}stop(){this.state!=i.STOPPED&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining=this.delay,this._state=i.STOPPED,window.Log.debug(`Timer [${this._id}] - Internal id [${this.internalTimerId}] Stopped`))}start(){this.lastStart=Date.now(),this.remaining=this.delay,this.internalTimerId=window.setInterval((()=>this.callbackFn()),this.delay),this._state=i.RUNNING,window.Log.debug(`Started Timer [${this._id}] - Internal id [${this.internalTimerId}]`)}restart(){this.stop(),this.start()}stopInternalTimer(){this.internalTimerId&&(window.clearInterval(this.internalTimerId),this.internalTimerId=null)}stopResumeTimer(){this.restartTimerId&&(window.clearTimeout(this.restartTimerId),this.restartTimerId=null)}}class c{static US_PrivacyCookieName="usprivacy";static US_PrivacyCookieDuration=365;static init(){Log.info2("Init IAB: Insert iframe locator into body"),a.insert(t.append,document.body,'<iframe name="__uspapiLocator" style="display:none;height:0;opacity:0;visibility:hidden;border:0;width:0;"></iframe>'),Log.info2("Install IAB message handler"),window.addEventListener("message",c.optOutMsgHandler,!1),Log.info2("Install global __uspapi function"),window.__uspapi=(e,t,i)=>{if(Log.info2(`IAB: __uspapi function called. Command: [${e}] `),"getuspdata"===e.toLowerCase()){let e={version:t,uspString:r.readCookie(c.US_PrivacyCookieName)};Log.info2("IAB: getuspdata command. Response: ",e),i(e,null!=e.uspString)}},r.isCookieExists(c.US_PrivacyCookieName)||(__adLib.usPrivacyConsent?(Log.info2("IAB: US privacy consent needed (CCPA), create default cookie [1YNY]"),c.createCookie(1,!0,!1,!0)):(Log.info2("IAB: No US privacy consent needed, create default cookie [1---]"),c.createCookie()))}static createCookie(e=1,t,i,o){let n=e=>!0===e?"Y":!1===e?"N":"-",a=e.toString()+n(t)+n(i)+n(o),r=`${c.US_PrivacyCookieName}=${a}; `,s=new Date;s.setTime(s.getTime()+24*c.US_PrivacyCookieDuration*60*60*1e3);let d=`expires=${s.toUTCString()}; `;document.cookie=r+d+"path=/; SameSite=Lax; "}static optOutMsgHandler(e){let t,i="string"==typeof e.data;if(t=i?-1!==e.data.indexOf("__uspapiCall")?JSON.parse(e.data):{}:e.data,t.__uspapiCall){Log.info2("Received __uspapiCall event. Will post message to sender with the cookie content");let o=t.__uspapiCall;window.__uspapi(o.command,o.version,(function(t,n){let a={__uspapiReturn:{returnValue:t,success:n,callId:o.callId}},r=e.source;Log.info2("IAB: post message back ",a,r),r.postMessage(i?JSON.stringify(a):a,"*")}))}}}class p{static async init(){if(__adLib.requiresConsent){if(!n.isDefined(window.__tcfapi)){Log.info2("__tcfapi not found -> Will load the oneTrust scripts");try{await a.loadScript("https://cdn.cookielaw.org/consent/cmp.stub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw Log.error("Unable to load oneTrust cmp.stub.js script"),e}try{await a.loadScript("https://cdn.cookielaw.org/scripttemplates/otSDKStub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw Log.error("Unable to load oneTrust otSDKStub.js script "),e}Log.info2("oneTrust scripts loaded")}Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2(`OptanonWrapper called. Defer Ads status is [${p.getDeferAdsStatus()}]`),p.getDeferAdsStatus()&&(Log.info2("Defer Ads status is true -> Set Read TCData callback"),window.__tcfapi("getTCData",2,((e,t)=>{if(Log.info2(`TCData read: success = [${t}] data = `,e),!t||p.statusOk(e))return Log.info2("Error or status already OK -> send message to the app to load the ads immediately "),void p.setDeferAdsStatus(!1);const i=(e,t)=>{Log.info2("Received __tcpapi status change Event: ",e),t&&p.statusOk(e)&&(Log.info2("Status now OK, remove the event listener and send message to the app to load the ads immediately"),window.__tcfapi("removeEventListener",2,i),p.setDeferAdsStatus(!1))};Log.info2("Status not OK yet. Set event listener to load the ads when it will be OK"),window.__tcfapi("addEventListener",2,i)})))},Log.info2("Defer the ads loading by default"),p.setDeferAdsStatus(!0)}else Log.info2("Not Consent Required")}static getDeferAdsStatus(){return __adLib.deferAds}static setDeferAdsStatus(e){__adLib.deferAds=e,e||document.dispatchEvent(new Event("endDeferAds"))}static statusOk(e){return"useractioncomplete"==e.eventStatus||"tcloaded"==e.eventStatus}static getPrebidConsentParameters(){return __adLib.usPrivacyConsent?__adLib.prebidCcpaConfiguration:__adLib.requiresConsent?__adLib.prebidGdprConfiguration:null}static onDNSMILinkClicked(){Log.info2("CCPA consent called"),Log.info2("create default IAB cookie [1YYY]"),c.createCookie(1,!0,!0,!0),Log.info2("Modifies onetrust OptanonConsent cookies and ActiveGroups global variables");let e=[4],t=decodeURIComponent(r.readCookie("OptanonConsent "));Log.info2("Current OptanonConsent cookie value = ",t);for(let i of e)t=t.replace(`,${i}:1,`,`,${i}:0,`),window.OptanonActiveGroups=window.OptanonActiveGroups.replace(`,${i},`,","),window.OnetrustActiveGroups=window.OnetrustActiveGroups.replace(`,${i},`,",");Log.info2("New OptanonConsent cookie value = ",t),Log.info2(`New OptanonActiveGroups = [${window.OptanonActiveGroups}]`),Log.info2(`New OneTrustActiveGroups = [${window.OnetrustActiveGroups}]`),r.createCookieSession("OptanonConsent",encodeURI(t),__adLib.topDomain),r.createCookieSession("EbConsentClosed","true"),Log.info2("created new OptanonConsent and EbConsentClosed cookies")}}class g{static async loadPrebidScript(){if(!__adLib.videoForPrebidLoaded&&!n.isDefined(window.pbjs)){Log.info(`Loading [${__adLib.prebidScriptUrl}] prebid script now`),window.pbjs={que:[]};try{await a.loadScript(__adLib.prebidScriptUrl)}catch(e){return void Log.error(`Unable to load [${__adLib.prebidScriptUrl}] prebid script -> skip ad`)}__adLib.videoForPrebidLoaded=!0}}}class f{static setJwplayerSetupWithPrebid(t,i,o,n=!1){n||__adLib.showPrerollAdInVideos?(g.loadPrebidScript(),pbjs.que.push((()=>{let n=__adLib.prebidConfiguration;n.debug=Log.getLevel()==e.Debug,pbjs.setConfig(n),pbjs.addAdUnits(__adLib.prebidVideoAdUnit),Log.info("Request Prebid bids with ad unit id: ",t),pbjs.requestBids({bidsBackHandler:()=>{let e={iu:`${`${__adLib.googleDfpId}/EB_${__adLib.leg}/${__adLib.dfpUnitPrefix}`}${t}`,output:"vast"};Log.info("Prebid video url called. Params = ",e);let n=pbjs.adServers.dfp.buildVideoUrl({adUnit:__adLib.prebidVideoAdUnit,params:e});Log.info(`Bidding completed. Set URL in jwplayer setup and call callback: [${n}]`),i.advertising={client:"googima",adschedule:[{offset:"pre",tag:n}]},o()}})}))):o()}static addJwPlayerAdSetup(e,t){t.advertising={client:"googima",adschedule:[{offset:"pre",tag:e}]}}}class u{static CONTAINER_CLASS="__alPrerollContainer";static WRAPPER_CLASS="__alPrerollWrapper";static JWPLAYER_CONTAINER_ID="__alPreroll";static async createPreRollAd(e,i,o=(()=>{})){if(__adLib.prerollAdIsRunning)return void Log.info("Preroll Ad is already running. Ignore this one");if(!__adLib.showPrerollAd)return Log.info("Preroll Ads not enabled -> return"),void o();if(class{static isAdBlockerActivated(){var e=a.get("#_MGS_");e||(a.insert(t.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=a.get("#_MGS_"));var i=a.get("div",e);return"none"===window.getComputedStyle(i).display}}.isAdBlockerActivated())return void o();if(__adLib.prerollAdIsRunning=!0,!n.isDefined(window.jwplayer)){Log.info("jwplayer not found. Loading the script now");try{await a.loadScript(`https://content.jwplatform.com/libraries/${__adLib.jwplayerId}.js`)}catch(e){return Log.error("Unable to load jwplayer script -> skip ad"),__adLib.prerollAdIsRunning=!1,void o()}}a.addClass(e,u.CONTAINER_CLASS),Log.info(`Insert preroll [${i}] Ad into`,e),a.insert(t.prepend,e,`<div class="${u.WRAPPER_CLASS}"><div id="${u.JWPLAYER_CONTAINER_ID}"></div></div>`);let r=a.get(`.${u.WRAPPER_CLASS}`,e),s={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};f.setJwplayerSetupWithPrebid(i,s,(()=>{Log.info("Prebid preroll completed. Init JWPlayer: ",s);let t=jwplayer(u.JWPLAYER_CONTAINER_ID);t.setup(s);const i=i=>{t&&(Log.info(`Preroll Ended. Cause: [${i}]. Will remove the player and its container`),t.remove(),t=null,a.remove(r),a.removeClass(e,u.CONTAINER_CLASS),__adLib.prerollAdIsRunning=!1,o())};t.on("adComplete",(()=>{i("Ad completed")})),t.on("adSkipped",(()=>{i("Ad Skipped")})),t.on("adError",(()=>{i("Ad Error")})),t.on("adBlock",(()=>{i("Ad Blocked")})),t.on("complete",(()=>{i("Video completed")})),t.on("error",(()=>{i("Error")}))}),!0)}}var h,b;!function(e,t){void 0===t&&(t={});var i=t.insertAt;if(e&&"undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css","top"===i&&o.firstChild?o.insertBefore(n,o.firstChild):o.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}}('/* banner ad */\n.__alAd {\n overflow: hidden;\n display: block;\n margin-left: auto;\n margin-right: auto;\n}\n\n.__alAd > div {\n text-align: center !important;\n display: block !important;\n margin: auto !important;\n}\n\n.__alAd > div > iframe,\n.__alAd > div > div {\n display: block !important;\n margin: auto !important;\n}\n\n/* sticky ad */\n.__alSticky {\n top: 0;\n position: sticky;\n}\n\n/* catfish */\n.__alCatfish {\n position: fixed;\n bottom: 0;\n left: 0;\n right: 0;\n margin: auto;\n z-index: 1030;\n width: fit-content;\n}\n\n/* preroll ad */\n.__alPrerollContainer {\n position: relative !important;\n}\n\n.__alPrerollWrapper {\n position: absolute;\n width: 100%;\n height: 100%;\n display: table;\n background: black url("https://cdn.britannica.com/ads/resources/loading.gif") center center no-repeat;\n}\n\n#__alPreroll {\n display: table-cell;\n vertical-align: middle;\n}\n\n/* inline ad */\n.__alInline {\n text-align: center;\n margin: 0 auto 20px auto;\n}\n.__alInline::before {\n border-bottom: 1px solid #ddd;\n color: #aaa;\n content: "Advertisement - Continue reading below";\n display: block;\n font-family: "Helvetica", "Segoe UI", "Arial", sans-serif;\n font-size: 11px;\n font-weight: bold;\n margin-bottom: 20px;\n padding-bottom: 5px;\n clear: left;\n}'),function(e){e.DFP="DFP"}(h||(h={}));!function(e){e.REGULAR="REGULAR",e.CATFISH="CATFISH"}(b||(b={}));class m extends class{type;ads;constructor(){this.ads=[],this.type=this.getType()}addAd(e){this.ads.push(e)}}{static PAGELOAD_TARGETING="PAGELOAD";index=1;getName(){return"Google DFP"}getType(){return h.DFP}constructor(){super()}async initProvider(){if(window.googletag={cmd:[]},!n.isDefined(googletag.defineSlot)){Log.info("Googletag not found. Load the script");try{await a.loadScript("https://securepubads.g.doubleclick.net/tag/js/gpt.js")}catch(e){throw Log.error("**** Unable to load gpt.js -> most ads and scripts will be broken ***"),e}}if(Log.info("Googletag script loaded: ",googletag.defineSlot),g.loadPrebidScript(),!n.isDefined(window.headertag)&&__adLib.includeIndex)try{await a.loadScript(__adLib.indexScriptUrl)}catch(e){Log.error(`Unable to load [${__adLib.indexScriptUrl}] Index script. We won't use it.`)}if(!n.isDefined(window.apstag)&&__adLib.includeA9)try{await a.loadScript("https://c.amazon-adsystem.com/aax2/apstag.js"),function(e,t){function i(i,o){t[e]._Q.push([i,o])}t[e]||(t[e]={init:function(){i("i",arguments)},fetchBids:function(){i("f",arguments)},setDisplayBids:function(){},targetingKeys:function(){return[]},_Q:[]})}("apstag",window)}catch(e){Log.error("Unable to load A9 script. Will disable it"),__adLib.includeA9=!1}googletag.cmd.push((function(){if(googletag.pubads().setTargeting("dc_ref",__adLib.url),n.isDefined(Storage)){var e=localStorage.getItem("bcDFPTargetingParams");if(e)Log.info("Setting Blueconic targeting parameters"),JSON.parse(e).forEach((e=>googletag.pubads().setTargeting(e.key,e.value)))}if(Log.info(`targeting: ${googletag.pubads().getTargetingKeys()}`),googletag.pubads().disableInitialLoad(),googletag.pubads().enableSingleRequest(),googletag.pubads().enableAsyncRendering(),googletag.pubads().setTagForChildDirectedTreatment(0),googletag.pubads().setTagForUnderAgeOfConsent(0),__adLib.dfpLazyLoad&&googletag.pubads().enableLazyLoad(__adLib.dfpLazyLoadParameters),googletag.enableServices(),__adLib.includeA9){var t={pubID:__adLib.a9Id,adServer:"googletag",bidTimeout:1200};__uspapi&&__uspapi("getuspdata","1",((e,i)=>{i&&(t.params={us_privacy:e.uspString})})),Log.info("Init A9 with ",t),apstag.init(t)}}))}createSlot(e,t){return this.initSlot(e,t)}initSlot(e,i){return new Promise((o=>{googletag.cmd.push((()=>{try{Log.info("process DFP ad: ",e);var n=e.adParameters,r=n.size[0][0],d=n.size[0][1];Log.info("Content container for this ad is ",i);var l="";if(e.displayType!=b.CATFISH)if(n.placeholderSize)l=`min-width:${s.substringBefore(n.placeholderSize,"x")}px;min-height:${s.substringAfter(n.placeholderSize,"x")}px;`;else if(1==n.size.length)l=`width:${r}px;height:${d}px;`;else{l=`min-height:${Math.round(n.size.map((e=>e[1])).reduce(((e,t)=>e+t))/n.size.length)}px;`}var c="DFP_"+this.index++;e.containerId=c,e.dfpSize=1==n.size.length?n.size[0]:n.size;var p=`style="${l}${s.defaultIfBlank(n.style,"")}"`,g=`<div data-type="${e.type}" class="__alAd ${s.defaultIfBlank(__adLib.adClass,"")} ${s.defaultIfBlank(n.cssClass,"")}" ${p} id="${c}"></div>`;Log.info(`Inject DIV: [${g}] into `,i),a.insert(t[e.injector],i,g);var f=this.setDfpA9Slot(e);let u=a.get(`#${c}`);u.setAttribute("data-identifier",e.dfpSlot.getAdUnitPath()),u.setAttribute("data-qa-identifier",f),o(u)}catch(t){Log.error("Init Slot Error: ",e,t),o(null)}}))}))}setDfpA9Slot=function(e){Log.info("Initializes DFP slot and A9 slot for ",e);var t=e.adParameters,i=__adLib.dfpIdPrefix.replace("${LEG}",__adLib.leg),o=`${__adLib.isPhone?"MOBILE":"DESKTOP"}_${t.id}`,n=`/${__adLib.googleDfpId}/${i}${o}`;return Log.info(`Define new slot: [${n}] with: size [${e.dfpSize}] id [${e.containerId}]`),e.dfpSlot=googletag.defineSlot(n,e.dfpSize,e.containerId),t.targeting&&Object.entries(t.targeting).forEach((([t,i])=>{e.dfpSlot.setTargeting(t,String(i))})),e.dfpSlot.addService(googletag.pubads()),__adLib.includeA9&&(e.a9Slot={slotID:e.containerId,slotName:n,sizes:t.size}),Log.info("DFP/A9 slot defined for ",e),o};refreshAllAds(){Log.info("Refresh all DFP ads."),googletag.cmd.push((()=>{m.setPageLoadTargeting(this.ads),this.refreshSlots()}))}requestBids(e){this.refreshAds(e)}refreshAds(e){Log.info("Refresh ads: ",e),googletag.cmd.push((()=>{m.setPageLoadTargeting(e),this.refreshSlots(e)}))}static setPageLoadTargeting(e){for(let t of e){const e=`REFRESH${t.refreshCounter}`;Log.info(`Update ${m.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(m.PAGELOAD_TARGETING,e)}}refreshSlots(t=this.ads){Log.info("Refresh slots - ads : ",t);let i=!1,o=!1,n=!1,a=()=>{n||!o||!i&&__adLib.includeA9||(-1!=c&&window.clearTimeout(c),Log.info("Prebid is completed and A9 completed or disabled -> call DFP"),r())},r=()=>{Log.info("Refresh ads ",t);let e=t.map((e=>e.dfpSlot));Log.info("Refresh DFP slots ",e),googletag.pubads().refresh(e)},s=[];for(let e of t)s.push({code:e.dfpSlot.getAdUnitPath(),mediaTypes:{banner:{sizes:e.adParameters.size}},bids:__adLib.prebidBannerBiddersConfiguration});Log.info("Prebid ad unit configuration: ",s);let d={...__adLib.prebidConfiguration,debug:Log.getLevel()==e.Debug,...p.getPrebidConsentParameters()};if(__adLib.includeA9){var l=t.map((e=>e.a9Slot));Log.info("Calls A9 with these slots:",l),apstag.fetchBids({slots:l},(()=>{Log.info("A9 bid request completed"),apstag.setDisplayBids(),i=!0,a()}))}pbjs.que.push((()=>{Log.info("Set Prebid Config: ",d),pbjs.setConfig(d),pbjs.addAdUnits(s),Log.info("Request Prebid bids"),pbjs.requestBids({timeout:__adLib.prebidTimeout,bidsBackHandler:()=>{Log.info("Prebid request bid completed"),pbjs.setTargetingForGPTAsync(t.map((e=>e.dfpSlot.getAdUnitPath()))),o=!0,a()}})}));let c=-1;0!=__adLib.biddersFailsafeTimeout&&(Log.info(`Bidders failsafe timeout set to [${__adLib.biddersFailsafeTimeout}] ms`),c=window.setTimeout((()=>{Log.info("Bidding Timeout! -> calls DFP directly"),n=!0,r()}),__adLib.biddersFailsafeTimeout))}}class _{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,i){Log.info("Create a catfish container");let o=`<div id="${_.CATFISH_ID}" class="__alCatfish" style=" ${e?`width:${e}px;`:""} ${i?`height:${i}px`:""}"></div>`;return a.insert(t.append,document.body,o),Log.info("Static Catfish Inserted",_.getCurrentCatfishElement()),_.getCurrentCatfishElement()}static getCurrentCatfishElement(){return a.get(`#${_.CATFISH_ID}`)}}class L{static providerClasses=new Map([[h.DFP,m]]);providers=new Map;timers=[];constructor(){n.isDefined(typeof window.__adLib)&&a.onDocumentReady((()=>{this.init()}))}isAdBlockerActivated(){var e=a.get("#_MGS_");e||(a.insert(t.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=a.get("#_MGS_"));var i=a.get("div",e);return"none"===window.getComputedStyle(i).display}async init(){Log.info("Init Ads manager at page load"),c.init(),await p.init(),Log.info("Set tab visibility event handler"),a.setEventListener(document,"visibilitychange",(()=>{let e="visible"===document.visibilityState;Log.info(`Tab visibility changed to [${e}]`),e?this.resumeAllPausedTimers():this.pauseAllRunningTimers()})),__adLib.deferAds?(Log.info("Ads need to be deferred. Will wait until the [endDeferAds] is fired"),a.setEventListener(document,"endDeferAds",(()=>{Log.info("Deferred Ads event triggered. Will now initialize the ads"),this.contentLoadInit(document.body,__adLib.initialLoadAds)}))):(Log.info("No deferred ads. Will initialize the ads now"),this.contentLoadInit(document.body,__adLib.initialLoadAds))}async contentLoadInit(e=document.body,t){let i;if(Log.info(" ============================================================================================="),Log.info("Initialize container with ads"),Log.info(" ============================================================================================="),t)i=t,Log.info("Ad definitions passed as parameter: ",i);else{Log.info("Look for json ads definition in ",e);let t=d.getJsonFromScriptSnippet("ads-script",e);if(!t)return void Log.info("Did not find ads definition.");if(i=t,!i)return;Log.info("Found ad definitions: ",i)}let o=new Map;for(let t of i){if(Log.info("Init this ad: ",t),!this.providers.has(t.type)){Log.info(`Initializes Provider: [${t.type}]`);try{let e=new(L.providerClasses.get(t.type));await e.initProvider(),this.providers.set(t.type,e)}catch(e){Log.error(`Unable to instantiate Ad Provider: [${t.type}]`,t,e);continue}}let i=this.providers.get(t.type);o.has(t.type)||o.set(t.type,[]),t.provider=i;let n=null;if(t.displayType==b.REGULAR)n=a.get(t.selector,e);else if(t.displayType==b.CATFISH){if(n=_.getCurrentCatfishElement(),n){let e=a.get(".__alAd",n).ad;e.provider.refreshAds([e]),Log.info("Catfish already exists, just refresh its ad");continue}n=_.newCatfish(),t.injector="append"}n?(t.$container=await i.createSlot(t,n),t.$container?(t.$container.ad=t,t.refreshCounter=0,i.addAd(t),o.get(t.type).push(t),t.autoRefresh?(t.$container.isInViewPort=!1,t.refreshTimer=new l((()=>{L.timerCallback(t)}),1e3*__adLib.refreshTimer),this.timers.push(t.refreshTimer),Log.info("This ad is autorefresh, added refresh timer: ",t.refreshTimer)):(t.refreshTimer=null,t.$container.isInViewPort=!0,Log.info("This ad is not autorefresh -> no refresh timer")),t.displayType==b.CATFISH?(Log.info("The ad is a catfish -> always in viewport and start refresh timer"),t.$container.isInViewPort=!0,t.refreshTimer&&t.refreshTimer.start()):t.autoRefresh&&(Log.info("Add the ad container to the observer -> ",t.$container),this.isInViewPortObserver.observe(t.$container)),Log.info("Ad initialized",t)):Log.info("Slot creation failed -> skip this ad")):Log.info("Error when initializing the ad/Existing ad -> skip it: ",t)}for(let[e,t]of o)0==t.length?Log.info(`No ads for [${e}] provider`):(Log.info(`Request Bids for [${e}] provider: `,t),this.providers.get(e).requestBids(t));if(__adLib.stickyContainerSelector){const t=a.getAll(`${__adLib.stickyContainerSelector} .__alAd`,e);let i=t.length;if(i>0){let e=t.item(i-1);Log.info("Last ad is sticky",e),a.addClass(e,"__alSticky",__adLib.stickyAdClass)}}}isInViewPortObserver=new IntersectionObserver((e=>{e.forEach((e=>{let t=e.target;t.isInViewPort=e.intersectionRatio>=__adLib.viewportThreshold,t.isInViewPort?(Log.info("Ad in viewport -> resume timer",t.ad),L.resumeRefreshTimer(t.ad)):(Log.info("Ad out of viewport -> stop timer",t.ad),L.pauseRefreshTimer(t.ad))}))}),{threshold:__adLib.viewportThreshold});static timerCallback(e){Log.info("Ad is refreshed.",e),e.refreshCounter++,e.provider.refreshAds([e])}static resumeRefreshTimer(e){Log.info("Resume refresh timer for ",e),e.refreshTimer.state==i.PAUSED?e.refreshTimer.resume():e.refreshTimer.state==i.STOPPED&&e.refreshTimer.start()}static pauseRefreshTimer(e){Log.info("Pause refresh timer for ",e),e.refreshTimer.pause()}pausedTimers=[];pauseAllRunningTimers(){this.pausedTimers=this.timers.filter((e=>e.state==i.RUNNING)),0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.pause())),Log.info("Pause these timers: ",this.pausedTimers.map((e=>e.id))))}resumeAllPausedTimers(){0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.resume())),Log.info("Resume these timers: ",this.pausedTimers.map((e=>e.id))))}refreshAllAds(){Log.info("Refresh All ads"),this.providers.forEach((e=>{Log.info(`will refresh ads for this provider: [${e.getName()}]`);for(let t of e.ads)t.refreshCounter++;e.refreshAllAds();for(let t of e.ads)t.refreshTimer&&t.refreshTimer.restart()}))}}window.Log=new o(n.isDefined(__adLib)?e[__adLib.logLevel]:e.None),Log.info("Ad Library Loaded"),__adLib.AdsManager=new L,__adLib.ConsentManager=p,__adLib.PrebidForVideo=f,__adLib.PrerollAd=u; | ||
//# sourceMappingURL=britannica-ads.cjs.js.map |
@@ -1,2 +0,2 @@ | ||
var e;!function(e){e[e.Debug=0]="Debug",e[e.Info2=1]="Info2",e[e.Info=2]="Info",e[e.None=3]="None"}(e||(e={}));class t{static INFO_STYLE="font-weight:bold; background-color: #084466; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static INFO_STYLE2="font-weight:bold; background-color: rebeccapurple; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static ERR_STYLE="font-weight:bold; background-color: red; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static WARN_STYLE="font-weight:bold; background-color: orange; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static DEBUG_STYLE="font-weight:bold; background-color: #88A95B; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";error=console.error.bind(window.console,"%cAd Lib",t.ERR_STYLE);warning=console.warn.bind(window.console,"%cAd Lib",t.WARN_STYLE);debug;info;info2;level;constructor(){this.level=s.isDefined(__adLib)?e[__adLib.logLevel]:e.None,this.info=e.Info>=this.level?console.log.bind(window.console,"%cAd Lib",t.INFO_STYLE):()=>null,this.info2=e.Info2>=this.level?console.log.bind(window.console,"%cAd Lib",t.INFO_STYLE2):()=>null,this.debug=e.Debug>=this.level?console.debug.bind(window.console,"%cAd Lib",t.DEBUG_STYLE):()=>null}getLevel(){return this.level}}const i=new t;class s{static isDefined(e){return void 0!==e}static isFunction(e){return"function"==typeof e}}var a,r,n,o;!function(e){e.before="beforeBegin",e.after="afterEnd",e.prepend="afterBegin",e.append="beforeEnd"}(a||(a={}));class d{static insert(e,t,i){t.insertAdjacentHTML(e,i)}static remove(e){e&&e.parentNode.removeChild(e)}static loadScript(e,t={}){return new Promise(((s,a)=>{let r=document.createElement("script");r.src=e,r.onload=()=>s(),r.onerror=()=>a();for(const[e,i]of Object.entries(t))r.setAttribute(e,i);document.head.append(r),i.info(`Loaded: [${e}]`)}))}static css(e,t,i){e.style.setProperty(t,i)}static addClass(e,...t){t.forEach((t=>{t&&e.classList.add(t)}))}static removeClass(e,t){e.classList.remove(t)}static onDocumentReady(e){"loading"!=document.readyState?e():document.addEventListener("DOMContentLoaded",e)}static get(e,t=document.body){return t.querySelector(e)}static getAll(e,t=document.body){return t.querySelectorAll(e)}static setEventListener(e,t,i){e.addEventListener(t,i)}static removeEventListener(e,t,i){e.removeEventListener(t,i)}static onInViewPort(e,t){new IntersectionObserver(((i,s)=>{i.forEach((i=>{i.isIntersecting&&(t(e),s.disconnect(),s=null)}))}),{threshold:1}).observe(e)}static onScroll(e,t){window.addEventListener("scroll",function(e,t){var i=!1;return function(){i||(e(window.scrollY),i=!0,setTimeout((function(){i=!1}),t))}}(e,t))}static delayedCall(e,t){t?setTimeout(e,1e3*t):e()}}class l{static createCookieSession(e,t,i){document.cookie=`${e}=${t}; path=/${i?";domain="+i:""}`}static readCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(`${e}=`))).split("=")[1]}static isCookieExists(e){return document.cookie.split(";").some((t=>t.trim().startsWith(`${e}=`)))}}class c{static substringBefore(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(0,i)}static substringAfter(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(i+1)}static defaultIfBlank(e,t){return e&&0!=e.length?e:t}}class p{static getJsonFromScriptSnippet(e,t=document.body){const i=d.get(`script[type="application/json"].${e}`,t);return i?p.elementContentToJson(i):null}static elementContentToJson(e){var t=e.innerText;try{return JSON.parse(t)}catch(e){return i.error("JSON parsing error: ",e),null}}}!function(e){e.PAUSED="PAUSED",e.RUNNING="RUNNING",e.STOPPED="STOPPED"}(r||(r={}));class f{_id=(Date.now()+Math.floor(100*Math.random())).toString().slice(-5);_state=r.STOPPED;internalTimerId;restartTimerId;lastStart;remaining;callback;delay;constructor(e,t){this.callback=e,this.delay=t}get id(){return this._id}get state(){return this._state}callbackFn(){this.lastStart=Date.now(),this.remaining=this.delay,this.callback()}pause(){this.state==r.RUNNING&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining-=Date.now()-this.lastStart,this._state=r.PAUSED,i.debug(`Timer [${this._id}] Paused - Remaining [${this.remaining}ms]`))}resume(){this.state==r.PAUSED&&(this.restartTimerId=window.setTimeout((()=>{this.callback(),this.start()}),this.remaining),this.lastStart=Date.now(),this._state=r.RUNNING,i.debug(`Timer [${this._id}] Resumed in [${this.remaining}ms].`))}stop(){this.state!=r.STOPPED&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining=this.delay,this._state=r.STOPPED,i.debug(`Timer [${this._id}] - Internal id [${this.internalTimerId}] Stopped`))}start(){this.lastStart=Date.now(),this.remaining=this.delay,this.internalTimerId=window.setInterval((()=>this.callbackFn()),this.delay),this._state=r.RUNNING,i.debug(`Started Timer [${this._id}] - Internal id [${this.internalTimerId}]`)}restart(){this.stop(),this.start()}stopInternalTimer(){this.internalTimerId&&(window.clearInterval(this.internalTimerId),this.internalTimerId=null)}stopResumeTimer(){this.restartTimerId&&(window.clearTimeout(this.restartTimerId),this.restartTimerId=null)}}class u{static US_PrivacyCookieName="usprivacy";static US_PrivacyCookieDuration=365;static init(){i.info2("Init IAB: Insert iframe locator into body"),d.insert(a.append,document.body,'<iframe name="__uspapiLocator" style="display:none;height:0;opacity:0;visibility:hidden;border:0;width:0;"></iframe>'),i.info2("Install IAB message handler"),window.addEventListener("message",u.optOutMsgHandler,!1),i.info2("Install global __uspapi function"),window.__uspapi=(e,t,s)=>{if(i.info2(`IAB: __uspapi function called. Command: [${e}] `),"getuspdata"===e.toLowerCase()){let e={version:t,uspString:l.readCookie(u.US_PrivacyCookieName)};i.info2("IAB: getuspdata command. Response: ",e),s(e,null!=e.uspString)}},l.isCookieExists(u.US_PrivacyCookieName)||(__adLib.usPrivacyConsent?(i.info2("IAB: US privacy consent needed (CCPA), create default cookie [1YNY]"),u.createCookie(1,!0,!1,!0)):(i.info2("IAB: No US privacy consent needed, create default cookie [1---]"),u.createCookie()))}static createCookie(e=1,t,i,s){let a=e=>!0===e?"Y":!1===e?"N":"-",r=e.toString()+a(t)+a(i)+a(s),n=`${u.US_PrivacyCookieName}=${r}; `,o=new Date;o.setTime(o.getTime()+24*u.US_PrivacyCookieDuration*60*60*1e3);let d=`expires=${o.toUTCString()}; `;document.cookie=n+d+"path=/; SameSite=Lax; "}static optOutMsgHandler(e){let t,s="string"==typeof e.data;if(t=s?-1!==e.data.indexOf("__uspapiCall")?JSON.parse(e.data):{}:e.data,t.__uspapiCall){i.info2("Received __uspapiCall event. Will post message to sender with the cookie content");let a=t.__uspapiCall;window.__uspapi(a.command,a.version,(function(t,r){let n={__uspapiReturn:{returnValue:t,success:r,callId:a.callId}},o=e.source;i.info2("IAB: post message back ",n,o),o.postMessage(s?JSON.stringify(n):n,"*")}))}}}class g{static async init(){if(__adLib.requiresConsent){if(!s.isDefined(window.__tcfapi)){i.info2("__tcfapi not found -> Will load the oneTrust scripts");try{await d.loadScript("https://cdn.cookielaw.org/consent/cmp.stub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw i.error("Unable to load oneTrust cmp.stub.js script"),e}try{await d.loadScript("https://cdn.cookielaw.org/scripttemplates/otSDKStub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw i.error("Unable to load oneTrust otSDKStub.js script "),e}i.info2("oneTrust scripts loaded")}i.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{i.info2(`OptanonWrapper called. Defer Ads status is [${g.getDeferAdsStatus()}]`),g.getDeferAdsStatus()&&(i.info2("Defer Ads status is true -> Set Read TCData callback"),window.__tcfapi("getTCData",2,((e,t)=>{if(i.info2(`TCData read: success = [${t}] data = `,e),!t||g.statusOk(e))return i.info2("Error or status already OK -> send message to the app to load the ads immediately "),void g.setDeferAdsStatus(!1);const s=(e,t)=>{i.info2("Received __tcpapi status change Event: ",e),t&&g.statusOk(e)&&(i.info2("Status now OK, remove the event listener and send message to the app to load the ads immediately"),window.__tcfapi("removeEventListener",2,s),g.setDeferAdsStatus(!1))};i.info2("Status not OK yet. Set event listener to load the ads when it will be OK"),window.__tcfapi("addEventListener",2,s)})))},i.info2("Defer the ads loading by default"),g.setDeferAdsStatus(!0)}else i.info2("Not Consent Required")}static getDeferAdsStatus(){return __adLib.deferAds}static setDeferAdsStatus(e){__adLib.deferAds=e,e||document.dispatchEvent(new Event("endDeferAds"))}static statusOk(e){return"useractioncomplete"==e.eventStatus||"tcloaded"==e.eventStatus}static getPrebidConsentParameters(){return __adLib.usPrivacyConsent?__adLib.prebidCcpaConfiguration:__adLib.requiresConsent?__adLib.prebidGdprConfiguration:null}static onDNSMILinkClicked(){i.info2("CCPA consent called"),i.info2("create default IAB cookie [1YYY]"),u.createCookie(1,!0,!0,!0),i.info2("Modifies onetrust OptanonConsent cookies and ActiveGroups global variables");let e=[4],t=decodeURIComponent(l.readCookie("OptanonConsent "));i.info2("Current OptanonConsent cookie value = ",t);for(let i of e)t=t.replace(`,${i}:1,`,`,${i}:0,`),window.OptanonActiveGroups=window.OptanonActiveGroups.replace(`,${i},`,","),window.OnetrustActiveGroups=window.OnetrustActiveGroups.replace(`,${i},`,",");i.info2("New OptanonConsent cookie value = ",t),i.info2(`New OptanonActiveGroups = [${window.OptanonActiveGroups}]`),i.info2(`New OneTrustActiveGroups = [${window.OnetrustActiveGroups}]`),l.createCookieSession("OptanonConsent",encodeURI(t),__adLib.topDomain),l.createCookieSession("EbConsentClosed","true"),i.info2("created new OptanonConsent and EbConsentClosed cookies")}}class h{static async loadPrebidScript(){if(!__adLib.videoForPrebidLoaded&&!s.isDefined(window.pbjs)){i.info(`Loading [${__adLib.prebidScriptUrl}] prebid script now`),window.pbjs={que:[]};try{await d.loadScript(__adLib.prebidScriptUrl)}catch(e){return void i.error(`Unable to load [${__adLib.prebidScriptUrl}] prebid script -> skip ad`)}__adLib.videoForPrebidLoaded=!0}}}class b{static setJwplayerSetupWithPrebid(t,s,a,r=!1){r||__adLib.showPrerollAdInVideos?(h.loadPrebidScript(),pbjs.que.push((()=>{let r=__adLib.prebidConfiguration;r.debug=i.getLevel()==e.Debug,pbjs.setConfig(r),pbjs.addAdUnits(__adLib.prebidVideoAdUnit),i.info("Request Prebid bids with ad unit id: ",t),pbjs.requestBids({bidsBackHandler:()=>{let e={iu:`${`${__adLib.googleDfpId}/EB_${__adLib.leg}/${__adLib.dfpUnitPrefix}`}${t}`,output:"vast"};i.info("Prebid video url called. Params = ",e);let r=pbjs.adServers.dfp.buildVideoUrl({adUnit:__adLib.prebidVideoAdUnit,params:e});i.info(`Bidding completed. Set URL in jwplayer setup and call callback: [${r}]`),s.advertising={client:"googima",adschedule:[{offset:"pre",tag:r}]},a()}})}))):a()}static addJwPlayerAdSetup(e,t){t.advertising={client:"googima",adschedule:[{offset:"pre",tag:e}]}}}class m{static CONTAINER_CLASS="__alPrerollContainer";static WRAPPER_CLASS="__alPrerollWrapper";static JWPLAYER_CONTAINER_ID="__alPreroll";static async createPreRollAd(e,t,r=(()=>{})){if(__adLib.prerollAdIsRunning)return void i.info("Preroll Ad is already running. Ignore this one");if(!__adLib.showPrerollAd)return i.info("Preroll Ads not enabled -> return"),void r();if(class{static isAdBlockerActivated(){var e=d.get("#_MGS_");e||(d.insert(a.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=d.get("#_MGS_"));var t=d.get("div",e);return"none"===window.getComputedStyle(t).display}}.isAdBlockerActivated())return void r();if(__adLib.prerollAdIsRunning=!0,!s.isDefined(window.jwplayer)){i.info("jwplayer not found. Loading the script now");try{await d.loadScript(`https://content.jwplatform.com/libraries/${__adLib.jwplayerId}.js`)}catch(e){return i.error("Unable to load jwplayer script -> skip ad"),__adLib.prerollAdIsRunning=!1,void r()}}d.addClass(e,m.CONTAINER_CLASS),i.info(`Insert preroll [${t}] Ad into`,e),d.insert(a.prepend,e,`<div class="${m.WRAPPER_CLASS}"><div id="${m.JWPLAYER_CONTAINER_ID}"></div></div>`);let n=d.get(`.${m.WRAPPER_CLASS}`,e),o={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};b.setJwplayerSetupWithPrebid(t,o,(()=>{i.info("Prebid preroll completed. Init JWPlayer: ",o);let t=jwplayer(m.JWPLAYER_CONTAINER_ID);t.setup(o);const s=s=>{t&&(i.info(`Preroll Ended. Cause: [${s}]. Will remove the player and its container`),t.remove(),t=null,d.remove(n),d.removeClass(e,m.CONTAINER_CLASS),__adLib.prerollAdIsRunning=!1,r())};t.on("adComplete",(()=>{s("Ad completed")})),t.on("adSkipped",(()=>{s("Ad Skipped")})),t.on("adError",(()=>{s("Ad Error")})),t.on("adBlock",(()=>{s("Ad Blocked")})),t.on("complete",(()=>{s("Video completed")})),t.on("error",(()=>{s("Error")}))}),!0)}}!function(e){e.DFP="DFP"}(n||(n={}));!function(e){e.REGULAR="REGULAR",e.CATFISH="CATFISH"}(o||(o={}));class _ extends class{type;ads;constructor(){this.ads=[],this.type=this.getType()}addAd(e){this.ads.push(e)}}{static PAGELOAD_TARGETING="PAGELOAD";index=1;getName(){return"Google DFP"}getType(){return n.DFP}constructor(){super()}async initProvider(){if(window.googletag={cmd:[]},!s.isDefined(googletag.defineSlot)){i.info("Googletag not found. Load the script");try{await d.loadScript("https://securepubads.g.doubleclick.net/tag/js/gpt.js")}catch(e){throw i.error("**** Unable to load gpt.js -> most ads and scripts will be broken ***"),e}}if(i.info("Googletag script loaded: ",googletag.defineSlot),h.loadPrebidScript(),!s.isDefined(window.headertag)&&__adLib.includeIndex)try{await d.loadScript(__adLib.indexScriptUrl)}catch(e){i.error(`Unable to load [${__adLib.indexScriptUrl}] Index script. We won't use it.`)}if(!s.isDefined(window.apstag)&&__adLib.includeA9)try{await d.loadScript("https://c.amazon-adsystem.com/aax2/apstag.js"),function(e,t){function i(i,s){t[e]._Q.push([i,s])}t[e]||(t[e]={init:function(){i("i",arguments)},fetchBids:function(){i("f",arguments)},setDisplayBids:function(){},targetingKeys:function(){return[]},_Q:[]})}("apstag",window)}catch(e){i.error("Unable to load A9 script. Will disable it"),__adLib.includeA9=!1}googletag.cmd.push((function(){if(googletag.pubads().setTargeting("dc_ref",__adLib.url),s.isDefined(Storage)){var e=localStorage.getItem("bcDFPTargetingParams");if(e)i.info("Setting Blueconic targeting parameters"),JSON.parse(e).forEach((e=>googletag.pubads().setTargeting(e.key,e.value)))}if(i.info(`targeting: ${googletag.pubads().getTargetingKeys()}`),googletag.pubads().disableInitialLoad(),googletag.pubads().enableSingleRequest(),googletag.pubads().enableAsyncRendering(),googletag.pubads().setTagForChildDirectedTreatment(0),googletag.pubads().setTagForUnderAgeOfConsent(0),__adLib.dfpLazyLoad&&googletag.pubads().enableLazyLoad(__adLib.dfpLazyLoadParameters),googletag.enableServices(),__adLib.includeA9){var t={pubID:__adLib.a9Id,adServer:"googletag",bidTimeout:1200};__uspapi&&__uspapi("getuspdata","1",((e,i)=>{i&&(t.params={us_privacy:e.uspString})})),i.info("Init A9 with ",t),apstag.init(t)}}))}createSlot(e,t){return this.initSlot(e,t)}initSlot(e,t){return new Promise((s=>{googletag.cmd.push((()=>{try{i.info("process DFP ad: ",e);var r=e.adParameters,n=r.size[0][0],l=r.size[0][1];i.info("Content container for this ad is ",t);var p="";if(e.displayType!=o.CATFISH)if(r.placeholderSize)p=`min-width:${c.substringBefore(r.placeholderSize,"x")}px;min-height:${c.substringAfter(r.placeholderSize,"x")}px;`;else if(1==r.size.length)p=`width:${n}px;height:${l}px;`;else{p=`min-height:${Math.round(r.size.map((e=>e[1])).reduce(((e,t)=>e+t))/r.size.length)}px;`}var f="DFP_"+this.index++;e.containerId=f,e.dfpSize=1==r.size.length?r.size[0]:r.size;var u=`style="${p}${c.defaultIfBlank(r.style,"")}"`,g=`<div data-type="${e.type}" class="__alAd ${c.defaultIfBlank(__adLib.adClass,"")} ${c.defaultIfBlank(r.cssClass,"")}" ${u} id="${f}"></div>`;i.info(`Inject DIV: [${g}] into `,t),d.insert(a[e.injector],t,g);var h=this.setDfpA9Slot(e);let b=d.get(`#${f}`);b.setAttribute("data-identifier",e.dfpSlot.getAdUnitPath()),b.setAttribute("data-qa-identifier",h),s(b)}catch(t){i.error("Init Slot Error: ",e,t),s(null)}}))}))}setDfpA9Slot=function(e){i.info("Initializes DFP slot and A9 slot for ",e);var t=e.adParameters,s=__adLib.dfpIdPrefix.replace("${LEG}",__adLib.leg),a=`${__adLib.isPhone?"MOBILE":"DESKTOP"}_${t.id}`,r=`/${__adLib.googleDfpId}/${s}${a}`;return i.info(`Define new slot: [${r}] with: size [${e.dfpSize}] id [${e.containerId}]`),e.dfpSlot=googletag.defineSlot(r,e.dfpSize,e.containerId),t.targeting&&Object.entries(t.targeting).forEach((([t,i])=>{e.dfpSlot.setTargeting(t,String(i))})),e.dfpSlot.addService(googletag.pubads()),__adLib.includeA9&&(e.a9Slot={slotID:e.containerId,slotName:r,sizes:t.size}),i.info("DFP/A9 slot defined for ",e),a};refreshAllAds(){i.info("Refresh all DFP ads."),googletag.cmd.push((()=>{_.setPageLoadTargeting(this.ads),this.refreshSlots()}))}requestBids(e){this.refreshAds(e)}refreshAds(e){i.info("Refresh ads: ",e),googletag.cmd.push((()=>{_.setPageLoadTargeting(e),this.refreshSlots(e)}))}static setPageLoadTargeting(e){for(let t of e){const e=`REFRESH${t.refreshCounter}`;i.info(`Update ${_.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(_.PAGELOAD_TARGETING,e)}}refreshSlots(t=this.ads){i.info("Refresh slots - ads : ",t);let s=!1,a=!1,r=!1,n=()=>{r||!a||!s&&__adLib.includeA9||(-1!=p&&window.clearTimeout(p),i.info("Prebid is completed and A9 completed or disabled -> call DFP"),o())},o=()=>{i.info("Refresh ads ",t);let e=t.map((e=>e.dfpSlot));i.info("Refresh DFP slots ",e),googletag.pubads().refresh(e)},d=[];for(let e of t)d.push({code:e.dfpSlot.getAdUnitPath(),mediaTypes:{banner:{sizes:e.adParameters.size}},bids:__adLib.prebidBannerBiddersConfiguration});i.info("Prebid ad unit configuration: ",d);let l={...__adLib.prebidConfiguration,debug:i.getLevel()==e.Debug,...g.getPrebidConsentParameters()};if(__adLib.includeA9){var c=t.map((e=>e.a9Slot));i.info("Calls A9 with these slots:",c),apstag.fetchBids({slots:c},(()=>{i.info("A9 bid request completed"),apstag.setDisplayBids(),s=!0,n()}))}pbjs.que.push((()=>{i.info("Set Prebid Config: ",l),pbjs.setConfig(l),pbjs.addAdUnits(d),i.info("Request Prebid bids"),pbjs.requestBids({timeout:__adLib.prebidTimeout,bidsBackHandler:()=>{i.info("Prebid request bid completed"),pbjs.setTargetingForGPTAsync(t.map((e=>e.dfpSlot.getAdUnitPath()))),a=!0,n()}})}));let p=-1;0!=__adLib.biddersFailsafeTimeout&&(i.info(`Bidders failsafe timeout set to [${__adLib.biddersFailsafeTimeout}] ms`),p=window.setTimeout((()=>{i.info("Bidding Timeout! -> calls DFP directly"),r=!0,o()}),__adLib.biddersFailsafeTimeout))}}class A{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,t){i.info("Create a catfish container");let s=`<div id="${A.CATFISH_ID}" class="__alCatfish" style=" ${e?`width:${e}px;`:""} ${t?`height:${t}px`:""}"></div>`;return d.insert(a.append,document.body,s),i.info("Static Catfish Inserted",A.getCurrentCatfishElement()),A.getCurrentCatfishElement()}static getCurrentCatfishElement(){return d.get(`#${A.CATFISH_ID}`)}}require("./AdsManager.scss");class S{static providerClasses=new Map([[n.DFP,_]]);providers=new Map;timers=[];constructor(){s.isDefined(typeof window.__adLib)&&d.onDocumentReady((()=>{i.info("Ad Library Loaded"),this.init()}))}isAdBlockerActivated(){var e=d.get("#_MGS_");e||(d.insert(a.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=d.get("#_MGS_"));var t=d.get("div",e);return"none"===window.getComputedStyle(t).display}async init(){i.info("Init Ads manager at page load"),u.init(),await g.init(),i.info("Set tab visibility event handler"),d.setEventListener(document,"visibilitychange",(()=>{let e="visible"===document.visibilityState;i.info(`Tab visibility changed to [${e}]`),e?this.resumeAllPausedTimers():this.pauseAllRunningTimers()})),__adLib.deferAds?(i.info("Ads need to be deferred. Will wait until the [endDeferAds] is fired"),d.setEventListener(document,"endDeferAds",(()=>{i.info("Deferred Ads event triggered. Will now initialize the ads"),this.contentLoadInit(document.body,__adLib.initialLoadAds)}))):(i.info("No deferred ads. Will initialize the ads now"),this.contentLoadInit(document.body,__adLib.initialLoadAds))}async contentLoadInit(e=document.body,t){let s;if(i.info(" ============================================================================================="),i.info("Initialize container with ads"),i.info(" ============================================================================================="),t)s=t,i.info("Ad definitions passed as parameter: ",s);else{i.info("Look for json ads definition in ",e);let t=p.getJsonFromScriptSnippet("ads-script",e);if(!t)return void i.info("Did not find ads definition.");if(s=t,!s)return;i.info("Found ad definitions: ",s)}let a=new Map;for(let t of s){if(i.info("Init this ad: ",t),!this.providers.has(t.type)){i.info(`Initializes Provider: [${t.type}]`);try{let e=new(S.providerClasses.get(t.type));await e.initProvider(),this.providers.set(t.type,e)}catch(e){i.error(`Unable to instantiate Ad Provider: [${t.type}]`,t,e);continue}}let s=this.providers.get(t.type);a.has(t.type)||a.set(t.type,[]),t.provider=s;let r=null;if(t.displayType==o.REGULAR)r=d.get(t.selector,e);else if(t.displayType==o.CATFISH){if(r=A.getCurrentCatfishElement(),r){let e=d.get(".__alAd",r).ad;e.provider.refreshAds([e]),i.info("Catfish already exists, just refresh its ad");continue}r=A.newCatfish(),t.injector="append"}r?(t.$container=await s.createSlot(t,r),t.$container?(t.$container.ad=t,t.refreshCounter=0,s.addAd(t),a.get(t.type).push(t),t.autoRefresh?(t.$container.isInViewPort=!1,t.refreshTimer=new f((()=>{S.timerCallback(t)}),1e3*__adLib.refreshTimer),this.timers.push(t.refreshTimer),i.info("This ad is autorefresh, added refresh timer: ",t.refreshTimer)):(t.refreshTimer=null,t.$container.isInViewPort=!0,i.info("This ad is not autorefresh -> no refresh timer")),t.displayType==o.CATFISH?(i.info("The ad is a catfish -> always in viewport and start refresh timer"),t.$container.isInViewPort=!0,t.refreshTimer&&t.refreshTimer.start()):t.autoRefresh&&(i.info("Add the ad container to the observer -> ",t.$container),this.isInViewPortObserver.observe(t.$container)),i.info("Ad initialized",t)):i.info("Slot creation failed -> skip this ad")):i.info("Error when initializing the ad/Existing ad -> skip it: ",t)}for(let[e,t]of a)0==t.length?i.info(`No ads for [${e}] provider`):(i.info(`Request Bids for [${e}] provider: `,t),this.providers.get(e).requestBids(t));if(__adLib.stickyContainerSelector){const t=d.getAll(`${__adLib.stickyContainerSelector} .__alAd`,e);let s=t.length;if(s>0){let e=t.item(s-1);i.info("Last ad is sticky",e),d.addClass(e,"__alSticky",__adLib.stickyAdClass)}}}isInViewPortObserver=new IntersectionObserver((e=>{e.forEach((e=>{let t=e.target;t.isInViewPort=e.intersectionRatio>=__adLib.viewportThreshold,t.isInViewPort?(i.info("Ad in viewport -> resume timer",t.ad),S.resumeRefreshTimer(t.ad)):(i.info("Ad out of viewport -> stop timer",t.ad),S.pauseRefreshTimer(t.ad))}))}),{threshold:__adLib.viewportThreshold});static timerCallback(e){i.info("Ad is refreshed.",e),e.refreshCounter++,e.provider.refreshAds([e])}static resumeRefreshTimer(e){i.info("Resume refresh timer for ",e),e.refreshTimer.state==r.PAUSED?e.refreshTimer.resume():e.refreshTimer.state==r.STOPPED&&e.refreshTimer.start()}static pauseRefreshTimer(e){i.info("Pause refresh timer for ",e),e.refreshTimer.pause()}pausedTimers=[];pauseAllRunningTimers(){this.pausedTimers=this.timers.filter((e=>e.state==r.RUNNING)),0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.pause())),i.info("Pause these timers: ",this.pausedTimers.map((e=>e.id))))}resumeAllPausedTimers(){0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.resume())),i.info("Resume these timers: ",this.pausedTimers.map((e=>e.id))))}refreshAllAds(){i.info("Refresh All ads"),this.providers.forEach((e=>{i.info(`will refresh ads for this provider: [${e.getName()}]`);for(let t of e.ads)t.refreshCounter++;e.refreshAllAds();for(let t of e.ads)t.refreshTimer&&t.refreshTimer.restart()}))}}const w=new S;export{w as AdsManager,g as ConsentManager,b as PrebidForVideo,m as PrerollAd}; | ||
var e,t,i;!function(e){e[e.Debug=0]="Debug",e[e.Info2=1]="Info2",e[e.Info=2]="Info",e[e.None=3]="None"}(e||(e={}));class o{static INFO_STYLE="font-weight:bold; background-color: #084466; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static INFO_STYLE2="font-weight:bold; background-color: rebeccapurple; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static ERR_STYLE="font-weight:bold; background-color: red; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static WARN_STYLE="font-weight:bold; background-color: orange; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static DEBUG_STYLE="font-weight:bold; background-color: #88A95B; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";error=console.error.bind(window.console,"%cAd Lib",o.ERR_STYLE);warning=console.warn.bind(window.console,"%cAd Lib",o.WARN_STYLE);debug;info;info2;level;constructor(t){this.level=t,this.info=e.Info>=this.level?console.log.bind(window.console,"%cAd Lib",o.INFO_STYLE):()=>null,this.info2=e.Info2>=this.level?console.log.bind(window.console,"%cAd Lib",o.INFO_STYLE2):()=>null,this.debug=e.Debug>=this.level?console.debug.bind(window.console,"%cAd Lib",o.DEBUG_STYLE):()=>null}getLevel(){return this.level}}class n{static isDefined(e){return void 0!==e}static isFunction(e){return"function"==typeof e}}!function(e){e.before="beforeBegin",e.after="afterEnd",e.prepend="afterBegin",e.append="beforeEnd"}(t||(t={}));class a{static insert(e,t,i){t.insertAdjacentHTML(e,i)}static remove(e){e&&e.parentNode.removeChild(e)}static loadScript(e,t={}){return new Promise(((i,o)=>{let n=document.createElement("script");n.src=e,n.onload=()=>i(),n.onerror=()=>o();for(const[e,i]of Object.entries(t))n.setAttribute(e,i);document.head.append(n),window.Log.info(`Loaded: [${e}]`)}))}static css(e,t,i){e.style.setProperty(t,i)}static addClass(e,...t){t.forEach((t=>{t&&e.classList.add(t)}))}static removeClass(e,t){e.classList.remove(t)}static onDocumentReady(e){"loading"!=document.readyState?e():document.addEventListener("DOMContentLoaded",e)}static get(e,t=document.body){return t.querySelector(e)}static getAll(e,t=document.body){return t.querySelectorAll(e)}static setEventListener(e,t,i){e.addEventListener(t,i)}static removeEventListener(e,t,i){e.removeEventListener(t,i)}static onInViewPort(e,t){new IntersectionObserver(((i,o)=>{i.forEach((i=>{i.isIntersecting&&(t(e),o.disconnect(),o=null)}))}),{threshold:1}).observe(e)}static onScroll(e,t){window.addEventListener("scroll",function(e,t){var i=!1;return function(){i||(e(window.scrollY),i=!0,setTimeout((function(){i=!1}),t))}}(e,t))}static delayedCall(e,t){t?setTimeout(e,1e3*t):e()}}class r{static createCookieSession(e,t,i){document.cookie=`${e}=${t}; path=/${i?";domain="+i:""}`}static readCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(`${e}=`))).split("=")[1]}static isCookieExists(e){return document.cookie.split(";").some((t=>t.trim().startsWith(`${e}=`)))}}class s{static substringBefore(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(0,i)}static substringAfter(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(i+1)}static defaultIfBlank(e,t){return e&&0!=e.length?e:t}}class d{static getJsonFromScriptSnippet(e,t=document.body){const i=a.get(`script[type="application/json"].${e}`,t);return i?d.elementContentToJson(i):null}static elementContentToJson(e){var t=e.innerText;try{return JSON.parse(t)}catch(e){return window.Log.error("JSON parsing error: ",e),null}}}!function(e){e.PAUSED="PAUSED",e.RUNNING="RUNNING",e.STOPPED="STOPPED"}(i||(i={}));class l{_id=(Date.now()+Math.floor(100*Math.random())).toString().slice(-5);_state=i.STOPPED;internalTimerId;restartTimerId;lastStart;remaining;callback;delay;constructor(e,t){this.callback=e,this.delay=t}get id(){return this._id}get state(){return this._state}callbackFn(){this.lastStart=Date.now(),this.remaining=this.delay,this.callback()}pause(){this.state==i.RUNNING&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining-=Date.now()-this.lastStart,this._state=i.PAUSED,window.Log.debug(`Timer [${this._id}] Paused - Remaining [${this.remaining}ms]`))}resume(){this.state==i.PAUSED&&(this.restartTimerId=window.setTimeout((()=>{this.callback(),this.start()}),this.remaining),this.lastStart=Date.now(),this._state=i.RUNNING,window.Log.debug(`Timer [${this._id}] Resumed in [${this.remaining}ms].`))}stop(){this.state!=i.STOPPED&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining=this.delay,this._state=i.STOPPED,window.Log.debug(`Timer [${this._id}] - Internal id [${this.internalTimerId}] Stopped`))}start(){this.lastStart=Date.now(),this.remaining=this.delay,this.internalTimerId=window.setInterval((()=>this.callbackFn()),this.delay),this._state=i.RUNNING,window.Log.debug(`Started Timer [${this._id}] - Internal id [${this.internalTimerId}]`)}restart(){this.stop(),this.start()}stopInternalTimer(){this.internalTimerId&&(window.clearInterval(this.internalTimerId),this.internalTimerId=null)}stopResumeTimer(){this.restartTimerId&&(window.clearTimeout(this.restartTimerId),this.restartTimerId=null)}}class c{static US_PrivacyCookieName="usprivacy";static US_PrivacyCookieDuration=365;static init(){Log.info2("Init IAB: Insert iframe locator into body"),a.insert(t.append,document.body,'<iframe name="__uspapiLocator" style="display:none;height:0;opacity:0;visibility:hidden;border:0;width:0;"></iframe>'),Log.info2("Install IAB message handler"),window.addEventListener("message",c.optOutMsgHandler,!1),Log.info2("Install global __uspapi function"),window.__uspapi=(e,t,i)=>{if(Log.info2(`IAB: __uspapi function called. Command: [${e}] `),"getuspdata"===e.toLowerCase()){let e={version:t,uspString:r.readCookie(c.US_PrivacyCookieName)};Log.info2("IAB: getuspdata command. Response: ",e),i(e,null!=e.uspString)}},r.isCookieExists(c.US_PrivacyCookieName)||(__adLib.usPrivacyConsent?(Log.info2("IAB: US privacy consent needed (CCPA), create default cookie [1YNY]"),c.createCookie(1,!0,!1,!0)):(Log.info2("IAB: No US privacy consent needed, create default cookie [1---]"),c.createCookie()))}static createCookie(e=1,t,i,o){let n=e=>!0===e?"Y":!1===e?"N":"-",a=e.toString()+n(t)+n(i)+n(o),r=`${c.US_PrivacyCookieName}=${a}; `,s=new Date;s.setTime(s.getTime()+24*c.US_PrivacyCookieDuration*60*60*1e3);let d=`expires=${s.toUTCString()}; `;document.cookie=r+d+"path=/; SameSite=Lax; "}static optOutMsgHandler(e){let t,i="string"==typeof e.data;if(t=i?-1!==e.data.indexOf("__uspapiCall")?JSON.parse(e.data):{}:e.data,t.__uspapiCall){Log.info2("Received __uspapiCall event. Will post message to sender with the cookie content");let o=t.__uspapiCall;window.__uspapi(o.command,o.version,(function(t,n){let a={__uspapiReturn:{returnValue:t,success:n,callId:o.callId}},r=e.source;Log.info2("IAB: post message back ",a,r),r.postMessage(i?JSON.stringify(a):a,"*")}))}}}class p{static async init(){if(__adLib.requiresConsent){if(!n.isDefined(window.__tcfapi)){Log.info2("__tcfapi not found -> Will load the oneTrust scripts");try{await a.loadScript("https://cdn.cookielaw.org/consent/cmp.stub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw Log.error("Unable to load oneTrust cmp.stub.js script"),e}try{await a.loadScript("https://cdn.cookielaw.org/scripttemplates/otSDKStub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw Log.error("Unable to load oneTrust otSDKStub.js script "),e}Log.info2("oneTrust scripts loaded")}Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2(`OptanonWrapper called. Defer Ads status is [${p.getDeferAdsStatus()}]`),p.getDeferAdsStatus()&&(Log.info2("Defer Ads status is true -> Set Read TCData callback"),window.__tcfapi("getTCData",2,((e,t)=>{if(Log.info2(`TCData read: success = [${t}] data = `,e),!t||p.statusOk(e))return Log.info2("Error or status already OK -> send message to the app to load the ads immediately "),void p.setDeferAdsStatus(!1);const i=(e,t)=>{Log.info2("Received __tcpapi status change Event: ",e),t&&p.statusOk(e)&&(Log.info2("Status now OK, remove the event listener and send message to the app to load the ads immediately"),window.__tcfapi("removeEventListener",2,i),p.setDeferAdsStatus(!1))};Log.info2("Status not OK yet. Set event listener to load the ads when it will be OK"),window.__tcfapi("addEventListener",2,i)})))},Log.info2("Defer the ads loading by default"),p.setDeferAdsStatus(!0)}else Log.info2("Not Consent Required")}static getDeferAdsStatus(){return __adLib.deferAds}static setDeferAdsStatus(e){__adLib.deferAds=e,e||document.dispatchEvent(new Event("endDeferAds"))}static statusOk(e){return"useractioncomplete"==e.eventStatus||"tcloaded"==e.eventStatus}static getPrebidConsentParameters(){return __adLib.usPrivacyConsent?__adLib.prebidCcpaConfiguration:__adLib.requiresConsent?__adLib.prebidGdprConfiguration:null}static onDNSMILinkClicked(){Log.info2("CCPA consent called"),Log.info2("create default IAB cookie [1YYY]"),c.createCookie(1,!0,!0,!0),Log.info2("Modifies onetrust OptanonConsent cookies and ActiveGroups global variables");let e=[4],t=decodeURIComponent(r.readCookie("OptanonConsent "));Log.info2("Current OptanonConsent cookie value = ",t);for(let i of e)t=t.replace(`,${i}:1,`,`,${i}:0,`),window.OptanonActiveGroups=window.OptanonActiveGroups.replace(`,${i},`,","),window.OnetrustActiveGroups=window.OnetrustActiveGroups.replace(`,${i},`,",");Log.info2("New OptanonConsent cookie value = ",t),Log.info2(`New OptanonActiveGroups = [${window.OptanonActiveGroups}]`),Log.info2(`New OneTrustActiveGroups = [${window.OnetrustActiveGroups}]`),r.createCookieSession("OptanonConsent",encodeURI(t),__adLib.topDomain),r.createCookieSession("EbConsentClosed","true"),Log.info2("created new OptanonConsent and EbConsentClosed cookies")}}class g{static async loadPrebidScript(){if(!__adLib.videoForPrebidLoaded&&!n.isDefined(window.pbjs)){Log.info(`Loading [${__adLib.prebidScriptUrl}] prebid script now`),window.pbjs={que:[]};try{await a.loadScript(__adLib.prebidScriptUrl)}catch(e){return void Log.error(`Unable to load [${__adLib.prebidScriptUrl}] prebid script -> skip ad`)}__adLib.videoForPrebidLoaded=!0}}}class f{static setJwplayerSetupWithPrebid(t,i,o,n=!1){n||__adLib.showPrerollAdInVideos?(g.loadPrebidScript(),pbjs.que.push((()=>{let n=__adLib.prebidConfiguration;n.debug=Log.getLevel()==e.Debug,pbjs.setConfig(n),pbjs.addAdUnits(__adLib.prebidVideoAdUnit),Log.info("Request Prebid bids with ad unit id: ",t),pbjs.requestBids({bidsBackHandler:()=>{let e={iu:`${`${__adLib.googleDfpId}/EB_${__adLib.leg}/${__adLib.dfpUnitPrefix}`}${t}`,output:"vast"};Log.info("Prebid video url called. Params = ",e);let n=pbjs.adServers.dfp.buildVideoUrl({adUnit:__adLib.prebidVideoAdUnit,params:e});Log.info(`Bidding completed. Set URL in jwplayer setup and call callback: [${n}]`),i.advertising={client:"googima",adschedule:[{offset:"pre",tag:n}]},o()}})}))):o()}static addJwPlayerAdSetup(e,t){t.advertising={client:"googima",adschedule:[{offset:"pre",tag:e}]}}}class u{static CONTAINER_CLASS="__alPrerollContainer";static WRAPPER_CLASS="__alPrerollWrapper";static JWPLAYER_CONTAINER_ID="__alPreroll";static async createPreRollAd(e,i,o=(()=>{})){if(__adLib.prerollAdIsRunning)return void Log.info("Preroll Ad is already running. Ignore this one");if(!__adLib.showPrerollAd)return Log.info("Preroll Ads not enabled -> return"),void o();if(class{static isAdBlockerActivated(){var e=a.get("#_MGS_");e||(a.insert(t.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=a.get("#_MGS_"));var i=a.get("div",e);return"none"===window.getComputedStyle(i).display}}.isAdBlockerActivated())return void o();if(__adLib.prerollAdIsRunning=!0,!n.isDefined(window.jwplayer)){Log.info("jwplayer not found. Loading the script now");try{await a.loadScript(`https://content.jwplatform.com/libraries/${__adLib.jwplayerId}.js`)}catch(e){return Log.error("Unable to load jwplayer script -> skip ad"),__adLib.prerollAdIsRunning=!1,void o()}}a.addClass(e,u.CONTAINER_CLASS),Log.info(`Insert preroll [${i}] Ad into`,e),a.insert(t.prepend,e,`<div class="${u.WRAPPER_CLASS}"><div id="${u.JWPLAYER_CONTAINER_ID}"></div></div>`);let r=a.get(`.${u.WRAPPER_CLASS}`,e),s={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};f.setJwplayerSetupWithPrebid(i,s,(()=>{Log.info("Prebid preroll completed. Init JWPlayer: ",s);let t=jwplayer(u.JWPLAYER_CONTAINER_ID);t.setup(s);const i=i=>{t&&(Log.info(`Preroll Ended. Cause: [${i}]. Will remove the player and its container`),t.remove(),t=null,a.remove(r),a.removeClass(e,u.CONTAINER_CLASS),__adLib.prerollAdIsRunning=!1,o())};t.on("adComplete",(()=>{i("Ad completed")})),t.on("adSkipped",(()=>{i("Ad Skipped")})),t.on("adError",(()=>{i("Ad Error")})),t.on("adBlock",(()=>{i("Ad Blocked")})),t.on("complete",(()=>{i("Video completed")})),t.on("error",(()=>{i("Error")}))}),!0)}}var h,b;!function(e,t){void 0===t&&(t={});var i=t.insertAt;if(e&&"undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css","top"===i&&o.firstChild?o.insertBefore(n,o.firstChild):o.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}}('/* banner ad */\n.__alAd {\n overflow: hidden;\n display: block;\n margin-left: auto;\n margin-right: auto;\n}\n\n.__alAd > div {\n text-align: center !important;\n display: block !important;\n margin: auto !important;\n}\n\n.__alAd > div > iframe,\n.__alAd > div > div {\n display: block !important;\n margin: auto !important;\n}\n\n/* sticky ad */\n.__alSticky {\n top: 0;\n position: sticky;\n}\n\n/* catfish */\n.__alCatfish {\n position: fixed;\n bottom: 0;\n left: 0;\n right: 0;\n margin: auto;\n z-index: 1030;\n width: fit-content;\n}\n\n/* preroll ad */\n.__alPrerollContainer {\n position: relative !important;\n}\n\n.__alPrerollWrapper {\n position: absolute;\n width: 100%;\n height: 100%;\n display: table;\n background: black url("https://cdn.britannica.com/ads/resources/loading.gif") center center no-repeat;\n}\n\n#__alPreroll {\n display: table-cell;\n vertical-align: middle;\n}\n\n/* inline ad */\n.__alInline {\n text-align: center;\n margin: 0 auto 20px auto;\n}\n.__alInline::before {\n border-bottom: 1px solid #ddd;\n color: #aaa;\n content: "Advertisement - Continue reading below";\n display: block;\n font-family: "Helvetica", "Segoe UI", "Arial", sans-serif;\n font-size: 11px;\n font-weight: bold;\n margin-bottom: 20px;\n padding-bottom: 5px;\n clear: left;\n}'),function(e){e.DFP="DFP"}(h||(h={}));!function(e){e.REGULAR="REGULAR",e.CATFISH="CATFISH"}(b||(b={}));class m extends class{type;ads;constructor(){this.ads=[],this.type=this.getType()}addAd(e){this.ads.push(e)}}{static PAGELOAD_TARGETING="PAGELOAD";index=1;getName(){return"Google DFP"}getType(){return h.DFP}constructor(){super()}async initProvider(){if(window.googletag={cmd:[]},!n.isDefined(googletag.defineSlot)){Log.info("Googletag not found. Load the script");try{await a.loadScript("https://securepubads.g.doubleclick.net/tag/js/gpt.js")}catch(e){throw Log.error("**** Unable to load gpt.js -> most ads and scripts will be broken ***"),e}}if(Log.info("Googletag script loaded: ",googletag.defineSlot),g.loadPrebidScript(),!n.isDefined(window.headertag)&&__adLib.includeIndex)try{await a.loadScript(__adLib.indexScriptUrl)}catch(e){Log.error(`Unable to load [${__adLib.indexScriptUrl}] Index script. We won't use it.`)}if(!n.isDefined(window.apstag)&&__adLib.includeA9)try{await a.loadScript("https://c.amazon-adsystem.com/aax2/apstag.js"),function(e,t){function i(i,o){t[e]._Q.push([i,o])}t[e]||(t[e]={init:function(){i("i",arguments)},fetchBids:function(){i("f",arguments)},setDisplayBids:function(){},targetingKeys:function(){return[]},_Q:[]})}("apstag",window)}catch(e){Log.error("Unable to load A9 script. Will disable it"),__adLib.includeA9=!1}googletag.cmd.push((function(){if(googletag.pubads().setTargeting("dc_ref",__adLib.url),n.isDefined(Storage)){var e=localStorage.getItem("bcDFPTargetingParams");if(e)Log.info("Setting Blueconic targeting parameters"),JSON.parse(e).forEach((e=>googletag.pubads().setTargeting(e.key,e.value)))}if(Log.info(`targeting: ${googletag.pubads().getTargetingKeys()}`),googletag.pubads().disableInitialLoad(),googletag.pubads().enableSingleRequest(),googletag.pubads().enableAsyncRendering(),googletag.pubads().setTagForChildDirectedTreatment(0),googletag.pubads().setTagForUnderAgeOfConsent(0),__adLib.dfpLazyLoad&&googletag.pubads().enableLazyLoad(__adLib.dfpLazyLoadParameters),googletag.enableServices(),__adLib.includeA9){var t={pubID:__adLib.a9Id,adServer:"googletag",bidTimeout:1200};__uspapi&&__uspapi("getuspdata","1",((e,i)=>{i&&(t.params={us_privacy:e.uspString})})),Log.info("Init A9 with ",t),apstag.init(t)}}))}createSlot(e,t){return this.initSlot(e,t)}initSlot(e,i){return new Promise((o=>{googletag.cmd.push((()=>{try{Log.info("process DFP ad: ",e);var n=e.adParameters,r=n.size[0][0],d=n.size[0][1];Log.info("Content container for this ad is ",i);var l="";if(e.displayType!=b.CATFISH)if(n.placeholderSize)l=`min-width:${s.substringBefore(n.placeholderSize,"x")}px;min-height:${s.substringAfter(n.placeholderSize,"x")}px;`;else if(1==n.size.length)l=`width:${r}px;height:${d}px;`;else{l=`min-height:${Math.round(n.size.map((e=>e[1])).reduce(((e,t)=>e+t))/n.size.length)}px;`}var c="DFP_"+this.index++;e.containerId=c,e.dfpSize=1==n.size.length?n.size[0]:n.size;var p=`style="${l}${s.defaultIfBlank(n.style,"")}"`,g=`<div data-type="${e.type}" class="__alAd ${s.defaultIfBlank(__adLib.adClass,"")} ${s.defaultIfBlank(n.cssClass,"")}" ${p} id="${c}"></div>`;Log.info(`Inject DIV: [${g}] into `,i),a.insert(t[e.injector],i,g);var f=this.setDfpA9Slot(e);let u=a.get(`#${c}`);u.setAttribute("data-identifier",e.dfpSlot.getAdUnitPath()),u.setAttribute("data-qa-identifier",f),o(u)}catch(t){Log.error("Init Slot Error: ",e,t),o(null)}}))}))}setDfpA9Slot=function(e){Log.info("Initializes DFP slot and A9 slot for ",e);var t=e.adParameters,i=__adLib.dfpIdPrefix.replace("${LEG}",__adLib.leg),o=`${__adLib.isPhone?"MOBILE":"DESKTOP"}_${t.id}`,n=`/${__adLib.googleDfpId}/${i}${o}`;return Log.info(`Define new slot: [${n}] with: size [${e.dfpSize}] id [${e.containerId}]`),e.dfpSlot=googletag.defineSlot(n,e.dfpSize,e.containerId),t.targeting&&Object.entries(t.targeting).forEach((([t,i])=>{e.dfpSlot.setTargeting(t,String(i))})),e.dfpSlot.addService(googletag.pubads()),__adLib.includeA9&&(e.a9Slot={slotID:e.containerId,slotName:n,sizes:t.size}),Log.info("DFP/A9 slot defined for ",e),o};refreshAllAds(){Log.info("Refresh all DFP ads."),googletag.cmd.push((()=>{m.setPageLoadTargeting(this.ads),this.refreshSlots()}))}requestBids(e){this.refreshAds(e)}refreshAds(e){Log.info("Refresh ads: ",e),googletag.cmd.push((()=>{m.setPageLoadTargeting(e),this.refreshSlots(e)}))}static setPageLoadTargeting(e){for(let t of e){const e=`REFRESH${t.refreshCounter}`;Log.info(`Update ${m.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(m.PAGELOAD_TARGETING,e)}}refreshSlots(t=this.ads){Log.info("Refresh slots - ads : ",t);let i=!1,o=!1,n=!1,a=()=>{n||!o||!i&&__adLib.includeA9||(-1!=c&&window.clearTimeout(c),Log.info("Prebid is completed and A9 completed or disabled -> call DFP"),r())},r=()=>{Log.info("Refresh ads ",t);let e=t.map((e=>e.dfpSlot));Log.info("Refresh DFP slots ",e),googletag.pubads().refresh(e)},s=[];for(let e of t)s.push({code:e.dfpSlot.getAdUnitPath(),mediaTypes:{banner:{sizes:e.adParameters.size}},bids:__adLib.prebidBannerBiddersConfiguration});Log.info("Prebid ad unit configuration: ",s);let d={...__adLib.prebidConfiguration,debug:Log.getLevel()==e.Debug,...p.getPrebidConsentParameters()};if(__adLib.includeA9){var l=t.map((e=>e.a9Slot));Log.info("Calls A9 with these slots:",l),apstag.fetchBids({slots:l},(()=>{Log.info("A9 bid request completed"),apstag.setDisplayBids(),i=!0,a()}))}pbjs.que.push((()=>{Log.info("Set Prebid Config: ",d),pbjs.setConfig(d),pbjs.addAdUnits(s),Log.info("Request Prebid bids"),pbjs.requestBids({timeout:__adLib.prebidTimeout,bidsBackHandler:()=>{Log.info("Prebid request bid completed"),pbjs.setTargetingForGPTAsync(t.map((e=>e.dfpSlot.getAdUnitPath()))),o=!0,a()}})}));let c=-1;0!=__adLib.biddersFailsafeTimeout&&(Log.info(`Bidders failsafe timeout set to [${__adLib.biddersFailsafeTimeout}] ms`),c=window.setTimeout((()=>{Log.info("Bidding Timeout! -> calls DFP directly"),n=!0,r()}),__adLib.biddersFailsafeTimeout))}}class _{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,i){Log.info("Create a catfish container");let o=`<div id="${_.CATFISH_ID}" class="__alCatfish" style=" ${e?`width:${e}px;`:""} ${i?`height:${i}px`:""}"></div>`;return a.insert(t.append,document.body,o),Log.info("Static Catfish Inserted",_.getCurrentCatfishElement()),_.getCurrentCatfishElement()}static getCurrentCatfishElement(){return a.get(`#${_.CATFISH_ID}`)}}class L{static providerClasses=new Map([[h.DFP,m]]);providers=new Map;timers=[];constructor(){n.isDefined(typeof window.__adLib)&&a.onDocumentReady((()=>{this.init()}))}isAdBlockerActivated(){var e=a.get("#_MGS_");e||(a.insert(t.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=a.get("#_MGS_"));var i=a.get("div",e);return"none"===window.getComputedStyle(i).display}async init(){Log.info("Init Ads manager at page load"),c.init(),await p.init(),Log.info("Set tab visibility event handler"),a.setEventListener(document,"visibilitychange",(()=>{let e="visible"===document.visibilityState;Log.info(`Tab visibility changed to [${e}]`),e?this.resumeAllPausedTimers():this.pauseAllRunningTimers()})),__adLib.deferAds?(Log.info("Ads need to be deferred. Will wait until the [endDeferAds] is fired"),a.setEventListener(document,"endDeferAds",(()=>{Log.info("Deferred Ads event triggered. Will now initialize the ads"),this.contentLoadInit(document.body,__adLib.initialLoadAds)}))):(Log.info("No deferred ads. Will initialize the ads now"),this.contentLoadInit(document.body,__adLib.initialLoadAds))}async contentLoadInit(e=document.body,t){let i;if(Log.info(" ============================================================================================="),Log.info("Initialize container with ads"),Log.info(" ============================================================================================="),t)i=t,Log.info("Ad definitions passed as parameter: ",i);else{Log.info("Look for json ads definition in ",e);let t=d.getJsonFromScriptSnippet("ads-script",e);if(!t)return void Log.info("Did not find ads definition.");if(i=t,!i)return;Log.info("Found ad definitions: ",i)}let o=new Map;for(let t of i){if(Log.info("Init this ad: ",t),!this.providers.has(t.type)){Log.info(`Initializes Provider: [${t.type}]`);try{let e=new(L.providerClasses.get(t.type));await e.initProvider(),this.providers.set(t.type,e)}catch(e){Log.error(`Unable to instantiate Ad Provider: [${t.type}]`,t,e);continue}}let i=this.providers.get(t.type);o.has(t.type)||o.set(t.type,[]),t.provider=i;let n=null;if(t.displayType==b.REGULAR)n=a.get(t.selector,e);else if(t.displayType==b.CATFISH){if(n=_.getCurrentCatfishElement(),n){let e=a.get(".__alAd",n).ad;e.provider.refreshAds([e]),Log.info("Catfish already exists, just refresh its ad");continue}n=_.newCatfish(),t.injector="append"}n?(t.$container=await i.createSlot(t,n),t.$container?(t.$container.ad=t,t.refreshCounter=0,i.addAd(t),o.get(t.type).push(t),t.autoRefresh?(t.$container.isInViewPort=!1,t.refreshTimer=new l((()=>{L.timerCallback(t)}),1e3*__adLib.refreshTimer),this.timers.push(t.refreshTimer),Log.info("This ad is autorefresh, added refresh timer: ",t.refreshTimer)):(t.refreshTimer=null,t.$container.isInViewPort=!0,Log.info("This ad is not autorefresh -> no refresh timer")),t.displayType==b.CATFISH?(Log.info("The ad is a catfish -> always in viewport and start refresh timer"),t.$container.isInViewPort=!0,t.refreshTimer&&t.refreshTimer.start()):t.autoRefresh&&(Log.info("Add the ad container to the observer -> ",t.$container),this.isInViewPortObserver.observe(t.$container)),Log.info("Ad initialized",t)):Log.info("Slot creation failed -> skip this ad")):Log.info("Error when initializing the ad/Existing ad -> skip it: ",t)}for(let[e,t]of o)0==t.length?Log.info(`No ads for [${e}] provider`):(Log.info(`Request Bids for [${e}] provider: `,t),this.providers.get(e).requestBids(t));if(__adLib.stickyContainerSelector){const t=a.getAll(`${__adLib.stickyContainerSelector} .__alAd`,e);let i=t.length;if(i>0){let e=t.item(i-1);Log.info("Last ad is sticky",e),a.addClass(e,"__alSticky",__adLib.stickyAdClass)}}}isInViewPortObserver=new IntersectionObserver((e=>{e.forEach((e=>{let t=e.target;t.isInViewPort=e.intersectionRatio>=__adLib.viewportThreshold,t.isInViewPort?(Log.info("Ad in viewport -> resume timer",t.ad),L.resumeRefreshTimer(t.ad)):(Log.info("Ad out of viewport -> stop timer",t.ad),L.pauseRefreshTimer(t.ad))}))}),{threshold:__adLib.viewportThreshold});static timerCallback(e){Log.info("Ad is refreshed.",e),e.refreshCounter++,e.provider.refreshAds([e])}static resumeRefreshTimer(e){Log.info("Resume refresh timer for ",e),e.refreshTimer.state==i.PAUSED?e.refreshTimer.resume():e.refreshTimer.state==i.STOPPED&&e.refreshTimer.start()}static pauseRefreshTimer(e){Log.info("Pause refresh timer for ",e),e.refreshTimer.pause()}pausedTimers=[];pauseAllRunningTimers(){this.pausedTimers=this.timers.filter((e=>e.state==i.RUNNING)),0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.pause())),Log.info("Pause these timers: ",this.pausedTimers.map((e=>e.id))))}resumeAllPausedTimers(){0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.resume())),Log.info("Resume these timers: ",this.pausedTimers.map((e=>e.id))))}refreshAllAds(){Log.info("Refresh All ads"),this.providers.forEach((e=>{Log.info(`will refresh ads for this provider: [${e.getName()}]`);for(let t of e.ads)t.refreshCounter++;e.refreshAllAds();for(let t of e.ads)t.refreshTimer&&t.refreshTimer.restart()}))}}window.Log=new o(n.isDefined(__adLib)?e[__adLib.logLevel]:e.None),Log.info("Ad Library Loaded"),__adLib.AdsManager=new L,__adLib.ConsentManager=p,__adLib.PrebidForVideo=f,__adLib.PrerollAd=u; | ||
//# sourceMappingURL=britannica-ads.esm.js.map |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@britannica/ads"]={})}(this,(function(e){"use strict";var t;!function(e){e[e.Debug=0]="Debug",e[e.Info2=1]="Info2",e[e.Info=2]="Info",e[e.None=3]="None"}(t||(t={}));class i{static INFO_STYLE="font-weight:bold; background-color: #084466; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static INFO_STYLE2="font-weight:bold; background-color: rebeccapurple; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static ERR_STYLE="font-weight:bold; background-color: red; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static WARN_STYLE="font-weight:bold; background-color: orange; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static DEBUG_STYLE="font-weight:bold; background-color: #88A95B; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";error=console.error.bind(window.console,"%cAd Lib",i.ERR_STYLE);warning=console.warn.bind(window.console,"%cAd Lib",i.WARN_STYLE);debug;info;info2;level;constructor(){this.level=a.isDefined(__adLib)?t[__adLib.logLevel]:t.None,this.info=t.Info>=this.level?console.log.bind(window.console,"%cAd Lib",i.INFO_STYLE):()=>null,this.info2=t.Info2>=this.level?console.log.bind(window.console,"%cAd Lib",i.INFO_STYLE2):()=>null,this.debug=t.Debug>=this.level?console.debug.bind(window.console,"%cAd Lib",i.DEBUG_STYLE):()=>null}getLevel(){return this.level}}const s=new i;class a{static isDefined(e){return void 0!==e}static isFunction(e){return"function"==typeof e}}var r,n,o,d;!function(e){e.before="beforeBegin",e.after="afterEnd",e.prepend="afterBegin",e.append="beforeEnd"}(r||(r={}));class l{static insert(e,t,i){t.insertAdjacentHTML(e,i)}static remove(e){e&&e.parentNode.removeChild(e)}static loadScript(e,t={}){return new Promise(((i,a)=>{let r=document.createElement("script");r.src=e,r.onload=()=>i(),r.onerror=()=>a();for(const[e,i]of Object.entries(t))r.setAttribute(e,i);document.head.append(r),s.info(`Loaded: [${e}]`)}))}static css(e,t,i){e.style.setProperty(t,i)}static addClass(e,...t){t.forEach((t=>{t&&e.classList.add(t)}))}static removeClass(e,t){e.classList.remove(t)}static onDocumentReady(e){"loading"!=document.readyState?e():document.addEventListener("DOMContentLoaded",e)}static get(e,t=document.body){return t.querySelector(e)}static getAll(e,t=document.body){return t.querySelectorAll(e)}static setEventListener(e,t,i){e.addEventListener(t,i)}static removeEventListener(e,t,i){e.removeEventListener(t,i)}static onInViewPort(e,t){new IntersectionObserver(((i,s)=>{i.forEach((i=>{i.isIntersecting&&(t(e),s.disconnect(),s=null)}))}),{threshold:1}).observe(e)}static onScroll(e,t){window.addEventListener("scroll",function(e,t){var i=!1;return function(){i||(e(window.scrollY),i=!0,setTimeout((function(){i=!1}),t))}}(e,t))}static delayedCall(e,t){t?setTimeout(e,1e3*t):e()}}class c{static createCookieSession(e,t,i){document.cookie=`${e}=${t}; path=/${i?";domain="+i:""}`}static readCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(`${e}=`))).split("=")[1]}static isCookieExists(e){return document.cookie.split(";").some((t=>t.trim().startsWith(`${e}=`)))}}class p{static substringBefore(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(0,i)}static substringAfter(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(i+1)}static defaultIfBlank(e,t){return e&&0!=e.length?e:t}}class f{static getJsonFromScriptSnippet(e,t=document.body){const i=l.get(`script[type="application/json"].${e}`,t);return i?f.elementContentToJson(i):null}static elementContentToJson(e){var t=e.innerText;try{return JSON.parse(t)}catch(e){return s.error("JSON parsing error: ",e),null}}}!function(e){e.PAUSED="PAUSED",e.RUNNING="RUNNING",e.STOPPED="STOPPED"}(n||(n={}));class u{_id=(Date.now()+Math.floor(100*Math.random())).toString().slice(-5);_state=n.STOPPED;internalTimerId;restartTimerId;lastStart;remaining;callback;delay;constructor(e,t){this.callback=e,this.delay=t}get id(){return this._id}get state(){return this._state}callbackFn(){this.lastStart=Date.now(),this.remaining=this.delay,this.callback()}pause(){this.state==n.RUNNING&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining-=Date.now()-this.lastStart,this._state=n.PAUSED,s.debug(`Timer [${this._id}] Paused - Remaining [${this.remaining}ms]`))}resume(){this.state==n.PAUSED&&(this.restartTimerId=window.setTimeout((()=>{this.callback(),this.start()}),this.remaining),this.lastStart=Date.now(),this._state=n.RUNNING,s.debug(`Timer [${this._id}] Resumed in [${this.remaining}ms].`))}stop(){this.state!=n.STOPPED&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining=this.delay,this._state=n.STOPPED,s.debug(`Timer [${this._id}] - Internal id [${this.internalTimerId}] Stopped`))}start(){this.lastStart=Date.now(),this.remaining=this.delay,this.internalTimerId=window.setInterval((()=>this.callbackFn()),this.delay),this._state=n.RUNNING,s.debug(`Started Timer [${this._id}] - Internal id [${this.internalTimerId}]`)}restart(){this.stop(),this.start()}stopInternalTimer(){this.internalTimerId&&(window.clearInterval(this.internalTimerId),this.internalTimerId=null)}stopResumeTimer(){this.restartTimerId&&(window.clearTimeout(this.restartTimerId),this.restartTimerId=null)}}class g{static US_PrivacyCookieName="usprivacy";static US_PrivacyCookieDuration=365;static init(){s.info2("Init IAB: Insert iframe locator into body"),l.insert(r.append,document.body,'<iframe name="__uspapiLocator" style="display:none;height:0;opacity:0;visibility:hidden;border:0;width:0;"></iframe>'),s.info2("Install IAB message handler"),window.addEventListener("message",g.optOutMsgHandler,!1),s.info2("Install global __uspapi function"),window.__uspapi=(e,t,i)=>{if(s.info2(`IAB: __uspapi function called. Command: [${e}] `),"getuspdata"===e.toLowerCase()){let e={version:t,uspString:c.readCookie(g.US_PrivacyCookieName)};s.info2("IAB: getuspdata command. Response: ",e),i(e,null!=e.uspString)}},c.isCookieExists(g.US_PrivacyCookieName)||(__adLib.usPrivacyConsent?(s.info2("IAB: US privacy consent needed (CCPA), create default cookie [1YNY]"),g.createCookie(1,!0,!1,!0)):(s.info2("IAB: No US privacy consent needed, create default cookie [1---]"),g.createCookie()))}static createCookie(e=1,t,i,s){let a=e=>!0===e?"Y":!1===e?"N":"-",r=e.toString()+a(t)+a(i)+a(s),n=`${g.US_PrivacyCookieName}=${r}; `,o=new Date;o.setTime(o.getTime()+24*g.US_PrivacyCookieDuration*60*60*1e3);let d=`expires=${o.toUTCString()}; `;document.cookie=n+d+"path=/; SameSite=Lax; "}static optOutMsgHandler(e){let t,i="string"==typeof e.data;if(t=i?-1!==e.data.indexOf("__uspapiCall")?JSON.parse(e.data):{}:e.data,t.__uspapiCall){s.info2("Received __uspapiCall event. Will post message to sender with the cookie content");let a=t.__uspapiCall;window.__uspapi(a.command,a.version,(function(t,r){let n={__uspapiReturn:{returnValue:t,success:r,callId:a.callId}},o=e.source;s.info2("IAB: post message back ",n,o),o.postMessage(i?JSON.stringify(n):n,"*")}))}}}class h{static async init(){if(__adLib.requiresConsent){if(!a.isDefined(window.__tcfapi)){s.info2("__tcfapi not found -> Will load the oneTrust scripts");try{await l.loadScript("https://cdn.cookielaw.org/consent/cmp.stub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw s.error("Unable to load oneTrust cmp.stub.js script"),e}try{await l.loadScript("https://cdn.cookielaw.org/scripttemplates/otSDKStub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw s.error("Unable to load oneTrust otSDKStub.js script "),e}s.info2("oneTrust scripts loaded")}s.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{s.info2(`OptanonWrapper called. Defer Ads status is [${h.getDeferAdsStatus()}]`),h.getDeferAdsStatus()&&(s.info2("Defer Ads status is true -> Set Read TCData callback"),window.__tcfapi("getTCData",2,((e,t)=>{if(s.info2(`TCData read: success = [${t}] data = `,e),!t||h.statusOk(e))return s.info2("Error or status already OK -> send message to the app to load the ads immediately "),void h.setDeferAdsStatus(!1);const i=(e,t)=>{s.info2("Received __tcpapi status change Event: ",e),t&&h.statusOk(e)&&(s.info2("Status now OK, remove the event listener and send message to the app to load the ads immediately"),window.__tcfapi("removeEventListener",2,i),h.setDeferAdsStatus(!1))};s.info2("Status not OK yet. Set event listener to load the ads when it will be OK"),window.__tcfapi("addEventListener",2,i)})))},s.info2("Defer the ads loading by default"),h.setDeferAdsStatus(!0)}else s.info2("Not Consent Required")}static getDeferAdsStatus(){return __adLib.deferAds}static setDeferAdsStatus(e){__adLib.deferAds=e,e||document.dispatchEvent(new Event("endDeferAds"))}static statusOk(e){return"useractioncomplete"==e.eventStatus||"tcloaded"==e.eventStatus}static getPrebidConsentParameters(){return __adLib.usPrivacyConsent?__adLib.prebidCcpaConfiguration:__adLib.requiresConsent?__adLib.prebidGdprConfiguration:null}static onDNSMILinkClicked(){s.info2("CCPA consent called"),s.info2("create default IAB cookie [1YYY]"),g.createCookie(1,!0,!0,!0),s.info2("Modifies onetrust OptanonConsent cookies and ActiveGroups global variables");let e=[4],t=decodeURIComponent(c.readCookie("OptanonConsent "));s.info2("Current OptanonConsent cookie value = ",t);for(let i of e)t=t.replace(`,${i}:1,`,`,${i}:0,`),window.OptanonActiveGroups=window.OptanonActiveGroups.replace(`,${i},`,","),window.OnetrustActiveGroups=window.OnetrustActiveGroups.replace(`,${i},`,",");s.info2("New OptanonConsent cookie value = ",t),s.info2(`New OptanonActiveGroups = [${window.OptanonActiveGroups}]`),s.info2(`New OneTrustActiveGroups = [${window.OnetrustActiveGroups}]`),c.createCookieSession("OptanonConsent",encodeURI(t),__adLib.topDomain),c.createCookieSession("EbConsentClosed","true"),s.info2("created new OptanonConsent and EbConsentClosed cookies")}}class b{static async loadPrebidScript(){if(!__adLib.videoForPrebidLoaded&&!a.isDefined(window.pbjs)){s.info(`Loading [${__adLib.prebidScriptUrl}] prebid script now`),window.pbjs={que:[]};try{await l.loadScript(__adLib.prebidScriptUrl)}catch(e){return void s.error(`Unable to load [${__adLib.prebidScriptUrl}] prebid script -> skip ad`)}__adLib.videoForPrebidLoaded=!0}}}class m{static setJwplayerSetupWithPrebid(e,i,a,r=!1){r||__adLib.showPrerollAdInVideos?(b.loadPrebidScript(),pbjs.que.push((()=>{let r=__adLib.prebidConfiguration;r.debug=s.getLevel()==t.Debug,pbjs.setConfig(r),pbjs.addAdUnits(__adLib.prebidVideoAdUnit),s.info("Request Prebid bids with ad unit id: ",e),pbjs.requestBids({bidsBackHandler:()=>{let t={iu:`${`${__adLib.googleDfpId}/EB_${__adLib.leg}/${__adLib.dfpUnitPrefix}`}${e}`,output:"vast"};s.info("Prebid video url called. Params = ",t);let r=pbjs.adServers.dfp.buildVideoUrl({adUnit:__adLib.prebidVideoAdUnit,params:t});s.info(`Bidding completed. Set URL in jwplayer setup and call callback: [${r}]`),i.advertising={client:"googima",adschedule:[{offset:"pre",tag:r}]},a()}})}))):a()}static addJwPlayerAdSetup(e,t){t.advertising={client:"googima",adschedule:[{offset:"pre",tag:e}]}}}class _{static CONTAINER_CLASS="__alPrerollContainer";static WRAPPER_CLASS="__alPrerollWrapper";static JWPLAYER_CONTAINER_ID="__alPreroll";static async createPreRollAd(e,t,i=(()=>{})){if(__adLib.prerollAdIsRunning)return void s.info("Preroll Ad is already running. Ignore this one");if(!__adLib.showPrerollAd)return s.info("Preroll Ads not enabled -> return"),void i();if(class{static isAdBlockerActivated(){var e=l.get("#_MGS_");e||(l.insert(r.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=l.get("#_MGS_"));var t=l.get("div",e);return"none"===window.getComputedStyle(t).display}}.isAdBlockerActivated())return void i();if(__adLib.prerollAdIsRunning=!0,!a.isDefined(window.jwplayer)){s.info("jwplayer not found. Loading the script now");try{await l.loadScript(`https://content.jwplatform.com/libraries/${__adLib.jwplayerId}.js`)}catch(e){return s.error("Unable to load jwplayer script -> skip ad"),__adLib.prerollAdIsRunning=!1,void i()}}l.addClass(e,_.CONTAINER_CLASS),s.info(`Insert preroll [${t}] Ad into`,e),l.insert(r.prepend,e,`<div class="${_.WRAPPER_CLASS}"><div id="${_.JWPLAYER_CONTAINER_ID}"></div></div>`);let n=l.get(`.${_.WRAPPER_CLASS}`,e),o={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};m.setJwplayerSetupWithPrebid(t,o,(()=>{s.info("Prebid preroll completed. Init JWPlayer: ",o);let t=jwplayer(_.JWPLAYER_CONTAINER_ID);t.setup(o);const a=a=>{t&&(s.info(`Preroll Ended. Cause: [${a}]. Will remove the player and its container`),t.remove(),t=null,l.remove(n),l.removeClass(e,_.CONTAINER_CLASS),__adLib.prerollAdIsRunning=!1,i())};t.on("adComplete",(()=>{a("Ad completed")})),t.on("adSkipped",(()=>{a("Ad Skipped")})),t.on("adError",(()=>{a("Ad Error")})),t.on("adBlock",(()=>{a("Ad Blocked")})),t.on("complete",(()=>{a("Video completed")})),t.on("error",(()=>{a("Error")}))}),!0)}}!function(e){e.DFP="DFP"}(o||(o={}));!function(e){e.REGULAR="REGULAR",e.CATFISH="CATFISH"}(d||(d={}));class A extends class{type;ads;constructor(){this.ads=[],this.type=this.getType()}addAd(e){this.ads.push(e)}}{static PAGELOAD_TARGETING="PAGELOAD";index=1;getName(){return"Google DFP"}getType(){return o.DFP}constructor(){super()}async initProvider(){if(window.googletag={cmd:[]},!a.isDefined(googletag.defineSlot)){s.info("Googletag not found. Load the script");try{await l.loadScript("https://securepubads.g.doubleclick.net/tag/js/gpt.js")}catch(e){throw s.error("**** Unable to load gpt.js -> most ads and scripts will be broken ***"),e}}if(s.info("Googletag script loaded: ",googletag.defineSlot),b.loadPrebidScript(),!a.isDefined(window.headertag)&&__adLib.includeIndex)try{await l.loadScript(__adLib.indexScriptUrl)}catch(e){s.error(`Unable to load [${__adLib.indexScriptUrl}] Index script. We won't use it.`)}if(!a.isDefined(window.apstag)&&__adLib.includeA9)try{await l.loadScript("https://c.amazon-adsystem.com/aax2/apstag.js"),function(e,t){function i(i,s){t[e]._Q.push([i,s])}t[e]||(t[e]={init:function(){i("i",arguments)},fetchBids:function(){i("f",arguments)},setDisplayBids:function(){},targetingKeys:function(){return[]},_Q:[]})}("apstag",window)}catch(e){s.error("Unable to load A9 script. Will disable it"),__adLib.includeA9=!1}googletag.cmd.push((function(){if(googletag.pubads().setTargeting("dc_ref",__adLib.url),a.isDefined(Storage)){var e=localStorage.getItem("bcDFPTargetingParams");if(e)s.info("Setting Blueconic targeting parameters"),JSON.parse(e).forEach((e=>googletag.pubads().setTargeting(e.key,e.value)))}if(s.info(`targeting: ${googletag.pubads().getTargetingKeys()}`),googletag.pubads().disableInitialLoad(),googletag.pubads().enableSingleRequest(),googletag.pubads().enableAsyncRendering(),googletag.pubads().setTagForChildDirectedTreatment(0),googletag.pubads().setTagForUnderAgeOfConsent(0),__adLib.dfpLazyLoad&&googletag.pubads().enableLazyLoad(__adLib.dfpLazyLoadParameters),googletag.enableServices(),__adLib.includeA9){var t={pubID:__adLib.a9Id,adServer:"googletag",bidTimeout:1200};__uspapi&&__uspapi("getuspdata","1",((e,i)=>{i&&(t.params={us_privacy:e.uspString})})),s.info("Init A9 with ",t),apstag.init(t)}}))}createSlot(e,t){return this.initSlot(e,t)}initSlot(e,t){return new Promise((i=>{googletag.cmd.push((()=>{try{s.info("process DFP ad: ",e);var a=e.adParameters,n=a.size[0][0],o=a.size[0][1];s.info("Content container for this ad is ",t);var c="";if(e.displayType!=d.CATFISH)if(a.placeholderSize)c=`min-width:${p.substringBefore(a.placeholderSize,"x")}px;min-height:${p.substringAfter(a.placeholderSize,"x")}px;`;else if(1==a.size.length)c=`width:${n}px;height:${o}px;`;else{c=`min-height:${Math.round(a.size.map((e=>e[1])).reduce(((e,t)=>e+t))/a.size.length)}px;`}var f="DFP_"+this.index++;e.containerId=f,e.dfpSize=1==a.size.length?a.size[0]:a.size;var u=`style="${c}${p.defaultIfBlank(a.style,"")}"`,g=`<div data-type="${e.type}" class="__alAd ${p.defaultIfBlank(__adLib.adClass,"")} ${p.defaultIfBlank(a.cssClass,"")}" ${u} id="${f}"></div>`;s.info(`Inject DIV: [${g}] into `,t),l.insert(r[e.injector],t,g);var h=this.setDfpA9Slot(e);let b=l.get(`#${f}`);b.setAttribute("data-identifier",e.dfpSlot.getAdUnitPath()),b.setAttribute("data-qa-identifier",h),i(b)}catch(t){s.error("Init Slot Error: ",e,t),i(null)}}))}))}setDfpA9Slot=function(e){s.info("Initializes DFP slot and A9 slot for ",e);var t=e.adParameters,i=__adLib.dfpIdPrefix.replace("${LEG}",__adLib.leg),a=`${__adLib.isPhone?"MOBILE":"DESKTOP"}_${t.id}`,r=`/${__adLib.googleDfpId}/${i}${a}`;return s.info(`Define new slot: [${r}] with: size [${e.dfpSize}] id [${e.containerId}]`),e.dfpSlot=googletag.defineSlot(r,e.dfpSize,e.containerId),t.targeting&&Object.entries(t.targeting).forEach((([t,i])=>{e.dfpSlot.setTargeting(t,String(i))})),e.dfpSlot.addService(googletag.pubads()),__adLib.includeA9&&(e.a9Slot={slotID:e.containerId,slotName:r,sizes:t.size}),s.info("DFP/A9 slot defined for ",e),a};refreshAllAds(){s.info("Refresh all DFP ads."),googletag.cmd.push((()=>{A.setPageLoadTargeting(this.ads),this.refreshSlots()}))}requestBids(e){this.refreshAds(e)}refreshAds(e){s.info("Refresh ads: ",e),googletag.cmd.push((()=>{A.setPageLoadTargeting(e),this.refreshSlots(e)}))}static setPageLoadTargeting(e){for(let t of e){const e=`REFRESH${t.refreshCounter}`;s.info(`Update ${A.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(A.PAGELOAD_TARGETING,e)}}refreshSlots(e=this.ads){s.info("Refresh slots - ads : ",e);let i=!1,a=!1,r=!1,n=()=>{r||!a||!i&&__adLib.includeA9||(-1!=p&&window.clearTimeout(p),s.info("Prebid is completed and A9 completed or disabled -> call DFP"),o())},o=()=>{s.info("Refresh ads ",e);let t=e.map((e=>e.dfpSlot));s.info("Refresh DFP slots ",t),googletag.pubads().refresh(t)},d=[];for(let t of e)d.push({code:t.dfpSlot.getAdUnitPath(),mediaTypes:{banner:{sizes:t.adParameters.size}},bids:__adLib.prebidBannerBiddersConfiguration});s.info("Prebid ad unit configuration: ",d);let l={...__adLib.prebidConfiguration,debug:s.getLevel()==t.Debug,...h.getPrebidConsentParameters()};if(__adLib.includeA9){var c=e.map((e=>e.a9Slot));s.info("Calls A9 with these slots:",c),apstag.fetchBids({slots:c},(()=>{s.info("A9 bid request completed"),apstag.setDisplayBids(),i=!0,n()}))}pbjs.que.push((()=>{s.info("Set Prebid Config: ",l),pbjs.setConfig(l),pbjs.addAdUnits(d),s.info("Request Prebid bids"),pbjs.requestBids({timeout:__adLib.prebidTimeout,bidsBackHandler:()=>{s.info("Prebid request bid completed"),pbjs.setTargetingForGPTAsync(e.map((e=>e.dfpSlot.getAdUnitPath()))),a=!0,n()}})}));let p=-1;0!=__adLib.biddersFailsafeTimeout&&(s.info(`Bidders failsafe timeout set to [${__adLib.biddersFailsafeTimeout}] ms`),p=window.setTimeout((()=>{s.info("Bidding Timeout! -> calls DFP directly"),r=!0,o()}),__adLib.biddersFailsafeTimeout))}}class S{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,t){s.info("Create a catfish container");let i=`<div id="${S.CATFISH_ID}" class="__alCatfish" style=" ${e?`width:${e}px;`:""} ${t?`height:${t}px`:""}"></div>`;return l.insert(r.append,document.body,i),s.info("Static Catfish Inserted",S.getCurrentCatfishElement()),S.getCurrentCatfishElement()}static getCurrentCatfishElement(){return l.get(`#${S.CATFISH_ID}`)}}require("./AdsManager.scss");class w{static providerClasses=new Map([[o.DFP,A]]);providers=new Map;timers=[];constructor(){a.isDefined(typeof window.__adLib)&&l.onDocumentReady((()=>{s.info("Ad Library Loaded"),this.init()}))}isAdBlockerActivated(){var e=l.get("#_MGS_");e||(l.insert(r.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=l.get("#_MGS_"));var t=l.get("div",e);return"none"===window.getComputedStyle(t).display}async init(){s.info("Init Ads manager at page load"),g.init(),await h.init(),s.info("Set tab visibility event handler"),l.setEventListener(document,"visibilitychange",(()=>{let e="visible"===document.visibilityState;s.info(`Tab visibility changed to [${e}]`),e?this.resumeAllPausedTimers():this.pauseAllRunningTimers()})),__adLib.deferAds?(s.info("Ads need to be deferred. Will wait until the [endDeferAds] is fired"),l.setEventListener(document,"endDeferAds",(()=>{s.info("Deferred Ads event triggered. Will now initialize the ads"),this.contentLoadInit(document.body,__adLib.initialLoadAds)}))):(s.info("No deferred ads. Will initialize the ads now"),this.contentLoadInit(document.body,__adLib.initialLoadAds))}async contentLoadInit(e=document.body,t){let i;if(s.info(" ============================================================================================="),s.info("Initialize container with ads"),s.info(" ============================================================================================="),t)i=t,s.info("Ad definitions passed as parameter: ",i);else{s.info("Look for json ads definition in ",e);let t=f.getJsonFromScriptSnippet("ads-script",e);if(!t)return void s.info("Did not find ads definition.");if(i=t,!i)return;s.info("Found ad definitions: ",i)}let a=new Map;for(let t of i){if(s.info("Init this ad: ",t),!this.providers.has(t.type)){s.info(`Initializes Provider: [${t.type}]`);try{let e=new(w.providerClasses.get(t.type));await e.initProvider(),this.providers.set(t.type,e)}catch(e){s.error(`Unable to instantiate Ad Provider: [${t.type}]`,t,e);continue}}let i=this.providers.get(t.type);a.has(t.type)||a.set(t.type,[]),t.provider=i;let r=null;if(t.displayType==d.REGULAR)r=l.get(t.selector,e);else if(t.displayType==d.CATFISH){if(r=S.getCurrentCatfishElement(),r){let e=l.get(".__alAd",r).ad;e.provider.refreshAds([e]),s.info("Catfish already exists, just refresh its ad");continue}r=S.newCatfish(),t.injector="append"}r?(t.$container=await i.createSlot(t,r),t.$container?(t.$container.ad=t,t.refreshCounter=0,i.addAd(t),a.get(t.type).push(t),t.autoRefresh?(t.$container.isInViewPort=!1,t.refreshTimer=new u((()=>{w.timerCallback(t)}),1e3*__adLib.refreshTimer),this.timers.push(t.refreshTimer),s.info("This ad is autorefresh, added refresh timer: ",t.refreshTimer)):(t.refreshTimer=null,t.$container.isInViewPort=!0,s.info("This ad is not autorefresh -> no refresh timer")),t.displayType==d.CATFISH?(s.info("The ad is a catfish -> always in viewport and start refresh timer"),t.$container.isInViewPort=!0,t.refreshTimer&&t.refreshTimer.start()):t.autoRefresh&&(s.info("Add the ad container to the observer -> ",t.$container),this.isInViewPortObserver.observe(t.$container)),s.info("Ad initialized",t)):s.info("Slot creation failed -> skip this ad")):s.info("Error when initializing the ad/Existing ad -> skip it: ",t)}for(let[e,t]of a)0==t.length?s.info(`No ads for [${e}] provider`):(s.info(`Request Bids for [${e}] provider: `,t),this.providers.get(e).requestBids(t));if(__adLib.stickyContainerSelector){const t=l.getAll(`${__adLib.stickyContainerSelector} .__alAd`,e);let i=t.length;if(i>0){let e=t.item(i-1);s.info("Last ad is sticky",e),l.addClass(e,"__alSticky",__adLib.stickyAdClass)}}}isInViewPortObserver=new IntersectionObserver((e=>{e.forEach((e=>{let t=e.target;t.isInViewPort=e.intersectionRatio>=__adLib.viewportThreshold,t.isInViewPort?(s.info("Ad in viewport -> resume timer",t.ad),w.resumeRefreshTimer(t.ad)):(s.info("Ad out of viewport -> stop timer",t.ad),w.pauseRefreshTimer(t.ad))}))}),{threshold:__adLib.viewportThreshold});static timerCallback(e){s.info("Ad is refreshed.",e),e.refreshCounter++,e.provider.refreshAds([e])}static resumeRefreshTimer(e){s.info("Resume refresh timer for ",e),e.refreshTimer.state==n.PAUSED?e.refreshTimer.resume():e.refreshTimer.state==n.STOPPED&&e.refreshTimer.start()}static pauseRefreshTimer(e){s.info("Pause refresh timer for ",e),e.refreshTimer.pause()}pausedTimers=[];pauseAllRunningTimers(){this.pausedTimers=this.timers.filter((e=>e.state==n.RUNNING)),0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.pause())),s.info("Pause these timers: ",this.pausedTimers.map((e=>e.id))))}resumeAllPausedTimers(){0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.resume())),s.info("Resume these timers: ",this.pausedTimers.map((e=>e.id))))}refreshAllAds(){s.info("Refresh All ads"),this.providers.forEach((e=>{s.info(`will refresh ads for this provider: [${e.getName()}]`);for(let t of e.ads)t.refreshCounter++;e.refreshAllAds();for(let t of e.ads)t.refreshTimer&&t.refreshTimer.restart()}))}}const v=new w;e.AdsManager=v,e.ConsentManager=h,e.PrebidForVideo=m,e.PrerollAd=_,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";var e,t,i;!function(e){e[e.Debug=0]="Debug",e[e.Info2=1]="Info2",e[e.Info=2]="Info",e[e.None=3]="None"}(e||(e={}));class o{static INFO_STYLE="font-weight:bold; background-color: #084466; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static INFO_STYLE2="font-weight:bold; background-color: rebeccapurple; color: white; border-radius:3px;display:inline-block;padding:2px 4px";static ERR_STYLE="font-weight:bold; background-color: red; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static WARN_STYLE="font-weight:bold; background-color: orange; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";static DEBUG_STYLE="font-weight:bold; background-color: #88A95B; color: white; border-radius:3px;display:inline-block;padding:2px 4px;";error=console.error.bind(window.console,"%cAd Lib",o.ERR_STYLE);warning=console.warn.bind(window.console,"%cAd Lib",o.WARN_STYLE);debug;info;info2;level;constructor(t){this.level=t,this.info=e.Info>=this.level?console.log.bind(window.console,"%cAd Lib",o.INFO_STYLE):()=>null,this.info2=e.Info2>=this.level?console.log.bind(window.console,"%cAd Lib",o.INFO_STYLE2):()=>null,this.debug=e.Debug>=this.level?console.debug.bind(window.console,"%cAd Lib",o.DEBUG_STYLE):()=>null}getLevel(){return this.level}}class n{static isDefined(e){return void 0!==e}static isFunction(e){return"function"==typeof e}}!function(e){e.before="beforeBegin",e.after="afterEnd",e.prepend="afterBegin",e.append="beforeEnd"}(t||(t={}));class a{static insert(e,t,i){t.insertAdjacentHTML(e,i)}static remove(e){e&&e.parentNode.removeChild(e)}static loadScript(e,t={}){return new Promise(((i,o)=>{let n=document.createElement("script");n.src=e,n.onload=()=>i(),n.onerror=()=>o();for(const[e,i]of Object.entries(t))n.setAttribute(e,i);document.head.append(n),window.Log.info(`Loaded: [${e}]`)}))}static css(e,t,i){e.style.setProperty(t,i)}static addClass(e,...t){t.forEach((t=>{t&&e.classList.add(t)}))}static removeClass(e,t){e.classList.remove(t)}static onDocumentReady(e){"loading"!=document.readyState?e():document.addEventListener("DOMContentLoaded",e)}static get(e,t=document.body){return t.querySelector(e)}static getAll(e,t=document.body){return t.querySelectorAll(e)}static setEventListener(e,t,i){e.addEventListener(t,i)}static removeEventListener(e,t,i){e.removeEventListener(t,i)}static onInViewPort(e,t){new IntersectionObserver(((i,o)=>{i.forEach((i=>{i.isIntersecting&&(t(e),o.disconnect(),o=null)}))}),{threshold:1}).observe(e)}static onScroll(e,t){window.addEventListener("scroll",function(e,t){var i=!1;return function(){i||(e(window.scrollY),i=!0,setTimeout((function(){i=!1}),t))}}(e,t))}static delayedCall(e,t){t?setTimeout(e,1e3*t):e()}}class r{static createCookieSession(e,t,i){document.cookie=`${e}=${t}; path=/${i?";domain="+i:""}`}static readCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(`${e}=`))).split("=")[1]}static isCookieExists(e){return document.cookie.split(";").some((t=>t.trim().startsWith(`${e}=`)))}}class s{static substringBefore(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(0,i)}static substringAfter(e,t){if(!e||!t)return e;const i=e.indexOf(t);return-1==i?"":e.substring(i+1)}static defaultIfBlank(e,t){return e&&0!=e.length?e:t}}class d{static getJsonFromScriptSnippet(e,t=document.body){const i=a.get(`script[type="application/json"].${e}`,t);return i?d.elementContentToJson(i):null}static elementContentToJson(e){var t=e.innerText;try{return JSON.parse(t)}catch(e){return window.Log.error("JSON parsing error: ",e),null}}}!function(e){e.PAUSED="PAUSED",e.RUNNING="RUNNING",e.STOPPED="STOPPED"}(i||(i={}));class l{_id=(Date.now()+Math.floor(100*Math.random())).toString().slice(-5);_state=i.STOPPED;internalTimerId;restartTimerId;lastStart;remaining;callback;delay;constructor(e,t){this.callback=e,this.delay=t}get id(){return this._id}get state(){return this._state}callbackFn(){this.lastStart=Date.now(),this.remaining=this.delay,this.callback()}pause(){this.state==i.RUNNING&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining-=Date.now()-this.lastStart,this._state=i.PAUSED,window.Log.debug(`Timer [${this._id}] Paused - Remaining [${this.remaining}ms]`))}resume(){this.state==i.PAUSED&&(this.restartTimerId=window.setTimeout((()=>{this.callback(),this.start()}),this.remaining),this.lastStart=Date.now(),this._state=i.RUNNING,window.Log.debug(`Timer [${this._id}] Resumed in [${this.remaining}ms].`))}stop(){this.state!=i.STOPPED&&(this.stopInternalTimer(),this.stopResumeTimer(),this.remaining=this.delay,this._state=i.STOPPED,window.Log.debug(`Timer [${this._id}] - Internal id [${this.internalTimerId}] Stopped`))}start(){this.lastStart=Date.now(),this.remaining=this.delay,this.internalTimerId=window.setInterval((()=>this.callbackFn()),this.delay),this._state=i.RUNNING,window.Log.debug(`Started Timer [${this._id}] - Internal id [${this.internalTimerId}]`)}restart(){this.stop(),this.start()}stopInternalTimer(){this.internalTimerId&&(window.clearInterval(this.internalTimerId),this.internalTimerId=null)}stopResumeTimer(){this.restartTimerId&&(window.clearTimeout(this.restartTimerId),this.restartTimerId=null)}}class c{static US_PrivacyCookieName="usprivacy";static US_PrivacyCookieDuration=365;static init(){Log.info2("Init IAB: Insert iframe locator into body"),a.insert(t.append,document.body,'<iframe name="__uspapiLocator" style="display:none;height:0;opacity:0;visibility:hidden;border:0;width:0;"></iframe>'),Log.info2("Install IAB message handler"),window.addEventListener("message",c.optOutMsgHandler,!1),Log.info2("Install global __uspapi function"),window.__uspapi=(e,t,i)=>{if(Log.info2(`IAB: __uspapi function called. Command: [${e}] `),"getuspdata"===e.toLowerCase()){let e={version:t,uspString:r.readCookie(c.US_PrivacyCookieName)};Log.info2("IAB: getuspdata command. Response: ",e),i(e,null!=e.uspString)}},r.isCookieExists(c.US_PrivacyCookieName)||(__adLib.usPrivacyConsent?(Log.info2("IAB: US privacy consent needed (CCPA), create default cookie [1YNY]"),c.createCookie(1,!0,!1,!0)):(Log.info2("IAB: No US privacy consent needed, create default cookie [1---]"),c.createCookie()))}static createCookie(e=1,t,i,o){let n=e=>!0===e?"Y":!1===e?"N":"-",a=e.toString()+n(t)+n(i)+n(o),r=`${c.US_PrivacyCookieName}=${a}; `,s=new Date;s.setTime(s.getTime()+24*c.US_PrivacyCookieDuration*60*60*1e3);let d=`expires=${s.toUTCString()}; `;document.cookie=r+d+"path=/; SameSite=Lax; "}static optOutMsgHandler(e){let t,i="string"==typeof e.data;if(t=i?-1!==e.data.indexOf("__uspapiCall")?JSON.parse(e.data):{}:e.data,t.__uspapiCall){Log.info2("Received __uspapiCall event. Will post message to sender with the cookie content");let o=t.__uspapiCall;window.__uspapi(o.command,o.version,(function(t,n){let a={__uspapiReturn:{returnValue:t,success:n,callId:o.callId}},r=e.source;Log.info2("IAB: post message back ",a,r),r.postMessage(i?JSON.stringify(a):a,"*")}))}}}class p{static async init(){if(__adLib.requiresConsent){if(!n.isDefined(window.__tcfapi)){Log.info2("__tcfapi not found -> Will load the oneTrust scripts");try{await a.loadScript("https://cdn.cookielaw.org/consent/cmp.stub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw Log.error("Unable to load oneTrust cmp.stub.js script"),e}try{await a.loadScript("https://cdn.cookielaw.org/scripttemplates/otSDKStub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw Log.error("Unable to load oneTrust otSDKStub.js script "),e}Log.info2("oneTrust scripts loaded")}Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2(`OptanonWrapper called. Defer Ads status is [${p.getDeferAdsStatus()}]`),p.getDeferAdsStatus()&&(Log.info2("Defer Ads status is true -> Set Read TCData callback"),window.__tcfapi("getTCData",2,((e,t)=>{if(Log.info2(`TCData read: success = [${t}] data = `,e),!t||p.statusOk(e))return Log.info2("Error or status already OK -> send message to the app to load the ads immediately "),void p.setDeferAdsStatus(!1);const i=(e,t)=>{Log.info2("Received __tcpapi status change Event: ",e),t&&p.statusOk(e)&&(Log.info2("Status now OK, remove the event listener and send message to the app to load the ads immediately"),window.__tcfapi("removeEventListener",2,i),p.setDeferAdsStatus(!1))};Log.info2("Status not OK yet. Set event listener to load the ads when it will be OK"),window.__tcfapi("addEventListener",2,i)})))},Log.info2("Defer the ads loading by default"),p.setDeferAdsStatus(!0)}else Log.info2("Not Consent Required")}static getDeferAdsStatus(){return __adLib.deferAds}static setDeferAdsStatus(e){__adLib.deferAds=e,e||document.dispatchEvent(new Event("endDeferAds"))}static statusOk(e){return"useractioncomplete"==e.eventStatus||"tcloaded"==e.eventStatus}static getPrebidConsentParameters(){return __adLib.usPrivacyConsent?__adLib.prebidCcpaConfiguration:__adLib.requiresConsent?__adLib.prebidGdprConfiguration:null}static onDNSMILinkClicked(){Log.info2("CCPA consent called"),Log.info2("create default IAB cookie [1YYY]"),c.createCookie(1,!0,!0,!0),Log.info2("Modifies onetrust OptanonConsent cookies and ActiveGroups global variables");let e=[4],t=decodeURIComponent(r.readCookie("OptanonConsent "));Log.info2("Current OptanonConsent cookie value = ",t);for(let i of e)t=t.replace(`,${i}:1,`,`,${i}:0,`),window.OptanonActiveGroups=window.OptanonActiveGroups.replace(`,${i},`,","),window.OnetrustActiveGroups=window.OnetrustActiveGroups.replace(`,${i},`,",");Log.info2("New OptanonConsent cookie value = ",t),Log.info2(`New OptanonActiveGroups = [${window.OptanonActiveGroups}]`),Log.info2(`New OneTrustActiveGroups = [${window.OnetrustActiveGroups}]`),r.createCookieSession("OptanonConsent",encodeURI(t),__adLib.topDomain),r.createCookieSession("EbConsentClosed","true"),Log.info2("created new OptanonConsent and EbConsentClosed cookies")}}class g{static async loadPrebidScript(){if(!__adLib.videoForPrebidLoaded&&!n.isDefined(window.pbjs)){Log.info(`Loading [${__adLib.prebidScriptUrl}] prebid script now`),window.pbjs={que:[]};try{await a.loadScript(__adLib.prebidScriptUrl)}catch(e){return void Log.error(`Unable to load [${__adLib.prebidScriptUrl}] prebid script -> skip ad`)}__adLib.videoForPrebidLoaded=!0}}}class f{static setJwplayerSetupWithPrebid(t,i,o,n=!1){n||__adLib.showPrerollAdInVideos?(g.loadPrebidScript(),pbjs.que.push((()=>{let n=__adLib.prebidConfiguration;n.debug=Log.getLevel()==e.Debug,pbjs.setConfig(n),pbjs.addAdUnits(__adLib.prebidVideoAdUnit),Log.info("Request Prebid bids with ad unit id: ",t),pbjs.requestBids({bidsBackHandler:()=>{let e={iu:`${`${__adLib.googleDfpId}/EB_${__adLib.leg}/${__adLib.dfpUnitPrefix}`}${t}`,output:"vast"};Log.info("Prebid video url called. Params = ",e);let n=pbjs.adServers.dfp.buildVideoUrl({adUnit:__adLib.prebidVideoAdUnit,params:e});Log.info(`Bidding completed. Set URL in jwplayer setup and call callback: [${n}]`),i.advertising={client:"googima",adschedule:[{offset:"pre",tag:n}]},o()}})}))):o()}static addJwPlayerAdSetup(e,t){t.advertising={client:"googima",adschedule:[{offset:"pre",tag:e}]}}}class u{static CONTAINER_CLASS="__alPrerollContainer";static WRAPPER_CLASS="__alPrerollWrapper";static JWPLAYER_CONTAINER_ID="__alPreroll";static async createPreRollAd(e,i,o=(()=>{})){if(__adLib.prerollAdIsRunning)return void Log.info("Preroll Ad is already running. Ignore this one");if(!__adLib.showPrerollAd)return Log.info("Preroll Ads not enabled -> return"),void o();if(class{static isAdBlockerActivated(){var e=a.get("#_MGS_");e||(a.insert(t.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=a.get("#_MGS_"));var i=a.get("div",e);return"none"===window.getComputedStyle(i).display}}.isAdBlockerActivated())return void o();if(__adLib.prerollAdIsRunning=!0,!n.isDefined(window.jwplayer)){Log.info("jwplayer not found. Loading the script now");try{await a.loadScript(`https://content.jwplatform.com/libraries/${__adLib.jwplayerId}.js`)}catch(e){return Log.error("Unable to load jwplayer script -> skip ad"),__adLib.prerollAdIsRunning=!1,void o()}}a.addClass(e,u.CONTAINER_CLASS),Log.info(`Insert preroll [${i}] Ad into`,e),a.insert(t.prepend,e,`<div class="${u.WRAPPER_CLASS}"><div id="${u.JWPLAYER_CONTAINER_ID}"></div></div>`);let r=a.get(`.${u.WRAPPER_CLASS}`,e),s={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};f.setJwplayerSetupWithPrebid(i,s,(()=>{Log.info("Prebid preroll completed. Init JWPlayer: ",s);let t=jwplayer(u.JWPLAYER_CONTAINER_ID);t.setup(s);const i=i=>{t&&(Log.info(`Preroll Ended. Cause: [${i}]. Will remove the player and its container`),t.remove(),t=null,a.remove(r),a.removeClass(e,u.CONTAINER_CLASS),__adLib.prerollAdIsRunning=!1,o())};t.on("adComplete",(()=>{i("Ad completed")})),t.on("adSkipped",(()=>{i("Ad Skipped")})),t.on("adError",(()=>{i("Ad Error")})),t.on("adBlock",(()=>{i("Ad Blocked")})),t.on("complete",(()=>{i("Video completed")})),t.on("error",(()=>{i("Error")}))}),!0)}}var h,b;!function(e,t){void 0===t&&(t={});var i=t.insertAt;if(e&&"undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css","top"===i&&o.firstChild?o.insertBefore(n,o.firstChild):o.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}}('/* banner ad */\n.__alAd {\n overflow: hidden;\n display: block;\n margin-left: auto;\n margin-right: auto;\n}\n\n.__alAd > div {\n text-align: center !important;\n display: block !important;\n margin: auto !important;\n}\n\n.__alAd > div > iframe,\n.__alAd > div > div {\n display: block !important;\n margin: auto !important;\n}\n\n/* sticky ad */\n.__alSticky {\n top: 0;\n position: sticky;\n}\n\n/* catfish */\n.__alCatfish {\n position: fixed;\n bottom: 0;\n left: 0;\n right: 0;\n margin: auto;\n z-index: 1030;\n width: fit-content;\n}\n\n/* preroll ad */\n.__alPrerollContainer {\n position: relative !important;\n}\n\n.__alPrerollWrapper {\n position: absolute;\n width: 100%;\n height: 100%;\n display: table;\n background: black url("https://cdn.britannica.com/ads/resources/loading.gif") center center no-repeat;\n}\n\n#__alPreroll {\n display: table-cell;\n vertical-align: middle;\n}\n\n/* inline ad */\n.__alInline {\n text-align: center;\n margin: 0 auto 20px auto;\n}\n.__alInline::before {\n border-bottom: 1px solid #ddd;\n color: #aaa;\n content: "Advertisement - Continue reading below";\n display: block;\n font-family: "Helvetica", "Segoe UI", "Arial", sans-serif;\n font-size: 11px;\n font-weight: bold;\n margin-bottom: 20px;\n padding-bottom: 5px;\n clear: left;\n}'),function(e){e.DFP="DFP"}(h||(h={}));!function(e){e.REGULAR="REGULAR",e.CATFISH="CATFISH"}(b||(b={}));class m extends class{type;ads;constructor(){this.ads=[],this.type=this.getType()}addAd(e){this.ads.push(e)}}{static PAGELOAD_TARGETING="PAGELOAD";index=1;getName(){return"Google DFP"}getType(){return h.DFP}constructor(){super()}async initProvider(){if(window.googletag={cmd:[]},!n.isDefined(googletag.defineSlot)){Log.info("Googletag not found. Load the script");try{await a.loadScript("https://securepubads.g.doubleclick.net/tag/js/gpt.js")}catch(e){throw Log.error("**** Unable to load gpt.js -> most ads and scripts will be broken ***"),e}}if(Log.info("Googletag script loaded: ",googletag.defineSlot),g.loadPrebidScript(),!n.isDefined(window.headertag)&&__adLib.includeIndex)try{await a.loadScript(__adLib.indexScriptUrl)}catch(e){Log.error(`Unable to load [${__adLib.indexScriptUrl}] Index script. We won't use it.`)}if(!n.isDefined(window.apstag)&&__adLib.includeA9)try{await a.loadScript("https://c.amazon-adsystem.com/aax2/apstag.js"),function(e,t){function i(i,o){t[e]._Q.push([i,o])}t[e]||(t[e]={init:function(){i("i",arguments)},fetchBids:function(){i("f",arguments)},setDisplayBids:function(){},targetingKeys:function(){return[]},_Q:[]})}("apstag",window)}catch(e){Log.error("Unable to load A9 script. Will disable it"),__adLib.includeA9=!1}googletag.cmd.push((function(){if(googletag.pubads().setTargeting("dc_ref",__adLib.url),n.isDefined(Storage)){var e=localStorage.getItem("bcDFPTargetingParams");if(e)Log.info("Setting Blueconic targeting parameters"),JSON.parse(e).forEach((e=>googletag.pubads().setTargeting(e.key,e.value)))}if(Log.info(`targeting: ${googletag.pubads().getTargetingKeys()}`),googletag.pubads().disableInitialLoad(),googletag.pubads().enableSingleRequest(),googletag.pubads().enableAsyncRendering(),googletag.pubads().setTagForChildDirectedTreatment(0),googletag.pubads().setTagForUnderAgeOfConsent(0),__adLib.dfpLazyLoad&&googletag.pubads().enableLazyLoad(__adLib.dfpLazyLoadParameters),googletag.enableServices(),__adLib.includeA9){var t={pubID:__adLib.a9Id,adServer:"googletag",bidTimeout:1200};__uspapi&&__uspapi("getuspdata","1",((e,i)=>{i&&(t.params={us_privacy:e.uspString})})),Log.info("Init A9 with ",t),apstag.init(t)}}))}createSlot(e,t){return this.initSlot(e,t)}initSlot(e,i){return new Promise((o=>{googletag.cmd.push((()=>{try{Log.info("process DFP ad: ",e);var n=e.adParameters,r=n.size[0][0],d=n.size[0][1];Log.info("Content container for this ad is ",i);var l="";if(e.displayType!=b.CATFISH)if(n.placeholderSize)l=`min-width:${s.substringBefore(n.placeholderSize,"x")}px;min-height:${s.substringAfter(n.placeholderSize,"x")}px;`;else if(1==n.size.length)l=`width:${r}px;height:${d}px;`;else{l=`min-height:${Math.round(n.size.map((e=>e[1])).reduce(((e,t)=>e+t))/n.size.length)}px;`}var c="DFP_"+this.index++;e.containerId=c,e.dfpSize=1==n.size.length?n.size[0]:n.size;var p=`style="${l}${s.defaultIfBlank(n.style,"")}"`,g=`<div data-type="${e.type}" class="__alAd ${s.defaultIfBlank(__adLib.adClass,"")} ${s.defaultIfBlank(n.cssClass,"")}" ${p} id="${c}"></div>`;Log.info(`Inject DIV: [${g}] into `,i),a.insert(t[e.injector],i,g);var f=this.setDfpA9Slot(e);let u=a.get(`#${c}`);u.setAttribute("data-identifier",e.dfpSlot.getAdUnitPath()),u.setAttribute("data-qa-identifier",f),o(u)}catch(t){Log.error("Init Slot Error: ",e,t),o(null)}}))}))}setDfpA9Slot=function(e){Log.info("Initializes DFP slot and A9 slot for ",e);var t=e.adParameters,i=__adLib.dfpIdPrefix.replace("${LEG}",__adLib.leg),o=`${__adLib.isPhone?"MOBILE":"DESKTOP"}_${t.id}`,n=`/${__adLib.googleDfpId}/${i}${o}`;return Log.info(`Define new slot: [${n}] with: size [${e.dfpSize}] id [${e.containerId}]`),e.dfpSlot=googletag.defineSlot(n,e.dfpSize,e.containerId),t.targeting&&Object.entries(t.targeting).forEach((([t,i])=>{e.dfpSlot.setTargeting(t,String(i))})),e.dfpSlot.addService(googletag.pubads()),__adLib.includeA9&&(e.a9Slot={slotID:e.containerId,slotName:n,sizes:t.size}),Log.info("DFP/A9 slot defined for ",e),o};refreshAllAds(){Log.info("Refresh all DFP ads."),googletag.cmd.push((()=>{m.setPageLoadTargeting(this.ads),this.refreshSlots()}))}requestBids(e){this.refreshAds(e)}refreshAds(e){Log.info("Refresh ads: ",e),googletag.cmd.push((()=>{m.setPageLoadTargeting(e),this.refreshSlots(e)}))}static setPageLoadTargeting(e){for(let t of e){const e=`REFRESH${t.refreshCounter}`;Log.info(`Update ${m.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(m.PAGELOAD_TARGETING,e)}}refreshSlots(t=this.ads){Log.info("Refresh slots - ads : ",t);let i=!1,o=!1,n=!1,a=()=>{n||!o||!i&&__adLib.includeA9||(-1!=c&&window.clearTimeout(c),Log.info("Prebid is completed and A9 completed or disabled -> call DFP"),r())},r=()=>{Log.info("Refresh ads ",t);let e=t.map((e=>e.dfpSlot));Log.info("Refresh DFP slots ",e),googletag.pubads().refresh(e)},s=[];for(let e of t)s.push({code:e.dfpSlot.getAdUnitPath(),mediaTypes:{banner:{sizes:e.adParameters.size}},bids:__adLib.prebidBannerBiddersConfiguration});Log.info("Prebid ad unit configuration: ",s);let d={...__adLib.prebidConfiguration,debug:Log.getLevel()==e.Debug,...p.getPrebidConsentParameters()};if(__adLib.includeA9){var l=t.map((e=>e.a9Slot));Log.info("Calls A9 with these slots:",l),apstag.fetchBids({slots:l},(()=>{Log.info("A9 bid request completed"),apstag.setDisplayBids(),i=!0,a()}))}pbjs.que.push((()=>{Log.info("Set Prebid Config: ",d),pbjs.setConfig(d),pbjs.addAdUnits(s),Log.info("Request Prebid bids"),pbjs.requestBids({timeout:__adLib.prebidTimeout,bidsBackHandler:()=>{Log.info("Prebid request bid completed"),pbjs.setTargetingForGPTAsync(t.map((e=>e.dfpSlot.getAdUnitPath()))),o=!0,a()}})}));let c=-1;0!=__adLib.biddersFailsafeTimeout&&(Log.info(`Bidders failsafe timeout set to [${__adLib.biddersFailsafeTimeout}] ms`),c=window.setTimeout((()=>{Log.info("Bidding Timeout! -> calls DFP directly"),n=!0,r()}),__adLib.biddersFailsafeTimeout))}}class _{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,i){Log.info("Create a catfish container");let o=`<div id="${_.CATFISH_ID}" class="__alCatfish" style=" ${e?`width:${e}px;`:""} ${i?`height:${i}px`:""}"></div>`;return a.insert(t.append,document.body,o),Log.info("Static Catfish Inserted",_.getCurrentCatfishElement()),_.getCurrentCatfishElement()}static getCurrentCatfishElement(){return a.get(`#${_.CATFISH_ID}`)}}class L{static providerClasses=new Map([[h.DFP,m]]);providers=new Map;timers=[];constructor(){n.isDefined(typeof window.__adLib)&&a.onDocumentReady((()=>{this.init()}))}isAdBlockerActivated(){var e=a.get("#_MGS_");e||(a.insert(t.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=a.get("#_MGS_"));var i=a.get("div",e);return"none"===window.getComputedStyle(i).display}async init(){Log.info("Init Ads manager at page load"),c.init(),await p.init(),Log.info("Set tab visibility event handler"),a.setEventListener(document,"visibilitychange",(()=>{let e="visible"===document.visibilityState;Log.info(`Tab visibility changed to [${e}]`),e?this.resumeAllPausedTimers():this.pauseAllRunningTimers()})),__adLib.deferAds?(Log.info("Ads need to be deferred. Will wait until the [endDeferAds] is fired"),a.setEventListener(document,"endDeferAds",(()=>{Log.info("Deferred Ads event triggered. Will now initialize the ads"),this.contentLoadInit(document.body,__adLib.initialLoadAds)}))):(Log.info("No deferred ads. Will initialize the ads now"),this.contentLoadInit(document.body,__adLib.initialLoadAds))}async contentLoadInit(e=document.body,t){let i;if(Log.info(" ============================================================================================="),Log.info("Initialize container with ads"),Log.info(" ============================================================================================="),t)i=t,Log.info("Ad definitions passed as parameter: ",i);else{Log.info("Look for json ads definition in ",e);let t=d.getJsonFromScriptSnippet("ads-script",e);if(!t)return void Log.info("Did not find ads definition.");if(i=t,!i)return;Log.info("Found ad definitions: ",i)}let o=new Map;for(let t of i){if(Log.info("Init this ad: ",t),!this.providers.has(t.type)){Log.info(`Initializes Provider: [${t.type}]`);try{let e=new(L.providerClasses.get(t.type));await e.initProvider(),this.providers.set(t.type,e)}catch(e){Log.error(`Unable to instantiate Ad Provider: [${t.type}]`,t,e);continue}}let i=this.providers.get(t.type);o.has(t.type)||o.set(t.type,[]),t.provider=i;let n=null;if(t.displayType==b.REGULAR)n=a.get(t.selector,e);else if(t.displayType==b.CATFISH){if(n=_.getCurrentCatfishElement(),n){let e=a.get(".__alAd",n).ad;e.provider.refreshAds([e]),Log.info("Catfish already exists, just refresh its ad");continue}n=_.newCatfish(),t.injector="append"}n?(t.$container=await i.createSlot(t,n),t.$container?(t.$container.ad=t,t.refreshCounter=0,i.addAd(t),o.get(t.type).push(t),t.autoRefresh?(t.$container.isInViewPort=!1,t.refreshTimer=new l((()=>{L.timerCallback(t)}),1e3*__adLib.refreshTimer),this.timers.push(t.refreshTimer),Log.info("This ad is autorefresh, added refresh timer: ",t.refreshTimer)):(t.refreshTimer=null,t.$container.isInViewPort=!0,Log.info("This ad is not autorefresh -> no refresh timer")),t.displayType==b.CATFISH?(Log.info("The ad is a catfish -> always in viewport and start refresh timer"),t.$container.isInViewPort=!0,t.refreshTimer&&t.refreshTimer.start()):t.autoRefresh&&(Log.info("Add the ad container to the observer -> ",t.$container),this.isInViewPortObserver.observe(t.$container)),Log.info("Ad initialized",t)):Log.info("Slot creation failed -> skip this ad")):Log.info("Error when initializing the ad/Existing ad -> skip it: ",t)}for(let[e,t]of o)0==t.length?Log.info(`No ads for [${e}] provider`):(Log.info(`Request Bids for [${e}] provider: `,t),this.providers.get(e).requestBids(t));if(__adLib.stickyContainerSelector){const t=a.getAll(`${__adLib.stickyContainerSelector} .__alAd`,e);let i=t.length;if(i>0){let e=t.item(i-1);Log.info("Last ad is sticky",e),a.addClass(e,"__alSticky",__adLib.stickyAdClass)}}}isInViewPortObserver=new IntersectionObserver((e=>{e.forEach((e=>{let t=e.target;t.isInViewPort=e.intersectionRatio>=__adLib.viewportThreshold,t.isInViewPort?(Log.info("Ad in viewport -> resume timer",t.ad),L.resumeRefreshTimer(t.ad)):(Log.info("Ad out of viewport -> stop timer",t.ad),L.pauseRefreshTimer(t.ad))}))}),{threshold:__adLib.viewportThreshold});static timerCallback(e){Log.info("Ad is refreshed.",e),e.refreshCounter++,e.provider.refreshAds([e])}static resumeRefreshTimer(e){Log.info("Resume refresh timer for ",e),e.refreshTimer.state==i.PAUSED?e.refreshTimer.resume():e.refreshTimer.state==i.STOPPED&&e.refreshTimer.start()}static pauseRefreshTimer(e){Log.info("Pause refresh timer for ",e),e.refreshTimer.pause()}pausedTimers=[];pauseAllRunningTimers(){this.pausedTimers=this.timers.filter((e=>e.state==i.RUNNING)),0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.pause())),Log.info("Pause these timers: ",this.pausedTimers.map((e=>e.id))))}resumeAllPausedTimers(){0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.resume())),Log.info("Resume these timers: ",this.pausedTimers.map((e=>e.id))))}refreshAllAds(){Log.info("Refresh All ads"),this.providers.forEach((e=>{Log.info(`will refresh ads for this provider: [${e.getName()}]`);for(let t of e.ads)t.refreshCounter++;e.refreshAllAds();for(let t of e.ads)t.refreshTimer&&t.refreshTimer.restart()}))}}window.Log=new o(n.isDefined(__adLib)?e[__adLib.logLevel]:e.None),Log.info("Ad Library Loaded"),__adLib.AdsManager=new L,__adLib.ConsentManager=p,__adLib.PrebidForVideo=f,__adLib.PrerollAd=u})); | ||
//# sourceMappingURL=britannica-ads.umd.js.map |
@@ -21,6 +21,5 @@ export declare type callbackFunction = () => void; | ||
private readonly level; | ||
constructor(); | ||
constructor(level: LogLevel); | ||
getLevel(): LogLevel; | ||
} | ||
export declare const Log: alLog; | ||
export declare class alObject { | ||
@@ -27,0 +26,0 @@ static isDefined(o: any): boolean; |
@@ -1,4 +0,1 @@ | ||
export { ConsentManager } from './consentmanagers/ConsentManager'; | ||
export { PrebidForVideo } from './video/PrebidForVideo'; | ||
export { PrerollAd } from './video/PrerollAd'; | ||
export { AdsManager } from './AdsManager'; | ||
export { IadLibConfiguration } from './global'; |
{ | ||
"name": "@britannica/ads", | ||
"version": "1.0.0-beta.5", | ||
"version": "1.0.0-beta.6", | ||
"description": "Britannica and MW ad library", | ||
@@ -5,0 +5,0 @@ "main": "dist/britannica-ads.cjs.js", |
import { Iab } from './consentmanagers/iab'; | ||
require('./AdsManager.scss'); | ||
import { alDOM, alJson, alObject, DomInsertPosition, IntervalTimer, Log, TimerState } from './helpers'; | ||
import './AdsManager.scss'; | ||
import { alDOM, alJson, alObject, DomInsertPosition, IntervalTimer, TimerState } from './helpers'; | ||
import { DfpProvider } from './providers/Dfp'; | ||
@@ -11,6 +11,6 @@ import { AbstractProvider, ProviderType } from './providers/AbstractProvider'; | ||
// ============================================================================================================================ | ||
// --- Ad Manager, read the ad configuration and insert/refresh these ads | ||
// --- Ad Manager, read the ad configuration and insert/refresh these ads----- | ||
// ============================================================================================================================ | ||
class _AdsManager { | ||
export class AdsManager { | ||
private static providerClasses: Map<ProviderType, { new (): DfpProvider }> = new Map([ | ||
@@ -29,3 +29,2 @@ [ProviderType.DFP, DfpProvider], | ||
alDOM.onDocumentReady(() => { | ||
Log.info('Ad Library Loaded'); | ||
this.init(); | ||
@@ -164,3 +163,3 @@ }); | ||
try { | ||
let provider = new (_AdsManager.providerClasses.get(ad.type))(); | ||
let provider = new (AdsManager.providerClasses.get(ad.type))(); | ||
await provider.initProvider(); | ||
@@ -233,3 +232,3 @@ this.providers.set(ad.type, provider); | ||
ad.refreshTimer = new IntervalTimer(() => { | ||
_AdsManager.timerCallback(ad); | ||
AdsManager.timerCallback(ad); | ||
}, __adLib.refreshTimer * 1000); | ||
@@ -307,6 +306,6 @@ this.timers.push(ad.refreshTimer); | ||
Log.info('Ad in viewport -> resume timer', $adContainer.ad); | ||
_AdsManager.resumeRefreshTimer($adContainer.ad); | ||
AdsManager.resumeRefreshTimer($adContainer.ad); | ||
} else { | ||
Log.info('Ad out of viewport -> stop timer', $adContainer.ad); | ||
_AdsManager.pauseRefreshTimer($adContainer.ad); | ||
AdsManager.pauseRefreshTimer($adContainer.ad); | ||
} | ||
@@ -385,3 +384,1 @@ }); | ||
} | ||
export const AdsManager = new _AdsManager(); |
@@ -1,2 +0,2 @@ | ||
import { alCookie, alDOM, alObject, Log } from '../helpers'; | ||
import { alCookie, alDOM, alObject } from '../helpers'; | ||
import { Iab } from './iab'; | ||
@@ -3,0 +3,0 @@ |
//US Privacy String API - required by the IAB to be a specific format | ||
import { alCookie, alDOM, DomInsertPosition, Log } from '../helpers'; | ||
import { alCookie, alDOM, DomInsertPosition } from '../helpers'; | ||
@@ -5,0 +5,0 @@ /** @function __uspapi |
import { callbackFunction } from './helpers'; | ||
import { IabPrivacyObject } from './consentmanagers/iab'; | ||
import { ItcData } from './consentmanagers/ConsentManager'; | ||
import { ConsentManager, ItcData } from './consentmanagers/ConsentManager'; | ||
import IPrebidAdUnit = pbjs.IPrebidAdUnit; | ||
import IBidderInfo = pbjs.IBidderInfo; | ||
import { IAd } from './common/types'; | ||
import { AdsManager } from './AdsManager'; | ||
import { PrebidForVideo } from './video/PrebidForVideo'; | ||
import { PrerollAd } from './video/PrerollAd'; | ||
@@ -12,3 +15,3 @@ declare module '*.module.scss'; | ||
interface IadLibConfiguration { | ||
export interface IadLibConfiguration { | ||
logLevel: string; | ||
@@ -55,2 +58,7 @@ refreshTimer: number; | ||
initialLoadAds?: IAd[]; | ||
AdsManager: AdsManager; | ||
ConsentManager: ConsentManager; | ||
PrebidForVideo: PrebidForVideo; | ||
PrerollAd: PrerollAd; | ||
} | ||
@@ -81,2 +89,3 @@ | ||
var __adLib: IadLibConfiguration; | ||
var Log: alLog; | ||
} |
@@ -34,4 +34,4 @@ export type callbackFunction = () => void; | ||
constructor() { | ||
this.level = alObject.isDefined(__adLib) ? LogLevel[__adLib.logLevel as keyof typeof LogLevel] : LogLevel.None; | ||
constructor(level: LogLevel) { | ||
this.level = level; | ||
this.info = | ||
@@ -50,4 +50,2 @@ LogLevel.Info >= this.level ? console.log.bind(window.console, '%cAd Lib', alLog.INFO_STYLE) : () => null; | ||
export const Log = new alLog(); | ||
// ------------------ | ||
@@ -111,3 +109,3 @@ // --- Object helpers | ||
document.head.append(script); | ||
Log.info(`Loaded: [${scriptUrl}]`); | ||
window.Log.info(`Loaded: [${scriptUrl}]`); | ||
}); | ||
@@ -332,3 +330,3 @@ } | ||
} catch (e) { | ||
Log.error('JSON parsing error: ', e); | ||
window.Log.error('JSON parsing error: ', e); | ||
return null; | ||
@@ -385,3 +383,3 @@ } | ||
this._state = TimerState.PAUSED; | ||
Log.debug(`Timer [${this._id}] Paused - Remaining [${this.remaining}ms]`); | ||
window.Log.debug(`Timer [${this._id}] Paused - Remaining [${this.remaining}ms]`); | ||
} | ||
@@ -398,3 +396,3 @@ } | ||
this._state = TimerState.RUNNING; | ||
Log.debug(`Timer [${this._id}] Resumed in [${this.remaining}ms].`); | ||
window.Log.debug(`Timer [${this._id}] Resumed in [${this.remaining}ms].`); | ||
} | ||
@@ -409,3 +407,3 @@ } | ||
this._state = TimerState.STOPPED; | ||
Log.debug(`Timer [${this._id}] - Internal id [${this.internalTimerId}] Stopped`); | ||
window.Log.debug(`Timer [${this._id}] - Internal id [${this.internalTimerId}] Stopped`); | ||
} | ||
@@ -419,3 +417,3 @@ } | ||
this._state = TimerState.RUNNING; | ||
Log.debug(`Started Timer [${this._id}] - Internal id [${this.internalTimerId}]`); | ||
window.Log.debug(`Started Timer [${this._id}] - Internal id [${this.internalTimerId}]`); | ||
} | ||
@@ -422,0 +420,0 @@ |
@@ -1,4 +0,17 @@ | ||
export { ConsentManager } from './consentmanagers/ConsentManager'; | ||
export { PrebidForVideo } from './video/PrebidForVideo'; | ||
export { PrerollAd } from './video/PrerollAd'; | ||
export { AdsManager } from './AdsManager'; | ||
import { alLog, alObject, LogLevel } from './helpers'; | ||
import { ConsentManager } from './consentmanagers/ConsentManager'; | ||
import { PrebidForVideo } from './video/PrebidForVideo'; | ||
import { PrerollAd } from './video/PrerollAd'; | ||
import { AdsManager } from './AdsManager'; | ||
export { IadLibConfiguration } from './global'; | ||
window.Log = new alLog( | ||
alObject.isDefined(__adLib) ? LogLevel[__adLib.logLevel as keyof typeof LogLevel] : LogLevel.None | ||
); | ||
Log.info('Ad Library Loaded'); | ||
__adLib.AdsManager = new AdsManager(); | ||
__adLib.ConsentManager = ConsentManager; | ||
__adLib.PrebidForVideo = PrebidForVideo; | ||
__adLib.PrerollAd = PrerollAd; |
@@ -5,3 +5,3 @@ // ============================================================================================================================ | ||
import { alDOM, DomInsertPosition, Log } from '../../helpers'; | ||
import { alDOM, DomInsertPosition } from '../../helpers'; | ||
@@ -8,0 +8,0 @@ export class Catfish { |
@@ -5,3 +5,3 @@ // *************************************** | ||
import { alDOM, alObject, alString, callbackFunction, DomInsertPosition, Log, LogLevel } from '../helpers'; | ||
import { alDOM, alObject, alString, callbackFunction, DomInsertPosition, LogLevel } from '../helpers'; | ||
import { AbstractProvider, ProviderType } from './AbstractProvider'; | ||
@@ -8,0 +8,0 @@ import { utils } from '../utils/utils'; |
@@ -1,2 +0,2 @@ | ||
import { alDOM, alObject, Log } from '../helpers'; | ||
import { alDOM, alObject } from '../helpers'; | ||
@@ -3,0 +3,0 @@ export class utils { |
@@ -1,2 +0,2 @@ | ||
import { Log, LogLevel } from '../helpers'; | ||
import { LogLevel } from '../helpers'; | ||
import { utils } from '../utils/utils'; | ||
@@ -3,0 +3,0 @@ |
@@ -1,2 +0,2 @@ | ||
import { alAdUtils, alDOM, alObject, callbackFunction, DomInsertPosition, Log } from '../helpers'; | ||
import { alAdUtils, alDOM, alObject, callbackFunction, DomInsertPosition } from '../helpers'; | ||
import { PrebidForVideo } from './PrebidForVideo'; | ||
@@ -3,0 +3,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
255629
2721
3