@britannica/ads
Advanced tools
Comparing version 1.0.0 to 1.0.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 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){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: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,o){let n=e=>!0===e?"Y":!1===e?"N":"-",a=e.toString()+n(t)+n(i)+n(o),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 o=t.__uspapiCall;window.__uspapi(o.command,o.version,(function(t,n){let a={__uspapiReturn:{returnValue:t,success:n,callId:o.callId}},s=e.source;Log.info2("IAB: post message back ",a,s),s.postMessage(i?JSON.stringify(a):a,"*")}))}}}class p{static async init(){if(__adLib.requiresConsent){if(!n.isDefined(window.__tcfapi)){Log.info2("__tcfapi not found -> Will load the oneTrust scripts");try{await a.loadScript("https://cdn.cookielaw.org/consent/cmp.stub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw Log.error("Unable to load oneTrust cmp.stub.js script"),e}try{await a.loadScript("https://cdn.cookielaw.org/scripttemplates/otSDKStub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw Log.error("Unable to load oneTrust otSDKStub.js script "),e}Log.info2("oneTrust scripts loaded")}__adLib.usPrivacyConsent||(Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2(`OptanonWrapper called. Defer Ads status is [${p.getDeferAdsStatus()}]`),p.getDeferAdsStatus()&&(Log.info2("Defer Ads status is true -> Set Read TCData callback"),window.__tcfapi("getTCData",2,((e,t)=>{if(Log.info2(`TCData read: success = [${t}] data = `,e),!t||p.statusOk(e))return Log.info2("Error or status already OK -> send message to the app to load the ads immediately "),void p.setDeferAdsStatus(!1);const i=(e,t)=>{Log.info2("Received __tcpapi status change Event: ",e),t&&p.statusOk(e)&&(Log.info2("Status now OK, remove the event listener and send message to the app to load the ads immediately"),window.__tcfapi("removeEventListener",2,i),p.setDeferAdsStatus(!1))};Log.info2("Status not OK yet. Set event listener to load the ads when it will be OK"),window.__tcfapi("addEventListener",2,i)})))},Log.info2("Defer the ads loading by default"),p.setDeferAdsStatus(!0))}else Log.info2("Not Consent Required")}static getDeferAdsStatus(){return __adLib.deferAds}static setDeferAdsStatus(e){__adLib.deferAds=e,e||document.dispatchEvent(new Event("endDeferAds"))}static statusOk(e){return"useractioncomplete"==e.eventStatus||"tcloaded"==e.eventStatus}static getPrebidConsentParameters(){return __adLib.usPrivacyConsent?__adLib.prebidCcpaConfiguration:__adLib.requiresConsent?__adLib.prebidGdprConfiguration:null}static onDNSMILinkClicked(){Log.info2("CCPA consent called"),Log.info2("create default IAB cookie [1YYY]"),c.createCookie(1,!0,!0,!0),Log.info2("Modifies onetrust OptanonConsent cookies and ActiveGroups global variables");let e=[4],t=decodeURIComponent(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 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 s=a.get(`.${u.WRAPPER_CLASS}`,e),r={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};f.setJwplayerSetupWithPrebid(i,r,(()=>{Log.info("Prebid preroll completed. Init JWPlayer: ",r);let t=jwplayer(u.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,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,s=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:${r.substringBefore(n.placeholderSize,"x")}px;min-height:${r.substringAfter(n.placeholderSize,"x")}px;`;else if(1==n.size.length)l=`width:${s}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}${r.defaultIfBlank(n.style,"")}"`,g=`<div data-type="${e.type}" class="__alAd ${r.defaultIfBlank(__adLib.adClass,"")} ${r.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"),s())},s=()=>{Log.info("Refresh ads ",t);let e=t.map((e=>e.dfpSlot));Log.info("Refresh DFP slots ",e),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,...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(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()))),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,s()}),__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 the [endDeferAds] is fired"),a.setEventListener(document,"endDeferAds",(()=>{Log.info("Deferred Ads event triggered. Will now initialize the ads"),this.contentLoadInit(document.body,__adLib.initialLoadAds)}))):(Log.info("No deferred ads. Will initialize the ads now"),this.contentLoadInit(document.body,__adLib.initialLoadAds))}async contentLoadInit(e=document.body,t){let i;if(Log.info(" ============================================================================================="),Log.info("Initialize container with ads"),Log.info(" ============================================================================================="),t)i=t,Log.info("Ad definitions passed as parameter: ",i);else{Log.info("Look for json ads definition in ",e);let t=d.getJsonFromScriptSnippet("ads-script",e);if(!t)return void Log.info("Did not find ads definition.");if(i=t,!i)return;Log.info("Found ad definitions: ",i)}let o=new Map;for(let t of i){if(Log.info("Init this ad: ",t),!this.providers.has(t.type)){Log.info(`Initializes Provider: [${t.type}]`);try{let e=new(L.providerClasses.get(t.type));await e.initProvider(),this.providers.set(t.type,e)}catch(e){Log.error(`Unable to instantiate Ad Provider: [${t.type}]`,t,e);continue}}let i=this.providers.get(t.type);o.has(t.type)||o.set(t.type,[]),t.provider=i;let n=null;if(t.displayType==b.REGULAR)n=a.get(t.selector,e);else if(t.displayType==b.CATFISH){if(n=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"),__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 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; | ||
//# 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 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||(Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2(`OptanonWrapper called. Defer Ads status is [${p.getDeferAdsStatus()}]`),p.getDeferAdsStatus()&&(Log.info2("Defer Ads status is true -> Set Read TCData callback"),window.__tcfapi("getTCData",2,((e,t)=>{if(Log.info2(`TCData read: success = [${t}] data = `,e),!t||p.statusOk(e))return Log.info2("Error or status already OK -> send message to the app to load the ads immediately "),void p.setDeferAdsStatus(!1);const i=(e,t)=>{Log.info2("Received __tcpapi status change Event: ",e),t&&p.statusOk(e)&&(Log.info2("Status now OK, remove the event listener and send message to the app to load the ads immediately"),window.__tcfapi("removeEventListener",2,i),p.setDeferAdsStatus(!1))};Log.info2("Status not OK yet. Set event listener to load the ads when it will be OK"),window.__tcfapi("addEventListener",2,i)})))},Log.info2("Defer the ads loading by default"),p.setDeferAdsStatus(!0))}else Log.info2("Not Consent Required")}static getDeferAdsStatus(){return __adLib.deferAds}static setDeferAdsStatus(e){__adLib.deferAds=e,e||document.dispatchEvent(new Event("endDeferAds"))}static statusOk(e){return"useractioncomplete"==e.eventStatus||"tcloaded"==e.eventStatus}static getPrebidConsentParameters(){return __adLib.usPrivacyConsent?__adLib.prebidCcpaConfiguration:__adLib.requiresConsent?__adLib.prebidGdprConfiguration:null}static onDNSMILinkClicked(){Log.info2("CCPA consent called"),Log.info2("create default IAB cookie [1YYY]"),c.createCookie(1,!0,!0,!0),Log.info2("Modifies onetrust OptanonConsent cookies and ActiveGroups global variables");let e=[4],t=decodeURIComponent(r.readCookie("OptanonConsent "));Log.info2("Current OptanonConsent cookie value = ",t);for(let i of e)t=t.replace(`,${i}:1,`,`,${i}:0,`),window.OptanonActiveGroups=window.OptanonActiveGroups.replace(`,${i},`,","),window.OnetrustActiveGroups=window.OnetrustActiveGroups.replace(`,${i},`,",");Log.info2("New OptanonConsent cookie value = ",t),Log.info2(`New OptanonActiveGroups = [${window.OptanonActiveGroups}]`),Log.info2(`New OneTrustActiveGroups = [${window.OnetrustActiveGroups}]`),r.createCookieSession("OptanonConsent",encodeURI(t),__adLib.topDomain),r.createCookieSession("EbConsentClosed","true"),Log.info2("created new OptanonConsent and EbConsentClosed cookies")}}class g{static async loadPrebidScript(){if(!(__adLib.videoForPrebidLoaded||n.isDefined(window.pbjs)&&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 the [endDeferAds] is fired"),a.setEventListener(document,"endDeferAds",(()=>{Log.info("Deferred Ads event triggered. Will now initialize the ads"),this.contentLoadInit(document.body,__adLib.initialLoadAds)}))):(Log.info("No deferred ads. Will initialize the ads now"),this.contentLoadInit(document.body,__adLib.initialLoadAds))}async contentLoadInit(e=document.body,t){let i;if(Log.info(" ============================================================================================="),Log.info("Initialize container with ads"),Log.info(" ============================================================================================="),t)i=t,Log.info("Ad definitions passed as parameter: ",i);else{Log.info("Look for json ads definition in ",e);let t=d.getJsonFromScriptSnippet("ads-script",e);if(!t)return void Log.info("Did not find ads definition.");if(i=t,!i)return;Log.info("Found ad definitions: ",i)}let o=new Map;for(let t of i){if(Log.info("Init this ad: ",t),!this.providers.has(t.type)){Log.info(`Initializes Provider: [${t.type}]`);try{let e=new(L.providerClasses.get(t.type));await e.initProvider(),this.providers.set(t.type,e)}catch(e){Log.error(`Unable to instantiate Ad Provider: [${t.type}]`,t,e);continue}}let i=this.providers.get(t.type);o.has(t.type)||o.set(t.type,[]),t.provider=i;let n=null;if(t.displayType==b.REGULAR)n=a.get(t.selector,e);else if(t.displayType==b.CATFISH){if(n=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"),__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 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; | ||
//# 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 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){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: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,o){let n=e=>!0===e?"Y":!1===e?"N":"-",a=e.toString()+n(t)+n(i)+n(o),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 o=t.__uspapiCall;window.__uspapi(o.command,o.version,(function(t,n){let a={__uspapiReturn:{returnValue:t,success:n,callId:o.callId}},s=e.source;Log.info2("IAB: post message back ",a,s),s.postMessage(i?JSON.stringify(a):a,"*")}))}}}class p{static async init(){if(__adLib.requiresConsent){if(!n.isDefined(window.__tcfapi)){Log.info2("__tcfapi not found -> Will load the oneTrust scripts");try{await a.loadScript("https://cdn.cookielaw.org/consent/cmp.stub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw Log.error("Unable to load oneTrust cmp.stub.js script"),e}try{await a.loadScript("https://cdn.cookielaw.org/scripttemplates/otSDKStub.js",{"data-domain-script":__adLib.oneTrustId})}catch(e){throw Log.error("Unable to load oneTrust otSDKStub.js script "),e}Log.info2("oneTrust scripts loaded")}__adLib.usPrivacyConsent||(Log.info2("set OptanonWrapper function"),window.OptanonWrapper=()=>{Log.info2(`OptanonWrapper called. Defer Ads status is [${p.getDeferAdsStatus()}]`),p.getDeferAdsStatus()&&(Log.info2("Defer Ads status is true -> Set Read TCData callback"),window.__tcfapi("getTCData",2,((e,t)=>{if(Log.info2(`TCData read: success = [${t}] data = `,e),!t||p.statusOk(e))return Log.info2("Error or status already OK -> send message to the app to load the ads immediately "),void p.setDeferAdsStatus(!1);const i=(e,t)=>{Log.info2("Received __tcpapi status change Event: ",e),t&&p.statusOk(e)&&(Log.info2("Status now OK, remove the event listener and send message to the app to load the ads immediately"),window.__tcfapi("removeEventListener",2,i),p.setDeferAdsStatus(!1))};Log.info2("Status not OK yet. Set event listener to load the ads when it will be OK"),window.__tcfapi("addEventListener",2,i)})))},Log.info2("Defer the ads loading by default"),p.setDeferAdsStatus(!0))}else Log.info2("Not Consent Required")}static getDeferAdsStatus(){return __adLib.deferAds}static setDeferAdsStatus(e){__adLib.deferAds=e,e||document.dispatchEvent(new Event("endDeferAds"))}static statusOk(e){return"useractioncomplete"==e.eventStatus||"tcloaded"==e.eventStatus}static getPrebidConsentParameters(){return __adLib.usPrivacyConsent?__adLib.prebidCcpaConfiguration:__adLib.requiresConsent?__adLib.prebidGdprConfiguration:null}static onDNSMILinkClicked(){Log.info2("CCPA consent called"),Log.info2("create default IAB cookie [1YYY]"),c.createCookie(1,!0,!0,!0),Log.info2("Modifies onetrust OptanonConsent cookies and ActiveGroups global variables");let e=[4],t=decodeURIComponent(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 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 s=a.get(`.${u.WRAPPER_CLASS}`,e),r={autostart:!0,mute:!0,controls:!1,file:"https://cdn.britannica.com/ads/resources/black.mp4"};f.setJwplayerSetupWithPrebid(i,r,(()=>{Log.info("Prebid preroll completed. Init JWPlayer: ",r);let t=jwplayer(u.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,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 m extends class{type;ads;constructor(){this.ads=[],this.type=this.getType()}addAd(e){this.ads.push(e)}}{static PAGELOAD_TARGETING="PAGELOAD";index=1;getName(){return"Google DFP"}getType(){return h.DFP}constructor(){super()}async initProvider(){if(window.googletag={cmd:[]},!n.isDefined(googletag.defineSlot)){Log.info("Googletag not found. Load the script");try{await a.loadScript("https://securepubads.g.doubleclick.net/tag/js/gpt.js")}catch(e){throw Log.error("**** Unable to load gpt.js -> most ads and scripts will be broken ***"),e}}if(Log.info("Googletag script loaded: ",googletag.defineSlot),g.loadPrebidScript(),!n.isDefined(window.headertag)&&__adLib.includeIndex)try{await a.loadScript(__adLib.indexScriptUrl)}catch(e){Log.error(`Unable to load [${__adLib.indexScriptUrl}] Index script. We won't use it.`)}if(!n.isDefined(window.apstag)&&__adLib.includeA9)try{await a.loadScript("https://c.amazon-adsystem.com/aax2/apstag.js"),function(e,t){function i(i,o){t[e]._Q.push([i,o])}t[e]||(t[e]={init:function(){i("i",arguments)},fetchBids:function(){i("f",arguments)},setDisplayBids:function(){},targetingKeys:function(){return[]},_Q:[]})}("apstag",window)}catch(e){Log.error("Unable to load A9 script. Will disable it"),__adLib.includeA9=!1}googletag.cmd.push((function(){if(googletag.pubads().setTargeting("dc_ref",__adLib.url),n.isDefined(Storage)){var e=localStorage.getItem("bcDFPTargetingParams");if(e)Log.info("Setting Blueconic targeting parameters"),JSON.parse(e).forEach((e=>googletag.pubads().setTargeting(e.key,e.value)))}if(Log.info(`targeting: ${googletag.pubads().getTargetingKeys()}`),googletag.pubads().disableInitialLoad(),googletag.pubads().enableSingleRequest(),googletag.pubads().enableAsyncRendering(),googletag.pubads().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,s=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:${r.substringBefore(n.placeholderSize,"x")}px;min-height:${r.substringAfter(n.placeholderSize,"x")}px;`;else if(1==n.size.length)l=`width:${s}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}${r.defaultIfBlank(n.style,"")}"`,g=`<div data-type="${e.type}" class="__alAd ${r.defaultIfBlank(__adLib.adClass,"")} ${r.defaultIfBlank(n.cssClass,"")}" ${p} id="${c}"></div>`;Log.info(`Inject DIV: [${g}] into `,i),a.insert(t[e.injector],i,g);var f=this.setDfpA9Slot(e);let u=a.get(`#${c}`);u.setAttribute("data-identifier",e.dfpSlot.getAdUnitPath()),u.setAttribute("data-qa-identifier",f),o(u)}catch(t){Log.error("Init Slot Error: ",e,t),o(null)}}))}))}setDfpA9Slot=function(e){Log.info("Initializes DFP slot and A9 slot for ",e);var t=e.adParameters,i=__adLib.dfpIdPrefix.replace("${LEG}",__adLib.leg),o=`${__adLib.isPhone?"MOBILE":"DESKTOP"}_${t.id}`,n=`/${__adLib.googleDfpId}/${i}${o}`;return Log.info(`Define new slot: [${n}] with: size [${e.dfpSize}] id [${e.containerId}]`),e.dfpSlot=googletag.defineSlot(n,e.dfpSize,e.containerId),t.targeting&&Object.entries(t.targeting).forEach((([t,i])=>{e.dfpSlot.setTargeting(t,String(i))})),e.dfpSlot.addService(googletag.pubads()),__adLib.includeA9&&(e.a9Slot={slotID:e.containerId,slotName:n,sizes:t.size}),Log.info("DFP/A9 slot defined for ",e),o};refreshAllAds(){Log.info("Refresh all DFP ads."),googletag.cmd.push((()=>{m.setPageLoadTargeting(this.ads),this.refreshSlots()}))}requestBids(e){this.refreshAds(e)}refreshAds(e){Log.info("Refresh ads: ",e),googletag.cmd.push((()=>{m.setPageLoadTargeting(e),this.refreshSlots(e)}))}static setPageLoadTargeting(e){for(let t of e){const e=`REFRESH${t.refreshCounter}`;Log.info(`Update ${m.PAGELOAD_TARGETING} targeting ${e} for `,t),t.dfpSlot.setTargeting(m.PAGELOAD_TARGETING,e)}}refreshSlots(t=this.ads){Log.info("Refresh slots - ads : ",t);let i=!1,o=!1,n=!1,a=()=>{n||!o||!i&&__adLib.includeA9||(-1!=c&&window.clearTimeout(c),Log.info("Prebid is completed and A9 completed or disabled -> call DFP"),s())},s=()=>{Log.info("Refresh ads ",t);let e=t.map((e=>e.dfpSlot));Log.info("Refresh DFP slots ",e),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,...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(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()))),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,s()}),__adLib.biddersFailsafeTimeout))}}class _{static CATFISH_ID="AD_STATIC_CATFISH";static newCatfish(e,i){Log.info("Create a catfish container");let o=`<div id="${_.CATFISH_ID}" class="__alCatfish" style=" ${e?`width:${e}px;`:""} ${i?`height:${i}px`:""}"></div>`;return a.insert(t.append,document.body,o),Log.info("Static Catfish Inserted",_.getCurrentCatfishElement()),_.getCurrentCatfishElement()}static getCurrentCatfishElement(){return a.get(`#${_.CATFISH_ID}`)}}class L{static providerClasses=new Map([[h.DFP,m]]);providers=new Map;timers=[];constructor(){n.isDefined(typeof window.__adLib)&&a.onDocumentReady((()=>{this.init()}))}isAdBlockerActivated(){var e=a.get("#_MGS_");e||(a.insert(t.append,document.body,'<div id="_MGS_"><div class="adBanner" style="height:1px"></div></div>'),e=a.get("#_MGS_"));var i=a.get("div",e);return"none"===window.getComputedStyle(i).display}async init(){Log.info("Init Ads manager at page load"),c.init(),await p.init(),Log.info("Set tab visibility event handler"),a.setEventListener(document,"visibilitychange",(()=>{let e="visible"===document.visibilityState;Log.info(`Tab visibility changed to [${e}]`),e?this.resumeAllPausedTimers():this.pauseAllRunningTimers()})),__adLib.deferAds?(Log.info("Ads need to be deferred. Will wait until the [endDeferAds] is fired"),a.setEventListener(document,"endDeferAds",(()=>{Log.info("Deferred Ads event triggered. Will now initialize the ads"),this.contentLoadInit(document.body,__adLib.initialLoadAds)}))):(Log.info("No deferred ads. Will initialize the ads now"),this.contentLoadInit(document.body,__adLib.initialLoadAds))}async contentLoadInit(e=document.body,t){let i;if(Log.info(" ============================================================================================="),Log.info("Initialize container with ads"),Log.info(" ============================================================================================="),t)i=t,Log.info("Ad definitions passed as parameter: ",i);else{Log.info("Look for json ads definition in ",e);let t=d.getJsonFromScriptSnippet("ads-script",e);if(!t)return void Log.info("Did not find ads definition.");if(i=t,!i)return;Log.info("Found ad definitions: ",i)}let o=new Map;for(let t of i){if(Log.info("Init this ad: ",t),!this.providers.has(t.type)){Log.info(`Initializes Provider: [${t.type}]`);try{let e=new(L.providerClasses.get(t.type));await e.initProvider(),this.providers.set(t.type,e)}catch(e){Log.error(`Unable to instantiate Ad Provider: [${t.type}]`,t,e);continue}}let i=this.providers.get(t.type);o.has(t.type)||o.set(t.type,[]),t.provider=i;let n=null;if(t.displayType==b.REGULAR)n=a.get(t.selector,e);else if(t.displayType==b.CATFISH){if(n=_.getCurrentCatfishElement(),n){let e=a.get(".__alAd",n).ad;e.provider.refreshAds([e]),Log.info("Catfish already exists, just refresh its ad");continue}n=_.newCatfish(),t.injector="append"}n?(t.$container=await i.createSlot(t,n),t.$container?(t.$container.ad=t,t.refreshCounter=0,i.addAd(t),o.get(t.type).push(t),t.autoRefresh?(t.$container.isInViewPort=!1,t.refreshTimer=new l((()=>{L.timerCallback(t)}),1e3*__adLib.refreshTimer),this.timers.push(t.refreshTimer),Log.info("This ad is autorefresh, added refresh timer: ",t.refreshTimer)):(t.refreshTimer=null,t.$container.isInViewPort=!0,Log.info("This ad is not autorefresh -> no refresh timer")),t.displayType==b.CATFISH?(Log.info("The ad is a catfish -> always in viewport and start refresh timer"),t.$container.isInViewPort=!0,t.refreshTimer&&t.refreshTimer.start()):t.autoRefresh&&(Log.info("Add the ad container to the observer -> ",t.$container),this.isInViewPortObserver.observe(t.$container)),Log.info("Ad initialized",t)):Log.info("Slot creation failed -> skip this ad")):Log.info("Error when initializing the ad/Existing ad -> skip it: ",t)}for(let[e,t]of o)0==t.length?Log.info(`No ads for [${e}] provider`):(Log.info(`Request Bids for [${e}] provider: `,t),this.providers.get(e).requestBids(t));if(__adLib.stickyContainerSelector){const t=a.getAll(`${__adLib.stickyContainerSelector} .__alAd`,e);let i=t.length;if(i>0){let e=t.item(i-1);Log.info("Last ad is sticky",e),a.addClass(e,"__alSticky",__adLib.stickyAdClass)}}}isInViewPortObserver=new IntersectionObserver((e=>{e.forEach((e=>{let t=e.target;t.isInViewPort=e.intersectionRatio>=__adLib.viewportThreshold,t.isInViewPort?(Log.info("Ad in viewport -> resume timer",t.ad),L.resumeRefreshTimer(t.ad)):(Log.info("Ad out of viewport -> stop timer",t.ad),L.pauseRefreshTimer(t.ad))}))}),{threshold:__adLib.viewportThreshold});static timerCallback(e){Log.info("Ad is refreshed.",e),e.refreshCounter++,e.provider.refreshAds([e])}static resumeRefreshTimer(e){Log.info("Resume refresh timer for ",e),e.refreshTimer.state==i.PAUSED?e.refreshTimer.resume():e.refreshTimer.state==i.STOPPED&&e.refreshTimer.start()}static pauseRefreshTimer(e){Log.info("Pause refresh timer for ",e),e.refreshTimer.pause()}pausedTimers=[];pauseAllRunningTimers(){this.pausedTimers=this.timers.filter((e=>e.state==i.RUNNING)),0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.pause())),Log.info("Pause these timers: ",this.pausedTimers.map((e=>e.id))))}resumeAllPausedTimers(){0!=this.pausedTimers.length&&(this.pausedTimers.forEach((e=>e.resume())),Log.info("Resume these timers: ",this.pausedTimers.map((e=>e.id))))}refreshAllAds(){Log.info("Refresh All ads"),this.providers.forEach((e=>{Log.info(`will refresh ads for this provider: [${e.getName()}]`);for(let t of e.ads)t.refreshCounter++;e.refreshAllAds();for(let t of e.ads)t.refreshTimer&&t.refreshTimer.restart()}))}}window.Log=new o(n.isDefined(__adLib)?e[__adLib.logLevel]:e.None),Log.info("Ad Library Loaded"),__adLib.AdsManager=new L,__adLib.ConsentManager=p,__adLib.PrebidForVideo=f,__adLib.PrerollAd=u})); | ||
!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})); | ||
//# sourceMappingURL=britannica-ads.umd.js.map |
@@ -1,14 +0,9 @@ | ||
export interface ItcData { | ||
gdprApplies: boolean; | ||
eventStatus: 'tcloaded' | 'cmpuishown' | 'useractioncomplete'; | ||
cmpStatus: 'stub' | 'loaded' | 'error'; | ||
listenerId: number; | ||
} | ||
export declare class ConsentManager { | ||
private static ONETRUST_COOKIE_NAME; | ||
static init(): Promise<void>; | ||
private static getDeferAdsStatus; | ||
private static setDeferAdsStatus; | ||
private static statusOk; | ||
private static userConsentCallback; | ||
static setOnUserConsent(callback: () => void): void; | ||
static getPrebidConsentParameters(): object; | ||
static onDNSMILinkClicked(): void; | ||
} |
{ | ||
"name": "@britannica/ads", | ||
"version": "1.0.0", | ||
"version": "1.0.1", | ||
"description": "Britannica and MW ad library", | ||
@@ -5,0 +5,0 @@ "main": "dist/britannica-ads.cjs.js", |
@@ -92,4 +92,4 @@ import { Iab } from './consentmanagers/iab'; | ||
if (__adLib.deferAds) { | ||
Log.info('Ads need to be deferred. Will wait until the [endDeferAds] is fired'); | ||
alDOM.setEventListener(document, 'endDeferAds', () => { | ||
Log.info('Ads need to be deferred. Will wait until user closes the consent manager'); | ||
ConsentManager.setOnUserConsent(() => { | ||
Log.info('Deferred Ads event triggered. Will now initialize the ads'); | ||
@@ -96,0 +96,0 @@ this.contentLoadInit(document.body, __adLib.initialLoadAds); |
import { alCookie, alDOM, alObject } from '../helpers'; | ||
import { Iab } from './iab'; | ||
export interface ItcData { | ||
gdprApplies: boolean; | ||
eventStatus: 'tcloaded' | 'cmpuishown' | 'useractioncomplete'; | ||
cmpStatus: 'stub' | 'loaded' | 'error'; | ||
listenerId: number; | ||
} | ||
export class ConsentManager { | ||
private static ONETRUST_COOKIE_NAME = 'OptanonAlertBoxClosed'; | ||
export class ConsentManager { | ||
// ======================================================================================================================== | ||
@@ -52,33 +47,13 @@ // loads the oneTrust scripts if needed, defers ads loading, and sets a hook to know when the user clicked on "accept", | ||
if (!__adLib.usPrivacyConsent) { | ||
if (!__adLib.usPrivacyConsent && !alCookie.isCookieExists(ConsentManager.ONETRUST_COOKIE_NAME)) { | ||
Log.info2('set OptanonWrapper function'); | ||
window.OptanonWrapper = () => { | ||
Log.info2(`OptanonWrapper called. Defer Ads status is [${ConsentManager.getDeferAdsStatus()}]`); | ||
Log.info2(`OptanonWrapper called`); | ||
if (ConsentManager.getDeferAdsStatus()) { | ||
Log.info2('Defer Ads status is true -> Set Read TCData callback'); | ||
window.__tcfapi('getTCData', 2, (tcData, success) => { | ||
Log.info2(`TCData read: success = [${success}] data = `, tcData); | ||
if (!success || ConsentManager.statusOk(tcData)) { | ||
Log.info2('Error or status already OK -> send message to the app to load the ads immediately '); | ||
ConsentManager.setDeferAdsStatus(false); | ||
return; | ||
} | ||
const callback = (tcData: ItcData, success: boolean) => { | ||
Log.info2('Received __tcpapi status change Event: ', tcData); | ||
if (success && ConsentManager.statusOk(tcData)) { | ||
Log.info2( | ||
'Status now OK, remove the event listener and send message to the app to load the ads immediately' | ||
); | ||
window.__tcfapi('removeEventListener', 2, callback); | ||
ConsentManager.setDeferAdsStatus(false); | ||
} | ||
}; | ||
Log.info2('Status not OK yet. Set event listener to load the ads when it will be OK'); | ||
window.__tcfapi('addEventListener', 2, callback); | ||
}); | ||
if (alCookie.isCookieExists(ConsentManager.ONETRUST_COOKIE_NAME) && ConsentManager.setOnUserConsent) { | ||
Log.info2('The consent manager popup was closed. Consent Manager callback will be called'); | ||
ConsentManager.setDeferAdsStatus(false); | ||
} else { | ||
Log.info2('The consent manager popup was not closed. Still waiting'); | ||
} | ||
@@ -92,15 +67,17 @@ }; | ||
private static getDeferAdsStatus(): boolean { | ||
return __adLib.deferAds; | ||
} | ||
private static setDeferAdsStatus(d: boolean): void { | ||
__adLib.deferAds = d; | ||
if (!d) { | ||
document.dispatchEvent(new Event('endDeferAds')); | ||
ConsentManager.userConsentCallback(); | ||
} | ||
} | ||
private static statusOk(tcData: ItcData): boolean { | ||
return tcData.eventStatus == 'useractioncomplete' || tcData.eventStatus == 'tcloaded'; | ||
// ======================================================================================================================== | ||
// set onUserConsent function | ||
// ======================================================================================================================== | ||
private static userConsentCallback: () => void; | ||
public static setOnUserConsent(callback: () => void) { | ||
ConsentManager.userConsentCallback = callback; | ||
} | ||
@@ -107,0 +84,0 @@ |
@@ -12,3 +12,3 @@ import { alLog, alObject, LogLevel } from './helpers'; | ||
); | ||
Log.info('Ad Library Loaded'); | ||
Log.info('Ad Library Loaded ', String.fromCodePoint(0x1f47e)); | ||
@@ -15,0 +15,0 @@ __adLib.AdsManager = new AdsManager(); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
252949
2698