@britannica/ads
Advanced tools
Comparing version 1.0.1 to 1.1.0-beta.1
@@ -1,2 +0,2 @@ | ||
"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 ONETRUST_COOKIE_NAME="OptanonAlertBoxClosed";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")}__adLib.usPrivacyConsent||r.isCookieExists(p.ONETRUST_COOKIE_NAME)||(Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2("OptanonWrapper called"),r.isCookieExists(p.ONETRUST_COOKIE_NAME)&&p.setOnUserConsent?(Log.info2("The consent manager popup was closed. Consent Manager callback will be called"),p.setDeferAdsStatus(!1)):Log.info2("The consent manager popup was not closed. Still waiting")},Log.info2("Defer the ads loading by default"),p.setDeferAdsStatus(!0))}else Log.info2("Not Consent Required")}static setDeferAdsStatus(e){__adLib.deferAds=e,e||p.userConsentCallback()}static userConsentCallback;static setOnUserConsent(e){p.userConsentCallback=e}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)&&n.isDefined(window.pbjs.requestBids))){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 0 auto;\n padding-bottom: 20px;\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 _ 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().setPrivacySettings({childDirectedTreatment:!1,underAgeOfConsent:!1}),__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((()=>{_.setPageLoadTargeting(this.ads),this.refreshSlots()}))}requestBids(e){this.refreshAds(e)}refreshAds(e){Log.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}`;Log.info(`Update ${_.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(_.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 m{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,i){Log.info("Create a catfish container");let o=`<div id="${m.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",m.getCurrentCatfishElement()),m.getCurrentCatfishElement()}static getCurrentCatfishElement(){return a.get(`#${m.CATFISH_ID}`)}}class L{static providerClasses=new Map([[h.DFP,_]]);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 user closes the consent manager"),p.setOnUserConsent((()=>{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=m.getCurrentCatfishElement(),n){let e=a.get(".__alAd",n).ad;e.provider.refreshAds([e]),Log.info("Catfish already exists, just refresh its ad");continue}n=m.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 ",String.fromCodePoint(128126)),__adLib.AdsManager=new L,__adLib.ConsentManager=p,__adLib.PrebidForVideo=f,__adLib.PrerollAd=u; | ||
"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 n{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",n.ERR_STYLE);warning=console.warn.bind(window.console,"%cAd Lib",n.WARN_STYLE);debug;info;info2;level;constructor(t){this.level=t,this.info=e.Info>=this.level?console.log.bind(window.console,"%cAd Lib",n.INFO_STYLE):()=>null,this.info2=e.Info2>=this.level?console.log.bind(window.console,"%cAd Lib",n.INFO_STYLE2):()=>null,this.debug=e.Debug>=this.level?console.debug.bind(window.console,"%cAd Lib",n.DEBUG_STYLE):()=>null}getLevel(){return this.level}}class o{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,n)=>{let o=document.createElement("script");o.src=e,o.onload=()=>i(),o.onerror=()=>n();for(const[e,i]of Object.entries(t))o.setAttribute(e,i);document.head.append(o),window.Log.info(`Loaded: [${e}]`)}))}static css(e,t,i){e.style.setProperty(t,i)}static show(e){a.css(e,"display","block")}static hide(e){a.css(e,"display","none")}static addClass(e,...t){t.forEach((t=>{t&&e.classList.add(t)}))}static setClass(e,t){e.className=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,n)=>{i.forEach((i=>{i.isIntersecting&&(t(e),n.disconnect(),n=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 s{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 r{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,i=!1){if(!e||!t)return e;const n=i?e.lastIndexOf(t):e.indexOf(t);return-1==n?"":e.substring(n+1)}static substringAfterLast(e,t){return r.substringAfter(e,t,!0)}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()}getRemaining(){return this.remaining}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:s.readCookie(c.US_PrivacyCookieName)};Log.info2("IAB: getuspdata command. Response: ",e),i(e,null!=e.uspString)}},s.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,n){let o=e=>!0===e?"Y":!1===e?"N":"-",a=e.toString()+o(t)+o(i)+o(n),s=`${c.US_PrivacyCookieName}=${a}; `,r=new Date;r.setTime(r.getTime()+24*c.US_PrivacyCookieDuration*60*60*1e3);let d=`expires=${r.toUTCString()}; `;document.cookie=s+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 n=t.__uspapiCall;window.__uspapi(n.command,n.version,(function(t,o){let a={__uspapiReturn:{returnValue:t,success:o,callId:n.callId}},s=e.source;Log.info2("IAB: post message back ",a,s),s.postMessage(i?JSON.stringify(a):a,"*")}))}}}class g{static ONETRUST_COOKIE_NAME="OptanonAlertBoxClosed";static async init(){if(__adLib.requiresConsent){if(!o.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")}__adLib.usPrivacyConsent||s.isCookieExists(g.ONETRUST_COOKIE_NAME)||(Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2("OptanonWrapper called"),s.isCookieExists(g.ONETRUST_COOKIE_NAME)&&g.setOnUserConsent?(Log.info2("The consent manager popup was closed. Consent Manager callback will be called"),g.setDeferAdsStatus(!1)):Log.info2("The consent manager popup was not closed. Still waiting")},Log.info2("Defer the ads loading by default"),g.setDeferAdsStatus(!0))}else Log.info2("Not Consent Required")}static setDeferAdsStatus(e){__adLib.deferAds=e,e||g.userConsentCallback()}static userConsentCallback;static setOnUserConsent(e){g.userConsentCallback=e}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(s.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}]`),s.createCookieSession("OptanonConsent",encodeURI(t),__adLib.topDomain),s.createCookieSession("EbConsentClosed","true"),Log.info2("created new OptanonConsent and EbConsentClosed cookies")}}class p{static async loadPrebidScript(){if(!(__adLib.videoForPrebidLoaded||o.isDefined(window.pbjs)&&o.isDefined(window.pbjs.requestBids))){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 u{static setJwplayerSetupWithPrebid(t,i,n,o=!1){o||__adLib.showPrerollAdInVideos?(p.loadPrebidScript(),pbjs.que.push((()=>{let o=__adLib.prebidConfiguration;o.debug=Log.getLevel()==e.Debug,pbjs.setConfig(o),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 o=pbjs.adServers.dfp.buildVideoUrl({adUnit:__adLib.prebidVideoAdUnit,params:e});Log.info(`Bidding completed. Set URL in jwplayer setup and call callback: [${o}]`),i.advertising={client:"googima",adschedule:[{offset:"pre",tag:o}]},n()}})}))):n()}static addJwPlayerAdSetup(e,t){t.advertising={client:"googima",adschedule:[{offset:"pre",tag:e}]}}}class h{static CONTAINER_CLASS="__alPrerollContainer";static WRAPPER_CLASS="__alPrerollWrapper";static JWPLAYER_CONTAINER_ID="__alPreroll";static async createPreRollAd(e,i,n=(()=>{})){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 n();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 n();if(__adLib.prerollAdIsRunning=!0,!o.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 n()}}a.addClass(e,h.CONTAINER_CLASS),Log.info(`Insert preroll [${i}] Ad into`,e),a.insert(t.prepend,e,`<div class="${h.WRAPPER_CLASS}"><div id="${h.JWPLAYER_CONTAINER_ID}"></div></div>`);let s=a.get(`.${h.WRAPPER_CLASS}`,e),r={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};u.setJwplayerSetupWithPrebid(i,r,(()=>{Log.info("Prebid preroll completed. Init JWPlayer: ",r);let t=jwplayer(h.JWPLAYER_CONTAINER_ID);t.setup(r);const i=i=>{t&&(Log.info(`Preroll Ended. Cause: [${i}]. Will remove the player and its container`),t.remove(),t=null,a.remove(s),a.removeClass(e,h.CONTAINER_CLASS),__adLib.prerollAdIsRunning=!1,n())};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 f,b;!function(e,t){void 0===t&&(t={});var i=t.insertAt;if(e&&"undefined"!=typeof document){var n=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css","top"===i&&n.firstChild?n.insertBefore(o,n.firstChild):n.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.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 0 auto;\n padding-bottom: 20px;\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}\n\n/* debug */\n#__adLib-debug-dashboard {\n width: 100%;\n height: 250px;\n overflow-y: scroll;\n padding: 20px;\n position: fixed;\n top: 0;\n left: 0;\n z-index: 10000000000000;\n background-color: #fafafa;\n border-bottom: solid 2px black;\n font-size: 11px;\n}\n#__adLib-debug-dashboard table {\n background-color: white;\n width: 100%;\n color: black;\n font-family: monospace;\n}\n#__adLib-debug-dashboard table th {\n background-color: #f2f2f2;\n font-weight: bold;\n text-align: center;\n}\n#__adLib-debug-dashboard table th,\n#__adLib-debug-dashboard table td {\n padding: 3px 6px;\n}\n#__adLib-debug-dashboard table,\n#__adLib-debug-dashboard th,\n#__adLib-debug-dashboard td {\n border: solid 1px #888;\n}\n\n#__adLib-debug-close,\n#__adLib-debug-open {\n cursor: pointer;\n}\n\n#__adLib-debug-open {\n top: 1px;\n left: 1px;\n font-size: 10px;\n font-family: monospace;\n position: fixed;\n z-index: 1000000000000;\n}\n\n#__adLib-debug-close {\n top: 5px;\n right: 5px;\n font-weight: bold;\n position: absolute;\n}\n\n.__adLib-debug-no {\n background-color: orange;\n color: white;\n text-align: center;\n}\n\n.__adLib-debug-yes {\n background-color: green;\n color: white;\n text-align: center;\n}'),function(e){e.DFP="DFP"}(f||(f={}));!function(e){e.REGULAR="REGULAR",e.CATFISH="CATFISH"}(b||(b={}));class _ extends class{type;ads;constructor(){this.ads=[],this.type=this.getType()}addAd(e){this.ads.push(e)}}{static PAGELOAD_TARGETING="PAGELOAD";index=1;dfpAds=new Map;debugDashboard;getName(){return"Google DFP"}getType(){return f.DFP}constructor(){super()}async initProvider(){if(window.googletag={cmd:[]},!o.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),p.loadPrebidScript(),!o.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(!o.isDefined(window.apstag)&&__adLib.includeA9)try{await a.loadScript("https://c.amazon-adsystem.com/aax2/apstag.js"),function(e,t){function i(i,n){t[e]._Q.push([i,n])}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((()=>{if(googletag.pubads().setTargeting("dc_ref",__adLib.url),o.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().setPrivacySettings({childDirectedTreatment:!1,underAgeOfConsent:!1}),__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)}googletag.pubads().addEventListener("slotVisibilityChanged",(e=>{let t=this.dfpAds.get(e.slot.getSlotElementId());if(t.isFetching)return;let n=e.inViewPercentage,o=e.slot.getSlotElementId(),s=a.get(`#${o}`);s.isInViewPort=n>=50,this.updateDebugDashboard(o,"visible",s.isInViewPort),t.refreshTimer&&(s.isInViewPort?t.refreshTimer.state==i.PAUSED&&(Log.info("Ad is in viewport -> resume timer",t),t.refreshTimer.resume(),this.updateDebugDashboard(o,"timer",t.refreshTimer.state)):t.refreshTimer.state==i.RUNNING&&(Log.info("Ad is out of viewport -> pause timer",t),t.refreshTimer.pause(),this.updateDebugDashboard(o,"timer",`${t.refreshTimer.state} (${Math.round(t.refreshTimer.getRemaining()/1e3)}s)`)))})),googletag.pubads().addEventListener("slotOnload",(e=>{this.dfpAds.get(e.slot.getSlotElementId()).isFetching=!1}))})),Log.getLevel()!=e.None&&(this.debugDashboard=new m)}updateDebugDashboard(e,t,i){this.debugDashboard&&this.debugDashboard.updateSlotStatus(e,t,i)}createSlot(e,t){return this.initSlot(e,t)}initSlot(e,i){return new Promise((n=>{googletag.cmd.push((()=>{try{Log.info("process DFP ad: ",e);let o=e.adParameters,s=o.size[0][0],d=o.size[0][1];Log.info("Content container for this ad is ",i);let l="";if(e.displayType!=b.CATFISH)if(o.placeholderSize)l=`min-width:${r.substringBefore(o.placeholderSize,"x")}px;min-height:${r.substringAfter(o.placeholderSize,"x")}px;`;else if(1==o.size.length)l=`width:${s}px;height:${d}px;`;else{l=`min-height:${Math.round(o.size.map((e=>e[1])).reduce(((e,t)=>e+t))/o.size.length)}px;`}let c="DFP_"+this.index++;e.containerId=c,e.dfpSize=1==o.size.length?o.size[0]:o.size,e.isFetching=!1;let g=`style="${l}${r.defaultIfBlank(o.style,"")}"`,p=`<div data-type="${e.type}" class="__alAd ${r.defaultIfBlank(__adLib.adClass,"")} ${r.defaultIfBlank(o.cssClass,"")}" ${g} id="${c}"></div>`;Log.info(`Inject DIV: [${p}] into `,i),a.insert(t[e.injector],i,p);let u=this.setDfpA9Slot(e),h=a.get(`#${c}`);h.setAttribute("data-identifier",e.dfpSlot.getAdUnitPath()),h.setAttribute("data-qa-identifier",u),this.dfpAds.set(c,e),this.debugDashboard&&this.debugDashboard.addAd(e),n(h)}catch(t){Log.error("Init Slot Error: ",e,t),n(null)}}))}))}setDfpA9Slot=function(e){Log.info("Initializes DFP slot and A9 slot for ",e);let t=e.adParameters,i=__adLib.dfpIdPrefix.replace("${LEG}",__adLib.leg),n=`${__adLib.isPhone?"MOBILE":"DESKTOP"}_${t.id}`,o=`/${__adLib.googleDfpId}/${i}${n}`;return Log.info(`Define new slot: [${o}] with: size [${e.dfpSize}] id [${e.containerId}]`),e.dfpSlot=googletag.defineSlot(o,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:o,sizes:t.size}),Log.info("DFP/A9 slot defined for ",e),n};initialDisplay(e){Log.info("Ad Initial Display",e);let t=e.dfpSlot.getSlotElementId();this.updateDebugDashboard(t,"initial-load",!0),this.refreshAds([e]),e.autoRefresh&&this.updateDebugDashboard(t,"timer",i.RUNNING)}handlesViewability(){return!0}refreshAllAds(){Log.info("Refresh all DFP ads."),googletag.cmd.push((()=>{_.setPageLoadTargeting(this.ads),this.refreshSlots()}))}refreshAds(e){Log.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}`;Log.info(`Update ${_.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(_.PAGELOAD_TARGETING,e)}}refreshSlots(t=this.ads){Log.info("Refresh slots - ads : ",t);let i=!1,n=!1,o=!1,a=()=>{o||!n||!i&&__adLib.includeA9||(-1!=c&&window.clearTimeout(c),Log.info("Prebid is completed and A9 completed or disabled -> call DFP"),s())},s=()=>{Log.info("Refresh ads ",t);let e=t.map((e=>e.dfpSlot));Log.info("Refresh DFP slots ",e),t.forEach((e=>{this.debugDashboard&&this.debugDashboard.updateRefreshStatus(e.containerId,e.refreshCounter),e.isFetching=!0})),googletag.pubads().refresh(e)},r=[];for(let e of t)r.push({code:e.dfpSlot.getAdUnitPath(),mediaTypes:{banner:{sizes:e.adParameters.size}},bids:__adLib.prebidBannerBiddersConfiguration});Log.info("Prebid ad unit configuration: ",r);let d={...__adLib.prebidConfiguration,debug:Log.getLevel()==e.Debug,...g.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(r),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()))),n=!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"),o=!0,s()}),__adLib.biddersFailsafeTimeout))}}class m{$debugDashboard;constructor(){a.insert(t.append,document.body,'<button id="__adLib-debug-open">Ad Debug</button>\n <div id="__adLib-debug-dashboard">\n <div id="__adLib-debug-close">X</div>\n <table>\n <thead>\n <tr>\n <th>DIV</th>\n <th>GPT Path</th>\n <th>Type</th>\n <th>Initial Load</th>\n <th>Fetched</th>\n <th>Rendered</th>\n <th>Rfsh Viewable</th>\n <th>Visible</th>\n <th>Refreshing</th>\n <th>Counter</th>\n <th>Timer</th>\n </tr>\n </thead>\n <tbody></tbody>\n </table>\n </div>'),this.$debugDashboard=a.get("#__adLib-debug-dashboard tbody"),a.setEventListener(a.get("#__adLib-debug-close"),"click",this.hide),a.setEventListener(a.get("#__adLib-debug-open"),"click",this.show),googletag.cmd.push((()=>{googletag.pubads().addEventListener("slotRequested",(e=>{this.updateSlotStatus(e.slot.getSlotElementId(),"fetched",!0),this.updateSlotStatus(e.slot.getSlotElementId(),"refreshing",!1)})),googletag.pubads().addEventListener("slotOnload",(e=>{this.updateSlotStatus(e.slot.getSlotElementId(),"rendered",!0)})),googletag.pubads().addEventListener("impressionViewable",(e=>{this.updateSlotStatus(e.slot.getSlotElementId(),"viewable",!0)}))}))}addAd(e){let i=e.dfpSlot.getSlotElementId(),n=r.substringAfterLast(e.dfpSlot.getAdUnitPath(),"/");a.insert(t.append,this.$debugDashboard,`<tr>\n <td><a href="#${i}">${i}</a></td>\n <td>${n}</td>\n <td>${e.displayType}</td>\n <td id="__adLib-debug-initial-load-${i}"></td>\n <td id="__adLib-debug-fetched-${i}"></td>\n <td id="__adLib-debug-rendered-${i}"></td>\n <td id="__adLib-debug-viewable-${i}"></td>\n <td id="__adLib-debug-visible-${i}"></td>\n <td id="__adLib-debug-refreshing-${i}"></td>\n <td id="__adLib-debug-counter-${i}"></td>\n <td id="__adLib-debug-timer-${i}"></td>\n </tr>`),this.resetSlotStatus(i),this.updateSlotStatus(i,"timer",e.refreshTimer?e.refreshTimer.state:"N/A")}updateSlotStatus(e,t,i){let n=a.get(`#__adLib-debug-${t}-${e}`);n?"boolean"==typeof i?(a.setClass(n,"__adLib-debug-"+(i?"yes":"no")),n.innerText=i?"YES":"NO"):n.innerText=i:Log.error(`Unknown AD : [${e}] - [${t}]`)}resetSlotStatus(e){this.updateSlotStatus(e,"initial-load",!1),this.updateSlotStatus(e,"fetched",!1),this.updateSlotStatus(e,"rendered",!1),this.updateSlotStatus(e,"viewable",!1),this.updateSlotStatus(e,"visible",!1),this.updateSlotStatus(e,"refreshing",!1),this.updateSlotStatus(e,"counter","0")}updateRefreshStatus(e,t){this.updateSlotStatus(e,"refreshing",!0),this.updateSlotStatus(e,"fetched",!1),this.updateSlotStatus(e,"rendered",!1),this.updateSlotStatus(e,"viewable",!1),this.updateSlotStatus(e,"visible",!1),this.updateSlotStatus(e,"counter",t.toString())}show(){a.show(a.get("#__adLib-debug-dashboard"))}hide(){a.hide(a.get("#__adLib-debug-dashboard"))}}class L{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,i){Log.info("Create a catfish container");let n=`<div id="${L.CATFISH_ID}" class="__alCatfish" style=" ${e?`width:${e}px;`:""} ${i?`height:${i}px`:""}"></div>`;return a.insert(t.append,document.body,n),Log.info("Static Catfish Inserted",L.getCurrentCatfishElement()),L.getCurrentCatfishElement()}static getCurrentCatfishElement(){return a.get(`#${L.CATFISH_ID}`)}}class S{static providerClasses=new Map([[f.DFP,_]]);providers=new Map;timers=[];constructor(){o.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 g.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 user closes the consent manager"),g.setOnUserConsent((()=>{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 n=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(S.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);n.has(t.type)||n.set(t.type,[]),t.provider=i;let o=null;if(t.displayType==b.REGULAR)o=a.get(t.selector,e);else if(t.displayType==b.CATFISH){if(o=L.getCurrentCatfishElement(),o){let e=a.get(".__alAd",o).ad;e.provider.refreshAds([e]),Log.info("Catfish already exists, just refresh its ad");continue}o=L.newCatfish(),t.injector="append"}o?(t.$container=await i.createSlot(t,o),t.$container?(t.$container.ad=t,t.refreshCounter=0,t.rendered=!1,i.addAd(t),n.get(t.type).push(t),t.autoRefresh?(t.$container.isInViewPort=!1,t.refreshTimer=new l((()=>{S.timerCallback(t)}),1e3*__adLib.refreshTimer),t.provider.handlesViewability()||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,i.initialDisplay(t),t.refreshTimer&&t.refreshTimer.start()):(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)}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("Las`t ad is sticky",e),a.addClass(e,"__alSticky",__adLib.stickyAdClass)}}}isInViewPortObserver=new IntersectionObserver((e=>{e.forEach((e=>{let t=e.target;if(t.isInViewPort=e.intersectionRatio>=__adLib.viewportThreshold,t.isInViewPort){let e=t.ad;Log.info("Ad in viewport",e),e.rendered||(e.provider.initialDisplay(e),e.rendered=!0,e.refreshTimer.start()),e.provider.handlesViewability()?this.isInViewPortObserver.unobserve(t):S.resumeRefreshTimer(e)}else Log.info("Ad out of viewport -> stop timer",t.ad),S.pauseRefreshTimer(t.ad)}))}),{threshold:__adLib.viewportThreshold});static timerCallback(e){Log.info("Ad is refreshed.",e),e.refreshCounter++,e.provider.refreshAds([e])}static resumeRefreshTimer(e){e.refreshTimer&&(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){e.refreshTimer&&(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 n(o.isDefined(__adLib)?e[__adLib.logLevel]:e.None),Log.info("Ad Library Loaded - viewability test 6",String.fromCodePoint(128126)),__adLib.AdsManager=new S,__adLib.ConsentManager=g,__adLib.PrebidForVideo=u,__adLib.PrerollAd=h; | ||
//# sourceMappingURL=britannica-ads.cjs.js.map |
@@ -1,2 +0,2 @@ | ||
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 ONETRUST_COOKIE_NAME="OptanonAlertBoxClosed";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")}__adLib.usPrivacyConsent||r.isCookieExists(p.ONETRUST_COOKIE_NAME)||(Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2("OptanonWrapper called"),r.isCookieExists(p.ONETRUST_COOKIE_NAME)&&p.setOnUserConsent?(Log.info2("The consent manager popup was closed. Consent Manager callback will be called"),p.setDeferAdsStatus(!1)):Log.info2("The consent manager popup was not closed. Still waiting")},Log.info2("Defer the ads loading by default"),p.setDeferAdsStatus(!0))}else Log.info2("Not Consent Required")}static setDeferAdsStatus(e){__adLib.deferAds=e,e||p.userConsentCallback()}static userConsentCallback;static setOnUserConsent(e){p.userConsentCallback=e}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)&&n.isDefined(window.pbjs.requestBids))){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 0 auto;\n padding-bottom: 20px;\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 _ 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().setPrivacySettings({childDirectedTreatment:!1,underAgeOfConsent:!1}),__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((()=>{_.setPageLoadTargeting(this.ads),this.refreshSlots()}))}requestBids(e){this.refreshAds(e)}refreshAds(e){Log.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}`;Log.info(`Update ${_.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(_.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 m{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,i){Log.info("Create a catfish container");let o=`<div id="${m.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",m.getCurrentCatfishElement()),m.getCurrentCatfishElement()}static getCurrentCatfishElement(){return a.get(`#${m.CATFISH_ID}`)}}class L{static providerClasses=new Map([[h.DFP,_]]);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 user closes the consent manager"),p.setOnUserConsent((()=>{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=m.getCurrentCatfishElement(),n){let e=a.get(".__alAd",n).ad;e.provider.refreshAds([e]),Log.info("Catfish already exists, just refresh its ad");continue}n=m.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 ",String.fromCodePoint(128126)),__adLib.AdsManager=new L,__adLib.ConsentManager=p,__adLib.PrebidForVideo=f,__adLib.PrerollAd=u; | ||
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 n{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",n.ERR_STYLE);warning=console.warn.bind(window.console,"%cAd Lib",n.WARN_STYLE);debug;info;info2;level;constructor(t){this.level=t,this.info=e.Info>=this.level?console.log.bind(window.console,"%cAd Lib",n.INFO_STYLE):()=>null,this.info2=e.Info2>=this.level?console.log.bind(window.console,"%cAd Lib",n.INFO_STYLE2):()=>null,this.debug=e.Debug>=this.level?console.debug.bind(window.console,"%cAd Lib",n.DEBUG_STYLE):()=>null}getLevel(){return this.level}}class o{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,n)=>{let o=document.createElement("script");o.src=e,o.onload=()=>i(),o.onerror=()=>n();for(const[e,i]of Object.entries(t))o.setAttribute(e,i);document.head.append(o),window.Log.info(`Loaded: [${e}]`)}))}static css(e,t,i){e.style.setProperty(t,i)}static show(e){a.css(e,"display","block")}static hide(e){a.css(e,"display","none")}static addClass(e,...t){t.forEach((t=>{t&&e.classList.add(t)}))}static setClass(e,t){e.className=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,n)=>{i.forEach((i=>{i.isIntersecting&&(t(e),n.disconnect(),n=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 s{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 r{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,i=!1){if(!e||!t)return e;const n=i?e.lastIndexOf(t):e.indexOf(t);return-1==n?"":e.substring(n+1)}static substringAfterLast(e,t){return r.substringAfter(e,t,!0)}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()}getRemaining(){return this.remaining}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:s.readCookie(c.US_PrivacyCookieName)};Log.info2("IAB: getuspdata command. Response: ",e),i(e,null!=e.uspString)}},s.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,n){let o=e=>!0===e?"Y":!1===e?"N":"-",a=e.toString()+o(t)+o(i)+o(n),s=`${c.US_PrivacyCookieName}=${a}; `,r=new Date;r.setTime(r.getTime()+24*c.US_PrivacyCookieDuration*60*60*1e3);let d=`expires=${r.toUTCString()}; `;document.cookie=s+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 n=t.__uspapiCall;window.__uspapi(n.command,n.version,(function(t,o){let a={__uspapiReturn:{returnValue:t,success:o,callId:n.callId}},s=e.source;Log.info2("IAB: post message back ",a,s),s.postMessage(i?JSON.stringify(a):a,"*")}))}}}class g{static ONETRUST_COOKIE_NAME="OptanonAlertBoxClosed";static async init(){if(__adLib.requiresConsent){if(!o.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")}__adLib.usPrivacyConsent||s.isCookieExists(g.ONETRUST_COOKIE_NAME)||(Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2("OptanonWrapper called"),s.isCookieExists(g.ONETRUST_COOKIE_NAME)&&g.setOnUserConsent?(Log.info2("The consent manager popup was closed. Consent Manager callback will be called"),g.setDeferAdsStatus(!1)):Log.info2("The consent manager popup was not closed. Still waiting")},Log.info2("Defer the ads loading by default"),g.setDeferAdsStatus(!0))}else Log.info2("Not Consent Required")}static setDeferAdsStatus(e){__adLib.deferAds=e,e||g.userConsentCallback()}static userConsentCallback;static setOnUserConsent(e){g.userConsentCallback=e}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(s.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}]`),s.createCookieSession("OptanonConsent",encodeURI(t),__adLib.topDomain),s.createCookieSession("EbConsentClosed","true"),Log.info2("created new OptanonConsent and EbConsentClosed cookies")}}class p{static async loadPrebidScript(){if(!(__adLib.videoForPrebidLoaded||o.isDefined(window.pbjs)&&o.isDefined(window.pbjs.requestBids))){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 u{static setJwplayerSetupWithPrebid(t,i,n,o=!1){o||__adLib.showPrerollAdInVideos?(p.loadPrebidScript(),pbjs.que.push((()=>{let o=__adLib.prebidConfiguration;o.debug=Log.getLevel()==e.Debug,pbjs.setConfig(o),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 o=pbjs.adServers.dfp.buildVideoUrl({adUnit:__adLib.prebidVideoAdUnit,params:e});Log.info(`Bidding completed. Set URL in jwplayer setup and call callback: [${o}]`),i.advertising={client:"googima",adschedule:[{offset:"pre",tag:o}]},n()}})}))):n()}static addJwPlayerAdSetup(e,t){t.advertising={client:"googima",adschedule:[{offset:"pre",tag:e}]}}}class h{static CONTAINER_CLASS="__alPrerollContainer";static WRAPPER_CLASS="__alPrerollWrapper";static JWPLAYER_CONTAINER_ID="__alPreroll";static async createPreRollAd(e,i,n=(()=>{})){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 n();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 n();if(__adLib.prerollAdIsRunning=!0,!o.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 n()}}a.addClass(e,h.CONTAINER_CLASS),Log.info(`Insert preroll [${i}] Ad into`,e),a.insert(t.prepend,e,`<div class="${h.WRAPPER_CLASS}"><div id="${h.JWPLAYER_CONTAINER_ID}"></div></div>`);let s=a.get(`.${h.WRAPPER_CLASS}`,e),r={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};u.setJwplayerSetupWithPrebid(i,r,(()=>{Log.info("Prebid preroll completed. Init JWPlayer: ",r);let t=jwplayer(h.JWPLAYER_CONTAINER_ID);t.setup(r);const i=i=>{t&&(Log.info(`Preroll Ended. Cause: [${i}]. Will remove the player and its container`),t.remove(),t=null,a.remove(s),a.removeClass(e,h.CONTAINER_CLASS),__adLib.prerollAdIsRunning=!1,n())};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 f,b;!function(e,t){void 0===t&&(t={});var i=t.insertAt;if(e&&"undefined"!=typeof document){var n=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css","top"===i&&n.firstChild?n.insertBefore(o,n.firstChild):n.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.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 0 auto;\n padding-bottom: 20px;\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}\n\n/* debug */\n#__adLib-debug-dashboard {\n width: 100%;\n height: 250px;\n overflow-y: scroll;\n padding: 20px;\n position: fixed;\n top: 0;\n left: 0;\n z-index: 10000000000000;\n background-color: #fafafa;\n border-bottom: solid 2px black;\n font-size: 11px;\n}\n#__adLib-debug-dashboard table {\n background-color: white;\n width: 100%;\n color: black;\n font-family: monospace;\n}\n#__adLib-debug-dashboard table th {\n background-color: #f2f2f2;\n font-weight: bold;\n text-align: center;\n}\n#__adLib-debug-dashboard table th,\n#__adLib-debug-dashboard table td {\n padding: 3px 6px;\n}\n#__adLib-debug-dashboard table,\n#__adLib-debug-dashboard th,\n#__adLib-debug-dashboard td {\n border: solid 1px #888;\n}\n\n#__adLib-debug-close,\n#__adLib-debug-open {\n cursor: pointer;\n}\n\n#__adLib-debug-open {\n top: 1px;\n left: 1px;\n font-size: 10px;\n font-family: monospace;\n position: fixed;\n z-index: 1000000000000;\n}\n\n#__adLib-debug-close {\n top: 5px;\n right: 5px;\n font-weight: bold;\n position: absolute;\n}\n\n.__adLib-debug-no {\n background-color: orange;\n color: white;\n text-align: center;\n}\n\n.__adLib-debug-yes {\n background-color: green;\n color: white;\n text-align: center;\n}'),function(e){e.DFP="DFP"}(f||(f={}));!function(e){e.REGULAR="REGULAR",e.CATFISH="CATFISH"}(b||(b={}));class _ extends class{type;ads;constructor(){this.ads=[],this.type=this.getType()}addAd(e){this.ads.push(e)}}{static PAGELOAD_TARGETING="PAGELOAD";index=1;dfpAds=new Map;debugDashboard;getName(){return"Google DFP"}getType(){return f.DFP}constructor(){super()}async initProvider(){if(window.googletag={cmd:[]},!o.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),p.loadPrebidScript(),!o.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(!o.isDefined(window.apstag)&&__adLib.includeA9)try{await a.loadScript("https://c.amazon-adsystem.com/aax2/apstag.js"),function(e,t){function i(i,n){t[e]._Q.push([i,n])}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((()=>{if(googletag.pubads().setTargeting("dc_ref",__adLib.url),o.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().setPrivacySettings({childDirectedTreatment:!1,underAgeOfConsent:!1}),__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)}googletag.pubads().addEventListener("slotVisibilityChanged",(e=>{let t=this.dfpAds.get(e.slot.getSlotElementId());if(t.isFetching)return;let n=e.inViewPercentage,o=e.slot.getSlotElementId(),s=a.get(`#${o}`);s.isInViewPort=n>=50,this.updateDebugDashboard(o,"visible",s.isInViewPort),t.refreshTimer&&(s.isInViewPort?t.refreshTimer.state==i.PAUSED&&(Log.info("Ad is in viewport -> resume timer",t),t.refreshTimer.resume(),this.updateDebugDashboard(o,"timer",t.refreshTimer.state)):t.refreshTimer.state==i.RUNNING&&(Log.info("Ad is out of viewport -> pause timer",t),t.refreshTimer.pause(),this.updateDebugDashboard(o,"timer",`${t.refreshTimer.state} (${Math.round(t.refreshTimer.getRemaining()/1e3)}s)`)))})),googletag.pubads().addEventListener("slotOnload",(e=>{this.dfpAds.get(e.slot.getSlotElementId()).isFetching=!1}))})),Log.getLevel()!=e.None&&(this.debugDashboard=new m)}updateDebugDashboard(e,t,i){this.debugDashboard&&this.debugDashboard.updateSlotStatus(e,t,i)}createSlot(e,t){return this.initSlot(e,t)}initSlot(e,i){return new Promise((n=>{googletag.cmd.push((()=>{try{Log.info("process DFP ad: ",e);let o=e.adParameters,s=o.size[0][0],d=o.size[0][1];Log.info("Content container for this ad is ",i);let l="";if(e.displayType!=b.CATFISH)if(o.placeholderSize)l=`min-width:${r.substringBefore(o.placeholderSize,"x")}px;min-height:${r.substringAfter(o.placeholderSize,"x")}px;`;else if(1==o.size.length)l=`width:${s}px;height:${d}px;`;else{l=`min-height:${Math.round(o.size.map((e=>e[1])).reduce(((e,t)=>e+t))/o.size.length)}px;`}let c="DFP_"+this.index++;e.containerId=c,e.dfpSize=1==o.size.length?o.size[0]:o.size,e.isFetching=!1;let g=`style="${l}${r.defaultIfBlank(o.style,"")}"`,p=`<div data-type="${e.type}" class="__alAd ${r.defaultIfBlank(__adLib.adClass,"")} ${r.defaultIfBlank(o.cssClass,"")}" ${g} id="${c}"></div>`;Log.info(`Inject DIV: [${p}] into `,i),a.insert(t[e.injector],i,p);let u=this.setDfpA9Slot(e),h=a.get(`#${c}`);h.setAttribute("data-identifier",e.dfpSlot.getAdUnitPath()),h.setAttribute("data-qa-identifier",u),this.dfpAds.set(c,e),this.debugDashboard&&this.debugDashboard.addAd(e),n(h)}catch(t){Log.error("Init Slot Error: ",e,t),n(null)}}))}))}setDfpA9Slot=function(e){Log.info("Initializes DFP slot and A9 slot for ",e);let t=e.adParameters,i=__adLib.dfpIdPrefix.replace("${LEG}",__adLib.leg),n=`${__adLib.isPhone?"MOBILE":"DESKTOP"}_${t.id}`,o=`/${__adLib.googleDfpId}/${i}${n}`;return Log.info(`Define new slot: [${o}] with: size [${e.dfpSize}] id [${e.containerId}]`),e.dfpSlot=googletag.defineSlot(o,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:o,sizes:t.size}),Log.info("DFP/A9 slot defined for ",e),n};initialDisplay(e){Log.info("Ad Initial Display",e);let t=e.dfpSlot.getSlotElementId();this.updateDebugDashboard(t,"initial-load",!0),this.refreshAds([e]),e.autoRefresh&&this.updateDebugDashboard(t,"timer",i.RUNNING)}handlesViewability(){return!0}refreshAllAds(){Log.info("Refresh all DFP ads."),googletag.cmd.push((()=>{_.setPageLoadTargeting(this.ads),this.refreshSlots()}))}refreshAds(e){Log.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}`;Log.info(`Update ${_.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(_.PAGELOAD_TARGETING,e)}}refreshSlots(t=this.ads){Log.info("Refresh slots - ads : ",t);let i=!1,n=!1,o=!1,a=()=>{o||!n||!i&&__adLib.includeA9||(-1!=c&&window.clearTimeout(c),Log.info("Prebid is completed and A9 completed or disabled -> call DFP"),s())},s=()=>{Log.info("Refresh ads ",t);let e=t.map((e=>e.dfpSlot));Log.info("Refresh DFP slots ",e),t.forEach((e=>{this.debugDashboard&&this.debugDashboard.updateRefreshStatus(e.containerId,e.refreshCounter),e.isFetching=!0})),googletag.pubads().refresh(e)},r=[];for(let e of t)r.push({code:e.dfpSlot.getAdUnitPath(),mediaTypes:{banner:{sizes:e.adParameters.size}},bids:__adLib.prebidBannerBiddersConfiguration});Log.info("Prebid ad unit configuration: ",r);let d={...__adLib.prebidConfiguration,debug:Log.getLevel()==e.Debug,...g.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(r),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()))),n=!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"),o=!0,s()}),__adLib.biddersFailsafeTimeout))}}class m{$debugDashboard;constructor(){a.insert(t.append,document.body,'<button id="__adLib-debug-open">Ad Debug</button>\n <div id="__adLib-debug-dashboard">\n <div id="__adLib-debug-close">X</div>\n <table>\n <thead>\n <tr>\n <th>DIV</th>\n <th>GPT Path</th>\n <th>Type</th>\n <th>Initial Load</th>\n <th>Fetched</th>\n <th>Rendered</th>\n <th>Rfsh Viewable</th>\n <th>Visible</th>\n <th>Refreshing</th>\n <th>Counter</th>\n <th>Timer</th>\n </tr>\n </thead>\n <tbody></tbody>\n </table>\n </div>'),this.$debugDashboard=a.get("#__adLib-debug-dashboard tbody"),a.setEventListener(a.get("#__adLib-debug-close"),"click",this.hide),a.setEventListener(a.get("#__adLib-debug-open"),"click",this.show),googletag.cmd.push((()=>{googletag.pubads().addEventListener("slotRequested",(e=>{this.updateSlotStatus(e.slot.getSlotElementId(),"fetched",!0),this.updateSlotStatus(e.slot.getSlotElementId(),"refreshing",!1)})),googletag.pubads().addEventListener("slotOnload",(e=>{this.updateSlotStatus(e.slot.getSlotElementId(),"rendered",!0)})),googletag.pubads().addEventListener("impressionViewable",(e=>{this.updateSlotStatus(e.slot.getSlotElementId(),"viewable",!0)}))}))}addAd(e){let i=e.dfpSlot.getSlotElementId(),n=r.substringAfterLast(e.dfpSlot.getAdUnitPath(),"/");a.insert(t.append,this.$debugDashboard,`<tr>\n <td><a href="#${i}">${i}</a></td>\n <td>${n}</td>\n <td>${e.displayType}</td>\n <td id="__adLib-debug-initial-load-${i}"></td>\n <td id="__adLib-debug-fetched-${i}"></td>\n <td id="__adLib-debug-rendered-${i}"></td>\n <td id="__adLib-debug-viewable-${i}"></td>\n <td id="__adLib-debug-visible-${i}"></td>\n <td id="__adLib-debug-refreshing-${i}"></td>\n <td id="__adLib-debug-counter-${i}"></td>\n <td id="__adLib-debug-timer-${i}"></td>\n </tr>`),this.resetSlotStatus(i),this.updateSlotStatus(i,"timer",e.refreshTimer?e.refreshTimer.state:"N/A")}updateSlotStatus(e,t,i){let n=a.get(`#__adLib-debug-${t}-${e}`);n?"boolean"==typeof i?(a.setClass(n,"__adLib-debug-"+(i?"yes":"no")),n.innerText=i?"YES":"NO"):n.innerText=i:Log.error(`Unknown AD : [${e}] - [${t}]`)}resetSlotStatus(e){this.updateSlotStatus(e,"initial-load",!1),this.updateSlotStatus(e,"fetched",!1),this.updateSlotStatus(e,"rendered",!1),this.updateSlotStatus(e,"viewable",!1),this.updateSlotStatus(e,"visible",!1),this.updateSlotStatus(e,"refreshing",!1),this.updateSlotStatus(e,"counter","0")}updateRefreshStatus(e,t){this.updateSlotStatus(e,"refreshing",!0),this.updateSlotStatus(e,"fetched",!1),this.updateSlotStatus(e,"rendered",!1),this.updateSlotStatus(e,"viewable",!1),this.updateSlotStatus(e,"visible",!1),this.updateSlotStatus(e,"counter",t.toString())}show(){a.show(a.get("#__adLib-debug-dashboard"))}hide(){a.hide(a.get("#__adLib-debug-dashboard"))}}class L{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,i){Log.info("Create a catfish container");let n=`<div id="${L.CATFISH_ID}" class="__alCatfish" style=" ${e?`width:${e}px;`:""} ${i?`height:${i}px`:""}"></div>`;return a.insert(t.append,document.body,n),Log.info("Static Catfish Inserted",L.getCurrentCatfishElement()),L.getCurrentCatfishElement()}static getCurrentCatfishElement(){return a.get(`#${L.CATFISH_ID}`)}}class S{static providerClasses=new Map([[f.DFP,_]]);providers=new Map;timers=[];constructor(){o.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 g.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 user closes the consent manager"),g.setOnUserConsent((()=>{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 n=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(S.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);n.has(t.type)||n.set(t.type,[]),t.provider=i;let o=null;if(t.displayType==b.REGULAR)o=a.get(t.selector,e);else if(t.displayType==b.CATFISH){if(o=L.getCurrentCatfishElement(),o){let e=a.get(".__alAd",o).ad;e.provider.refreshAds([e]),Log.info("Catfish already exists, just refresh its ad");continue}o=L.newCatfish(),t.injector="append"}o?(t.$container=await i.createSlot(t,o),t.$container?(t.$container.ad=t,t.refreshCounter=0,t.rendered=!1,i.addAd(t),n.get(t.type).push(t),t.autoRefresh?(t.$container.isInViewPort=!1,t.refreshTimer=new l((()=>{S.timerCallback(t)}),1e3*__adLib.refreshTimer),t.provider.handlesViewability()||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,i.initialDisplay(t),t.refreshTimer&&t.refreshTimer.start()):(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)}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("Las`t ad is sticky",e),a.addClass(e,"__alSticky",__adLib.stickyAdClass)}}}isInViewPortObserver=new IntersectionObserver((e=>{e.forEach((e=>{let t=e.target;if(t.isInViewPort=e.intersectionRatio>=__adLib.viewportThreshold,t.isInViewPort){let e=t.ad;Log.info("Ad in viewport",e),e.rendered||(e.provider.initialDisplay(e),e.rendered=!0,e.refreshTimer.start()),e.provider.handlesViewability()?this.isInViewPortObserver.unobserve(t):S.resumeRefreshTimer(e)}else Log.info("Ad out of viewport -> stop timer",t.ad),S.pauseRefreshTimer(t.ad)}))}),{threshold:__adLib.viewportThreshold});static timerCallback(e){Log.info("Ad is refreshed.",e),e.refreshCounter++,e.provider.refreshAds([e])}static resumeRefreshTimer(e){e.refreshTimer&&(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){e.refreshTimer&&(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 n(o.isDefined(__adLib)?e[__adLib.logLevel]:e.None),Log.info("Ad Library Loaded - viewability test 6",String.fromCodePoint(128126)),__adLib.AdsManager=new S,__adLib.ConsentManager=g,__adLib.PrebidForVideo=u,__adLib.PrerollAd=h; | ||
//# sourceMappingURL=britannica-ads.esm.js.map |
@@ -1,2 +0,2 @@ | ||
!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 ONETRUST_COOKIE_NAME="OptanonAlertBoxClosed";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")}__adLib.usPrivacyConsent||r.isCookieExists(p.ONETRUST_COOKIE_NAME)||(Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2("OptanonWrapper called"),r.isCookieExists(p.ONETRUST_COOKIE_NAME)&&p.setOnUserConsent?(Log.info2("The consent manager popup was closed. Consent Manager callback will be called"),p.setDeferAdsStatus(!1)):Log.info2("The consent manager popup was not closed. Still waiting")},Log.info2("Defer the ads loading by default"),p.setDeferAdsStatus(!0))}else Log.info2("Not Consent Required")}static setDeferAdsStatus(e){__adLib.deferAds=e,e||p.userConsentCallback()}static userConsentCallback;static setOnUserConsent(e){p.userConsentCallback=e}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)&&n.isDefined(window.pbjs.requestBids))){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 0 auto;\n padding-bottom: 20px;\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 _ 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().setPrivacySettings({childDirectedTreatment:!1,underAgeOfConsent:!1}),__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((()=>{_.setPageLoadTargeting(this.ads),this.refreshSlots()}))}requestBids(e){this.refreshAds(e)}refreshAds(e){Log.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}`;Log.info(`Update ${_.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(_.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 m{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,i){Log.info("Create a catfish container");let o=`<div id="${m.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",m.getCurrentCatfishElement()),m.getCurrentCatfishElement()}static getCurrentCatfishElement(){return a.get(`#${m.CATFISH_ID}`)}}class L{static providerClasses=new Map([[h.DFP,_]]);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 user closes the consent manager"),p.setOnUserConsent((()=>{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=m.getCurrentCatfishElement(),n){let e=a.get(".__alAd",n).ad;e.provider.refreshAds([e]),Log.info("Catfish already exists, just refresh its ad");continue}n=m.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 ",String.fromCodePoint(128126)),__adLib.AdsManager=new L,__adLib.ConsentManager=p,__adLib.PrebidForVideo=f,__adLib.PrerollAd=u})); | ||
!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 n{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",n.ERR_STYLE);warning=console.warn.bind(window.console,"%cAd Lib",n.WARN_STYLE);debug;info;info2;level;constructor(t){this.level=t,this.info=e.Info>=this.level?console.log.bind(window.console,"%cAd Lib",n.INFO_STYLE):()=>null,this.info2=e.Info2>=this.level?console.log.bind(window.console,"%cAd Lib",n.INFO_STYLE2):()=>null,this.debug=e.Debug>=this.level?console.debug.bind(window.console,"%cAd Lib",n.DEBUG_STYLE):()=>null}getLevel(){return this.level}}class o{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,n)=>{let o=document.createElement("script");o.src=e,o.onload=()=>i(),o.onerror=()=>n();for(const[e,i]of Object.entries(t))o.setAttribute(e,i);document.head.append(o),window.Log.info(`Loaded: [${e}]`)}))}static css(e,t,i){e.style.setProperty(t,i)}static show(e){a.css(e,"display","block")}static hide(e){a.css(e,"display","none")}static addClass(e,...t){t.forEach((t=>{t&&e.classList.add(t)}))}static setClass(e,t){e.className=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,n)=>{i.forEach((i=>{i.isIntersecting&&(t(e),n.disconnect(),n=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 s{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 r{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,i=!1){if(!e||!t)return e;const n=i?e.lastIndexOf(t):e.indexOf(t);return-1==n?"":e.substring(n+1)}static substringAfterLast(e,t){return r.substringAfter(e,t,!0)}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()}getRemaining(){return this.remaining}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:s.readCookie(c.US_PrivacyCookieName)};Log.info2("IAB: getuspdata command. Response: ",e),i(e,null!=e.uspString)}},s.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,n){let o=e=>!0===e?"Y":!1===e?"N":"-",a=e.toString()+o(t)+o(i)+o(n),s=`${c.US_PrivacyCookieName}=${a}; `,r=new Date;r.setTime(r.getTime()+24*c.US_PrivacyCookieDuration*60*60*1e3);let d=`expires=${r.toUTCString()}; `;document.cookie=s+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 n=t.__uspapiCall;window.__uspapi(n.command,n.version,(function(t,o){let a={__uspapiReturn:{returnValue:t,success:o,callId:n.callId}},s=e.source;Log.info2("IAB: post message back ",a,s),s.postMessage(i?JSON.stringify(a):a,"*")}))}}}class g{static ONETRUST_COOKIE_NAME="OptanonAlertBoxClosed";static async init(){if(__adLib.requiresConsent){if(!o.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")}__adLib.usPrivacyConsent||s.isCookieExists(g.ONETRUST_COOKIE_NAME)||(Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2("OptanonWrapper called"),s.isCookieExists(g.ONETRUST_COOKIE_NAME)&&g.setOnUserConsent?(Log.info2("The consent manager popup was closed. Consent Manager callback will be called"),g.setDeferAdsStatus(!1)):Log.info2("The consent manager popup was not closed. Still waiting")},Log.info2("Defer the ads loading by default"),g.setDeferAdsStatus(!0))}else Log.info2("Not Consent Required")}static setDeferAdsStatus(e){__adLib.deferAds=e,e||g.userConsentCallback()}static userConsentCallback;static setOnUserConsent(e){g.userConsentCallback=e}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(s.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}]`),s.createCookieSession("OptanonConsent",encodeURI(t),__adLib.topDomain),s.createCookieSession("EbConsentClosed","true"),Log.info2("created new OptanonConsent and EbConsentClosed cookies")}}class p{static async loadPrebidScript(){if(!(__adLib.videoForPrebidLoaded||o.isDefined(window.pbjs)&&o.isDefined(window.pbjs.requestBids))){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 u{static setJwplayerSetupWithPrebid(t,i,n,o=!1){o||__adLib.showPrerollAdInVideos?(p.loadPrebidScript(),pbjs.que.push((()=>{let o=__adLib.prebidConfiguration;o.debug=Log.getLevel()==e.Debug,pbjs.setConfig(o),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 o=pbjs.adServers.dfp.buildVideoUrl({adUnit:__adLib.prebidVideoAdUnit,params:e});Log.info(`Bidding completed. Set URL in jwplayer setup and call callback: [${o}]`),i.advertising={client:"googima",adschedule:[{offset:"pre",tag:o}]},n()}})}))):n()}static addJwPlayerAdSetup(e,t){t.advertising={client:"googima",adschedule:[{offset:"pre",tag:e}]}}}class f{static CONTAINER_CLASS="__alPrerollContainer";static WRAPPER_CLASS="__alPrerollWrapper";static JWPLAYER_CONTAINER_ID="__alPreroll";static async createPreRollAd(e,i,n=(()=>{})){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 n();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 n();if(__adLib.prerollAdIsRunning=!0,!o.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 n()}}a.addClass(e,f.CONTAINER_CLASS),Log.info(`Insert preroll [${i}] Ad into`,e),a.insert(t.prepend,e,`<div class="${f.WRAPPER_CLASS}"><div id="${f.JWPLAYER_CONTAINER_ID}"></div></div>`);let s=a.get(`.${f.WRAPPER_CLASS}`,e),r={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};u.setJwplayerSetupWithPrebid(i,r,(()=>{Log.info("Prebid preroll completed. Init JWPlayer: ",r);let t=jwplayer(f.JWPLAYER_CONTAINER_ID);t.setup(r);const i=i=>{t&&(Log.info(`Preroll Ended. Cause: [${i}]. Will remove the player and its container`),t.remove(),t=null,a.remove(s),a.removeClass(e,f.CONTAINER_CLASS),__adLib.prerollAdIsRunning=!1,n())};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 n=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css","top"===i&&n.firstChild?n.insertBefore(o,n.firstChild):n.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.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 0 auto;\n padding-bottom: 20px;\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}\n\n/* debug */\n#__adLib-debug-dashboard {\n width: 100%;\n height: 250px;\n overflow-y: scroll;\n padding: 20px;\n position: fixed;\n top: 0;\n left: 0;\n z-index: 10000000000000;\n background-color: #fafafa;\n border-bottom: solid 2px black;\n font-size: 11px;\n}\n#__adLib-debug-dashboard table {\n background-color: white;\n width: 100%;\n color: black;\n font-family: monospace;\n}\n#__adLib-debug-dashboard table th {\n background-color: #f2f2f2;\n font-weight: bold;\n text-align: center;\n}\n#__adLib-debug-dashboard table th,\n#__adLib-debug-dashboard table td {\n padding: 3px 6px;\n}\n#__adLib-debug-dashboard table,\n#__adLib-debug-dashboard th,\n#__adLib-debug-dashboard td {\n border: solid 1px #888;\n}\n\n#__adLib-debug-close,\n#__adLib-debug-open {\n cursor: pointer;\n}\n\n#__adLib-debug-open {\n top: 1px;\n left: 1px;\n font-size: 10px;\n font-family: monospace;\n position: fixed;\n z-index: 1000000000000;\n}\n\n#__adLib-debug-close {\n top: 5px;\n right: 5px;\n font-weight: bold;\n position: absolute;\n}\n\n.__adLib-debug-no {\n background-color: orange;\n color: white;\n text-align: center;\n}\n\n.__adLib-debug-yes {\n background-color: green;\n color: white;\n text-align: center;\n}'),function(e){e.DFP="DFP"}(h||(h={}));!function(e){e.REGULAR="REGULAR",e.CATFISH="CATFISH"}(b||(b={}));class _ extends class{type;ads;constructor(){this.ads=[],this.type=this.getType()}addAd(e){this.ads.push(e)}}{static PAGELOAD_TARGETING="PAGELOAD";index=1;dfpAds=new Map;debugDashboard;getName(){return"Google DFP"}getType(){return h.DFP}constructor(){super()}async initProvider(){if(window.googletag={cmd:[]},!o.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),p.loadPrebidScript(),!o.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(!o.isDefined(window.apstag)&&__adLib.includeA9)try{await a.loadScript("https://c.amazon-adsystem.com/aax2/apstag.js"),function(e,t){function i(i,n){t[e]._Q.push([i,n])}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((()=>{if(googletag.pubads().setTargeting("dc_ref",__adLib.url),o.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().setPrivacySettings({childDirectedTreatment:!1,underAgeOfConsent:!1}),__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)}googletag.pubads().addEventListener("slotVisibilityChanged",(e=>{let t=this.dfpAds.get(e.slot.getSlotElementId());if(t.isFetching)return;let n=e.inViewPercentage,o=e.slot.getSlotElementId(),s=a.get(`#${o}`);s.isInViewPort=n>=50,this.updateDebugDashboard(o,"visible",s.isInViewPort),t.refreshTimer&&(s.isInViewPort?t.refreshTimer.state==i.PAUSED&&(Log.info("Ad is in viewport -> resume timer",t),t.refreshTimer.resume(),this.updateDebugDashboard(o,"timer",t.refreshTimer.state)):t.refreshTimer.state==i.RUNNING&&(Log.info("Ad is out of viewport -> pause timer",t),t.refreshTimer.pause(),this.updateDebugDashboard(o,"timer",`${t.refreshTimer.state} (${Math.round(t.refreshTimer.getRemaining()/1e3)}s)`)))})),googletag.pubads().addEventListener("slotOnload",(e=>{this.dfpAds.get(e.slot.getSlotElementId()).isFetching=!1}))})),Log.getLevel()!=e.None&&(this.debugDashboard=new m)}updateDebugDashboard(e,t,i){this.debugDashboard&&this.debugDashboard.updateSlotStatus(e,t,i)}createSlot(e,t){return this.initSlot(e,t)}initSlot(e,i){return new Promise((n=>{googletag.cmd.push((()=>{try{Log.info("process DFP ad: ",e);let o=e.adParameters,s=o.size[0][0],d=o.size[0][1];Log.info("Content container for this ad is ",i);let l="";if(e.displayType!=b.CATFISH)if(o.placeholderSize)l=`min-width:${r.substringBefore(o.placeholderSize,"x")}px;min-height:${r.substringAfter(o.placeholderSize,"x")}px;`;else if(1==o.size.length)l=`width:${s}px;height:${d}px;`;else{l=`min-height:${Math.round(o.size.map((e=>e[1])).reduce(((e,t)=>e+t))/o.size.length)}px;`}let c="DFP_"+this.index++;e.containerId=c,e.dfpSize=1==o.size.length?o.size[0]:o.size,e.isFetching=!1;let g=`style="${l}${r.defaultIfBlank(o.style,"")}"`,p=`<div data-type="${e.type}" class="__alAd ${r.defaultIfBlank(__adLib.adClass,"")} ${r.defaultIfBlank(o.cssClass,"")}" ${g} id="${c}"></div>`;Log.info(`Inject DIV: [${p}] into `,i),a.insert(t[e.injector],i,p);let u=this.setDfpA9Slot(e),f=a.get(`#${c}`);f.setAttribute("data-identifier",e.dfpSlot.getAdUnitPath()),f.setAttribute("data-qa-identifier",u),this.dfpAds.set(c,e),this.debugDashboard&&this.debugDashboard.addAd(e),n(f)}catch(t){Log.error("Init Slot Error: ",e,t),n(null)}}))}))}setDfpA9Slot=function(e){Log.info("Initializes DFP slot and A9 slot for ",e);let t=e.adParameters,i=__adLib.dfpIdPrefix.replace("${LEG}",__adLib.leg),n=`${__adLib.isPhone?"MOBILE":"DESKTOP"}_${t.id}`,o=`/${__adLib.googleDfpId}/${i}${n}`;return Log.info(`Define new slot: [${o}] with: size [${e.dfpSize}] id [${e.containerId}]`),e.dfpSlot=googletag.defineSlot(o,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:o,sizes:t.size}),Log.info("DFP/A9 slot defined for ",e),n};initialDisplay(e){Log.info("Ad Initial Display",e);let t=e.dfpSlot.getSlotElementId();this.updateDebugDashboard(t,"initial-load",!0),this.refreshAds([e]),e.autoRefresh&&this.updateDebugDashboard(t,"timer",i.RUNNING)}handlesViewability(){return!0}refreshAllAds(){Log.info("Refresh all DFP ads."),googletag.cmd.push((()=>{_.setPageLoadTargeting(this.ads),this.refreshSlots()}))}refreshAds(e){Log.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}`;Log.info(`Update ${_.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(_.PAGELOAD_TARGETING,e)}}refreshSlots(t=this.ads){Log.info("Refresh slots - ads : ",t);let i=!1,n=!1,o=!1,a=()=>{o||!n||!i&&__adLib.includeA9||(-1!=c&&window.clearTimeout(c),Log.info("Prebid is completed and A9 completed or disabled -> call DFP"),s())},s=()=>{Log.info("Refresh ads ",t);let e=t.map((e=>e.dfpSlot));Log.info("Refresh DFP slots ",e),t.forEach((e=>{this.debugDashboard&&this.debugDashboard.updateRefreshStatus(e.containerId,e.refreshCounter),e.isFetching=!0})),googletag.pubads().refresh(e)},r=[];for(let e of t)r.push({code:e.dfpSlot.getAdUnitPath(),mediaTypes:{banner:{sizes:e.adParameters.size}},bids:__adLib.prebidBannerBiddersConfiguration});Log.info("Prebid ad unit configuration: ",r);let d={...__adLib.prebidConfiguration,debug:Log.getLevel()==e.Debug,...g.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(r),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()))),n=!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"),o=!0,s()}),__adLib.biddersFailsafeTimeout))}}class m{$debugDashboard;constructor(){a.insert(t.append,document.body,'<button id="__adLib-debug-open">Ad Debug</button>\n <div id="__adLib-debug-dashboard">\n <div id="__adLib-debug-close">X</div>\n <table>\n <thead>\n <tr>\n <th>DIV</th>\n <th>GPT Path</th>\n <th>Type</th>\n <th>Initial Load</th>\n <th>Fetched</th>\n <th>Rendered</th>\n <th>Rfsh Viewable</th>\n <th>Visible</th>\n <th>Refreshing</th>\n <th>Counter</th>\n <th>Timer</th>\n </tr>\n </thead>\n <tbody></tbody>\n </table>\n </div>'),this.$debugDashboard=a.get("#__adLib-debug-dashboard tbody"),a.setEventListener(a.get("#__adLib-debug-close"),"click",this.hide),a.setEventListener(a.get("#__adLib-debug-open"),"click",this.show),googletag.cmd.push((()=>{googletag.pubads().addEventListener("slotRequested",(e=>{this.updateSlotStatus(e.slot.getSlotElementId(),"fetched",!0),this.updateSlotStatus(e.slot.getSlotElementId(),"refreshing",!1)})),googletag.pubads().addEventListener("slotOnload",(e=>{this.updateSlotStatus(e.slot.getSlotElementId(),"rendered",!0)})),googletag.pubads().addEventListener("impressionViewable",(e=>{this.updateSlotStatus(e.slot.getSlotElementId(),"viewable",!0)}))}))}addAd(e){let i=e.dfpSlot.getSlotElementId(),n=r.substringAfterLast(e.dfpSlot.getAdUnitPath(),"/");a.insert(t.append,this.$debugDashboard,`<tr>\n <td><a href="#${i}">${i}</a></td>\n <td>${n}</td>\n <td>${e.displayType}</td>\n <td id="__adLib-debug-initial-load-${i}"></td>\n <td id="__adLib-debug-fetched-${i}"></td>\n <td id="__adLib-debug-rendered-${i}"></td>\n <td id="__adLib-debug-viewable-${i}"></td>\n <td id="__adLib-debug-visible-${i}"></td>\n <td id="__adLib-debug-refreshing-${i}"></td>\n <td id="__adLib-debug-counter-${i}"></td>\n <td id="__adLib-debug-timer-${i}"></td>\n </tr>`),this.resetSlotStatus(i),this.updateSlotStatus(i,"timer",e.refreshTimer?e.refreshTimer.state:"N/A")}updateSlotStatus(e,t,i){let n=a.get(`#__adLib-debug-${t}-${e}`);n?"boolean"==typeof i?(a.setClass(n,"__adLib-debug-"+(i?"yes":"no")),n.innerText=i?"YES":"NO"):n.innerText=i:Log.error(`Unknown AD : [${e}] - [${t}]`)}resetSlotStatus(e){this.updateSlotStatus(e,"initial-load",!1),this.updateSlotStatus(e,"fetched",!1),this.updateSlotStatus(e,"rendered",!1),this.updateSlotStatus(e,"viewable",!1),this.updateSlotStatus(e,"visible",!1),this.updateSlotStatus(e,"refreshing",!1),this.updateSlotStatus(e,"counter","0")}updateRefreshStatus(e,t){this.updateSlotStatus(e,"refreshing",!0),this.updateSlotStatus(e,"fetched",!1),this.updateSlotStatus(e,"rendered",!1),this.updateSlotStatus(e,"viewable",!1),this.updateSlotStatus(e,"visible",!1),this.updateSlotStatus(e,"counter",t.toString())}show(){a.show(a.get("#__adLib-debug-dashboard"))}hide(){a.hide(a.get("#__adLib-debug-dashboard"))}}class L{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,i){Log.info("Create a catfish container");let n=`<div id="${L.CATFISH_ID}" class="__alCatfish" style=" ${e?`width:${e}px;`:""} ${i?`height:${i}px`:""}"></div>`;return a.insert(t.append,document.body,n),Log.info("Static Catfish Inserted",L.getCurrentCatfishElement()),L.getCurrentCatfishElement()}static getCurrentCatfishElement(){return a.get(`#${L.CATFISH_ID}`)}}class S{static providerClasses=new Map([[h.DFP,_]]);providers=new Map;timers=[];constructor(){o.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 g.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 user closes the consent manager"),g.setOnUserConsent((()=>{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 n=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(S.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);n.has(t.type)||n.set(t.type,[]),t.provider=i;let o=null;if(t.displayType==b.REGULAR)o=a.get(t.selector,e);else if(t.displayType==b.CATFISH){if(o=L.getCurrentCatfishElement(),o){let e=a.get(".__alAd",o).ad;e.provider.refreshAds([e]),Log.info("Catfish already exists, just refresh its ad");continue}o=L.newCatfish(),t.injector="append"}o?(t.$container=await i.createSlot(t,o),t.$container?(t.$container.ad=t,t.refreshCounter=0,t.rendered=!1,i.addAd(t),n.get(t.type).push(t),t.autoRefresh?(t.$container.isInViewPort=!1,t.refreshTimer=new l((()=>{S.timerCallback(t)}),1e3*__adLib.refreshTimer),t.provider.handlesViewability()||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,i.initialDisplay(t),t.refreshTimer&&t.refreshTimer.start()):(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)}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("Las`t ad is sticky",e),a.addClass(e,"__alSticky",__adLib.stickyAdClass)}}}isInViewPortObserver=new IntersectionObserver((e=>{e.forEach((e=>{let t=e.target;if(t.isInViewPort=e.intersectionRatio>=__adLib.viewportThreshold,t.isInViewPort){let e=t.ad;Log.info("Ad in viewport",e),e.rendered||(e.provider.initialDisplay(e),e.rendered=!0,e.refreshTimer.start()),e.provider.handlesViewability()?this.isInViewPortObserver.unobserve(t):S.resumeRefreshTimer(e)}else Log.info("Ad out of viewport -> stop timer",t.ad),S.pauseRefreshTimer(t.ad)}))}),{threshold:__adLib.viewportThreshold});static timerCallback(e){Log.info("Ad is refreshed.",e),e.refreshCounter++,e.provider.refreshAds([e])}static resumeRefreshTimer(e){e.refreshTimer&&(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){e.refreshTimer&&(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 n(o.isDefined(__adLib)?e[__adLib.logLevel]:e.None),Log.info("Ad Library Loaded - viewability test 6",String.fromCodePoint(128126)),__adLib.AdsManager=new S,__adLib.ConsentManager=g,__adLib.PrebidForVideo=u,__adLib.PrerollAd=f})); | ||
//# sourceMappingURL=britannica-ads.umd.js.map |
@@ -23,2 +23,3 @@ import { IntervalTimer } from '../helpers'; | ||
injector?: string; | ||
rendered: boolean; | ||
} |
@@ -39,3 +39,6 @@ export declare type callbackFunction = () => void; | ||
static css($element: HTMLElement, style: string, value: string): void; | ||
static show($element: HTMLElement): void; | ||
static hide($element: HTMLElement): void; | ||
static addClass($element: HTMLElement, ...className: string[]): void; | ||
static setClass($element: HTMLElement, className: string): void; | ||
static removeClass($element: HTMLElement, className: string): void; | ||
@@ -61,3 +64,4 @@ static onDocumentReady(callback: callbackFunction): void; | ||
static substringBefore(s: string, s2: string): string; | ||
static substringAfter(s: string, s2: string): string; | ||
static substringAfter(s: string, s2: string, afterLast?: boolean): string; | ||
static substringAfterLast(s: string, s2: string): string; | ||
static defaultIfBlank(o: string, def: string): string; | ||
@@ -92,4 +96,5 @@ } | ||
restart(): void; | ||
getRemaining(): number; | ||
private stopInternalTimer; | ||
private stopResumeTimer; | ||
} |
@@ -14,5 +14,6 @@ import { IAd } from '../common/types'; | ||
abstract createSlot(ad: IAd, $adContainer: HTMLElement): Promise<HTMLElement>; | ||
abstract requestBids(ads: IAd[]): void; | ||
abstract initialDisplay(ad: IAd): void; | ||
abstract refreshAds(ads: IAd[]): void; | ||
abstract refreshAllAds(): void; | ||
abstract handlesViewability(): boolean; | ||
} |
@@ -29,2 +29,3 @@ /// <reference types="googletag" /> | ||
dfpSlot: googletag.Slot; | ||
isFetching: boolean; | ||
adParameters: { | ||
@@ -43,2 +44,4 @@ size?: googletag.MultiSize; | ||
private index; | ||
private dfpAds; | ||
private debugDashboard; | ||
getName(): string; | ||
@@ -48,7 +51,9 @@ getType(): ProviderType; | ||
initProvider(): Promise<void>; | ||
private updateDebugDashboard; | ||
createSlot(ad: IAd, $container: HTMLElement): Promise<HTMLElement>; | ||
private initSlot; | ||
private setDfpA9Slot; | ||
initialDisplay(ad: IAd): void; | ||
handlesViewability(): boolean; | ||
refreshAllAds(): void; | ||
requestBids(ads: IAd[]): void; | ||
refreshAds(ads: IdfpAd[]): void; | ||
@@ -55,0 +60,0 @@ private static setPageLoadTargeting; |
{ | ||
"name": "@britannica/ads", | ||
"version": "1.0.1", | ||
"version": "1.1.0-beta.1", | ||
"description": "Britannica and MW ad library", | ||
@@ -72,3 +72,3 @@ "main": "dist/britannica-ads.cjs.js", | ||
"babel-plugin-dev-expression": "^0.2.3", | ||
"husky": "^7.0.0", | ||
"husky": "8.0.1", | ||
"prettier": "^2.6.2", | ||
@@ -75,0 +75,0 @@ "pretty-quick": "^3.1.3", |
{ | ||
"extends": ["config:base", "schedule:monthly"], | ||
"baseBranches": ["master"], | ||
"baseBranches": ["dev"], | ||
"packageRules": [ | ||
{ | ||
"matchDatasources": ["npm"], | ||
"matchDepTypes": ["devDependencies"], | ||
"matchUpdateTypes": ["patch", "minor"], | ||
"groupName": "package.json dependencies (non-major)", | ||
"groupSlug": "js-dependencies" | ||
"groupName": "devDependencies (non-major)", | ||
"groupSlug": "dev-dependencies" | ||
}, | ||
{ | ||
"matchDepTypes": ["dependencies"], | ||
"matchUpdateTypes": ["patch", "minor"], | ||
"groupName": "dependencies (non-major)", | ||
"groupSlug": "dependencies" | ||
} | ||
], | ||
"js": { | ||
"reviewers": ["ebtschembri", "arminbro", "ryanwalters"] | ||
} | ||
] | ||
} |
@@ -214,2 +214,3 @@ import { Iab } from './consentmanagers/iab'; | ||
ad.refreshCounter = 0; | ||
ad.rendered = false; | ||
@@ -232,3 +233,5 @@ // --------------------------------------------------- | ||
}, __adLib.refreshTimer * 1000); | ||
this.timers.push(ad.refreshTimer); | ||
if (!ad.provider.handlesViewability()) { | ||
this.timers.push(ad.refreshTimer); | ||
} | ||
Log.info('This ad is autorefresh, added refresh timer: ', ad.refreshTimer); | ||
@@ -248,6 +251,7 @@ } else { | ||
ad.$container.isInViewPort = true; // catfish are always in viewport | ||
adProvider.initialDisplay(ad); | ||
if (ad.refreshTimer) { | ||
ad.refreshTimer.start(); | ||
} | ||
} else if (ad.autoRefresh) { | ||
} else { | ||
Log.info('Add the ad container to the observer -> ', ad.$container); | ||
@@ -263,15 +267,2 @@ this.isInViewPortObserver.observe(ad.$container); | ||
// -------------------------------------------------------------------------------------------------------------------- | ||
// bid request for each provider | ||
// -------------------------------------------------------------------------------------------------------------------- | ||
for (let [providerType, ads] of adsMap) { | ||
if (ads.length == 0) { | ||
Log.info(`No ads for [${providerType}] provider`); | ||
} else { | ||
Log.info(`Request Bids for [${providerType}] provider: `, ads); | ||
this.providers.get(providerType).requestBids(ads); | ||
} | ||
} | ||
// -------------------------------------------------------------------------------------------------------------------- | ||
// make the last right rail ad sticky (if any) | ||
@@ -285,3 +276,3 @@ // -------------------------------------------------------------------------------------------------------------------- | ||
let $stickyAd = $rrAds.item(l - 1); | ||
Log.info('Last ad is sticky', $stickyAd); | ||
Log.info('Las`t ad is sticky', $stickyAd); | ||
alDOM.addClass($stickyAd, '__alSticky', __adLib.stickyAdClass); | ||
@@ -306,4 +297,14 @@ } | ||
if ($adContainer.isInViewPort) { | ||
Log.info('Ad in viewport -> resume timer', $adContainer.ad); | ||
AdsManager.resumeRefreshTimer($adContainer.ad); | ||
let ad = $adContainer.ad; | ||
Log.info('Ad in viewport', ad); | ||
if (!ad.rendered) { | ||
ad.provider.initialDisplay(ad); | ||
ad.rendered = true; | ||
ad.refreshTimer.start(); | ||
} | ||
if (ad.provider.handlesViewability()) { | ||
this.isInViewPortObserver.unobserve($adContainer); | ||
} else { | ||
AdsManager.resumeRefreshTimer(ad); | ||
} | ||
} else { | ||
@@ -329,7 +330,9 @@ Log.info('Ad out of viewport -> stop timer', $adContainer.ad); | ||
private static resumeRefreshTimer(ad: IAd): void { | ||
Log.info('Resume refresh timer for ', ad); | ||
if (ad.refreshTimer.state == TimerState.PAUSED) { | ||
ad.refreshTimer.resume(); | ||
} else if (ad.refreshTimer.state == TimerState.STOPPED) { | ||
ad.refreshTimer.start(); | ||
if (ad.refreshTimer) { | ||
Log.info('Resume refresh timer for ', ad); | ||
if (ad.refreshTimer.state == TimerState.PAUSED) { | ||
ad.refreshTimer.resume(); | ||
} else if (ad.refreshTimer.state == TimerState.STOPPED) { | ||
ad.refreshTimer.start(); | ||
} | ||
} | ||
@@ -339,4 +342,6 @@ } | ||
private static pauseRefreshTimer(ad: IAd): void { | ||
Log.info('Pause refresh timer for ', ad); | ||
ad.refreshTimer.pause(); | ||
if (ad.refreshTimer) { | ||
Log.info('Pause refresh timer for ', ad); | ||
ad.refreshTimer.pause(); | ||
} | ||
} | ||
@@ -343,0 +348,0 @@ |
@@ -26,2 +26,3 @@ import { IntervalTimer } from '../helpers'; | ||
injector?: string; | ||
rendered: boolean; | ||
} |
@@ -119,2 +119,10 @@ export type callbackFunction = () => void; | ||
static show($element: HTMLElement) { | ||
alDOM.css($element, 'display', 'block'); | ||
} | ||
static hide($element: HTMLElement) { | ||
alDOM.css($element, 'display', 'none'); | ||
} | ||
static addClass($element: HTMLElement, ...className: string[]) { | ||
@@ -128,2 +136,6 @@ className.forEach((cl) => { | ||
static setClass($element: HTMLElement, className: string) { | ||
$element.className = className; | ||
} | ||
static removeClass($element: HTMLElement, className: string) { | ||
@@ -294,7 +306,7 @@ $element.classList.remove(className); | ||
static substringAfter(s: string, s2: string): string { | ||
static substringAfter(s: string, s2: string, afterLast: boolean = false): string { | ||
if (!s || !s2) { | ||
return s; | ||
} | ||
const p = s.indexOf(s2); | ||
const p = afterLast ? s.lastIndexOf(s2) : s.indexOf(s2); | ||
if (p == -1) { | ||
@@ -307,2 +319,6 @@ return ''; | ||
static substringAfterLast(s: string, s2: string): string { | ||
return alString.substringAfter(s, s2, true); | ||
} | ||
static defaultIfBlank(o: string, def: string) { | ||
@@ -422,2 +438,6 @@ return o && o.length != 0 ? o : def; | ||
public getRemaining() { | ||
return this.remaining; | ||
} | ||
// --------------------- | ||
@@ -424,0 +444,0 @@ // --- Internal interval |
@@ -12,3 +12,3 @@ import { alLog, alObject, LogLevel } from './helpers'; | ||
); | ||
Log.info('Ad Library Loaded ', String.fromCodePoint(0x1f47e)); | ||
Log.info('Ad Library Loaded - viewability test 6', String.fromCodePoint(0x1f47e)); | ||
@@ -15,0 +15,0 @@ __adLib.AdsManager = new AdsManager(); |
@@ -23,2 +23,3 @@ import { IAd } from '../common/types'; | ||
public abstract initProvider(): void; // async | ||
public abstract getName(): string; | ||
@@ -28,3 +29,3 @@ | ||
public abstract requestBids(ads: IAd[]): void; | ||
public abstract initialDisplay(ad: IAd): void; | ||
@@ -34,2 +35,4 @@ public abstract refreshAds(ads: IAd[]): void; | ||
public abstract refreshAllAds(): void; | ||
public abstract handlesViewability(): boolean; | ||
} |
@@ -5,9 +5,9 @@ // *************************************** | ||
import { alDOM, alObject, alString, callbackFunction, DomInsertPosition, LogLevel } from '../helpers'; | ||
import { alDOM, alObject, alString, callbackFunction, DomInsertPosition, LogLevel, TimerState } from '../helpers'; | ||
import { AbstractProvider, ProviderType } from './AbstractProvider'; | ||
import { utils } from '../utils/utils'; | ||
import { DisplayType, IAd, IAdContainer } from '../common/types'; | ||
import { ConsentManager } from '../consentmanagers/ConsentManager'; | ||
import InitParameters = apstag.InitParameters; | ||
import IPrebidAdUnit = pbjs.IPrebidAdUnit; | ||
import { DisplayType, IAd } from '../common/types'; | ||
import { ConsentManager } from '../consentmanagers/ConsentManager'; | ||
@@ -33,3 +33,5 @@ // ---------------------------------------------------------------------------------------------------------------------------- | ||
function init(initParams: InitParameters): void; | ||
function fetchBids(params: { slots: Ia9Slot[] }, f: callbackFunction): void; | ||
function setDisplayBids(): void; | ||
@@ -46,2 +48,3 @@ } | ||
dfpSlot: googletag.Slot; | ||
isFetching: boolean; | ||
adParameters: { | ||
@@ -72,2 +75,4 @@ size?: googletag.MultiSize; | ||
private index: number = 1; | ||
private dfpAds: Map<string, IdfpAd> = new Map(); | ||
private debugDashboard: DfpDebugDashboard; | ||
@@ -146,3 +151,3 @@ // ======================================================================================================================== | ||
googletag.cmd.push(function () { | ||
googletag.cmd.push(() => { | ||
// global targeting | ||
@@ -201,5 +206,55 @@ | ||
} | ||
// set visibility event | ||
googletag.pubads().addEventListener('slotVisibilityChanged', (event) => { | ||
let ad: IdfpAd = this.dfpAds.get(event.slot.getSlotElementId()); | ||
if (ad.isFetching) { | ||
return; | ||
} | ||
let viewPercentage = event.inViewPercentage; | ||
let containerId = event.slot.getSlotElementId(); | ||
let $adContainer: IAdContainer = alDOM.get(`#${containerId}`) as IAdContainer; | ||
$adContainer.isInViewPort = viewPercentage >= 50; | ||
this.updateDebugDashboard(containerId, 'visible', $adContainer.isInViewPort); | ||
if (ad.refreshTimer) { | ||
if ($adContainer.isInViewPort) { | ||
if (ad.refreshTimer.state == TimerState.PAUSED) { | ||
Log.info('Ad is in viewport -> resume timer', ad); | ||
ad.refreshTimer.resume(); | ||
this.updateDebugDashboard(containerId, 'timer', ad.refreshTimer.state); | ||
} | ||
} else if (ad.refreshTimer.state == TimerState.RUNNING) { | ||
Log.info('Ad is out of viewport -> pause timer', ad); | ||
ad.refreshTimer.pause(); | ||
this.updateDebugDashboard( | ||
containerId, | ||
'timer', | ||
`${ad.refreshTimer.state} (${Math.round(ad.refreshTimer.getRemaining() / 1000)}s)` | ||
); | ||
} | ||
} | ||
}); | ||
// set rendered event | ||
googletag.pubads().addEventListener('slotOnload', (event) => { | ||
this.dfpAds.get(event.slot.getSlotElementId()).isFetching = false; | ||
}); | ||
}); | ||
// --- init debug dashboard | ||
if (Log.getLevel() != LogLevel.None) { | ||
this.debugDashboard = new DfpDebugDashboard(); | ||
} | ||
} | ||
private updateDebugDashboard(containerId: string, property: string, value: boolean | string) { | ||
if (this.debugDashboard) { | ||
this.debugDashboard.updateSlotStatus(containerId, property, value); | ||
} | ||
} | ||
// ======================================================================================================================== | ||
@@ -225,5 +280,5 @@ // --- init an ad | ||
var params = ad.adParameters; | ||
var defaultWidth = params.size[0][0]; | ||
var defaultHeight = params.size[0][1]; | ||
let params = ad.adParameters; | ||
let defaultWidth = params.size[0][0]; | ||
let defaultHeight = params.size[0][1]; | ||
@@ -236,3 +291,3 @@ // --- container | ||
var placeholderCss = ''; | ||
let placeholderCss = ''; | ||
@@ -249,3 +304,3 @@ if (ad.displayType != DisplayType.CATFISH) { | ||
// find the average heigh of all possible renditions | ||
var avgHeight = Math.round( | ||
const avgHeight = Math.round( | ||
params.size.map((s) => s[1] as number).reduce((sum, height) => sum + height) / params.size.length | ||
@@ -259,10 +314,11 @@ ); | ||
var id = `DFP_${this.index++}`; | ||
let id = `DFP_${this.index++}`; | ||
ad.containerId = id; | ||
ad.dfpSize = params.size.length == 1 ? params.size[0] : params.size; | ||
ad.isFetching = false; | ||
// --- Inject the ad container in the DOM | ||
var style = `style="${placeholderCss}${alString.defaultIfBlank(params.style, '')}"`; | ||
var html = `<div data-type="${ad.type}" class="__alAd ${alString.defaultIfBlank( | ||
let style = `style="${placeholderCss}${alString.defaultIfBlank(params.style, '')}"`; | ||
let html = `<div data-type="${ad.type}" class="__alAd ${alString.defaultIfBlank( | ||
__adLib.adClass, | ||
@@ -276,3 +332,3 @@ '' | ||
var idSuffix = this.setDfpA9Slot(ad); | ||
let si = this.setDfpA9Slot(ad); | ||
@@ -283,3 +339,16 @@ // --- update container | ||
$container.setAttribute('data-identifier', ad.dfpSlot.getAdUnitPath()); | ||
$container.setAttribute('data-qa-identifier', idSuffix); | ||
$container.setAttribute('data-qa-identifier', si); | ||
// --- add ad to the ads map | ||
this.dfpAds.set(id, ad); | ||
// --- add in debug dashboard | ||
if (this.debugDashboard) { | ||
this.debugDashboard.addAd(ad); | ||
} | ||
// --- | ||
resolve($container); | ||
@@ -300,6 +369,6 @@ } catch (e) { | ||
Log.info('Initializes DFP slot and A9 slot for ', ad); | ||
var params = ad.adParameters; | ||
var idPrefix = __adLib.dfpIdPrefix.replace('${LEG}', __adLib.leg); | ||
var idSuffix = `${__adLib.isPhone ? 'MOBILE' : 'DESKTOP'}_${params.id}`; | ||
var adUnit = `/${__adLib.googleDfpId}/${idPrefix}${idSuffix}`; | ||
let params = ad.adParameters; | ||
let idPrefix = __adLib.dfpIdPrefix.replace('${LEG}', __adLib.leg); | ||
let idSuffix = `${__adLib.isPhone ? 'MOBILE' : 'DESKTOP'}_${params.id}`; | ||
let adUnit = `/${__adLib.googleDfpId}/${idPrefix}${idSuffix}`; | ||
Log.info(`Define new slot: [${adUnit}] with: size [${ad.dfpSize}] id [${ad.containerId}]`); | ||
@@ -316,2 +385,3 @@ ad.dfpSlot = googletag.defineSlot(adUnit, ad.dfpSize, ad.containerId); | ||
} | ||
Log.info('DFP/A9 slot defined for ', ad); | ||
@@ -322,5 +392,23 @@ return idSuffix; | ||
// ======================================================================================================================== | ||
// --- Ad Initial display | ||
// ======================================================================================================================== | ||
initialDisplay(ad: IAd): void { | ||
Log.info('Ad Initial Display', ad); | ||
let id = (ad as IdfpAd).dfpSlot.getSlotElementId(); | ||
this.updateDebugDashboard(id, 'initial-load', true); | ||
this.refreshAds([ad as IdfpAd]); | ||
if (ad.autoRefresh) { | ||
this.updateDebugDashboard(id, 'timer', TimerState.RUNNING); | ||
} | ||
} | ||
// ======================================================================================================================== | ||
// --- Refresh ads | ||
// ======================================================================================================================== | ||
handlesViewability(): boolean { | ||
return true; | ||
} | ||
// ------------------------------------------------------------------------------------------------------------------------ | ||
@@ -342,7 +430,2 @@ // --- Refresh all ads | ||
public requestBids(ads: IAd[]): void { | ||
// required by AbstractProvider.ts | ||
this.refreshAds(ads as IdfpAd[]); | ||
} | ||
public refreshAds(ads: IdfpAd[]): void { | ||
@@ -395,2 +478,8 @@ Log.info('Refresh ads: ', ads); | ||
Log.info('Refresh DFP slots ', slots); | ||
ads.forEach((ad) => { | ||
if (this.debugDashboard) { | ||
this.debugDashboard.updateRefreshStatus(ad.containerId, ad.refreshCounter); | ||
} | ||
ad.isFetching = true; | ||
}); | ||
googletag.pubads().refresh(slots); | ||
@@ -478,1 +567,153 @@ }; | ||
} | ||
// ============================================================================================================================ | ||
// --- Debugging Dashboard | ||
// ============================================================================================================================ | ||
class DfpDebugDashboard { | ||
private readonly $debugDashboard: HTMLElement; | ||
// ======================================================================================================================== | ||
// --- Constructor | ||
// ======================================================================================================================== | ||
constructor() { | ||
// ----------------------- | ||
// --- create dashboard UI | ||
// ----------------------- | ||
alDOM.insert( | ||
DomInsertPosition.append, | ||
document.body, | ||
`<button id="__adLib-debug-open">Ad Debug</button> | ||
<div id="__adLib-debug-dashboard"> | ||
<div id="__adLib-debug-close">X</div> | ||
<table> | ||
<thead> | ||
<tr> | ||
<th>DIV</th> | ||
<th>GPT Path</th> | ||
<th>Type</th> | ||
<th>Initial Load</th> | ||
<th>Fetched</th> | ||
<th>Rendered</th> | ||
<th>Rfsh Viewable</th> | ||
<th>Visible</th> | ||
<th>Refreshing</th> | ||
<th>Counter</th> | ||
<th>Timer</th> | ||
</tr> | ||
</thead> | ||
<tbody></tbody> | ||
</table> | ||
</div>` | ||
); | ||
this.$debugDashboard = alDOM.get('#__adLib-debug-dashboard tbody'); | ||
// ---------------------- | ||
// --- close/open buttons | ||
// ---------------------- | ||
alDOM.setEventListener(alDOM.get('#__adLib-debug-close'), 'click', this.hide); | ||
alDOM.setEventListener(alDOM.get('#__adLib-debug-open'), 'click', this.show); | ||
// ------------------- | ||
// --- event listeners | ||
// ------------------- | ||
googletag.cmd.push(() => { | ||
googletag.pubads().addEventListener('slotRequested', (event) => { | ||
this.updateSlotStatus(event.slot.getSlotElementId(), 'fetched', true); | ||
this.updateSlotStatus(event.slot.getSlotElementId(), 'refreshing', false); | ||
}); | ||
googletag.pubads().addEventListener('slotOnload', (event) => { | ||
this.updateSlotStatus(event.slot.getSlotElementId(), 'rendered', true); | ||
}); | ||
googletag.pubads().addEventListener('impressionViewable', (event) => { | ||
this.updateSlotStatus(event.slot.getSlotElementId(), 'viewable', true); | ||
}); | ||
}); | ||
} | ||
// ======================================================================================================================== | ||
// Add an ad in the dashboard | ||
// ======================================================================================================================== | ||
public addAd(ad: IdfpAd) { | ||
let containerId = ad.dfpSlot.getSlotElementId(); | ||
let slotId = alString.substringAfterLast(ad.dfpSlot.getAdUnitPath(), '/'); | ||
alDOM.insert( | ||
DomInsertPosition.append, | ||
this.$debugDashboard, | ||
`<tr> | ||
<td><a href="#${containerId}">${containerId}</a></td> | ||
<td>${slotId}</td> | ||
<td>${ad.displayType}</td> | ||
<td id="__adLib-debug-initial-load-${containerId}"></td> | ||
<td id="__adLib-debug-fetched-${containerId}"></td> | ||
<td id="__adLib-debug-rendered-${containerId}"></td> | ||
<td id="__adLib-debug-viewable-${containerId}"></td> | ||
<td id="__adLib-debug-visible-${containerId}"></td> | ||
<td id="__adLib-debug-refreshing-${containerId}"></td> | ||
<td id="__adLib-debug-counter-${containerId}"></td> | ||
<td id="__adLib-debug-timer-${containerId}"></td> | ||
</tr>` | ||
); | ||
this.resetSlotStatus(containerId); | ||
this.updateSlotStatus(containerId, 'timer', ad.refreshTimer ? ad.refreshTimer.state : 'N/A'); | ||
} | ||
// ======================================================================================================================== | ||
// Update a cell of the dashboard | ||
// ======================================================================================================================== | ||
public updateSlotStatus(containerId: string, property: string, value: boolean | string) { | ||
let $cell: HTMLElement = alDOM.get(`#__adLib-debug-${property}-${containerId}`); | ||
if (!$cell) { | ||
Log.error(`Unknown AD : [${containerId}] - [${property}]`); | ||
return; | ||
} | ||
if (typeof value == 'boolean') { | ||
alDOM.setClass($cell, `__adLib-debug-${value ? 'yes' : 'no'}`); | ||
$cell.innerText = value ? 'YES' : 'NO'; | ||
} else { | ||
$cell.innerText = value; | ||
} | ||
} | ||
private resetSlotStatus(containerId: string): void { | ||
this.updateSlotStatus(containerId, 'initial-load', false); | ||
this.updateSlotStatus(containerId, 'fetched', false); | ||
this.updateSlotStatus(containerId, 'rendered', false); | ||
this.updateSlotStatus(containerId, 'viewable', false); | ||
this.updateSlotStatus(containerId, 'visible', false); | ||
this.updateSlotStatus(containerId, 'refreshing', false); | ||
this.updateSlotStatus(containerId, 'counter', '0'); | ||
} | ||
public updateRefreshStatus(containerId: string, counter: number) { | ||
this.updateSlotStatus(containerId, 'refreshing', true); | ||
this.updateSlotStatus(containerId, 'fetched', false); | ||
this.updateSlotStatus(containerId, 'rendered', false); | ||
this.updateSlotStatus(containerId, 'viewable', false); | ||
this.updateSlotStatus(containerId, 'visible', false); | ||
this.updateSlotStatus(containerId, 'counter', counter.toString()); | ||
} | ||
// ======================================================================================================================== | ||
// show/hide debug dashboard | ||
// ======================================================================================================================== | ||
private show() { | ||
alDOM.show(alDOM.get('#__adLib-debug-dashboard')); | ||
} | ||
private hide() { | ||
alDOM.hide(alDOM.get('#__adLib-debug-dashboard')); | ||
} | ||
} |
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
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
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
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
296581
3000
3