1(()=>{let e=!1,t=!1,i=!1;window.__MAI_PB_INIT__?(console.warn("[maiPub] Detected another Prebid wrapper. Entering compat mode (no Prebid init)."),window.__MAI_PB_COMPAT__=!0):(window.__MAI_PB_INIT__=!0,window.__MAI_PB_OWNED__=!0,window.pbjs=window.pbjs||{que:[]}),window.googletag=window.googletag||{},window.googletag.cmd=window.googletag.cmd||[],googletag.cmd.push(function(){"function"==typeof googletag.setConfig?googletag.setConfig({singleRequest:!0}):googletag.pubads().enableSingleRequest()});const n=[],s=[],o={},a={},r=2800,d=window.location.search.includes("dfpdeb")||window.location.search.includes("maideb")||window.location.search.includes("pbjs_debug=true")||!0===window.__MAI_PUB_DEBUG__,l="refresh";let c=Date.now(),u=null;const p={pendingSlugs:new Set,pendingSources:new Map,batchTimeout:null,batchDelay:maiPubAdsVars.batchDelay||100,processing:!1},g=maiPubAdsVars.ads,h=maiPubAdsVars.gamBase,m=maiPubAdsVars.gamChildNetworkCode,f=maiPubAdsVars.targets.refresh,b=maiPubAdsVars.debug,y=(maiPubAdsVars.ppid,"Manage Account"===maiPubAdsVars.manager_domain);if(console.info("[maiPub] Adapter Status: Magnite DM: ",maiPubAdsVars.magnite),console.info("[maiPub] Adapter Status: RevIQ: ",maiPubAdsVars.reviq),console.info("[maiPub] Adapter Status: Catalyst: ",maiPubAdsVars.catalyst),Array.isArray(maiPubAdsVars.prebidSplit)&&maiPubAdsVars.prebidSplit.length){const e=function(e){const t="maipub_pb_split",i=e.map(e=>`${e.key}:${e.percent}`).join(",");if(window.location.hash){if("#forcenone"===window.location.hash)return ae(t,{key:"none",label:"none"},i),_e("Prebid split: forced to no wrapper via #forcenone"),null;for(const n of e)if(`#force${n.key}`===window.location.hash){const e={key:n.key,label:n.label};return ae(t,e,i),_e("Prebid split: forced via hash:",e),e}}const n=document.cookie.match(/maipub_pb_split=([^;]+)/);if(n)try{const t=JSON.parse(decodeURIComponent(n[1]));if(t&&t.sig===i){if("none"===t.key)return null;const i=e.find(e=>e.key===t.key);if(i)return{key:i.key,label:i.label}}else _e("Prebid split: Backend settings changed. Ignoring stale cookie.")}catch(e){_e("Prebid split: cookie parse error:",e)}const s=100*Math.random();let o=0,a=null;for(const t of e)if(o+=Math.max(0,Number(t.percent)||0),s<o){a={key:t.key,label:t.label};break}return ae(t,a||{key:"none",label:"none"},i),a}(maiPubAdsVars.prebidSplit);maiPubAdsVars.magnite=!!e&&"magnite"===e.key,maiPubAdsVars.catalyst=!!e&&"catalyst"===e.key,maiPubAdsVars.reviq=!!e&&"reviq"===e.key,console.info("[maiPub] Prebid Adapter split: adapter winner =",e?e.label:"none (GAM Only)"),_e("Prebid Adapter split: adapter winner =",e?e.label:"none (GAM Only)")}const A=maiPubAdsVars.reviq?"reviq":maiPubAdsVars.magnite?"magnite":maiPubAdsVars.catalyst?"catalyst":"gam-direct";console.info("[maiPub] Display Mode:",A),_e("Display Mode:",A);const v="maiPubSessionData",P=["source","hasConsent","gdprConsentUUID","gdprApplies","gdprConsentedToAll","usnatConsentUUID","usnatApplies"],S=["tcString","gppString"],w="1.0.5";let C=!1,E=[];function M(){if(C)return;C=!0;const e=E;E=[],e.forEach(function(e){try{e()}catch(e){_e("GEO gate: waiter threw",e)}})}const T={other:0,hem:1,phone:2,xpuid:3,xpuidSource:4,puid:5,idfa:6,gaid:7,url:8,domain:9,ipv4:10,ipv6:11,ua:12,isBurnerEmail:13,idfv:14,iabToken:17};let I={},$=[],R=!0,V="",_=!1,k=null,U=!document.hidden;console.info("[maiPub] Script Version: 976"),_e("[maiPub] Script Version: 976"),void 0===window._maiPubConsentQueue&&(window._maiPubConsentQueue=[]),window._maiPubConsentQueue&&window._maiPubConsentQueue.length>0?(console.info("[maiPub] Processing "+window._maiPubConsentQueue.length+" queued consent events"),window._maiPubConsentQueue.forEach(function(e){if(console.info("[maiPub] Processing queued consent:",e.consentData),Ae(e.consentData),e.privacyManager&&!0===e.privacyManager.applies){const t=document.getElementById("pmLink");t&&(console.info("[maiPub] Setting up privacy manager link:",e.privacyManager.linkText),t.innerHTML=e.privacyManager.linkText,t.oncl
1ick=function(t){t.preventDefault(),e.privacyManager.modalLoader()})}}),window._maiPubConsentQueue=[]):_e("[maiPub] No queued consent events to process"),window._sp_queue=window._sp_queue||[],window._sp_queue.push(function(){_e("CMP: Sourcepoint loaded. Registering dynamic event listener.");const e=function(e,t,i,n){_e("CMP: Processing consent state for "+e),Ae({message_type:e,consentUUID:t,consentSource:"cmp",applies:!!n&&n.applies,consentedToAll:!!n&&n.consentedToAll,typeApplies:!!n&&(n.typeApplies||n.applies),uuid:t,euconsent:i})};if(window._sp_.addEventListener("onConsentReady",e),window._sp_.gdpr?.consentData||window._sp_.usnat?.consentData){if(_e("CMP: Cached consent data detected on boot. Resolving gateway immediately."),window._sp_.gdpr?.consentData){const t=window._sp_.gdpr;e("gdpr",t.uuid,t.euconsent,{applies:t.applies,consentedToAll:t.consentedToAll})}if(window._sp_.usnat?.consentData){const t=window._sp_.usnat;e("usnat",t.uuid,null,{applies:t.applies})}}}),function(){try{const e=sessionStorage.getItem(v);e?(I=JSON.parse(e),I.ppid&&"object"==typeof I.ppid&&null!==I.ppid&&(_e("Session: Detected corrupted PPID during load, repairing to string:",I.ppid),I.ppid=Object.values(I.ppid).join(""),pe({ppid:I.ppid}),_e("PPID repaired and saved to session passport:",I.ppid)),function(){const e=I.consent;if(!e||"object"!=typeof e||Array.isArray(e))return;const t=Object.keys(e).filter(e=>!S.includes(e));if(!t.length)return;const i={};S.forEach(t=>{void 0!==e[t]&&(i[t]=e[t])}),I.consent=i,_e(`Session: pruned ${t.length} legacy key(s) from passport.consent.`)}(),I.pageCount=(I.pageCount||1)+1,sessionStorage.setItem(v,JSON.stringify(I)),_e("Session data successfully loaded and updated from cache:",I)):(I={version:"1.1",createdAt:Date.now(),pageCount:1,hasConsent:!0,gdprConsentUUID:"",usnatConsentUUID:"",gdprApplies:!1,usnatApplies:!1},sessionStorage.setItem(v,JSON.stringify(I)),_e("First page view: Initialized session data."))}catch(e){_e("Could not parse session data, starting fresh."),sessionStorage.removeItem(v),I={version:"1.0",createdAt:Date.now(),pageCount:1}}}(),"boolean"==typeof I.hasConsent?(R=I.hasConsent,_e("Consent: Set from session data:",{hasConsent:R})):(R=!0,_e("Consent: Session data missing hasConsent flag, defaulting global state to true.")),!0===I.consentResolved&&I.pageCount>1&&(_e("CMP: Reusing the consent decision resolved earlier this session â skipping the wait.",{hasConsent:R}),j()),I.pageCount>1?(_e("Session: applying optimizations, subsequent page visit ",I.pageCount),I.geo&&I.geo.country?(_e("Session: Using cached Geo Data from session passport:",I.geo),window.maiPubGeo=I.geo,Pe(I.geo),M()):(_e("Session: no cached geo in the passport on a subsequent pageview â fetching geo.js."),we(function(e){_e(e?"GEO: data available from worker and enrichment is done":"GEO: unavailable â continuing without geo enrichment or region gating."),M()})),I.ppid&&"object"==typeof I.ppid&&null!==I.ppid&&(_e("Session: detected corrupted PPID (object format), repairing to string"),I.ppid=Object.values(I.ppid).join(""),pe({ppid:I.ppid}))):(_e("First page load detected., calling geo.js"),we(function(e){_e(e?"GEO: data available from worker and enrichment is done":"GEO: unavailable â continuing without geo enrichment or region gating."),M()})),function(){const e=maiPubAdsVars.id5Identity||{};if(e.hem)I.hem===e.hem&&"server"===I.hemSource||(I.hem=e.hem,I.hemSource="server",I.isBurnerEmail=e.isBurnerEmail||"",I.phone=e.phone||"",pe({hem:I.hem,hemSource:"server",isBurnerEmail:I.isBurnerEmail,phone:I.phone}),Se(e.hem),_e("ID5: identity signals stored in session passport."));else if(!I.hem){const e=function(){const e=document.cookie.match(/(?:^|;)\s*maipub_hem=([^;]*)(?:;|$)/);return e?decodeURIComponent(e[1]):""}();e&&(I.hem=e,I.hemSource="cookie",I.phone="",I.isBurnerEmail="",pe({hem:e,hemSource:"cookie",phone:"",isBurnerEmail:""}),_e("ID5: hashed email restored from persistent cookie."))}}(),ce(),function(){const e=maiPubAdsVars.fpid||{},t=void 0===e.param?"sw_fpid":e.param;if(!t)return;let i;try{i=new URLSearchParams(window.location.search).get(t)}catch(e){return}if(null!==i&&(i&&function(e,t){if(maiPubAdsVars.id5Identity&&maiPubAdsVars.id5Identity.hem)return void _e(`Identity: ${e} present but the user is logged in â keeping the server hash.`);const i=function(e){if(!e||"string"!=typeof e)return"";const t=e.trim();if(/^[a-f0-9]{64}$/i.test(t))return t.toLowerCase();if(/^[A-Za-z0-9+/_-]{43}=?$/.test(t))try{const e=atob(t.replace(/-/g,"+").replace(/_/g,"/"));if(32!==e.length)return"";let i=0;for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);n>=32&&n<=126&&i++}if(i===e.length)return _e("Identity: fpid decoded to printable text, not a digest â rejected. Check the email platform is sending a SHA-256 hash, not a base64-encoded address."),"";let n="";for(let t=0;t<e.length;t++)n+=e.charCodeAt(t).toString(16).padStart(2,"0");return n}catch(e){return""}return""}(t);if(!i)return I.fpidRaw=t,pe({fpidRaw:t}),void _e(`Identity: ${e} is not a recognizable SHA256 digest â stored for debugging, NOT used as a hashed email.`);I.hem!==i&&(I.hem=i,I.hemSource="fpid",I.phone="",I.isBurnerEmail="",pe({hem:i,hemSource:"fpid",phone:"",isBurnerEmail:""}),Se(i),_e(`Identity: hashed email captured from ${e} (newsletter click).`))}(t,i),e.strip))try{const e=new URL(window.location.href);e.searchParams.delete(t),window.history.replaceState({},"",e.toString()),_e(`Identity: ${t} stripped from the URL.`)}catch(e){_e(`Identity: could not strip ${t} from the URL.`,e)}}(),function(){if(maiPubAdsVars.ppid){const e=maiPubAdsVars.ppid;return I.ppid===e&&"server"===I.ppidSource||(_e(`PPID: server id present (logged in) â upgrading from '${I.ppidSource||"none"}' to 'server'.`),I.ppid=e,I.ppidSource="server",pe({ppid:e,ppidSource:"server"}),re(e,"server")),V=e,V}if(I.hem&&"server"!==I.ppidSource){const e=I.hem;return I.ppid===e&&"fpid"===I.ppidSource||(_e(`PPID: hashed email in the passport â upgrading from '${I.ppidSource||"none"}' to 'fpid'.`),I.ppid=e,I.ppidSource="fpid",pe({ppid:e,ppidSource:"fpid"}),re(e,"fpid")),V=e,V}if(I.ppid&&I.ppidSource)return V=I.ppid,V;const e=function(){const e=document.cookie.match(/(?:^|;)\s*maipub_ppid=([^;]*)(?:;|$)/);return e?decodeURIComponent(e[1]):""}();if(e){const t=function(){const e=document.cookie.match(/(?:^|;)\s*maipub_ppid_source=([^;]*)(?:;|$)/);return e?decodeURIComponent(e[1]):""}()||"cookie";return I.ppid=e,I.ppidSource=t,pe({ppid:e,ppidSource:t}),_e(`PPID: adopted from cookie (source: ${t}).`),V=e,V}try{if(!window.crypto)throw new Error("Web Crypto API is not available.");const e="function"==typeof crypto.randomUUID?crypto.randomUUID():Array.from(crypto.getRandomValues(new Uint8Array(16))).map(e=>e.toString(16).padStart(2,"0")).join("");return I.ppid=e,I.ppidSource="random",pe({ppid:e,ppidSource:"random"}),re(e,"random"),_e("PPID: no prior identity â generated a random id."),V=e,V}catch(e){return _e("PPID: generation failed.",e),V||""}}(),_e("PPID resolved.",I.ppid,`(source: ${I.ppidSource||"none"})`);const D=1,L=3;function j(){if(!0===_)return void _e("CMP: Already marked as ready - skipping duplicate dispatch.");_=!0,_e("CMP: Marked as ready - dispatching event."),he();const e=new CustomEvent("maiPubCMPReady",{detail:{timestamp:Date.now()}});window.dispatchEvent(e)}function O(){const e=document.querySelector(".mai-ad-unit-sticky-footer"),t=e?Math.max(e.offsetHeight,90):0;t>0&&(document.body.style.paddingBottom=`${t}px`);const i=t+15,n=["mobile","tablet","desktop"],s=document.querySelectorAll(".mai-ad-unit-video");
1s.forEach(e=>{const t=window.getComputedStyle(e);n.forEach(n=>{const s=parseInt(t.getPropertyValue(`--gutter-y-${n}`),10)||0;e.style.setProperty(`--footer-offset-${n}`,0===s?`${i}px`:"0px")})}),_e(`Sticky footer: synced --footer-offset (auto=${t}+15gap px where Gutter Y=0, else forced gutter; footer ${e?"present":"absent"}) to ${s.length} floating video player(s).`)}function q(){if(i)return!0;O();const e=document.querySelector(".mai-ad-unit-sticky-footer");return!!e&&(i=!0,_e("Sticky footer ad found."),"function"==typeof ResizeObserver&&new ResizeObserver(()=>O()).observe(e),!0)}function z(e){return"ts"===e||"bs"===e}function B(e,t){const i=e.getAttribute("id");if(!i)return _e("maiPubClassifyAdUnit: Skipping ad unit with no ID",e),null;const n=i.replace("mai-ad-",""),s="object"==typeof g&&g?g[n]:null;if(!s)return _e(`Skipping ${i}, no config found.`),null;o[i]||(o[i]={processing:!1,visible:null,lastRefreshTime:0,firstRender:!0,retryCount:0,slotObject:null});const a=e.closest(".mai-ad-unit-container"),r=s.targets&&s.targets.ap?s.targets.ap:null,d=z(r)||!(!a||!a.classList.contains("mai-ad-unit-sticky-header")&&!a.classList.contains("mai-ad-unit-sticky-footer")),l="vs"===r,c="atf"===r,u=e.getBoundingClientRect(),p=window.innerHeight||document.documentElement.clientHeight,h=u.top<p;let m=!1;return c?m=0===u.width&&0===u.height||h:d?m=!0:l&&(m=!(0===u.width&&0===u.height)&&h,m||_e(`maiPubRun: Vertical sticky ${n} is below the fold (top: ${Math.round(u.top)}px, viewport: ${p}px) â lazy-loading it instead of fast-pathing.`)),m?(_e(`maiPubRun: Fastpath candidate: ${n} (fixed adhesion: ${d}, vertical sticky: ${l}, atf: ${c})`),n):(_e(`maiPubRun: Lazyload candidate: ${n}. Observing.`),t.observe(e),null)}function x(t,i){t.length?(_e(`maiPubRun: Fastpath slot processing: ${t.length} ${t.join(", ")}`),googletag.cmd.push(()=>{t.forEach(e=>{const t=`mai-ad-${e}`,i=N(e);i&&(o[t]||(o[t]={processing:!1,visible:null,lastRefreshTime:0,firstRender:!0,retryCount:0,slotObject:null}),o[t].slotObject=i,o[t].processing=!0,o[t].visible=!0,_e(`maiPubRun: Fastpath: Prepared slot ${t} for ad request`))}),e||(googletag.enableServices(),e=!0),_e(`maiPubRun: Fastpath: Requesting ads for slots: ${t.join(", ")}`),F(t,i)})):_e("maiPubRun: No Fastpath slots found, proceeding with lazy-load processing only")}function G(e){if(!g[e]||"spotlight"!==g[e].id)return!1;const t=g[e].sizes;return Array.isArray(t)?t.includes("out-of-page"):"out-of-page"===t}function N(e){const t=document.getElementById("mai-ad-"+e);if(t&&t.classList.contains("mai-ad-video"))return _e(`maiPubDefineSlot(): Skipping video ad slot ${e} - should be handled by video player`),null;if(!g[e])return _e(`maiPubDefineSlot(): Halting definition for slug '${e}' because no configuration was found in the 'ads' object.`),null;if(G(e)&&u&&u!==e)return _e(`maiPubDefineSlot(): Skipping duplicate spotlight slot ${e}; only one per page.`),null;const i="mai-ad-"+e,o=googletag.pubads().getSlots().find(e=>e.getSlotElementId()===i);if(o)return _e(`maiPubDefineSlot(): Slot ${i} already defined, returning existing slot`),o;const a=g?.[e]?.context&&"client"===g[e].context?m:h;_e(`maiPubDefineSlot() base: ${a}`),_e(`maiPubDefineSlot() slotDivId: ${i}`);const r=a+g[e].id;let d;_e(`maiPubDefineSlot() GAM Ad Unit Path: ${r}`);const c={};if(g[e].sizes&&(Array.isArray(g[e].sizes)?g[e].sizes.includes("out-of-page"):"out-of-page"===g[e].sizes)?(d=googletag.defineOutOfPageSlot(r,i),_e(`maiPubDefineSlot() defineOutOfPageSlot: ${r}`)):(d=googletag.defineSlot(r,g[e].sizes,i),_e(`maiPubDefineSlot() defineSlot: ${r}, sizes: ${g[e].sizes}, slotDivId: ${i}`)),!d)return _e(`maiPubDefineSlot(): Failed to define slot for ${i} - googletag.defineSlot returned null`),null;if(G(e)&&(u=e),d.addService(googletag.pubads()),_e("maiPubDefineSlot() addService"),c[l]=f.toString(),_e(`maiPubDefineSlot() targetingConfig: Added ${l}: ${c[l]}`),g[e].targets&&Object.keys(g[e].targets).forEach(t=>{let i=g[e].targets[t];"string"==typeof i||Array.isArray(i)?Array.isArray(i)&&(i=i.map(e=>e.toString())):i=i.toString(),c[t]=i,_e(`maiPubDefineSlot() targetingConfig: Added slot target ${t}: ${i}`)}),g[e].splitTest&&"rand"===g[e].splitTest){const e=Math.floor(100*Math.random()).toString();c.st=e,_e(`maiPubDefineSlot() targetingConfig: Added splitTest 'st': ${e}`)}const p=document.getElementById(i),b=p?p.getAttribute("data-ap"):null;if(b&&("ts"===b||"bs"===b||"vs"===b)&&(c.ad_placement_type="sticky",_e("maiPubDefineSlot() targetingConfig: Added sticky 'ad_placement_type': 'sticky'"),_e(`maiPubDefineSlot() Sticky ad detected ${i} (position: ${b}) - ORTB2 imp.viewability will be set later`,{isSticky:!0,position:b,ortb2Status:"Will be set at 100% for Prebid bidders during requestBids"})),Object.keys(c).length>0?(d.setConfig({targeting:c}),_e("maiPubDefineSlot() Applied setConfig with targeting:",c)):_e("maiPubDefineSlot() No targeting keys found, skipping setConfig."),_e(`maiPubDefineSlot() checking sizes for ${e}:`,{sizes:g[e].sizes,sizesDesktop:g[e].sizesDesktop,sizesTablet:g[e].sizesTablet,sizesMobile:g[e].sizesMobile}),g[e].sizes&&(Array.isArray(g[e].sizes)?g[e].sizes.includes("out-of-page"):"out-of-page"===g[e].sizes))_e(`maiPubDefineSlot() skipping size mapping for out-of-page ad: ${e}`);else{const t=g[e].sizesDesktop||[],i=g[e].sizesTablet||[],n=g[e].sizesMobile||[];d.defineSizeMapping(googletag.sizeMapping().addSize([1024,768],t).addSize([728,480],i).addSize([0,0],n).build()),_e("maiPubDefineSlot() defineSizeMapping")}return _e(`Defined slot: ${i} via ${r}`,()=>({gamId:r,slot:d,targets:d.getTargetingMap()})),n.push(r),s.push(d),d}function F(t,i="unknown"){t&&t.length&&(_e(()=>`maiPubBatchRequestSlots(): Adding ${t.length} slots from ${i}: ${t.join(", ")}`),document.hidden&&i.includes("refresh-timeout")?_e(`maiPubBatchRequestSlots(): Blocked scheduled refresh from ${i}
1 because the page is hidden.`):(t.forEach(e=>{p.pendingSlugs.add(e),p.pendingSources.set(e,i)}),p.batchTimeout&&clearTimeout(p.batchTimeout),p.batchTimeout=setTimeout(()=>{!function(){if(p.processing||0===p.pendingSlugs.size)return;const t=Array.from(p.pendingSlugs),i=new Map(p.pendingSources);p.pendingSlugs.clear(),p.pendingSources.clear(),p.batchTimeout=null,p.processing=!0,_e(()=>`maiPubProcessBatchedRequests(): Processing batch of ${t.length} slots: ${t.join(", ")}`);const n=Array.from(i.values()).some(e=>e.includes("fast-path")||e.includes("sticky")||e.includes("atf")),s=n?1500:r;_e(`maiPubProcessBatchedRequests(): Using ${s}ms timeout (${n?"fast-path":"regular"})`);const l=t.map(e=>i.get(e)||"").join("|");(function(t,i=2800,n=""){googletag.cmd.push(()=>{Date.now();const s=t.map(e=>{const t="mai-ad-"+e,i=o[t];if(!i||!i.slotObject||!oe(i.slotObject))return _e(`maiPubMaybeRequestSlots(): warning: Slot info or object missing/not refreshable for slug ${e}.`,i),null;const n=i.slotObject;return i.firstRender?(_e(`maiPubMaybeRequestSlots(): first request for ${t}`),n):i.processing?(_e(`maiPubMaybeRequestSlots(): skipping request for ${t} - already being processed`),null):i.visible?n:(_e(`maiPubMaybeRequestSlots(): skipping request for ${t} - not visible`),clearTimeout(a[t]),delete a[t],null)}).filter(e=>null!==e);s.length&&function(t,i=2800,n=""){if("demo"===maiPubAdsVars.mode)return void _e(`Demo Mode: Simulating request for ${t.length} slots (no network calls).`);Date.now(),t.forEach(e=>{const t=e.getSlotElementId();o[t].processing=!0,clearTimeout(a[t]),delete a[t]}),_e(()=>`Requesting slots: ${t.map(e=>e.getSlotElementId()).join(", ")}`);const s={adserverRequestSent:!1,magniteReady:!maiPubAdsVars.magnite,catalystReady:!maiPubAdsVars.catalyst,magniteAuction:null,isPrebidEnabled:()=>maiPubAdsVars.magnite,isCatalystEnabled:()=>maiPubAdsVars.catalyst,canProceedWithAdserverRequest(){return this.magniteReady&&this.catalystReady}};Date.now();let l=null;const c=function(){if(s.adserverRequestSent)return void _e("Adserver request already sent, skipping. State:",{magniteReady:s.magniteReady,catalystReady:s.catalystReady,slots:t.map(e=>e.getSlotElementId())});const i=n.includes("refresh")||n.includes("empty-slot")||n.includes("observer-visible")||n.includes("viewability-change"),a=n.includes("refresh")||n.includes("empty-slot");if(i)H().length>0&&_e(`sendAdserverRequest(): Skipping video gate for refresh batch (source: ${n})`);else{const e=H();if(e.length>0)return _e(`sendAdserverRequest(): Waiting for ${e.length} video ad(s) to finish loading...`),void Promise.all(e).then(()=>{_e("sendAdserverRequest(): All video ads finished. Proceeding with display ad refresh."),c()})}s.adserverRequestSent=!0,clearTimeout(l),_e(()=>`sendAdserverRequest(): requestManager() set to true to refresh slots: ${t.map(e=>e.getSlotElementId()).join(", ")}`),googletag.cmd.push(()=>{e||(googletag.enableServices(),e=!0),t.forEach(e=>{const t=e.getSlotElementId();o[t]&&(o[t].firstRender=!1)}),maiPubAdsVars.magnite&&"undefined"!=typeof pbjs&&(function(e){if("undefined"==typeof pbjs)return;const t=e.map(e=>e.getSlotElementId()),i=()=>
1{if("function"==typeof pbjs.setTargetingForGPTAsync)try{pbjs.setTargetingForGPTAsync(t),_e(()=>`sendAdserverRequest(): Clean asynchronous targeting map compiled for: ${t.join(", ")}`)}catch(e){_e("sendAdserverRequest(): pbjs.setTargetingForGPTAsync failed",e)}else if("function"==typeof pbjs.setTargetingForGPT)try{pbjs.setTargetingForGPT(t),_e(()=>`sendAdserverRequest(): pbjs.setTargetingForGPT() for: ${t.join(", ")}`)}catch(e){_e("sendAdserverRequest(): pbjs.setTargetingForGPT failed",e)}else _e("sendAdserverRequest(): Prebid setTargetingForGPT(Async) unavailable; using manual HB targeting only");!function(e){if("undefined"==typeof pbjs)return;const t=pbjs.getAdserverTargetingForAdUnitCode,i="function"==typeof t;e.forEach(e=>{const n=e.getSlotElementId(),s=Q(e);let o=!1;const a=e.getAdUnitPath(),r=a.includes(",")?"/"+a.split(",")[1]:a,d=[...new Set([...s.filter(e=>-1!==e.indexOf("#")||e===n||e===n.replace("mai-ad-","")),a,r])];if(i)for(const i of d){const s=t(i);if(s&&Object.keys(s).some(e=>0===e.indexOf("hb_"))&&J(e,s)){o=!0,_e(`Applied Prebid ad-server targeting for ${n} via code "${i}"`,s);break}}if(!o){const t=function(e){if("undefined"==typeof pbjs||!e)return null;for(const t of Q(e)){const e=K(t);if(e.length)return e.reduce((e,t)=>!e||t.cpm>e.cpm?t:e,null)}if("function"==typeof pbjs.getAllWinningBids){const t=Q(e),i=pbjs.getAllWinningBids().find(e=>t.includes(e.adUnitCode));if(i)return i}return null}(e);t&&function(e,t){if(!e||!t)return!1;const i={};"function"==typeof pbjs.getAdserverTargeting&&(t.adUnitCode||t.code)&&Object.assign(i,pbjs.getAdserverTargeting(t)||{}),null!=t.cpm&&null==i.hb_pb&&(i.hb_pb=Number(t.cpm).toFixed(2)),!t.bidderCode&&!t.bidder||i.hb_bidder||(i.hb_bidder=t.bidderCode||t.bidder),t.adId&&!i.hb_adid&&(i.hb_adid=t.adId),t.ad&&!i.hb_adid&&(i.hb_adid=t.ad),t.size&&!i.hb_size&&(i.hb_size=`${t.size[0]}x${t.size[1]}`);const n=Object.keys(i).filter(e=>0===e.indexOf("hb_"));if(!n.length)return!1;const s={};if(n.forEach(e=>{const t=i[e];s[e]=Array.isArray(t)?String(t[0]):String(t)}),"function"==typeof e.setConfig){const t=e.getConfig("targeting")||{},i=t.targeting||t;e.setConfig({targeting:{...i,...s}})}else{const t={};n.forEach(e=>{t[e]=s[e]}),e.setConfig({targeting:t})}return!0}(e,t)&&_e(`Applied Prebid bid object for ${n}`,()=>({cpm:t.cpm,bidder:t.bidderCode||t.bidder,adUnitCode:t.adUnitCode}))}})}(e)};void 0!==pbjs.que?pbjs.que.push(i):i()}(t,s.magniteAuction),function(e){if(maiPubAdsVars.magnite&&"undefined"!=typeof pbjs&&"function"==typeof pbjs.setPAAPIConfigForGPT)try{if(e&&1===e.length){const t=e[0].getSlotElementId().replace("mai-ad-","");pbjs.setPAAPIConfigForGPT({adUnitCode:t}),_e(`sendAdserverRequest(): pbjs.setPAAPIConfigForGPT({ adUnitCode: '${t}' })`)}else pbjs.setPAAPIConfigForGPT(),_e("sendAdserverRequest(): pbjs.setPAAPIConfigForGPT()")}catch(e){_e("sendAdserverRequest(): setPAAPIConfigForGPT failed",e)}}(t));const i={changeCorrelator:a},n=()=>{try{googletag.pubads().refresh(t,i),_e(()=>`sendAdserverRequest(): googletag.pubads().refresh() called for slots ${t.length} ${1===t.length?"slot":"slots"} (changeCorrelator: ${i.changeCorrelator}): ${t.map(e=>e.getSlotElementId()).join(", ")}`),t.forEach(e=>{const t=e.getSlotElementId();o[t]&&o[t].visible&&o[t].firstRender&&(googletag.display(t),_e(`sendAdserverRequest(): Displayed Fastpath slot ${t}`))})}catch(e){_e("Error calling googletag.pubads().refresh():",e)}};maiPubAdsVars.magnite&&"undefined"!=typeof pbjs?setTimeout(()=>{ee(t,"before refresh"),n()},50):n()})},u=function(){s.canProceedWithAdserverRequest()&&c()},p=i+400+300;if(l=setTimeout(()=>{s.adserverRequestSent||(_e(()=>`maiPubRequestSlots(): FAILSAFE timeout (${p}ms) reached before all bidders returned (prebid:${s.magniteReady} catalyst:${s.catalystReady}). Forcing adserver request for: ${t.map(e=>e.getSlotElementId()).join(", ")}`),c())},p),!0!==R&&maiPubAdsVars.ortb2&&maiPubAdsVars.ortb2.user&&delete maiPubAdsVars.ortb2.user.data,!0===maiPubAdsVars.magnite&&!0===R){_e("maiPubRequestSlots(): Magnite DM adapter enabled, requesting bids");const e=t.filter(e=>{const t=e.getSlotElementId().replace("mai-ad-",""),i=!!g[t]?.enabled_bidders?.includes("magnite");return _e("Prebid slot check:",()=>({slug:t,enabled_bidders:g[t]?.enabled_bidders,hasPrebidEnabled:i,adsConfig:g[t]})),i});_e("Prebid slot filtering results:",()=>({totalSlots:t.length,prebidEligibleSlots:e.length,prebidSlotIds:e.map(e=>e.getSlotElementId())})),e.length>0?pbjs.que.push(function(){const t=Date.now();pbjs.rp.requestBids({gptSlotObjects:e,ortb2:maiPubAdsVars.ortb2,timeout:i,callback:function(i,n,o){s.magniteAuction={bids:i,prebidSlots:e,timedOut:n,auctionId:o},googletag.cmd.push(()=>
1{s.magniteReady=!0,u(),_e(`sendAdserverRequest(): Prebid response time: ${Date.now()-t}ms`,{bids:i,timedOut:n,auctionId:o}),(d||b)&&W(e)})}})}):(_e("No slots eligible for Magnite DM bidding. Marking magniteReady as true."),s.magniteReady=!0)}else!0===maiPubAdsVars.magnite&&!1===R?_e("Magnite DM adapter enabled but hasConsent is false (GDPR timeout). Skipping Prebid request, using non-personalized GAM ads."):_e("Magnite DM adapter disabled globally, skipping Prebid request."),s.magniteReady=!0;if(!0===maiPubAdsVars.catalyst&&!0===R){const e=t.filter(e=>{const t=e.getSlotElementId().replace("mai-ad-","");return!!maiPubAdsVars.ads[t]?.enabled_bidders?.includes("catalyst")});e.length>0?(_e("Catalyst: Checking GVL ID 1494 consent before sending bid request"),(!1===I.gdprApplies?(_e("TCF: GDPR does not apply (US/Global). Skipping GVL check for 1494."),Promise.resolve(!0)):"function"==typeof window.__tcfapi?new Promise(e=>{let t=!1;const i=setTimeout(()=>{t||(t=!0,_e("TCF: Timeout checking GVL ID 1494. Defaulting to false."),e(!1))},2e3);window.__tcfapi("getTCData",2,(n,s)=>{if(t)return;if(t=!0,clearTimeout(i),!s||!n)return _e(`TCF: getTCData failed for GVL ID 1494. success=${s}`),void e(!1);if(_e(`TCF: gdprApplies=${n.gdprApplies}, eventStatus=${n.eventStatus}, cmpStatus=${n.cmpStatus}`),!1===n.gdprApplies)return _e("TCF: GDPR does not apply per TCF response. Allowing GVL ID 1494."),void e(!0);const o=!0===n?.vendor?.consents?.[1494],a=!0===n?.vendor?.legitimateInterests?.[1494];_e(`TCF: GVL ID 1494 - consent=${o}, legInt=${a}`),e(o||a)})}):(_e("TCF: No __tcfapi found but GDPR applies. Blocking GVL ID 1494."),Promise.resolve(!1))).then(t=>{if(!t)return _e("Catalyst: No consent for GVL ID 1494 - blocking bid request to comply with GDPR"),void(s.catalystReady=!1);if(_e(`Catalyst: GVL ID 1494 consent verified - requesting bids for ${e.length} slots`),"function"==typeof window.catalyst?.requestBids){const t=Date.now(),n={slots:e.map(e=>{const t=e.getSlotElementId().replace("mai-ad-",""),i=maiPubAdsVars.ads[t];return{divId:e.getSlotElementId(),sizes:i?.sizes||[[300,250]]}}),timeout:maiPubAdsVars.catalystTimeout||i,user:{gdprApplies:I?.gdprApplies||!1,consent:I?.consent?.tcString||"",id:I?.ppid||maiPubAdsVars?.ppid,ext:{}}};if("undefined"!=typeof pbjs&&"function"==typeof pbjs.getUserIdsAsEids){const e=pbjs.getUserIdsAsEids();e&&e.length>0?(n.user.ext.eids=e,_e(`Catalyst: Added ${e.length} extended user IDs (eids) from Prebid`,e)):_e("Catalyst: No extended user IDs available from Prebid")}else _e("Catalyst: Prebid.js getUserIdsAsEids() not available");if(maiPubAdsVars?.ortb2?.device&&(n.device=maiPubAdsVars.ortb2.device,_e("Catalyst: Added ORTB2 device data")),maiPubAdsVars?.ortb2?.site){const{id:e,publisher:t,...i}=maiPubAdsVars.ortb2.site,s={...i};if(t){const{id:e,...i}=t;s.publisher=i}n.site=s,_e("Catalyst: Added ORTB2 site data (incl. site.content; Magnite site.id/publisher.id stripped)")}maiPubAdsVars?.ortb2?.app&&(n.app=maiPubAdsVars.ortb2.app,_e("Catalyst: Added ORTB2 app data")),window.catalyst.requestBids(n,i=>{googletag.cmd.push(()=>{_e(`Catalyst response time: ${Date.now()-t}ms`,i),window.catalyst.setTargeting(e.map(e=>e.getSlotElementId())),s.catalystReady=!0,u()})})}else _e("Catalyst SDK not available (window.catalyst missing). Marking done."),s.catalystReady=!0}).catch(e=>{_e("Catalyst: Error checking GVL consent:",e),s.catalystReady=!0})):(_e("Catalyst: No eligible slots found"),s.catalystReady=!0)}else!0===maiPubAdsVars.catalyst&&!1===R?_e("Catalyst enabled but hasConsent is false (GDPR timeout). Skipping Catalyst request."):_e("No Catalyst enabled, skipping Catalyst request."),s.catalystReady=!0;maiPubAdsVars.magnite||maiPubAdsVars.reviq||maiPubAdsVars.catalyst||(_e(`No bidder adapters available. Sending adserver request with GAM: ${t.map(e=>e.getSlotElementId()).join(", ")}`,t),c()),u(),setTimeout(()=>{s.adserverRequestSent||(_e("Failsafe timeout reached. Sending adserver request without all bids."),c())},r)}(s,i,n)})})(t,s,l),setTimeout(()=>{p.processing=!1},50)}()},p.batchDelay)))}function H(){const e=window.innerHeight||document.documentElement.clientHeight;return $.filter(t=>{if(null===t.adLoadPromise)return!1;const i=t.container||document.getElementById(t.config.id);if(!i)return!0;const n=i.getBoundingClientRect();return n.bottom>0&&n.top<e}).map(e=>e.adLoadPromise)}function W(e){if("undefined"==typeof pbjs)return;_e("Magnite auction for GPT slots:",e.map(e=>e.getSlotElementId())),pbjs.rp&&!W._rpLogged&&(W._rpLogged=!0,_e("pbjs.rp functions:",Object.keys(pbjs.rp).filter(e=>"function"==typeof pbjs.rp[e]))),pbjs.adUnits&&pbjs.adUnits.length&&_e("Prebid adUnits:",pbjs.adUnits.map(e=>({code:e.code,bids:K(e.code).length})));const t="function"==typeof pbjs.getAllWinningBids?pbjs.getAllWinningBids():[];t.length?_e("Prebid winning bids:",t.map(e=>({adUnitCode:e.adUnitCode,cpm:e.cpm,bidder:e.bidderCode||e.bidder}
1))):_e("Prebid winning bids: none"),e.forEach(e=>{const t=e.getSlotElementId(),i=Q(e),n={};i.forEach(e=>{const t="function"==typeof pbjs.getAdserverTargetingForAdUnitCode?pbjs.getAdserverTargetingForAdUnitCode(e):null;t&&Object.keys(t).length&&(n[e]=t)}),Object.keys(n).length&&_e(`Prebid ad-server targeting candidates for ${t}:`,n)})}function Q(e){const t=e.getSlotElementId(),i=t.replace("mai-ad-",""),n=e.getAdUnitPath(),s=n.includes(",")?"/"+n.split(",")[1]:n;return[...new Set([t,i,n,s,n+"#"+t,n+"#"+i,s+"#"+t,s+"#"+i])]}function K(e){if("undefined"==typeof pbjs||!e)return[];if("function"==typeof pbjs.getHighestCpmBids){const t=pbjs.getHighestCpmBids(e);if(t&&t.length)return t}if("function"!=typeof pbjs.getBidResponses)return[];const t=pbjs.getBidResponses(e);return t?Array.isArray(t)?t:t.bids||[]:[]}function J(e,t){if(!e||!t||"object"!=typeof t)return!1;const i={};if(Object.keys(t).forEach(e=>{if(0!==e.indexOf("hb_"))return;const n=t[e];i[e]=Array.isArray(n)?String(n[0]):String(n)}),!Object.keys(i).length)return!1;if("function"==typeof e.setConfig){const t=e.getConfig("targeting")||{},n=t.targeting||t;e.setConfig({targeting:{...n,...i}})}
1else"function"==typeof e.setTargeting&&Object.keys(i).forEach(t=>{e.setTargeting(t,i[t])});return!0}function Z(e){const t={};if(!e)return t;if("function"==typeof e.getTargetingMap){const i=e.getTargetingMap()||{};return Object.keys(i).forEach(e=>{0===e.indexOf("hb_")&&(t[e]=i[e])}),t}if("function"==typeof e.getConfig){const i=e.getConfig("targeting")||{},n=i.targeting||i;Object.keys(n).forEach(e=>{0===e.indexOf("hb_")&&(t[e]=n[e])})}return t}function Y(e){if(null==e||""===e)return null;if(Array.isArray(e)){if(0===e.length)return null;const t=e[0];return null==t||""===t?null:String(t)}const t=String(e);return"undefined"===t||"null"===t?null:t}function X(e){const t=Z(e),i=Y(t.hb_pb),n=null!=(s=i)&&""!==s&&/^\d+(\.\d+)?$/.test(String(s))?i:null;var s;return{hasHbPb:!!n,hb_pb:n,hb_bidder:Y(t.hb_bidder),hb_size:Y(t.hb_size)}}function ee(e,t){(d||b)&&e.forEach(e=>{const i=Z(e),n=e.getSlotElementId(),s=Array.isArray(i.hb_pb)?i.hb_pb[0]:i.hb_pb,o=Array.isArray(i.hb_bidder)?i.hb_bidder[0]:i.hb_bidder;s||o||i.hb_adid||Array.isArray(i.hb_adid)&&i.hb_adid.length?_e(`HB targeting (${t}) ${n}:`,i):_e(`HB targeting (${t}) ${n}: no hb_pb/hb_bidder on slot â Prebid bid not applied (check ad unit code vs div id / duplicate GAM path)`,{adUnitPath:e.getAdUnitPath(),keysPresent:Object.keys(i),hb:i})})}function te(e){return e&&n.includes(e.getAdUnitPath())}function ie(e){const t=o[e];if(!t||t.isOOP||t.seenSince||!U)return;t.seenSince=Date.now();const i=Math.max(0,32e3-(t.seenMs||0));clearTimeout(a[e]),a[e]=setTimeout(()=>se(e),i)}function ne(e){const t=o[e];t&&!t.isOOP&&t.seenSince&&(t.seenMs=(t.seenMs||0)+(Date.now()-t.seenSince),t.seenSince=null,clearTimeout(a[e]),delete a[e])}function se(e){const t=o[e];if(!t)return;t.seenSince&&(t.seenMs=(t.seenMs||0)+(Date.now()-t.seenSince),t.seenSince=null);const i=t.vizThreshold||50,n=(t.currentInView||0)>=i;t.hasBeenViewable&&n&&U&&t.seenMs>=32e3&&oe(t.slotObject)?(_e(()=>`Viewable-refresh: ${e} â banked ${Math.round(t.seenMs/1e3)}s seen at >=${i}%, impressionViewable=true. Refreshing.`),F([e.replace("mai-ad-","")],"viewable-refresh")):n&&U&&(t.deferChecks||0)<5&&(t.deferChecks=(t.deferChecks||0)+1,_e(()=>`Viewable-refresh: ${e} deferred (${t.deferChecks}/5) â seenMs=${Math.round(t.seenMs)} hasBeenViewable=${t.hasBeenViewable} inView=${Math.round(t.currentInView||0)}% (need >=${i}%).`),clearTimeout(a[e]),a[e]=setTimeout(()=>se(e),1e3))}function oe(e){if(!e)return!1;let t;if("function"==typeof e.getConfig){const i=e.getConfig("targeting")||{};t=(i.targeting||i)[l]}return Boolean(Array.isArray(t)?t[0]:t)}function ae(e,t,i){const n="https:"===location.protocol?"; Secure":"";t.sig=i,document.cookie=`${e}=${encodeURIComponent(JSON.stringify(t))}; Path=/; Max-Age=3600; SameSite=Lax${n}`}function re(e,t="unknown"){if(!ge())return void _e("Consent not settled (or withheld). Deferring persistent PPID cookie.");if(!e)return;const i=new Date(Date.now()+31536e6).toUTCString();document.cookie=`maipub_ppid=${encodeURIComponent(e)};path=/;expires=${i};SameSite=Lax;Secure`,document.cookie=`maipub_ppid_source=${encodeURIComponent(t)};path=/;expires=${i};SameSite=Lax;Secure`,_e("PPID and Source saved to persistent cookies.",t)}window.maiPubIdentity=function(){const e=ce(),t=ue();return{arrival:e,tier:t,matomoDimensions:{[D]:e,[L]:t}}}(),maiPubAdsVars.pubGoogleTag?_e(`CMP: Publisher Google Tag: ${maiPubAdsVars.pubGoogleTag}`):_e("CMP: No Publisher Google Tag found"),maiPubAdsVars.swGoogleTag?_e(`CMP: Springwire Google Tag: ${maiPubAdsVars.swGoogleTag}`):_e("CMP: No Springwire Google Tag found"),function(){_e("=== PARALLEL INITIALIZATION STARTED ===");const i=new Promise(e=>{_e("=== BIDDING SYSTEMS INITIALIZATION (STRICT MODE) ===");const i={prebid:!1,reviq:!1,catalyst:!1,cmp:!1,magniteDisabled:!maiPubAdsVars.magnite,reviqDisabled:!maiPubAdsVars.reviq,catalystDisabled:!maiPubAdsVars.catalyst,cmpDisabled:!1},n=(e,t,i,n={})=>{if(document.getElementById(e))return _e(`Script ${e} already exists. Calling callback.`),void i();_e(`Dynamically injecting script: ${t}`);const s=document.createElement("script");s.id=e,s.async=!0,s.src=t;const o=setTimeout(()=>{_e(`Warning: Script ${e} took too long to load. Proceeding without it to save LCP.`),i()},3e3);
1s.setAttribute("fetchpriority","high"),Object.keys(n).forEach(e=>{s.setAttribute(e,n[e])}),s.onload=()=>{clearTimeout(o),i()},s.onerror=()=>{clearTimeout(o),_e(`Error loading script ${t}`),i()},document.head.appendChild(s)},s=()=>{const n=i.magniteDisabled||i.prebid,s=i.reviqDisabled||i.reviq,o=i.catalystDisabled||i.catalyst,a=i.cmpDisabled||i.cmp;n&&s&&o&&a&&(_e("=== ALL BIDDING SYSTEMS READY ==="),t||(_e("GPT Init: Initializing core GPT configuration"),googletag.cmd.push(()=>{const e=googletag.pubads();if(t=!0,"function"==typeof googletag.setConfig){const e={centering:!0,disableInitialLoad:!0};maiPubAdsVars.targets&&(e.targeting={},Object.keys(maiPubAdsVars.targets).forEach(t=>{e.targeting[t]=String(maiPubAdsVars.targets[t])})),maiPubAdsVars.identityProbe&&(e.targeting=e.targeting||{},e.targeting.ps=function(){const e=I.ppidSource||"";return I.ppid&&["server","fpid","cookie","matomo","random"].includes(e)?e:"none"}(),e.targeting.ha=function(){const e=document.cookie.match(/(?:^|;)\s*maipub_hem_set=([^;]*)(?:;|$)/);if(!e)return"none";const t=parseInt(e[1],10);if(!t||Number.isNaN(t)||1e3*t>Date.now())return"none";const i=(Date.now()-1e3*t)/36e5;return i<24?"h0to24":i<48?"h24to48":i<168?"d2to7":"d7plus"}(),e.targeting.ref=ce(),e.targeting.id=ue(),e.targeting.cn=!0!==I.consentResolved?"unknown":!1===I.hasConsent?I.usnatApplies?"usnat_out":I.gdprApplies?"gdpr_ltd":"npa":!0===I.hasConsent?"full":"unknown",_e(`Identity probe: ps=${e.targeting.ps}, ha=${e.targeting.ha}, ref=${e.targeting.ref}, id=${e.targeting.id}, cn=${e.targeting.cn}`)),googletag.setConfig(e)}else{try{e.setCentering(!0)}catch(e){}try{e.disableInitialLoad()}catch(e){}maiPubAdsVars.targets&&Object.keys(maiPubAdsVars.targets).forEach(t=>e.setTargeting(t,String(maiPubAdsVars.targets[t])))}if(!0===R){const t=Re(I.ppid);if(t){try{e.setPublisherProvidedId(t)}catch(e){console.error(e)}_e("GPT Init: Set Publisher Provided ID:",t)}else I.ppid&&_e("GPT Init: PPID present but not GAM-valid (need 32-150 alphanumeric); skipping setPublisherProvidedId.");"function"==typeof googletag.setConfig&&maiPubAdsVars.pps&&Object.keys(maiPubAdsVars.pps).length>0&&(googletag.setConfig(maiPubAdsVars.pps),_e("GPT Init: PPS signals sent (consent present)."))}else{_e("GPT Init: No consent, setting non-personalized ads.");try{e.setPrivacySettings({nonPersonalizedAds:!0})}catch(t){try{e.setRequestNonPersonalizedAds(1)}catch(e){}}}_e("GPT Init: Core GPT Configuration (services not enabled yet).")})),e(),_e("Bidding Promise: resolve() called (all systems ready)"))};_e("CMP: Waiting for onConsentReady event before injecting scripts..."),(!0===_?(_e("CMP: Already processed - ready immediately."),Promise.resolve()):k?(_e("CMP: Readiness check already in progress - returning existing promise."),k):(k=new Promise(e=>{_e("=== CMP READINESS CHECK STARTED ==="),_e("CMP: Not yet processed - setting up event listener and timeout fallback.");const t=!(!I.geo?.country&&!window.maiPubGeo?.country),i=be();let n=5e3;t?n=i?2e3:1e4:_e("CMP: Geo location unknown at initialization. Defaulting to 5000ms safety window."),_e(`CMP: Timeout set to ${n}ms (${i?"USNat":"GDPR"} region, geo=${fe()}).`);let s=!1;const o=()=>{s||(s=!0,_e("CMP: Resolving promise."),e())},a=()=>{window.removeEventListener("maiPubCMPReady",a),clearTimeout(r),_e("CMP: Event detected - marking as ready."),o()};window.addEventListener("maiPubCMPReady",a),_e("CMP: Event listener active, waiting for CMP to fire (bidding systems paused until then).");let r=setTimeout(d,n);function d(){!s&&(window.removeEventListener("maiPubCMPReady",a),_e("CMP: Timeout reached - checking fallback conditions."),be()?(_e("CMP: North America detected - applying fallback (hasConsent = true)."),R=!0,I.hasConsent=!0,pe({hasConsent:!0})):(_e("CMP: Timeout fallback - GDPR region, no consent (hasConsent = false). Skipping bidding adapters, using non-personalized GAM ads."),R=!1,I.hasConsent=!1,pe({hasConsent:!1})),j(),o())}window.maiPubExtendCmpTimeout=function(e){if(s)return;clearTimeout(r);const t=Date.now()-c,i=Math.max(e-t,1e3);r=setTimeout(d,i),_e(`CMP Circuit Guard: Timeout extended dynamically to ${e}ms (${i}ms remaining).`)}}),k)).then(()=>
1{if(_e("CMP: Ready - proceeding with Strict Script Injection."),i.cmp=!0,!0===maiPubAdsVars.reviq&&!0===R){_e("RevIQ Init: Wiring RevIQ display takeover.");let e=0,t=0;document.querySelectorAll(".mai-ad-unit").forEach(i=>{const n=i.getAttribute("id");if(!n)return;const s=n.replace("mai-ad-","");if(G(s)){if(u&&u!==s)return _e(`RevIQ: removing duplicate spotlight (${n}); only one per page.`),void i.remove();u||(u=s)}const o=g?g[s]:null;if(!o)return b&&_e(`RevIQ: no ads config for slot ${n}; skipping.`),void t++;const a=o.reviq_placement||"";if(!a)return b&&_e(`RevIQ: no reviq_placement mapped for ad-unit '${o.id}' (slot ${n}); skipping. Set it in config.php's ad_units.`),void t++;i.setAttribute("data-ad",a),o.targets&&Object.keys(o.targets).forEach(e=>{const t=o.targets[e];Array.isArray(t)?b&&_e(`RevIQ: data-kv-${e} value is array; skipping (single-value only).`,t):i.setAttribute(`data-kv-${e}`,String(t))}),i.setAttribute("data-kv-refresh",f.toString());const r=i.getAttribute("data-ap");"ts"!==r&&"bs"!==r&&"vs"!==r||i.setAttribute("data-kv-ad_placement_type","sticky"),o.splitTest&&"rand"===o.splitTest&&i.setAttribute("data-kv-st",Math.floor(100*Math.random()).toString()),i.removeAttribute("id"),e++}),_e(`RevIQ: marked ${e} slot div(s); ${t} unmapped/skipped.`);const o=`//js.rev.iq/${maiPubAdsVars.domain}`,a=y?{dev:""}:{};_e(`RevIQ Init: Injecting loader ${o}${y?" (dev mode)":""}`),n("mai-publisher-reviq",o,()=>{_e("RevIQ Init: Loader callback fired."),i.reviq=!0,s()},a),globalThis.reviq=globalThis.reviq||[],globalThis.reviq.push(e=>{if(maiPubAdsVars.targets&&Object.keys(maiPubAdsVars.targets).length>0)try{const t={};Object.keys(maiPubAdsVars.targets).forEach(e=>{const i=maiPubAdsVars.targets[e];t[e]=Array.isArray(i)?i.map(String):String(i)}),e.setKvs(t),_e("RevIQ: setKvs page-level targets (stringified).",t)}catch(e){_e("RevIQ: setKvs failed.",e)}if("function"==typeof e.setContentMetadata){const t=maiPubAdsVars.ortb2&&maiPubAdsVars.ortb2.site&&maiPubAdsVars.ortb2.site.content;if(t)try{e.setContentMetadata(t),_e("RevIQ: setContentMetadata content payload sent.",t)}catch(e){_e("RevIQ: setContentMetadata failed.",e)}}else b&&_e("RevIQ: setContentMetadata not yet available â content metadata not passed this load.");const t=I.hem,i=I.ppid,n=I.ppidSource;if(t||i)try{t?(e.setUid({e:{sha256:t}}),_e("RevIQ: setUid sent hashed email (normalized).")):$e(n)?(e.setUid({e:{sha256:i}}),_e(`RevIQ: setUid sent hashed email (${n} PPID).`)):(e.setUid({u:i}),_e(`RevIQ: setUid sent pseudonymous session id (source: ${n||"unknown"}).`))}catch(e){_e("RevIQ: setUid failed.",e)}else b&&_e("RevIQ: no PPID in session passport â setUid skipped this load.")})}else!0===maiPubAdsVars.reviq&&!1===R?(_e("RevIQ Init: No consent, skipping RevIQ. Bucket will render no display ads this load."),i.reviq=!0,s()):(_e("RevIQ Init: RevIQ disabled, skipping."),s());!0===maiPubAdsVars.catalyst&&!0===R?(_e("Catalyst Init: Injecting Catalyst script..."),n("mai-publisher-catalyst","https://ads.thenexusengine.com/assets/catalyst-sdk-v1.0.0.js",()=>{try{void 0!==window.catalyst&&"function"==typeof window.catalyst.init?(window.catalyst.init({accountId:maiPubAdsVars.catalystAccountId,serverUrl:"https://ads.thenexusengine.com",timeout:maiPubAdsVars.catalystTimeout||2800,debug:maiPubAdsVars.catalystDebug,targeting:{}}),_e("Catalyst Init: Catalyst SDK initialized successfully")):_e("Catalyst Init: Error - catalyst object not available")}catch(e){_e("Catalyst Init: Error initializing catalyst",e)}i.catalyst=!0,s()})):!0===maiPubAdsVars.catalyst&&!1===R?(_e("Catalyst Init: No consent, skipping Catalyst script."),i.catalyst=!0,s()):(_e("Catalyst Init: Catalyst disabled, skipping script."),s());const e=!0===maiPubAdsVars.magnite||Me();e&&!0===R?(_e(`pbjs Init: Injecting Magnite/Prebid script... (display: ${!0===maiPubAdsVars.magnite}, video: ${Me()})`),n("mai-publisher-prebid","//micro.rubiconproject.com/prebid/dynamic/26298.js",()=>{_e("pbjs Init: Script loaded. Configuring..."),window.pbjs=window.pbjs||{que:[]},pbjs.que.push(function(){!function(e){if(C||I.geo&&I.geo.country)return void e();let t=!1;const i=function(i){t||(t=!0,_e(`GEO gate: releasing Prebid configuration (${i}).`),e())};E.push(function(){i("geo settled")}),setTimeout(function(){i("timed out after 300ms")},300),_e("GEO gate: geo not resolved yet â holding Prebid configuration for up to 300ms so ID5 pd can carry the IP.")}(function(){try{const e={bidderTimeout:r,enableTIDs:!0,ortb2:maiPubAdsVars.ortb2,bidderSettings:{standard:{storageAllowed:!0}}};maiPubAdsVars.ortb2=maiPubAdsVars.ortb2||{},maiPubAdsVars.ortb2.source=maiPubAdsVars.ortb2.source||{},maiPubAdsVars.ortb2.source.schain={ver:"1.0",complete:1,nodes:[{asi:"true"===maiPubAdsVars.manager_domain?"bizbudding.com":maiPubAdsVars.domain,sid:maiPubAdsVars.sellersId,hp:1}]};let t=[{name:"pubCommonId",storage:{type:"cookie",name:"_pubcid",expires:365,refreshInSeconds:28800}}];maiPubAdsVars.id5UserSync&&maiPubAdsVars.id5UserSync.userIds&&Array.isArray(maiPubAdsVars.id5UserSync.userIds)&&t.push(...maiPubAdsVars.id5UserSync.userIds);const i=t.find(e=>e&&"id5Id"===e.name);if(i){const e=function(){if(!0!==R)return _e("ID5: no consent â pd not built."),"";const e={},t=I.geo||window.maiPubGeo||{},i=I.hem||"";i&&(e.hem=i,I.isBurnerEmail&&(e.isBurnerEmail=I.isBurnerEmail),I.phone&&(e.phone=I.phone)),I.ppid&&!$e()&&(e.puid=I.ppid),maiPubAdsVars.domain&&(e.domain=maiPubAdsVars.domain),t.ipv4&&(e.ipv4=t.ipv4),t.ipv6&&(e.ipv6=t.ipv6),navigator.userAgent&&(e.ua=navigator.userAgent);const n=[];if(Object.keys(e).forEach(t=>{const i=T[t],s=e[t];void 0!==i&&s&&n.push(i+"="+encodeURIComponent(String(s)))}),!n.length)return _e("ID5: no signals available â pd omitted."),"";const s=btoa(n.join("&"));return _e(`ID5: pd built with ${n.length} key(s):`,Object.keys(e).join(", ")),s}();i.params=i.params||{},e?i.params.pd=e:delete i.params.pd}if(I.ppid){const e=$e()?3:1;t.push({name:"pubProvidedId",params:{eids:[{source:maiPubAdsVars.domain,uids:[{id:I.ppid,atype:e}]}]}}),_e(`pubProvidedId: eid configured (source: ${maiPubAdsVars.domain}, atype: ${e}, ppidSource: ${I.ppidSource||"unknown"}).`),maiPubAdsVars.ortb2=maiPubAdsVars.ortb2||{},maiPubAdsVars.ortb2.user=maiPubAdsVars.ortb2.user||{},maiPubAdsVars.ortb2.user.ext=maiPubAdsVars.ortb2.user.ext||{},maiPubAdsVars.ortb2.user.ext.eids=maiPubAdsVars.ortb2.user.ext.eids||[],maiPubAdsVars.ortb2.user.ext.eids.push({source:maiPubAdsVars.domain,uids:[{id:I.ppid,atype:e}]}),_e("pubProvidedId: also injected into ortb2.user.ext.eids so it reaches bidders without the submodule.")}e.userSync={auctionDelay:400,syncsPerBidder:5,userIds:t},e.customGptSlotMatching=function(e){return function(e){const t=e.getSlotElementId(),i=t.replace("mai-ad-",""),n=e.getAdUnitPath(),s=n.includes(",")?"/"+n.split(",")[1]:n;return function(e){return!!e&&(e===t||e===i||e===n||e===s||e===n+"#"+t||e===n+"#"+i||e===s+"#"+t||e===s+"#"+i)}}(e)},pbjs.setConfig(e),"undefined"!=typeof pbjs&&_e("pbjs Init: PAAPI config owned by Magnite (wrapper build + parameter set). paapiForGpt: "+("function"==typeof pbjs.setPAAPIConfigForGPT?"available â bridging via setPAAPIConfigForGPT":"not in
1wrapper â enable PAAPI in Magnite DM so the module is in the build")),_e("pbjs Init: Prebid.js configured successfully")}catch(e){_e("pbjs Init: Prebid.js configuration failed:",e)}i.prebid=!0,s()})})})):e&&!1===R?(_e("pbjs Init: No consent, skipping Magnite/Prebid script."),i.prebid=!0,s()):(_e("pbjs Init: Magnite/Prebid disabled, skipping script (display and video both off)."),s())})});i.then(()=>{_e("Bidding Promise: Promise resolved (biddingPromise.then() fired)")});const n=new Promise(e=>{(()=>{let t=!1;const i=setTimeout(()=>{t||(t=!0,_e("LCP Failsafe Timeout. Resolving LCP promise."),e(),_e("LCP Promise: resolveLCP() called (failsafe timeout)"))},750);try{new PerformanceObserver(n=>{n.getEntries().length>0&&!t&&(t=!0,clearTimeout(i),_e("LCP Detected. Resolving LCP promise."),e(),_e("LCP Promise: resolveLCP() called (PerformanceObserver)"))}).observe({type:"largest-contentful-paint",buffered:!0})}catch(i){_e("PerformanceObserver not supported. Wait 2 seconds for this old browser to load before triggering ads."),setTimeout(()=>{t||(t=!0,_e("Fallback timeout reached. Resolving LCP promise."),e(),_e("LCP Promise: resolveLCP() called (fallback timeout)"))},2e3)}})()});n.then(()=>{_e("LCP Promise: Promise resolved (lcpPromise.then() fired)")}),Promise.all([i,n]).then(()=>{_e("=== PARALLEL INIT COMPLETE === Bidders (inc. CMP) and LCP are ready."),function(){_e("maiPubRun starting...");const t=document.querySelectorAll(".mai-ad-unit"),i=document.querySelectorAll(".mai-ad-unit-video"),n=document.querySelectorAll(".mai-ad-unit-audio");(function(e){q()||"loading"!==document.readyState||document.addEventListener("DOMContentLoaded",q,{once:!0}),_e("maiPubRun: setting up event listeners for visibility and refreshes."),document.addEventListener("visibilitychange",function(){if(_e("GLOBAL EVENT: Visibility changed. document.hidden:",document.hidden),document.hidden){U=!1,_e("Status: HIDDEN. Pausing all ad activity.");let e=0;for(const t in o)o[t].seenSince&&(ne(t),e++);for(const e in a)clearTimeout(a[e]),delete a[e];e>0&&_e(`Paused ${e} display ad refresh countdowns (seen-time banked).`);let t=0;$.forEach(e=>{e.retryTimer&&(clearTimeout(e.retryTimer),e.retryTimer=null),e.adsManager&&e.isAdPlaying&&(_e(`Pausing video ad for #${e.config.id}`),e.adsManager.pause(),e.wasPausedByVisibility=!0,t++)}),t>0&&_e(`Paused ${t} video ads.`)}else{U=!0,_e("Status: VISIBLE. Resuming ad activity.");let e=0;for(const t in o){const i=o[t];if(i.isOOP)continue;const n=i.vizThreshold||50;i.slotObject&&!i.processing&&(i.currentInView||0)>=n&&(ie(t),e++)}e>0&&_e(`Resumed ${e} display ad refresh countdowns.`);let t=0;$.forEach(e=>{e.adsManager&&e.wasPausedByVisibility&&(_e(`Resuming video ad for #${e.config.id}`),e.adsManager.resume(),e.wasPausedByVisibility=!1,e.justResumed=!0,setTimeout(()=>{e.justResumed=!1},2e3),t++)}),setTimeout(()=>{$.forEach(e=>{e.wasPausedByVisibility||e.justResumed||e.isAdPlaying||!U||!e.adsLoader||"loading"===e.adState||"completed"===e.adState||e.maxRetriesReached||(_e(`Starting new video ad cycle for #${e.config.id}`),e.loadAdPod())})},100)}}),"reviq"!==A&&e.forEach(e=>{const t=e.getAttribute("id");if(!t)return;const i=t.replace("mai-ad-","");return G(i)?u&&u!==i?(_e(`maiPubRun: Skipping duplicate spotlight (${t}); only one per page.`),void e.remove()):void(u||(u=i)):void 0})})(t),t.length||i.length||n.length?(_e(`Found ${t.length} ad units. Processing in a single loop...`),_e(`Found ${i.length} video ad units.`),_e(`Found ${n.length} audio ad units.`),t.length>0&&function(){if("reviq"===A)return void _e("maiPubRunDisplay: RevIQ owns display this bucket; skipping our display pipeline.");const t=document.querySelectorAll(".mai-ad-unit"),i=new IntersectionObserver((t,i)=>{const n=[];_e(`Observer: IntersectionObserver entries: ${t.length}`),t.forEach(e=>{if(!(e.isIntersecting||e.intersectionRatio>0))return void _e(`Observer: Entry is not intersecting, skipping: ${e.target.getAttribute("id")}`);const t=e.target.getAttribute("id"),s=t.replace("mai-ad-","");_e(`Observer: Entry is intersecting, adding to newlyVisibleSlots: ${s}`),o[t]&&!o[t].processing&&(o[t].processing=!0,o[t].visible=!0,n.push(s),i.unobserve(e.target))}),0!==n.length?googletag.cmd.push(()=>
1{n.forEach(e=>{const t=`mai-ad-${e}`,i=N(e);i?(o[t]&&(o[t].slotObject=i),googletag.cmd.push(()=>{googletag.display(t)}),_e(`Observer: Layout container cleanly displayed: ${t}`)):_e(`Observer: Skipping display for slot ${t} - slot definition failed`)}),e||(googletag.enableServices(),e=!0),_e(()=>`Observer: Requesting ads for visible slots: ${n.join(", ")}`),F(n,"observer-visible")}):_e("Observer: No newly visible slots to process.")},{root:null,rootMargin:"200px 0px 200px 0px",threshold:0});_e("=== AD PROCESSING: Processing High-Priority and Lazy-Load Ads ===");const n=[];t.forEach(e=>{const t=B(e,i);t&&n.push(t)}),x(n,"fast-path-immediate"),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>function(e){const t=document.querySelectorAll(".mai-ad-unit"),i=[];let n=0;t.forEach(t=>{const s=t.getAttribute("id");if(!s||o[s])return;n++;const a=B(t,e);a&&i.push(a)}),q(),0!==n?(_e(`maiPubReconcileLateAdUnits: processing ${n} late-parsed ad unit(s).`),x(i,"fast-path-late-reconcile")):_e("maiPubReconcileLateAdUnits: no late-parsed ad units found.")}(i),{once:!0}):_e("maiPubRunDisplay: document already fully parsed; no late-DOM reconciliation needed."),googletag.cmd.push(()=>{googletag.pubads().addEventListener("slotRenderEnded",e=>{const t=e.slot,i=t.getSlotElementId();if(te(t)&&o[i])if(o[i].lastRefreshTime=Date.now(),o[i].processing=!1,void 0===o[i].retryCount&&(o[i].retryCount=0),e.isEmpty){o[i].visible=!0,_e(`maiPubRun event slotRenderEnded: Slot is empty ${i}`,()=>({slug:i.replace("mai-ad-",""),adUnitPath:t.getAdUnitPath(),sizes:e.size,targeting:t.getTargetingMap(),event:e})),ee([t],"slotRenderEnded empty"),function(e,t){if(!d&&!b)return;const i=X(e);if(!i.hasHbPb)return;const n=e.getSlotElementId(),s=e.getAdUnitPath(),o=t.size&&t.size.length>=2?`${t.size[0]}x${t.size[1]}`:"unknown";_e(`HB on slot but GAM empty ${n}: hb_pb=${i.hb_pb} hb_bidder=${i.hb_bidder||"n/a"} hb_size=${i.hb_size||"n/a"} â check GAM HB line items for ${s} (render size ${o})`,{hb_pb:i.hb_pb,hb_bidder:i.hb_bidder,hb_size:i.hb_size,adUnitPath:s,renderSize:o})}(t,e);const n=!0===o[i].visible;oe(t)&&(U||n)&&o[i].retryCount<1?(o[i].retryCount++,_e(`Slot empty: ${i}. Retrying (Attempt ${o[i].retryCount})...`),clearTimeout(a[i]),a[i]=setTimeout(()=>{o[i].visible&&(U||n)&&F([i.replace("mai-ad-","")],"empty-slot-timeout")},2e3)):_e(`Slot ${i} empty. Giving up.`,{retryCount:o[i].retryCount,maxEmptyRetries:1,refreshable:oe(t),isPageVisible:U,slotInView:n})}else{o[i].retryCount=0,function(e,t){if(!d&&!b)return;const i=e.getSlotElementId(),n=t.size&&t.size.length>=2?`${t.size[0]}x${t.size[1]}`:"string"==typeof t.size?t.size:"unknown",s=t.lineItemId||t.sourceAgnosticLineItemId||null;let o;o=t.isBackfill?"adx-backfill":t.yieldGroupIds&&t.yieldGroupIds.length?"open-bidding":s?"gam-line-item":"unknown";const a=X(e);_e(`Fill source ${i}: ${o} size=${n} lineItem=${s||"n/a"} advertiser=${t.advertiserId||"n/a"}`+(a.hasHbPb?` | HB bid on slot: hb_pb=${a.hb_pb} hb_bidder=${a.hb_bidder||"n/a"} hb_size=${a.hb_size||"n/a"}`:" | no HB bid on slot"),{source:o,renderSize:n,isBackfill:!!t.isBackfill,lineItemId:s,advertiserId:t.advertiserId||null,campaignId:t.campaignId||null,creativeId:t.creativeId||t.sourceAgnosticCreativeId||null,yieldGroupIds:t.yieldGroupIds||null,companyIds:t.companyIds||null,hb:a})}(t,e),_e(`Slot filled: ${i}`,()=>({slug:i.replace("mai-ad-",""),adUnitPath:t.getAdUnitPath(),sizes:e.size,targeting:t.getTargetingMap(),event:e}));const n=document.getElementById(i);if(n){const e=n.closest(".mai-ad-unit-container");e&&(e.classList.add("is-filled"),_e(`Added 'is-filled' class to container for ${i}`))}_e(`Display ad rendered: ${i}`),function(e,t){(d||b)&&setTimeout(()=>{try{const i=document.getElementById(e);if(!i)return void _e(`[SIZE-DIAG] ${e}: element not found`);const n=i.closest(".mai-ad-unit-container"),s=n||i,o=Array.isArray(t.size)?t.size.join("x"):String(t.size),a=getComputedStyle(s),r=(a.getPropertyValue("--mai-ad-unit-width")||"").trim()||"n/a",d=(a.getPropertyValue("--mai-ad-unit-height")||"").trim()||"n/a",l=i.querySelector("iframe"),c=l?l.offsetWidth:null,u=l?l.offsetHeight:null,p=l?`${c}x${u}`:"none",g=i.getAttribute("data-ap")||"";let h="";if(l&&null!=c){const e=s.offsetWidth-c,t=s.offsetHeight-u;h=` | whitespace w=${e}px h=${t}px${e>20||t>20?" <-- MISMATCH":""}`}_e(`[SIZE-DIAG] ${e} | served(gam) ${o} | reserved(css) ${r}x${d} | inner ${i.offsetWidth}x${i.offsetHeight} | container `+(n?`${n.offsetWidth}x${n.offsetHeight}`:"n/a")+` | creative(iframe) ${p} | vp ${window.innerWidth} | ap=${g}${h}`)}catch(t){_e(`[SIZE-DIAG] ${e}: diag error â ${t&&t.message}`)}},60)}(i,e),function(e,t,i){const n=o[e];n&&(clearTimeout(a[e]),delete a[e],n.slotObject=t,n.seenMs=0,n.seenSince=null,n.hasBeenViewable=!1,n.deferChecks=0,n.isOOP=function(e){const t=g[e]&&g[e].sizes;return!!t&&(Array.isArray(t)?t.includes("out-of-page"):"out-of-page"===t)}(e.replace("mai-ad-","")),n.isOOP||(n.vizThreshold=function(e,t){let i=0;const n=document.getElementById(e);if(n){const e=n.getBoundingClientRect();i=e.width*e.height}return!i&&t&&Array.isArray(t.size)&&t.size.length>=2&&(i=t.size[0]*t.size[1]),i>=242500?30:50}(e,i),oe(t)&&U&&(n.currentInView||0)>=n.vizThreshold&&ie(e)))}(i,t,e)}}),googletag.pubads().addEventListener("slotVisibilityChanged",e=>{const t=e.slot,i=t.getSlotElementId(),n=e.inViewPercentage>5,s=Math.round(e.inViewPercentage);if(!te(t)||!o[i])return;const a=o[i].visible;o[i].visible=n,o[i].currentInView=e.inViewPercentage;try{const e=document.getElementById(i),o=z(e?e.getAttribute("data-ap"):null),r={ad_visible:n?"true":"false",viewability_percent:s.toString()};o&&(r.ad_placement_type="sticky"),n&&!a?r.viewability_event="entered_viewport":!n&&a&&(r.viewability_event="left_viewport"),t.setConfig({targeting:r})}catch(e){_e(`Error tracking viewability for display ad ${i}:`,e)}const r=o[i].vizThreshold||50;e.inViewPercentage>=r?ie(i):ne(i)}),googletag.pubads().addEventListener("impressionViewable",e=>{const t=e.slot,i=t.getSlotElementId();te(t)&&o[i]&&(o[i].hasBeenViewable=!0,_e(()=>`Impression viewable (Active View): ${i} â refresh-eligible once 32s seen-time is banked at >=${o[i].vizThreshold||50}%.`))})})}(),i.length>0?function(e){try{!function(e){_e("MaiAdUnitVideo: Initializing MaiAdUnitVideo video players."),_e(`MaiAdUnitVideo: Using provided ${e.length}
1 video ad units.`),e.forEach(e=>{const t=new Te(e);$.push(t)}),$.forEach(e=>{e.initialize()})}(e)}catch(e){_e("Error initializing video players:",e)}}(i):_e("maiPubRun: skipping maiPubInitVideoAds, zero on page"),n.length>0&&function(e){try{const t=[];e.forEach((e,i)=>{const n=0===i?"":`-${i+1}`;e.id=`mai-ad-unit-audio${n}`;const s=new Ie(e);!0===maiPubAdsVars.magnite&&s.adUnitConfig&&t.push(s.adUnitConfig)}),t.length>0&&"undefined"!=typeof pbjs&&pbjs.que.push(()=>{pbjs.addAdUnits(t),_e(`MaiAudioPlayer: Registered ${t.length} audio ad unit(s) with Prebid.`)})}catch(e){_e("Error initializing audio players:",e)}}(n)):_e("No ad units, video ad units, or audio ad units found on page - this may be a page without ads or ad units not yet rendered")}()})}();const de=["google.","bing.","duckduckgo.","yahoo.","ecosia.","brave."],le=["facebook.","instagram.","linkedin.","twitter.","x.com","t.co","reddit.","bsky.","threads."];function ce(){if(I.arrival)return I.arrival;let e="other";const t=maiPubAdsVars.fpid&&void 0!==maiPubAdsVars.fpid.param?maiPubAdsVars.fpid.param:"sw_fpid";let i=!1;try{i=!(!t||!new URLSearchParams(window.location.search).has(t))}catch(e){i=!1}if(i)e="newsletter";else if(maiPubAdsVars.id5Identity&&maiPubAdsVars.id5Identity.hem)e="login";else{const t=document.referrer||"";if(t)try{const i=new URL(t).hostname.toLowerCase();i===window.location.hostname?e="other":de.some(e=>i.includes(e))?e="search":le.some(e=>i.includes(e))&&(e="social")}catch(t){e="other"}else e="direct"}return I.arrival=e,pe({arrival:e}),e}function ue(){if(I.hem){switch(I.hemSource){case"server":return"person_login";case"fpid":return"person_newsletter";case"cookie":return"person_returning"}return"person_returning"}return I.ppid&&"random"!==I.ppidSource?"device":"anonymous"}function pe(e){try{for(const t in e)if(e.hasOwnProperty(t))if("ppid"===t){let i=String(e[t]);I[t]=i,_e("maiPubSaveSessionData new ppid as ",i)}else"object"!=typeof e[t]||null===e[t]||Array.isArray(e[t])?I[t]=e[t]:I[t]={...I[t],...e[t]};sessionStorage.setItem(v,JSON.stringify(I)),_e("Session data updated and saved:",I)}catch(e){console.error("[Mai Publisher] Failed to save session data:",e)}}function ge(){return!0===R&&!0===_}function he(){ge()&&(I.hem&&Se(I.hem),I.ppid&&I.ppidSource&&re(I.ppid,I.ppidSource))}function me(){if("boolean"!=typeof I.hasConsent)return void _e("cmp: no boolean consent decision to resolve â not marking.");const e={consentResolved:!0};P.forEach(t=>{void 0!==I[t]&&(e[t]=I[t])}),I.consentResolved=!0,pe(e),he(),_e("cmp: consent decision resolved and persisted:",{hasConsent:I.hasConsent})}function fe(){const e=window.maiPubGeo||I.geo||{};return!0===e.isNorthAmerica||"US"===e.country||"CA"===e.country?"na":!1===e.isNorthAmerica||e.country&&"US"!==e.country&&"CA"!==e.country?"non-na":"unknown"}function be(){const e=fe();return"na"===e||"unknown"===e}function ye(){_e("cmp: consent allowed, initialize any additional vendors.")}function Ae(e){if("function"!=typeof window.maiPubSetConsent&&(window.maiPubSetConsent=Ae),!e||!e.consentSource)return void _e("maiPubSetConsent: Invalid consentData - missing or no source");if("geo"===e.consentSource&&("cmp"===I.source||"cookie"===I.source))return void _e("cmp: Skipping geo-based consent; an explicit user choice already exists.");I.source=e.consentSource;const t="cmp"===e.consentSource;if(R=!0,"gdpr"===e.message_type&&(I.gdprConsentUUID=e.consentUUID,I.gdprApplies=e.applies,I.gdprConsentedToAll=e.consentedToAll,!0===e.applies&&(!0===e.consentedToAll?(R=!0,I.hasConsent=!0,ye(),_e("cmp: GDPR applies and all consent granted.")):(R=!1,I.hasConsent=!1,_e("cmp: GDPR applies but consent denied.")),t&&me()),t)){const t=fe();if("na"===t)_e("cmp: GDPR processed, but user is in North America - waiting for USNat before marking CMP ready.");else if("non-na"===t){const t=!0===_;j(),_e(t?`cmp: GDPR consent arrived late (after timeout) - consent state updated: hasConsent=${R}, applies=${e.applies}, consentedToAll=${e.consentedToAll}`:"cmp: GDPR consent processed - CMP marked as ready.")}else _e("cmp: GDPR processed - geo unknown, waiting for USNat (or geo) before marking CMP ready.")}if("usnat"===e.message_type){if(I.usnatConsentUUID=e.consentUUID,I.usnatApplies=e.typeApplies,!0===e.typeApplies)_e("cmp: USNat applies, checking consent."),window._sp_.usnat.getUserConsents((e,t)=>function(e,t){if(!t||!e||!e.categories)return _e("cmp: Sourcepoint consent check failed: Invalid status or missing consents object."),j(),void _e("cmp: USNat consent check failed - CMP marked as ready (error case).");const i=Object.values(e.categories).find(e=>3==e.systemId);i&&!0===i.consented?(_e("cmp: Consent for Sale or Sharing / Targeted Advert
1ising found (System ID 3)"),ye(),R=!0,I.hasConsent=!0):(_e("cmp: Consent for Sale or Sharing / Targeted Advertising NOT granted (System ID 3)"),R=!1,I.hasConsent=!1),me(),"non-na"!==fe()?(j(),_e("cmp: USNat consent check completed - CMP marked as ready.")):_e("cmp: USNat consent check completed, but user is NOT in North America - waiting for GDPR before marking CMP ready.")}(e,t));else if(R=!0,I.hasConsent=!0,ye(),_e("cmp: USNat does not apply."),t){me();const e=fe();"na"===e?(j(),_e("cmp: USNat does not apply - CMP marked as ready.")):_?_e("cmp: USNat does not apply (CMP already marked ready)."):"non-na"===e&&I.gdprConsentUUID?(j(),_e("cmp: USNat does not apply - CMP marked as ready (GDPR is primary).")):_e("cmp: USNat does not apply - waiting for GDPR before marking CMP ready.")}_e("cmp: USNat consent updated in session passport:",I.usnatConsentUUID,I.usnatApplies)}e.euconsent&&(I.consent||(I.consent={}),I.consent.tcString=e.euconsent,_e("TCF consent string stored for server-side validation"));const i={};P.forEach(e=>{void 0!==I[e]&&(i[e]=I[e])}),I.consent&&(i.consent=I.consent),pe(i),_e("Consent for personalized ads:",I.hasConsent)}function ve(){try{const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(e&&e.effectiveType)return e.effectiveType}catch(e){_e("Could not retrieve connection type from browser:",e)}return""}function Pe(e){if(e)if(window.maiPubAdsVars&&window.maiPubAdsVars.ortb2){const t=window.maiPubAdsVars.ortb2;t.device=t.device||{},t.device.geo=t.device.geo||{},t.user=t.user||{},t.user.ext=t.user.ext||{},t.user.ext.data=t.user.ext.data||{},e.country&&(t.device.geo.country=e.country),e.region&&(t.device.geo.region=e.region),e.city&&(t.device.geo.city=e.city),e.postalCode&&(t.device.geo.zip=e.postalCode),e.metroCode&&(t.device.geo.metro=e.metroCode.toString()),e.lat&&(t.device.geo.lat=e.lat),e.lon&&(t.device.geo.lon=e.lon),t.device.geo.ipservice=3;const i={desktop:2,mobile:4,tablet:5};e.deviceType&&i[e.deviceType]&&(t.device.devicetype=i[e.deviceType]);const n={ethernet:1,wifi:2,cellular:3,"2g":4,"slow-2g":4,"3g":5,"4g":6,"5g":7};let s=e.connectionType||ve();s&&n[s.toLowerCase()]&&(t.device.connectiontype=n[s.toLowerCase()]),e.isp&&(t.user.ext.data.isp=e.isp),_e("ORTB2 object updated with geo data:",t)}else _e("maiPubAdsVars.ortb2 object not found. Cannot update with geo data.");else _e("enrichOrtb2FromGeo: No geo data provided.")}function Se(e){if(!ge())return void _e("Identity: consent not settled (or withheld) â deferring the hashed-email cookie.");if(!e)return;const t=new Date(Date.now()+31536e6).toUTCString();document.cookie=`maipub_hem=${encodeURIComponent(e)};path=/;expires=${t};SameSite=Lax;Secure`,document.cookie=`maipub_hem_set=${Math.floor(Date.now()/1e3)};path=/;expires=${t};SameSite=Lax;Secure`,_e("Hashed email saved to persistent cookie.")}function we(e){if(I.geo&&I.geo.country)return _e("[Mai Publisher] Geo data was loaded from session. Skipping worker call."),void("function"==typeof e&&e(!0));const t=document.createElement("script");t.src="/geo.js",t.async=!0,t.onload=function(){try{if(!window.maiPubGeo)return _e("[Mai Publisher] geo.js loaded, but window.maiPubGeo is missing."),void("function"==typeof e&&e(!1));let t=JSON.parse(atob(window.maiPubGeo));if(!function(e,t){if(!e||"string"!=typeof e)return!1;const i=e.split(".").map(e=>parseInt(e,10)||0),n=t.split(".").map(e=>parseInt(e,10)||0),s=Math.max(i.length,n.length);for(let e=0;e<s;e++){const t=i[e]||0,s=n[e]||0;if(t>s)return!0;if(t<s)return!1}return!0}(t.version,w))return _e(`[Mai Publisher] geo.js version too old, got "${t.version}", need >= ${w}`),void("function"==typeof e&&e(!1));const i={version:t.version||"",cfRay:t.cfRay||"",isNorthAmerica:t.isNorthAmerica||!1,city:t.city||"",region:t.regionCode||"",country:t.country||"",postalCode:t.postalCode||"",metroCode:t.metroCode||"",continent:t.continent||"",timezone:t.timezone||"",lat:t.latFloat||null,lon:t.lonFloat||null,asn:t.asn||"",isp:t.asnDesc||"",deviceType:t.deviceType||"",connectionType:t.connectionType||"",ipv4:t.ipv4||"",ipv6:t.ipv6||"",ppid:t.ppid||window.maiPubAdsVars?.ppid||"",screenWidth:window.screen?.width||"",screenHeight:window.screen?.height||""};window.maiPubGeo=i,_e("[Mai Publisher] geo.js enrichment complete:",i),pe({geo:i}),!1===i.isNorthAmerica&&"function"==typeof window.maiPubExtendCmpTimeout&&window.maiPubExtendCmpTimeout(1e4),R?Pe(i):_e("No consent. Skipping ORTB2 enrichment."),"function"==typeof e&&e(!0)}catch(t){console.error("[Mai Publisher] geo.js processing error:",t),"function"==typeof e&&e(!1)}},t.onerror=function(){_e(`geo.js failed to load from ${window.location.origin}/geo.js â check that a Cloudflare Worker route covers this exact hostname. Falling back to server-side data only.`),"function"==typeof e&&e(!1)},document.head.appendChild(t)}let Ce="merge";try{const e=new URLSearchParams(window.location.search).get("maivideobid");e&&["merge","adtag","vast"].includes(e)&&(Ce=e)}catch(e){}let Ee=null;try{const e=new URLSearchParams(window.location.search).get("maivideohb");null!==e&&(Ee=["1","on","true","yes"].includes(e.toLowerCase()))}catch(e){}function Me(){return null!==Ee?Ee:!0===maiPubAdsVars.magniteVideo}class Te{constructor(e){this.container=e,this.innerEl=e.querySelector(".mai-ad-unit-video__inner"),this.videoEl=e.querySelector(".mai-ad-unit-video__video"),this.adContainer=e.querySelector(".mai-ad-unit-video__ad"),this.controls={container:e.querySelector(".mai-ad-unit-video__controls"),playPauseBtn:e.querySelector(".mai-ad-unit-video__play"),progressBar:e.querySelector(".mai-ad-unit-video__progress"),progressFilled:e.querySelector(".mai-ad-unit-video__progress-filled"),currentTimeEl:e.querySelector(".mai-ad-unit-video__time"),durationEl:e.querySelector(".mai-ad-unit-video__duration"),muteBtn:e.querySelector(".mai-ad-unit-video__mute"),fullscreenBtn:e.querySelector(".mai-ad-unit-video__fullscreen")};const t=this.container.dataset.unitId;this.config={id:this.container.id,isPlaceholder:this.container.classList.contains("is-placeholder"),playerType:this.container.dataset.playerType||"outstream",unitId:t,contentSrc:this.videoEl?this.videoEl.getAttribute("src"):"",vastUrl:maiPubAdsVars.videoAds[t]?.url,adSlotName:maiPubAdsVars.videoAds[t]?.adSlotName||"",width:maiPubAdsVars.videoAds[t]?.width||640,height:maiPubAdsVars.videoAds[t]?.height||360,clickToStart:"instream"===this.container.dataset.playerType||"true"===this.container.dataset.clickToStart,loopAds:"true"===this.container.dataset.loopAds,mediaType:this.container.dataset.mediaType},this.isAdPlaying=!1,this.adsLoader=null,this.adsManager=null,this.adProcessStarted=!1,this.retryTimer=null,this.adState="init",this.wasPausedByVisibility=!1,this.wasPausedByViewability=!1,this._handlingAdError=!1,this._destroyingAdsManager=!1,this._adRequestSeq=0,this._adErrorRetryCount=0,this.maxRetriesReached=!1,this.viewabilityObserver=null,this._resizeObserver=null,this._resizeRafId=0,this.isMuted="true"===this.container.dataset.muted,this.isFloating=!1,this._onScroll=null,this._syncPending=!1,this._syncRafId=null,this.adLoadPromise=null,this.resolveAdLoadPromise=null}initialize(){if(this.videoEl&&this.adContainer||this.config.isPlaceholder)return this.closeBtn=this.container.querySelector(".mai-ad-unit-video__close"),!this.closeBtn&&this.innerEl&&(this.closeBtn=document.createElement("button"),this.closeBtn.className="mai-ad-unit-video__close",this.closeBtn.setAttribute("aria-label","Dismiss Advert
1isement"),this.innerEl.appendChild(this.closeBtn),_e(`MaiAdUnitVideo Cleanup: Programmatically injected close button into ${this.config.id}`)),this.controls.container&&this.controls.container.parentNode!==this.innerEl&&(this.innerEl.appendChild(this.controls.container),_e("MaiAdUnitVideo Cleanup: Safely migrated controls tray into the floating canvas layer.")),this.videoEl&&this.videoEl.addEventListener("loadedmetadata",()=>{const e=this.videoEl.videoWidth,t=this.videoEl.videoHeight;_e(`MaiAdUnitVideo Sizing Engine: Native media file metadata loaded (${e}x${t}) for ${this.config.id}`),e&&t&&(this.container.style.setProperty("--aspect-ratio",`${e}/${t}`),e<t&&(_e("MaiAdUnitVideo Sizing Engine: Vertical media asset confirmed. Adjusting container constraints."),this.container.style.setProperty("--max-width","360px"),this.container.style.setProperty("--max-height","640px")))}),this.bindEvents(),this.viewabilityObserver=new IntersectionObserver(this.handleViewabilityChange.bind(this),{root:null,rootMargin:"200px 0px",threshold:[.5]}),this.viewabilityObserver.observe(this.container),this._onScroll=()=>{this._syncPending||(this._syncPending=!0,this._syncRafId=requestAnimationFrame(()=>{this.syncPlaybackState(),this._syncPending=!1}))},window.addEventListener("scroll",this._onScroll,{passive:!0}),this.syncPlaybackState(),O(),"outstream"===this.config.playerType?(_e(`MaiAdUnitVideo: Outstream video ${this.config.id} initialized. Loop ads: ${this.config.loopAds}, Muted: ${this.isMuted}`),this.adLoaded=!1,void(void 0!==this.isMuted&&null!==this.isMuted||(this.isMuted=!0,_e(`MaiAdUnitVideo: Auto-setting muted=true for autoplay compliance: ${this.config.id}`)))):void 0;_e(`MaiAdUnitVideo Error: Missing critical elements for player: ${this.config.id}`)}startAdProcess(){this.adProcessStarted||(this.adProcessStarted=!0,Me()?(_e(`MaiAdUnitVideo: Magnite video enabled. Starting Prebid auction for ${this.config.id}.`),this.runPrebidAuction()):(_e(`MaiAdUnitVideo: Magnite disabled. Skipping Prebid, calling loadIMA directly from GAM for ${this.config.id}.`),this.loadIMA(this.config.vastUrl)))}loadAdPod(){this.isAdPlaying||"loading"===this.adState?_e(`MaiAdUnitVideo: Skipping loadAdPod for ${this.config.id} â ad is already ${this.adState}.`):this.maxRetriesReached?_e(`MaiAdUnitVideo: Skipping loadAdPod for ${this.config.id} â max retries reached.`):(this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.adState="loading",!this.adLoaded||this.config.loopAds?(this.adLoadPromise=new Promise(e=>{this.resolveAdLoadPromise=e}),this.adLoaded&&this.config.loopAds?_e(`MaiAdUnitVideo: Retrying ad pod for ${this.config.id}
1 (looping enabled)`):(this.adLoaded=!0,_e(`MaiAdUnitVideo: Loading ad pod for outstream video ${this.config.id}`)),Me()?(_e(`MaiAdUnitVideo: Magnite video enabled. Starting Prebid auction for ${this.config.id}.`),this.runPrebidAuction()):(_e(`MaiAdUnitVideo: Magnite disabled. Skipping Prebid, calling loadIMA directly from GAM for ${this.config.id}.`),this.loadIMA(this.config.vastUrl))):_e(`MaiAdUnitVideo: Ad pod already loaded for ${this.config.id} and looping is disabled`))}bindEvents(){this.closeBtn&&this.closeBtn.addEventListener("click",e=>{e.stopPropagation(),e.preventDefault(),_e(`MaiAdUnitVideo Close Button Fired for ${this.config.id}`),this.dismissPlayerPermanently()}),this.videoEl.addEventListener("click",e=>(_e(`MaiAdUnitVideo: Video element clicked for ${this.config.id}`),"outstream"===this.config.playerType?this.adsManager&&!this.isAdPlaying?(_e(`MaiAdUnitVideo: Starting outstream ad for ${this.config.id}`),void this.adsManager.start()):void this.toggleMute():"instream"===this.config.playerType&&this.config.clickToStart&&!this.adProcessStarted?(e.preventDefault(),e.stopPropagation(),_e("MaiAdUnitVideo: Video surface clicked before ad process initialization. Booting ad pipeline."),void this.startAdProcess()):void("instream"===this.config.playerType&&this.videoEl.controls?_e("MaiAdUnitVideo: Canvas frame click delegated entirely to native browser control logic."):(e.preventDefault(),e.stopPropagation(),this.togglePlay())))),"instream"===this.config.playerType&&this.innerEl&&this.innerEl.addEventListener("click",e=>{e.target.closest(".mai-ad-unit-video__close")||e.target.closest(".mai-ad-unit-video__controls")||e.target!==this.videoEl&&this.config.clickToStart&&(e.stopPropagation(),this.adProcessStarted?(_e("MaiAdUnitVideo: Center overlay area clicked post-ad. Toggling content playback."),this.togglePlay()):(e.preventDefault(),_e("MaiAdUnitVideo: Inner layout wrapper clicked. Booting ad pipeline."),this.startAdProcess()))}),this.controls.muteBtn&&this.controls.muteBtn.addEventListener("click",e=>{e.stopPropagation(),this.toggleMute()}),"instream"===this.config.playerType?(this.controls.playPauseBtn.addEventListener("click",()=>{this.config.clickToStart&&!this.adProcessStarted?this.startAdProcess():this.isAdPlaying||this.togglePlay()}),this.videoEl.addEventListener("timeupdate",()=>this.updateProgressBar()),this.videoEl.addEventListener("durationchange",()=>this.updateTimeDisplay()),this.videoEl.addEventListener("play",()=>{this.container.classList.remove("is-paused"),this.container.classList.add("is-playing")}),this.videoEl.addEventListener("pause",()=>{this.container.classList.remove("is-playing"),this.container.classList.add("is-paused")}),this.videoEl.addEventListener("ended",()=>{_e(`MaiAdUnitVideo: Content ended for ${this.config.id}, notifying IMA for post-roll`),this.adsLoader&&this.adsLoader.contentComplete()}),this.controls.muteBtn.addEventListener("click",()=>this.toggleMute()),this.controls.fullscreenBtn&&("instream"===this.config.playerType?(this.controls.fullscreenBtn.addEventListener("click",()=>this.toggleFullscreen()),_e("MaiAdUnitVideo Controls: Instream view verified. Fullscreen button active.")):(this.controls.fullscreenBtn.style.setProperty("display","none","important"),_e("MaiAdUnitVideo Controls: Outstream ad verified. Fullscreen button hidden programmatically."))),this.controls.progressBar.addEventListener("click",e=>this.seek(e))):(this.videoEl.addEventListener("play",()=>{this.container.classList.remove("is-paused"),this.container.classList.add("is-playing"),_e(`MaiAdUnitVideo: Video started playing for ${this.config.id}`)}),this.videoEl.addEventListener("pause",()=>{this.container.classList.remove("is-playing"),this.container.classList.add("is-paused"),_e(`MaiAdUnitVideo: Video paused for ${this.config.id}`)}))}togglePlay(){this.videoEl.paused?this.videoEl.play():this.videoEl.pause()}toggleMute(){if(this.isMuted=!this.isMuted,this.videoEl.muted=this.isMuted,this.container.classList.toggle("is-muted",this.isMuted),this.adsManager){const e=this.isMuted?0:1;this.adsManager.setVolume(e),_e(`MaiAdUnitVideo: Toggled adsManager volume level to ${e}`)}}toggleFullscreen(){document.fullscreenElement?document.exitFullscreen():this.container.requestFullscreen().catch(e=>{_e(`Fullscreen Error: ${e.message}`)})}updateProgressBar(){const e=this.videoEl.currentTime/this.videoEl.duration*100;this.controls.progressFilled.style.width=`${e}%`,this.updateTimeDisplay()}updateTimeDisplay(){this.controls.currentTimeEl.textContent=this.formatTime(this.videoEl.currentTime),isNaN(this.videoEl.duration)||(this.controls.durationEl.textContent=this.formatTime(this.videoEl.duration))}formatTime(e){const t=Math.floor(e/60),i=Math.floor(e%60).toString().padStart(2,"0");return isNaN(t)||isNaN(i)?"0:00":`${t}:${i}`}startAdCountdown(){this.adCountdownTimer&&clearInterval(this.adCountdownTimer),this.container.classList.add("is-ad-playing"),this.container.classList.toggle("is-muted",this.isMuted);const e=this.container.querySelector(".mai-ad-unit-video__ad-badge-time"),t=this.container.querySelector(".mai-ad-unit-video__sound-prompt"),i=()=>
1{if(!this.adsManager)return;const t=this.adsManager.getRemainingTime();e&&(e.textContent=this.formatTime(t>0?t:0))};i(),this.adCountdownTimer=setInterval(i,250),t&&!this.soundPromptBound&&(t.addEventListener("click",e=>{e.stopPropagation(),this.adsManager&&this.adsManager.setVolume(1),this.videoEl.muted=!1,this.isMuted=!1,this.container.classList.remove("is-muted"),this.container.classList.add("is-sound-prompt-dismissed")}),this.soundPromptBound=!0)}stopAdCountdown(){this.adCountdownTimer&&(clearInterval(this.adCountdownTimer),this.adCountdownTimer=null),this.container.classList.remove("is-ad-playing")}seek(e){const t=this.controls.progressBar.getBoundingClientRect(),i=Math.min(Math.max(0,e.clientX-t.left),t.width)/t.width;this.videoEl.currentTime=i*this.videoEl.duration}handleViewabilityChange(e){const t=e[0];this.isPlaceholderIntersecting=t.isIntersecting,t.isIntersecting&&(this.config.isPlaceholder||("outstream"!==this.config.playerType||this.adLoaded?"instream"!==this.config.playerType||this.config.clickToStart||(_e(`MaiAdUnitVideo: Instream ad ${this.config.id} is visible. Calling startAdProcess().`),this.startAdProcess()):(_e(`MaiAdUnitVideo: Outstream ad ${this.config.id} is visible. Calling loadAdPod().`),this.loadAdPod())),this.container.classList.contains("is-seen")||this.container.classList.add("is-seen")),this.syncPlaybackState()}canFloatOnCurrentViewport(){const e=window.innerWidth||document.documentElement.clientWidth;let t="none";return t=e<=727?this.container.getAttribute("data-float-position-mobile"):e>=728&&e<=1023?this.container.getAttribute("data-float-position-tablet"):this.container.getAttribute("data-float-position-desktop"),t&&"none"!==t&&"inline"!==t}syncPlaybackState(){if(!this.container)return;const e=window.scrollY||document.documentElement.scrollTop;void 0===this._headerEl&&(this._headerEl=document.querySelector(".site-header"));const t=this._headerEl;let i=e<120,n=0;if(t){const s=window.getComputedStyle(t),o="fixed"===s.position||"sticky"===s.position,a=t.getBoundingClientRect();i=o?e<150:a.bottom>0,n=Math.max(0,a.bottom)}const s=this.container.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight;if(this.container.style.setProperty("--computed-header-offset",`${n}px`),0===s.width||0===s.height)return;const a=s.bottom>n&&s.top<o,r=s.top>=o;r&&0===e&&this.container.classList.remove("is-seen"),a&&this.container.classList.add("is-seen");const d=this.canFloatOnCurrentViewport()&&this.container.classList.contains("is-seen")&&!a&&!r&&e>0,l=i&&d;a||d&&!l?(this.container.classList.contains("is-menu-collapsed")&&(this.container.classList.remove("is-menu-collapsed"),this.innerEl&&this.innerEl.style.removeProperty("display"),_e("MaiAdUnitVideo Sync: Clearing menu collapse fields.")),!this.adsManager||"playing"!==this.adState||this.isAdPlaying&&!this.wasPausedByViewability||(_e("MaiAdUnitVideo Sync: Re
1suming active video ad playback."),this.adsManager.resume(),this.isAdPlaying=!0,this.wasPausedByViewability=!1)):(l&&!this.container.classList.contains("is-menu-collapsed")&&(this.container.classList.add("is-menu-collapsed"),this.innerEl&&this.innerEl.style.setProperty("display","none","important"),_e("MaiAdUnitVideo Sync: Near top header layout. Collapsing floating container.")),this.adsManager&&this.isAdPlaying&&(_e("MaiAdUnitVideo Sync: Pausing active video ad playback."),this.adsManager.pause(),this.isAdPlaying=!1,this.wasPausedByViewability=!0)),d&&!l?this.container.classList.remove("in-view"):this.container.classList.add("in-view")}isPlayerUserVisible(){if(!this.container)return!1;const e=window.scrollY||document.documentElement.scrollTop;void 0===this._headerEl&&(this._headerEl=document.querySelector(".site-header"));const t=this._headerEl;let i=e<120,n=0;if(t){const s=window.getComputedStyle(t),o="fixed"===s.position||"sticky"===s.position,a=t.getBoundingClientRect();i=o?e<150:a.bottom>0,n=Math.max(0,a.bottom)}const s=this.container.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight;if(0===s.width||0===s.height)return!1;const a=s.bottom>n&&s.top<o,r=s.top>=o,d=this.canFloatOnCurrentViewport()&&this.container.classList.contains("is-seen")&&!a&&!r&&e>0;return a||d&&!(i&&d)}cleanPlayerDOMState(e=!1){this.adContainer&&(this.adContainer.innerHTML=""),this.container&&(this.container.classList.remove("is-playing","in-view","is-sound-prompt-dismissed","is-menu-collapsed"),e||this.container.classList.remove("is-seen")),this.innerEl&&(this.innerEl.style.removeProperty("display"),this.innerEl.style.removeProperty("position"))}runPrebidAuction(){const e=this.config.vastUrl;let t=!1;const i=(e,i)=>{t||(t=!0,_e(`MaiAdUnitVideo DM: ${this.config.id} using ${i}.`),this.loadIMA(e))};this.config.adSlotName?"undefined"!=typeof pbjs&&pbjs.que?pbjs.que.push(()=>{if(!pbjs.rp||"function"!=typeof pbjs.rp.requestVideoBids)return void i(e,"gam-pod (pbjs.rp.requestVideoBids unavailable)");const t=setTimeout(()=>{i(e,"gam-pod (DM timeout 3000ms)")},3e3),n=this.config.adSlotName,s=[this.config.width,this.config.height],o="function"==typeof pbjs.getEvents&&(pbjs.getEvents()||[]).length||0;_e(`MaiAdUnitVideo DM: requesting video bids for ${this.config.id}`,()=>({adSlotName:n,emitted:this.config.adSlotName,playerSize:s,mode:Ce}));try{pbjs.rp.requestVideoBids({adSlotName:n,playerSize:s,callback:n=>{clearTimeout(t),_e(`MaiAdUnitVideo DM: video bid result for ${this.config.id}`,()=>({hasAdTagUrl:!(!n||!n.adTagUrl),hasVastUrl:!(!n||!n.vastUrl),mode:Ce,keys:n?Object.keys(n):null,raw:n})),n&&(n.adTagUrl||n.vastUrl)||function(e,t){if(d||b)if("undefined"!=typeof pbjs)try{const i=(pbjs.adUnits||[]).map(e=>({code:e.code,mediaTypes:Object.keys(e.mediaTypes||{}),bidders:(e.bids||[]).map(e=>e.bidder)}));if(_e(`MaiAdUnitVideo DM: ${e} pbjs.adUnits at callback time:`,i.length?i:"none"),"function"!=typeof pbjs.getEvents)return void _e(`MaiAdUnitVideo DM: ${e} diagnostics - pbjs.getEvents unavailable.`);const n=pbjs.getEvents()||[],s=function(e){const t={},i=e=>(t[e]=t[e]||{adUnitCodes:[],hasVideo:!1,biddersRequested:[],bidResponses:[],noBids:0,timeouts:0,videoMediaType:null,ortb2Imp:null,adUnitParams:{},requestedParams:{}},t[e]);(e||[]).forEach(e=>{const t=e.args||{},n=t.auctionId||Array.isArray(t)&&t[0]&&t[0].auctionId;switch(e.eventType){case"auctionInit":{const e=i(n);(t.adUnits||[]).forEach(t=>{-1===e.adUnitCodes.indexOf(t.code)&&e.adUnitCodes.push(t.code),t.mediaTypes&&t.mediaTypes.video&&(e.hasVideo=!0,e.videoMediaType||(e.videoMediaType=t.mediaTypes.video),t.ortb2Imp&&!e.ortb2Imp&&(e.ortb2Imp=t.ortb2Imp),(t.bids||[]).forEach(t=>{t&&t.bidder&&(e.adUnitParams[t.bidder]=t.params||null)}))});break}case"bidRequested":{const e=i(n),s=t.bidderCode||t.bidderRequestId;s&&-1===e.biddersRequested.indexOf(s)&&e.biddersRequested.push(s),(t.bids||[]).forEach(t=>{t&&t.bidder&&(e.requestedParams[t.bidder]=t.params||null)});break}case"bidResponse":i(n).bidResponses.push({bidder:t.bidderCode||t.bidder,cpm:t.cpm,mediaType:t.mediaType});break;case"noBid":i(n).noBids++;break;
1case"bidTimeout":(Array.isArray(t)?t:[t]).forEach(e=>{i(e&&e.auctionId).timeouts++})}});const n=Object.keys(t).filter(e=>t[e].hasVideo),s={adUnitCodes:[],biddersRequested:[],bidResponses:[],noBids:0,timeouts:0,videoMediaType:null,ortb2Imp:null,adUnitParams:{},requestedParams:{}};let o;return n.forEach(e=>{const i=t[e];s.adUnitCodes=s.adUnitCodes.concat(i.adUnitCodes),s.biddersRequested=s.biddersRequested.concat(i.biddersRequested),s.bidResponses=s.bidResponses.concat(i.bidResponses),s.noBids+=i.noBids,s.timeouts+=i.timeouts,s.videoMediaType=s.videoMediaType||i.videoMediaType,s.ortb2Imp=s.ortb2Imp||i.ortb2Imp,Object.assign(s.adUnitParams,i.adUnitParams),Object.assign(s.requestedParams,i.requestedParams)}),o=n.length?s.biddersRequested.length?s.bidResponses.length?`${s.bidResponses.length} bid response(s) â empty result is downstream of the auction`:`bidders requested, none responded (${s.noBids} noBid, ${s.timeouts} timeout) â no demand`:"AUP matched, ZERO bidders requested â no bidders / no video MTO on the pattern":"NO video auction â adSlotName matched no AUP",{auctions:t,videoAuctionIds:n,verdict:o,video:s}}("number"==typeof t?n.slice(t):n);_e(`MaiAdUnitVideo DM: ${e} verdict â ${s.verdict}`,()=>s),s.videoAuctionIds.length&&!s.video.bidResponses.length&&function(e,t){const i=e&&e.video;
1if(!i||!i.videoMediaType)return void console.warn(`[maiPub] ${t}: no video mediaType captured (auctionInit carried no video ad unit).`);const n=i.videoMediaType,s=n.context||"(unset)";console.log(`[maiPub] ${t}: video MTO â context="${s}", playerSize=${JSON.stringify(n.playerSize)}, plcmt=${void 0!==n.plcmt?n.plcmt:"(unset)"}, placement=${void 0!==n.placement?n.placement:"(unset)"}`),"instream"!==s&&console.warn(`[maiPub] ${t}: MTO context is "${s}", not "instream". Magnite specified a web_video_instream MTO for this inventory â an outstream context alone can explain broad DSP rejection.`),console.log(`[maiPub] ${t}: full video mediaType:`,n),i.ortb2Imp&&console.log(`[maiPub] ${t}: ortb2Imp (plcmt/placement often live here):`,i.ortb2Imp);const o=Object.keys(i.requestedParams).length?i.requestedParams:i.adUnitParams;Object.keys(o).length?console.log(`[maiPub] ${t}: bidder params as sent:`,o):console.warn(`[maiPub] ${t}: no bidder params captured.`)}(s,e)}catch(t){_e(`MaiAdUnitVideo DM: ${e} diagnostics threw: ${t.message}`)}else _e(`MaiAdUnitVideo DM: ${e} diagnostics - pbjs undefined.`)}(this.config.id,o);const s=function(e,t){const i=e&&e.adTagUrl,n=e&&e.vastUrl;if(!i&&!n)return{url:t,source:"gam-pod (no bid)"};if("vast"===Ce&&n)return{url:n,source:"dm-vast (bypasses GAM, no pod)"};if("adtag"===Ce&&i)return{url:i,source:"dm-adtag"};if("merge"===Ce&&i){const e=function(e,t){if(!e||!t)return null;try{const i=new URL(t),n=new URL(e),s=new URLSearchParams(i.searchParams.get("cust_params")||""),o=new URLSearchParams(n.searchParams.get("cust_params")||""),a=[];return s.forEach((e,t)=>{0===t.indexOf("hb_")&&(o.set(t,e),a.push(t))}),i.searchParams.forEach((e,t)=>{0===t.indexOf("hb_")&&(o.set(t,e),a.push(t))}),a.length?(n.searchParams.set("cust_params",o.toString()),_e(`MaiAdUnitVideo DM: merged ${a.length} hb_* key(s) into the GAM pod URL.`,()=>a),n.toString()):null}catch(e){return _e(`MaiAdUnitVideo DM: could not merge hb targeting: ${e.message}`),null}}(t,i);return e?{url:e,source:"gam-pod + dm hb targeting"}:{url:i,source:"dm-adtag (merge found no hb_*)"}}return{url:i||n||t,source:i?"dm-adtag (fallback path)":n?"dm-vast (fallback path)":"gam-pod"}}(n,e);i(s.url,s.source)}})}catch(n){clearTimeout(t),i(e,`gam-pod (requestVideoBids threw: ${n.message})`)}}):i(e,"gam-pod (pbjs unavailable)"):i(e,"gam-pod (no adSlotName)")}loadIMA(e){window.googletag&&window.googletag.pubads&&"function"==typeof window.googletag.pubads?(_e(`MaiAdUnitVideo: GPT is loaded for ${this.config.id}. Proceeding with IMA SDK loading.`),this.loadIMASDK(e)):window.googletag.cmd.push(()=>{_e(`MaiAdUnitVideo: GPT is now loaded for ${this.config.id}. Proceeding with IMA SDK loading.`),this.loadIMASDK(e)})}loadIMASDK(e){if(window.google&&window.google.ima)return _e(`MaiAdUnitVideo: IMA SDK already loaded for ${this.config.id}.`),void this.requestAd(e);if(window.isImaSdkLoading)return _e(`MaiAdUnitVideo: IMA SDK is loading via another player for ${this.config.id}. Waiting.`),void document.addEventListener("imaReady",()=>{_e(`MaiAdUnitVideo: imaReady event received for ${this.config.id}.`),this.requestAd(e)},{once:!0});_e(`MaiAdUnitVideo: Attempting to load IMA SDK for ${this.config.id}.`),window.isImaSdkLoading=!0;const t=document.createElement("script");t.src="https://imasdk.googleapis.com/js/sdkloader/ima3.js",t.onload=()=>{_e(`MaiAdUnitVideo: IMA SDK successfully loaded for ${this.config.id}.`),window.isImaSdkLoading=!1,document.dispatchEvent(new CustomEvent("imaReady")),this.requestAd(e)},t.onerror=()=>{_e(`MaiAdUnitVideo Error: Failed to load Google IMA SDK script for ${this.config.id}.`),window.isImaSdkLoading=!1,"instream"===this.config.playerType&&this.config.contentSrc&&this.videoEl.play()},document.head.appendChild(t)}requestAd(e){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.adRequestTimeout&&(clearTimeout(this.adRequestTimeout),this.adRequestTimeout=null);const t=++this._adRequestSeq;if(e&&e.includes("pubads.g.doubleclick.net"))try{const t=new URL(e);let i=t.searchParams.get("cust_params")||"";const n=window.maiPubGeo||{},s={asn:this.config.id,geo_ct:n.country||"",geo_rg:n.region||"",geo_ci:n.city||"",geo_zi:n.postalCode||"",geo_lat:n.lat||"",geo_lon:n.lon||"",conn:n.connectionType||ve()||""},o=Object.entries(s).filter(([e,t])=>""!==t).map(([e,t])=>`${e}=${encodeURIComponent(t)}`);if(o.length>0){const e=o.join("&");
1i?o.forEach(e=>{const t=e.split("=")[0]+"=";i.includes(t)||(i+=`&${e}`)}):i=e}t.searchParams.set("cust_params",i),Ve(t),e=t.toString()}catch(e){_e("MaiAdUnitVideo: Error appending ORTB2 targeting to VAST URL:",e)}if(_e("Requesting VAST URL:",e),_e(`MaiAdUnitVideo: requestAd called for ${this.config.id}`,{vastUrl:e,playerType:this.config.playerType,hasVideoElement:!!this.videoEl,hasAdContainer:!!this.adContainer}),!e)return _e(`MaiAdUnitVideo Error: No VAST URL available for ${this.config.id}.`),void("instream"===this.config.playerType&&this.config.contentSrc&&this.videoEl.play());if(!this.adsLoader){let e;try{e="instream"===this.config.playerType?new google.ima.AdDisplayContainer(this.adContainer,this.videoEl):new google.ima.AdDisplayContainer(this.adContainer),e.initialize(),"outstream"===this.config.playerType&&this.isMuted&&this.container.classList.add("is-muted")}catch(e){return void _e(`MaiAdUnitVideo: Error creating AdDisplayContainer for ${this.config.id}:`,e)}this.adsLoader=new google.ima.AdsLoader(e);try{this.adsLoader.getSettings().setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.INSECURE)}catch(e){_e(`MaiAdUnitVideo: Unable to set VPAID mode for ${this.config.id}:`,e)}this.adsLoader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,e=>this.onAdsManagerLoaded(e),!1),this.adsLoader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,e=>this.onAdError(e.error),!1)}const i=new google.ima.AdsRequest;i.adTagUrl=e,i.linearAdSlotWidth=this.config.width,i.linearAdSlotHeight=this.config.height,_e(`MaiAdUnitVideo: Requesting ad with dimensions ${this.config.width}x${this.config.height} for ${this.config.id}`),i.setAdWillAutoPlay(!this.config.clickToStart),i.setAdWillPlayMuted(this.isMuted),this.adRequestTimeout=setTimeout(()=>{t===this._adRequestSeq&&(_e(`MaiAdUnitVideo: Ad request timeout for ${this.config.id} - no response after 10 seconds`),this.onAdError({message:"Ad request timeout",getErrorCode:()=>1010,getErrorType:()=>"AD_LOAD"}))},1e4),this.adsLoader.requestAds(i)}onAdsManagerLoaded(e){this.adRequestTimeout&&(clearTimeout(this.adRequestTimeout),this.adRequestTimeout=null),this.adsManager&&this._destroyAdsManager(!0),this.isAdPlaying=!1,this.wasPausedByVisibility=!1,this.wasPausedByViewability=!1,"instream"===this.config.playerType?this.videoEl:this.adContainer;let t=null;try{t=new google.ima.AdsRenderingSettings,t.loadVideoTimeout=15e3,t.enablePreloading=!0}catch(e){_e(`MaiAdUnitVideo: Unable to build AdsRenderingSettings for ${this.config.id}:`,e)}this.adsManager=t?e.getAdsManager(this.adContainer,t):e.getAdsManager(this.adContainer),this.adsManager.addEventListener(google.ima.AdEvent.Type.STARTED,()=>this.onAdEvent("STARTED")),this.adsManager.addEventListener(google.ima.AdEvent.Type.COMPLETE,()=>this.onAdEvent("COMPLETE")),this.adsManager.addEventListener(google.ima.AdEvent.Type.SKIPPED,()=>this.onAdEvent("SKIPPED")),this.adsManager.addEventListener(google.ima.AdEvent.Type.ALL_ADS_COMPLETED,()=>this.onAdEvent("ALL_ADS_COMPLETED")),this.adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,e=>this.onAdError(e.error)),this.adsManager.addEventListener(google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,()=>{"instream"===this.config.playerType&&(_e(`MaiAdUnitVideo: CONTENT_PAUSE_REQUESTED for ${this.config.id}`),this.wasPlayingBeforeAd=!this.videoEl.paused,this.videoEl.pause())},!1),this.adsManager.addEventListener(google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,()=>{"instream"===this.config.playerType&&this.config.contentSrc&&this.wasPlayingBeforeAd&&(_e(`MaiAdUnitVideo: CONTENT_RESUME_REQUESTED for ${this.config.id}`),this.videoEl.play().catch(e=>_e(`MaiAdUnitVideo: play() rejected for ${this.config.id}: ${e.message}`)))},!1);try{this._attachResizeObserver();const e=this.innerEl||this.container;this.adsManager.init(e.clientWidth,e.clientHeight,google.ima.ViewMode.NORMAL);const t=this.isMuted?0:1;this.adsManager.setVolume(t),_e(`MaiAdUnitVideo: Outstream ad initialized with volume tracking context: ${t}`),this.adsManager.start()}catch(e){this.onAdError(e)}}dismissPlayerPermanently(){this.maxRetriesReached=!0,this.adState="completed",this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.adRequestTimeout&&(clearTimeout(this.adRequestTimeout),this.adRequestTimeout=null),this._destroyAdsManager(!0),this.cleanPlayerDOMState(!1),this.container&&this.container.style.setProperty("display","none","important"),this._onScroll&&(window.removeEventListener("scroll",this._onScroll),this._onScroll=null),this._syncRafId&&(cancelAnimationFrame(this._syncRafId),this._syncRafId=null),this.viewabilityObserver&&(this.viewabilityObserver.disconnect(),this.viewabilityObserver=null,this._detachResizeObserver())}_attachResizeObserver(){"undefined"!=typeof ResizeObserver&&!this._resizeObserver&&this.innerEl&&(this._resizeObserver=new ResizeObserver(()=>{this._resizeRafId||(this._resizeRafId=requestAnimationFrame(()=>{if(this._resizeRafId=0,!this.adsManager||!this.innerEl)return;const e=this.innerEl.clientWidth,t=this.innerEl.clientHeight;if(e&&t)try{this.adsManager.resize(e,t,google.ima.ViewMode.NORMAL)}catch(e){_e(`MaiAdUnitVideo: adsManager.resize() skipped for ${this.config.id}: ${e.message}`)}}))}),this._resizeObserver.observe(this.innerEl))}_detachResizeObserver(){this._resizeRafId&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=0),this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null)}_destroyAdsManager(e=!1){if(this.stopAdCountdown(),this.isAdPlaying=!1,"outstream"===this.config.playerType?this.cleanPlayerDOMState(!0):this.adContainer&&(this.adContainer.innerHTML=e?"":this.adContainer.innerHTML,this.adContainer.style.pointerEvents="none"),this.adsManager){const e=this.adsManager;this.adsManager=null;try{e.destroy()}
1catch(e){_e("MaiAdUnitVideo: adsManager.destroy() skipped:",e.message)}}this.adsLoader&&(e||"outstream"===this.config.playerType)&&(this.adsLoader=null,_e(`MaiAdUnitVideo Cleanup: Reset adsLoader state for ${this.config.id}.`)),this.syncPlaybackState(),_e(`MaiAdUnitVideo Cleanup: Force coordinate sync after adsManager.destroy() for ${this.config.id}.`)}_scheduleLoopRetry(e){this.config.loopAds&&"outstream"===this.config.playerType&&U&&!this.maxRetriesReached&&(this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>{if(this.retryTimer=null,U&&!this.isAdPlaying&&"loading"!==this.adState){if(!this.isPlayerUserVisible())return _e(`MaiAdUnitVideo: Loop retry deferred for ${this.config.id} â player off screen. Re-checking.`),void this._scheduleLoopRetry(1e3);_e(`MaiAdUnitVideo: Loop retry for ${this.config.id}.`),this.loadAdPod()}},e))}onAdEvent(e){switch(_e(`MaiAdUnitVideo: Ad event '${e}' for ${this.config.id}`,{playerType:this.config.playerType,isAdPlaying:this.isAdPlaying,loopAds:this.config.loopAds}),e){case"STARTED":if(this.adState="playing",this._adErrorRetryCount=0,this.isAdPlaying=!0,this.container.classList.add("is-playing"),_e(`MaiAdUnitVideo: Ad started playing for ${this.config.id}`),this.adsManager)try{const e=this.adsManager.getCurrentAd();if(e){const t=e.getWidth(),i=e.getHeight();t&&i&&t>0&&i>0&&(this.container.style.setProperty("--aspect-ratio",`${t}/${i}`),_e(`MaiAdUnitVideo Layout Sync: Adjusted container to match creative context (${t}x${i}).`))}}catch(e){_e(`MaiAdUnitVideo Layout Sync: Dimension check bypassed: ${e.message}`)}"outstream"===this.config.playerType&&this.startAdCountdown(),this.resolveAdLoadPromise&&(this.resolveAdLoadPromise(),this.adLoadPromise=null,this.resolveAdLoadPromise=null);break;case"COMPLETE":_e(`MaiAdUnitVideo: Ad completed for ${this.config.id}`);break;case"SKIPPED":_e(`MaiAdUnitVideo: Ad skipped for ${this.config.id}`);break;case"ALL_ADS_COMPLETED":this.adState="completed",this.isAdPlaying=!1,this.container.classList.remove("is-playing"),this.stopAdCountdown(),_e(`MaiAdUnitVideo: All ads completed for ${this.config.id}`),this._destroyAdsManager(!1),this.viewabilityObserver&&!this.config.loopAds&&(this.viewabilityObserver.disconnect(),this.viewabilityObserver=null,_e(`MaiAdUnitVideo: Disconnected viewability observer for ${this.config.id} (looping disabled).`),this._detachResizeObserver(),this.container&&"outstream"===this.config.playerType&&(this.container.style.setProperty("display","none","important"),_e("MaiAdUnitVideo Cleanup: Collapsed container footprint out of the document tree."))),"outstream"===this.config.playerType&&this.config.loopAds?(_e(`MaiAdUnitVideo: Ad pod for ${this.config.id} completed. Looping enabled, scheduling next pod.`),this._scheduleLoopRetry(300)):"instream"===this.config.playerType&&this.config.contentSrc&&(this.videoEl.controls=!0,this.container.style.removeProperty("--aspect-ratio"),this.syncPlaybackState(),this.videoEl.play())}}onAdError(e){if(!this._handlingAdError&&!this._destroyingAdsManager){this._handlingAdError=!0;try{this.adState="error",this.isAdPlaying=!1,this.stopAdCountdown(),this.resolveAdLoadPromise&&(this.resolveAdLoadPromise(),this.adLoadPromise=null,this.resolveAdLoadPromise=null),"outstream"===this.config.playerType&&this.viewabilityObserver&&!this.config.loopAds&&(this.viewabilityObserver.disconnect(),this.viewabilityObserver=null,_e(`MaiAdUnitVideo: Disconnected viewability observer after error for ${this.config.id} (looping disabled).`)),this.adRequestTimeout&&(clearTimeout(this.adRequestTimeout),this.adRequestTimeout=null);const t=e.getErrorCode?e.getErrorCode():null,i=e.getErrorType?e.getErrorType():null,n=e.getVastErrorCode?e.getVastErrorCode():null,s=303===t||1009===t||1010===t;if(_e(`MaiAdUnitVideo Ad Error for ${this.config.id}:`,{message:e.message||"No message",code:t??"No code",vastCode:n??"No VAST code",type:i??"No type",vastUrl:this.config.vastUrl,playerType:this.config.playerType}),function(e){if(!d)return;const t=window.innerWidth||document.documentElement.clientWidth||0,i=t<=727?"mobile":t<=1023?"tablet":"desktop",n=window.maiPubVastErrors=window.maiPubVastErrors||{total:0,byVastCode:{},byImaCode:{},byDevice:{},entries:[]},s=e.vastCode??"none",o=e.code??"none";n.total++,n.byVastCode[s]=(n.byVastCode[s]||0)+1,n.byImaCode[o]=(n.byImaCode[o]||0)+1,n.byDevice[i]=(n.byDevice[i]||0)+1,n.entries.push({t:(new Date).toLocaleTimeString("en-US",{hour12:!0}),id:e.id,vastCode:s,imaCode:o,type:e.type??"none",device:i,playerType:e.playerType,message:e.message||"",connection:ve(),ua:navigator.userAgent}),n.entries.length>100&&n.entries.shift(),_e(`MaiAdUnitVideo VAST error tally [${i}] vast:${s} ima:${o} â total ${n.total}`,()=>({byVastCode:n.byVastCode,byDevice:n.byDevice}))}({id:this.config.id,code:t,vastCode:n,type:i,message:e.message||null,playerType:this.config.playerType}),s||"Ad request timeout"===e.message||console.error("Full IMA Error Object:",e),this._destroyAdsManager(!0),this.container.classList.remove("is-playing"),"outstream"===this.config.playerType&&this.config.loopAds){this._adErrorRetryCount++;const t=e.getErrorCode?e.getErrorCode():null,i=303===t||1009===t||1010===t?2:3;if(this._adErrorRetryCount>
1=i)return this.maxRetriesReached=!0,_e(`MaiAdUnitVideo Circuit Breaker: Tripped for ${this.config.id} after ${this._adErrorRetryCount} consecutive errors. Halting auction requests.`),this.cleanPlayerDOMState(!1),this.container&&(this.container.style.display="none"),this._onScroll&&(window.removeEventListener("scroll",this._onScroll),this._onScroll=null),this._syncRafId&&(cancelAnimationFrame(this._syncRafId),this._syncRafId=null),void(this.viewabilityObserver&&(this.viewabilityObserver.disconnect(),this.viewabilityObserver=null,this._detachResizeObserver()));if(U){const e=Math.min(1e4*this._adErrorRetryCount,6e4);_e(`MaiAdUnitVideo: Ad error managed. Backing off for ${e}ms before attempt ${this._adErrorRetryCount+1}.`),this.syncPlaybackState(),this._scheduleLoopRetry(e)}else _e("MaiAdUnitVideo: Ad error managed. Page hidden â retry deferred until visible.")}else"outstream"!==this.config.playerType||this.config.loopAds?"instream"===this.config.playerType&&this.config.contentSrc&&(this.videoEl.controls=!0,this.syncPlaybackState(),this.videoEl.play()):(_e("MaiAdUnitVideo Cleanup: Outstream unit failed to fill and looping is disabled. Hard-collapsing layout frame."),this.cleanPlayerDOMState(!1),this.container&&this.container.style.setProperty("display","none","important"),this.viewabilityObserver&&(this.viewabilityObserver.disconnect(),this.viewabilityObserver=null,this._detachResizeObserver()))}finally{this._handlingAdError=!1}}}}class Ie{constructor(e){this.container=e,this.audioEl=e.querySelector(".mai-ad-unit-audio__audio"),this.adContainer=e.querySelector(".mai-ad-unit-audio__ad"),this.config={id:e.id,slotSlug:e.id.replace("mai-ad-unit-",""),unitId:e.dataset.unitId||"audio-default",audioSrc:e.dataset.audioSrc||"",vastUrl:maiPubAdsVars.audioAds?.[e.dataset.unitId||"audio-default"]?.url||"",preroll:"true"===e.dataset.preroll,postroll:"true"===e.dataset.postroll,midrollInterval:parseInt(e.dataset.midrollInterval||"0",10),targets:e.dataset.targets||"",mediaType:e.dataset.mediaType||"ao"},this.state={adPlaying:!1,nextMidrollAt:this.config.midrollInterval||0,prerollPlayed:!1,postrollPlayed:!1},!0===maiPubAdsVars.magnite?this.adUnitConfig=function(e,t){if(!document.getElementById(e))return null;const i="object"==typeof g&&g?g[t]:null;return{code:e,mediaTypes:{audio:{context:"instream",playerSize:[1,1],mimes:["audio/mp3","audio/aac","audio/ogg"],protocols:[2,3,5,6],delivery:[1]}},bids:i&&i.bids||[]}}(this.config.id,this.config.slotSlug):this.adUnitConfig=null,this.init()}init(){this.audioEl?(_e(`MaiAdUnitAudio: initialized ${this.config.id}`,this.config),this.audioEl.addEventListener("play",()=>this.onPlay()),this.audioEl.addEventListener("timeupdate",()=>this.onTimeUpdate()),this.audioEl.addEventListener("ended",()=>this.onEnded())):_e(`MaiAdUnitAudio: no audio element found for ${this.config.id}`)}onPlay(){!this.config.preroll||this.state.prerollPlayed||this.state.adPlaying||(this.state.prerollPlayed=!0,this.loadAudioPod("preroll"))}onTimeUpdate(){this.config.midrollInterval&&!this.state.adPlaying&&this.audioEl.currentTime>=this.state.nextMidrollAt&&(_e(`MaiAdUnitAudio: midroll trigger at ${this.audioEl.currentTime.toFixed(1)}s for ${this.config.id}`),this.state.nextMidrollAt+=this.config.midrollInterval,this.loadAudioPod("midroll"))}onEnded(){!this.config.postroll||this.state.postrollPlayed||this.state.adPlaying||(this.state.postrollPlayed=!0,this.loadAudioPod("postroll"))}loadIMA(e){if(window.google&&window.google.ima)return void e();if(window.isImaSdkLoading)return _e("MaiAdUnitAudio: IMA SDK is loading via another component. Deferring execution request."),void document.addEventListener("imaReady",()=>e(),{once:!0});_e("MaiAdUnitAudio: IMA SDK missing from page layout tree. Dynamically injecting loader..."),window.isImaSdkLoading=!0;const t=document.createElement("script");t.src="https://imasdk.googleapis.com/js/sdkloader/ima3.js",t.async=!0,t.onload=()=>{_e("MaiAdUnitAudio: IMA SDK successfully loaded for audio stream tracking."),window.isImaSdkLoading=!1,document.dispatchEvent(new CustomEvent("imaReady")),e()},t.onerror=()=>{_e("MaiAdUnitAudio Error: Failed to fetch Google IMA SDK framework hooks."),window.isImaSdkLoading=!1,this.resumeAudio(),this.state.adPlaying=!1},document.head.appendChild(t)}loadAudioPod(e){if(this.state.adPlaying)return;_e(`MaiAdUnitAudio: Preparing pipeline loop for break profile: [${e}]`);let t=maiPubAdsVars.audioAds?.[this.config.unitId]?.url||this.config.vastUrl;this.pauseAudio(),this.state.adPlaying=!0;const i=t=>{this.requestAd(t,e)};!0===maiPubAdsVars.magnite&&this.adUnitConfig?(_e(`MaiAdUnitAudio: Starting Prebid auction for ${this.config.id} [${e}]`),pbjs.que.push(()=>{pbjs.requestBids({adUnitCodes:[this.adUnitConfig.code],bidsBackHandler:e=>{const n=e[this.adUnitConfig.code]?.bids?.[0];n&&n.vastUrl?(_e(`MaiAdUnitAudio: Prebid won auction for ${this.config.id}. CPM: ${n.cpm}`),i(n.vastUrl)):(_e("MaiAdUnitAudio: Prebid auction had no fills. Falling back to default tag."),i(t))}})})):i(t)}requestAd(e,t){_e(`MaiAdUnitAudio.requestAd[${t}
1]: Executing VAST request for ${this.config.id}`),this.loadIMA(()=>{this.adContainer||(this.adContainer=document.createElement("div"),this.adContainer.className="mai-ad-unit-audio__ad",this.container.appendChild(this.adContainer));const i=new google.ima.AdDisplayContainer(this.adContainer);i.initialize();const n=new google.ima.AdsLoader(i);try{n.getSettings().setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.INSECURE)}catch(e){_e(`MaiAdUnitAudio: Unable to set VPAID mode for ${this.config.id}:`,e)}n.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,e=>{const t=e.getError(),i=t.getVastErrorCode?t.getVastErrorCode():null,s=t.getErrorCode?t.getErrorCode():null;_e(`MaiAdUnitAudio Error: IMA Ad compilation failed for ${this.config.id}:`,{message:t.getMessage?t.getMessage():"No message",code:s??"No code",vastCode:i??"No VAST code"}),this.state.adPlaying=!1,n.destroy(),this.resumeAudio()},!1),n.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,e=>{let t=null;try{t=new google.ima.AdsRenderingSettings,t.loadVideoTimeout=15e3,t.enablePreloading=!0}catch(e){_e(`MaiAdUnitAudio: Unable to build AdsRenderingSettings for ${this.config.id}:`,e)}const i=t?e.getAdsManager(this.adContainer,t):e.getAdsManager(this.adContainer);i.addEventListener(google.ima.AdEvent.Type.STARTED,()=>{_e(`MaiAdUnitAudio: Ad track playing on ${this.config.id}`)}),i.addEventListener(google.ima.AdEvent.Type.ALL_ADS_COMPLETED,()=>{_e(`MaiAdUnitAudio: Ad track complete on ${this.config.id}. Restoring content track.`),this.state.adPlaying=!1,i.destroy(),n.destroy(),this.resumeAudio()});try{i.init(this.container.clientWidth||300,40,google.ima.ViewMode.NORMAL),i.start()}catch(e){this.state.adPlaying=!1,this.resumeAudio()}},!1);try{const i=new URL(e);let s=i.searchParams.get("cust_params")||"",o={};s&&s.split("&").forEach(e=>{const[t,i]=e.split("=");t&&(o[decodeURIComponent(t)]=decodeURIComponent(i||""))});const a=["iu","sz","description_url","gdfp_req","env","output","unviewed_position_start","correlator","ad_type","vpmute","tfcd","npa","ciu_szs","impl"];Array.from(i.searchParams.keys()).forEach(e=>{a.includes(e)||"cust_params"===e||(o[e]=i.searchParams.get(e),i.searchParams.delete(e))}),o.asn=this.config.id,o.break_position=t;const r=Object.entries(o).map(([e,t])=>`${e}=${t}`).join("&");i.searchParams.set("cust_params",r),Ve(i),e=i.toString(),_e(`MaiAdUnitAudio Final VAST URL [${t}]:`,e);const d=new google.ima.AdsRequest;d.adTagUrl=e,d.linearAdSlotWidth=this.container.clientWidth||300,d.linearAdSlotHeight=40,d.setAdWillAutoPlay(!0),d.setAdWillPlayMuted(!1),n.requestAds(d)}catch(e){_e("MaiAdUnitAudio Sizing Engine Error:",e),this.state.adPlaying=!1,this.resumeAudio()}})}pauseAudio(){this.audioEl.pause()}resumeAudio(){this.audioEl.play()}}function $e(e){const t=void 0===e?I.ppidSource:e;return"server"===t||"fpid"===t}function Re(e){if(!e)return"";const t=String(e).replace(/-/g,"");return t.length>=32&&t.length<=150?t:""}function Ve(e){try{if(!e||!/(^|\.)pubads\.g\.doubleclick\.net$/.test(e.hostname))return;if(!0===R){e.searchParams.set("npa","0");const t=Re(I.ppid);t?(e.searchParams.set("ppid",t),_e(`VAST identity: attached ppid (source: ${I.ppidSource||"unknown"}).`)):_e("VAST identity: no valid PPID to attach (length out of 32-150 range).")}else e.searchParams.set("npa","1"),e.searchParams.delete("ppid"),_e("VAST identity: no consent â set npa=1, removed ppid.")}catch(e){_e("maiPubApplyVastIdentity: error applying identity to VAST URL",e)}}function _e(...e){if(!d&&!b)return;e=e.map(e=>"function"==typeof e?e():e);let t="maipub ";const i=Date.now(),n=(new Date).toLocaleTimeString("en-US",{hour12:!0});t+=c===i?"start":i-c+"ms",console.log(`${t} ${n}`,...e)}"undefined"!=typeof window&&(window.maiPubVastErrorReport=function(){const e=window.maiPubVastErrors;return e?(console.log(`maipub VAST errors â total ${e.total}`),console.table(e.byVastCode),console.log("By device:",e.byDevice,"| By IMA code:",e.byImaCode),e):(console.log("maipub: no VAST errors recorded (is ?maideb on?)"),null)})})(); 2//# sourceMappingURL=mai-publisher-ads.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.