var isWbst;
if (window.wp || window.wpApiSettings) {
    isWbst = 'wb';
} else {
    isWbst = 'ht';
}

var ix_ipl_scriptUrl = document.currentScript.src;
var ix_ipl_urlParams = new URL(ix_ipl_scriptUrl);
var ix_ipl_bsParam = ix_ipl_urlParams.searchParams.get('bs');
var ix_ipl_floaterParam = ix_ipl_urlParams.searchParams.get('floater');
function getParentElement() {
    var container = document.querySelector('[data-ix-instream-player]');
    if (container) {
        return container;
    }
    var parent = document.currentScript ? document.currentScript.parentElement : null;

    if (parent && parent.tagName === 'HEAD') {
        return document.body || document.documentElement;
    }

    return parent || document.body || document.documentElement;
}

var ix_ipl_prnElmnt = getParentElement();

var ix_ipl_href = document.currentScript.src;
var ix_ipl_macro1 = new URL(ix_ipl_href);
var ix_ipl_vzId = ix_ipl_macro1.searchParams.get('vzId');
var ix_ipl_wd = ix_ipl_macro1.searchParams.get('wd');
var ix_ipl_ht = ix_ipl_macro1.searchParams.get('ht');
var ix_ipl_pUrl = window.location.href;
var ix_ipl_mb = ix_ipl_macro1.searchParams.get('mb');
var ix_ipl_cB = Math.floor((Math.random() * 1000000) + 1);

var ix_ipl_mbEnabled = ix_ipl_mb === '1';
var ix_ipl_isMobile = ix_ipl_mbEnabled && (window.innerWidth <= 768 || window.screen.width <= 768);

function shouldUseMobileResponsive() {
    return ix_ipl_isMobile;
}

function getResponsiveDimensions() {
    return {
        width: ix_ipl_wd ? parseInt(ix_ipl_wd) : 300,
        height: ix_ipl_ht ? parseInt(ix_ipl_ht) : 250
    };
}

var dimensions = getResponsiveDimensions();
var IX_MOBILE_HEIGHT = 230;
var IX_DESKTOP_CONTENT_HEIGHT = dimensions.height ;

function injectProtectiveCSS() {
    const styleId = 'ix-player-protection-' + ix_ipl_cB;

    if (document.getElementById(styleId)) {
        return;
    }

    const style = document.createElement('style');
    style.id = styleId;

    let responsiveRules = '';
    if (ix_ipl_mbEnabled) {
        responsiveRules = `
        @media (min-width: 769px) {
            .ix-player-container:not(.ix-player-floating) {
                width: ${dimensions.width}px !important;
                height: ${IX_DESKTOP_CONTENT_HEIGHT}px !important;
            }
       }
        @media (max-width: 768px) {
            .ix-player-wrapper {
                width: 100% !important;
                max-width: 100% !important;
                box-sizing: border-box !important;
                display: block !important;
            }
            .ix-player-container:not(.ix-player-floating) {
                width: 100% !important;
                height: ${IX_MOBILE_HEIGHT}px !important;
            }
        }
        `;
    } else {
        responsiveRules = `
        .ix-player-container:not(.ix-player-floating) {
            width: ${dimensions.width}px !important;
            height: ${IX_DESKTOP_CONTENT_HEIGHT}px !important;
        }
        `;
    }

    style.textContent = `
        .ix-player-container {
            box-sizing: border-box !important;
            margin: 0 !important;
            padding: 0 !important;
            border: none !important;
            background: transparent !important;
            font-family: Arial, sans-serif !important;
            font-size: 14px !important;
            line-height: normal !important;
            color: #000 !important;
            text-align: left !important;
            display: block !important;
            overflow: visible !important;
            transform: none !important;
            opacity: 1 !important;
            visibility: visible !important;
            float: none !important;
            clear: none !important;
            outline: none !important;
            filter: none !important;
            clip: auto !important;
            clip-path: none !important;
            position: relative !important;
        }

        ${responsiveRules}

        .ix-player-close-btn {
            position: absolute 
            top: -20px 
            left: 0px 
            width: 30px 
            height: 20px 
            margin: 0 !
            padding: 0 
            background: black 
            color: white 
            border: none 
            cursor: pointer 
            font-size: small 
            font-weight: bolder 
            line-height: 20px 
            text-align: center 
            display: none 
            z-index: 10001 
            box-sizing: border-box 
            transform: none 
            border-radius: 0 
        }

        .ix-player-close-btn:hover {
            background: #333 !important;
        }

       .ix-player-container iframe {
           all: revert !important;
           border: none !important;
           margin: 0 !important;
           padding: 0 !important;
           width: 100% !important;
           height: 100% !important;
           overflow: hidden !important;
           display: block !important;
           background: transparent !important;
           transform: none !important;
           border-radius: 0 !important;
       }

       .ix-player-container.ix-player-floating {
           position: fixed !important;
           z-index: 2147483647 !important;
           box-shadow: 0 4px 12px rgba(0,0,0,0.3) !important;
           margin-top: 0 !important;
       }
   `;

    document.head.appendChild(style);
}

function createPlayerIframe() {
    injectProtectiveCSS();

    var containerHeight = ix_ipl_isMobile ? IX_MOBILE_HEIGHT : IX_DESKTOP_CONTENT_HEIGHT;

    const containerDiv = document.createElement('div');
    containerDiv.id = 'ix-player-container-' + ix_ipl_cB;
    containerDiv.className = 'ix-player-container';

    containerDiv.setAttribute('style',
        'position: relative; ' +
        'margin: 0; ' +
        'padding: 0; ' +
        'border: none; ' +
        'background: transparent; ' +
        'box-sizing: border-box; ' +
        'display: block; ' +
        'transform: none; ' +
        'overflow: visible; ' +
        'width: ' + (ix_ipl_isMobile ? '100%' : dimensions.width + 'px') + '; ' +
        'height: ' + containerHeight + 'px;'
    );

    const playerIframe = document.createElement('iframe');
    playerIframe.id = 'ix-player-iframe-' + ix_ipl_cB;
    playerIframe.name = 'ix-player-frame-' + ix_ipl_cB;
    playerIframe.setAttribute('frameborder', '0');
    playerIframe.setAttribute('scrolling', 'no');
    playerIframe.setAttribute('allowfullscreen', 'true');
    playerIframe.setAttribute('allow', 'autoplay');
    playerIframe.setAttribute('data-ix-player', 'true');

    playerIframe.style.cssText =
        'border: none; ' +
        'margin: 0; ' +
        'padding: 0; ' +
        'width: 100%; ' +
        'height: 100%; ' +
        'overflow: hidden; ' +
        'display: block; ' +
        'background: transparent;';

    const closeButton = document.createElement('button');
    closeButton.id = 'ix-player-close-' + ix_ipl_cB;
    closeButton.className = 'ix-player-close-btn';
    closeButton.textContent = 'X';
    closeButton.setAttribute('style',
        'position: absolute; ' +
        'top: -20px; ' +
        'left: 0; ' +
        'width: 30px; ' +
        'height: 20px; ' +
        'margin: 0; ' +
        'padding: 0; ' +
        'background: black; ' +
        'color: white; ' +
        'border: none; ' +
        'cursor: pointer; ' +
        'font-size: small; ' +
        'font-weight: bolder; ' +
        'display: none; ' +
        'z-index: 10001; ' +
        'box-sizing: border-box; ' +
        'transform: none; ' +
        'border-radius: 0; ' +
        'line-height: 20px; ' +
        'text-align: center;'
    );

    containerDiv.appendChild(closeButton);
    containerDiv.appendChild(playerIframe);

    if (ix_ipl_mbEnabled && ix_ipl_prnElmnt && ix_ipl_prnElmnt.style) {
        ix_ipl_prnElmnt.classList.add('ix-player-wrapper');
        ix_ipl_prnElmnt.style.setProperty('width', '100%', 'important');
        ix_ipl_prnElmnt.style.setProperty('max-width', '100%', 'important');
        ix_ipl_prnElmnt.style.setProperty('box-sizing', 'border-box', 'important');
        ix_ipl_prnElmnt.style.setProperty('margin', '0', 'important');
    }

    ix_ipl_prnElmnt.appendChild(containerDiv);

    if (ix_ipl_mbEnabled && typeof ResizeObserver !== 'undefined') {
        containerDiv._ixLastNotifiedWidth = 0;
        containerDiv._ixLastNotifiedHeight = 0;

        var resizeObserver = new ResizeObserver(function (entries) {
            var iframe = containerDiv.querySelector('iframe');
            if (!iframe) return;
            if (containerDiv.classList.contains('ix-player-floating')) return;

            for (var i = 0; i < entries.length; i++) {
                var entry = entries[i];
                var newW = Math.round(entry.contentRect.width);
                var newH = Math.round(entry.contentRect.height);

                if (newW < 10 || newH < 10) {
                    continue;
                }

                if (newW !== containerDiv._ixLastNotifiedWidth || newH !== containerDiv._ixLastNotifiedHeight) {
                    containerDiv._ixLastNotifiedWidth = newW;
                    containerDiv._ixLastNotifiedHeight = newH;

                    ix_ipl_isMobile = newW <= 768 || window.innerWidth <= 768;

                    if (iframe.contentWindow) {
                        iframe.contentWindow.postMessage({
                            type: 'ix_player_resize',
                            dimensions: { width: newW, height: newH }
                        }, '*');
                    }
                }
            }
        });

        resizeObserver.observe(containerDiv);
        containerDiv._ixResizeObserver = resizeObserver;
    }

    return { containerDiv, playerIframe, closeButton };
}
function initializePlayerInIframe(playerIframe) {

    if (window.__IX_IFRAME_INIT_DONE__) {
        return;
    }
    window.__IX_IFRAME_INIT_DONE__ = true;

    const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    const iframeDoc = playerIframe.contentDocument || playerIframe.contentWindow.document;
    const iframeHTML = `
<!DOCTYPE html>
<html style='margin: 0; padding: 0; overflow: hidden;'>
<head>
   <meta charset='UTF-8'>
   <meta name='viewport' content='width=device-width, initial-scale=1.0'>
   <title>IX Player</title>
<link rel='preconnect' href='https://video-instream.incrementxserv.com'>
<link rel='dns-prefetch' href='https://video-instream.incrementxserv.com'>

   <link rel='stylesheet' href='https://video-instream.incrementxserv.com/video-js.css'>
   <link rel='stylesheet' href='https://video-instream.incrementxserv.com/videojs.ads.css'>
   <link rel='stylesheet' href='https://video-instream.incrementxserv.com/videojs.ima.css'>

   <style>
       * {
           margin: 0;
           padding: 0;
           box-sizing: border-box;
       }

       html, body {
           margin: 0 !important;
           padding: 0 !important;
           overflow: hidden !important;
           width: 100% !important;
           height: 100% !important;
           background: transparent !important;
       }

       #incrx-video-container {
           position: relative;
           top: 0;
           height: 100%;
           width: 100%;
       }

       .video-js,
       #my-video {
           background: transparent !important;
           width: 100% !important;
           height: 100% !important;
           object-fit: fill !important;
           background: black !important;
           background-color: black !important;
       }

       #my-video_ima-ad-container {
           position: absolute !important;
           top: 0 !important;
           left: 0 !important;
           width: 100% !important;
           height: 100% !important;
           background: transparent !important;
       }

       #my-video_ima-ad-container video {
           width: 100% !important;
           height: 100% !important;
           object-fit: fill !important;
       }

       #incrx-video-container .ix_ipl_cls_ad-cntrls {
           position: absolute;
           bottom: 10px;
           left: 10px;
           visibility: hidden;
           z-index: 9999;
           display: flex;
           justify-content: center;
           gap: 10px;
       }

       #incrx-video-container .ix_ipl_ad-btn {
           background-color: #2421c9;
           color: white;
           border: none;
           border-radius: 50%;
           display: flex;
           justify-content: center;
           align-items: center;
           cursor: pointer;
           width: 25px;
           height: 25px;
       }

       #incrx-video-container div:not(#my-video_ima-ad-container):not(#my-video_ima-ad-container *),
       #incrx-video-container p:not(#my-video_ima-ad-container):not(#my-video_ima-ad-container *) {
           margin-bottom: 0 !important;
           font-size: 10px;
       }
   </style>
</head>
<body>
   <div id='incrx-video-container'>

       <video id='my-video'
              class='video-js vjs-default-skin'
              controls
              preload='auto'
              autoplay
              muted
			   disablePictureInPicture
              data-setup='{"controlBar": {"pictureInPictureToggle": false}}'
              style='width: 100%; height: 100%; object-fit: fill;'>
           <source id='video-source'
                   src='https://video-instream.incrementxserv.com/nature/playlist.m3u8'
                   type='application/x-mpegURL'>
       </video>

       <div class='ix_ipl_cls_ad-cntrls'>
           <button id='ad-play' class='ix_ipl_ad-btn'>
               <svg class='play-icon' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='25' height='25'>
                   <path d='M8 5v14l11-7z' fill='currentColor' />
               </svg>
           </button>
           <button id='ad-pause' class='ix_ipl_ad-btn'>
               <svg class='pause-icon' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='25' height='25'>
                   <path d='M6 19h4V5H6zm8-14v14h4V5z' fill='currentColor' />
               </svg>
           </button>
       </div>
   </div>

   <script src='https://video-instream.incrementxserv.com/video.min.js'></script>
   <script src='https://video-instream.incrementxserv.com/videojs-contrib-ads.min.js'></script>
   <script src='https://video-instream.incrementxserv.com/videojs.ima.js'></script>
   <script src='https://imasdk.googleapis.com/js/sdkloader/ima3.js'></script>

   <script>
       (function() {
           const vzId = '${ix_ipl_vzId}';
           const pUrl = '${ix_ipl_pUrl}';
           const mbEnabled = ${ix_ipl_mbEnabled};
           const dimensions = ${JSON.stringify(dimensions)};

           let hasViewedMainVideo = false;
           let isPlayerReady = false;
           let isVideoPlaying = false;
           let isImaInitialized = false;
           let isAdContainerReady = false;
           let firstAdRequested = false;
           let imaIsBusy = false;
           let adIsPlaying = false;
           let adsManager = null;
           let lastKnownTime = 0;

           var isFirefox = typeof InstallTrigger !== 'undefined';

           let isTabHidden = false;
           let userManuallyPaused = false;

           let vastResponseReceived = false;
           let creativeLoaded = false;        
           let creativeCheckTimeoutId = null;     

           let masterTimeoutId = null;
           let retryTimeoutId = null;
           let initCheckIntervalId = null;

           const MASTER_TIMEOUT = 25000;     
           const RETRY_DELAY_NORMAL = 2000;       
           const RETRY_DELAY_SLOW = 5000;          
           const RETRY_DELAY_NO_FILL = 1500;       
           const INITIAL_DELAY = 1000;
           const INIT_CHECK_INTERVAL = 500;
           const MAX_INIT_WAIT = 10000;
           const CREATIVE_LOAD_TIMEOUT = 4000;  

           let initStartTime = Date.now();

           function showAdLoader() {
           }

           function hideAdLoader() {
           }

           let networkSlow = false;

           function checkNetworkSpeed() {
               const t0 = Date.now();
               const img = new Image();
               const timeout = setTimeout(function() {
                   img.onload = img.onerror = null;
                   networkSlow = true;
               }, 5000);

               img.onload = function() {
                   clearTimeout(timeout);
                   networkSlow = (Date.now() - t0) > 2000;
               };
               img.onerror = function() {
                   clearTimeout(timeout);
                   networkSlow = true;
               };
           }

           function getRetryDelay() {
               return networkSlow ? RETRY_DELAY_SLOW : RETRY_DELAY_NORMAL;
           }

           function getVastUrl() {
               var currentIsMobile = mbEnabled && (window.innerWidth <= 768);
                return \`https://video.incrementxserv.com/vast?vzId=\${vzId}&cb=\${Math.floor(Math.random()*1e9)+1}&pageurl=\${encodeURIComponent(pUrl)}&width=\${dimensions.width}&height=\${dimensions.height}&mb=\${currentIsMobile ? 1 : 0}\`;
          }

           function clearAllTimeouts() {
               if (masterTimeoutId) {
                   clearTimeout(masterTimeoutId);
                   masterTimeoutId = null;
               }
               if (retryTimeoutId) {
                   clearTimeout(retryTimeoutId);
                   retryTimeoutId = null;
               }
               if (initCheckIntervalId) {
                   clearInterval(initCheckIntervalId);
                   initCheckIntervalId = null;
               }
               if (creativeCheckTimeoutId) {
                   clearTimeout(creativeCheckTimeoutId);
                   creativeCheckTimeoutId = null;
               }
           }

           function resumeMainVideo() {
               hideAdLoader();

               if (isTabHidden) return;
               if (userManuallyPaused) return;

               setTimeout(function() {
                   try {
                       if (isTabHidden) return;
                       if (userManuallyPaused) return;
                       if (player && !player.isDisposed() && player.paused()) {
                           player.muted(true);
                           player.play().catch(function(e) {
                               setTimeout(function() {
                                   if (!isTabHidden && !userManuallyPaused) player.play();
                               }, 100);
                           });
                       }
                   } catch (e) {
                   }
               }, 100);
           }

           function scheduleNextRetry(delay, reason) {
               if (retryTimeoutId) {
                   clearTimeout(retryTimeoutId);
               }

               const actualDelay = delay || getRetryDelay();

               retryTimeoutId = setTimeout(function() {
                   retryTimeoutId = null;
                   requestAd();
               }, actualDelay);
         }

           function resetAdState() {
               vastResponseReceived = false;
               creativeLoaded = false;
               adIsPlaying = false;

               if (creativeCheckTimeoutId) {
                   clearTimeout(creativeCheckTimeoutId);
                   creativeCheckTimeoutId = null;
               }
           }

           function setImaBusy(busy, reason) {
               const wasBusy = imaIsBusy;
               imaIsBusy = busy;

               if (busy) {
                   if (retryTimeoutId) {
                       clearTimeout(retryTimeoutId);
                       retryTimeoutId = null;
                   }

                   if (masterTimeoutId) {
                       clearTimeout(masterTimeoutId);
                   }
                   masterTimeoutId = setTimeout(function() {
                       masterTimeoutId = null;
                       setImaBusy(false, 'master timeout');
                       adIsPlaying = false;
                       resumeMainVideo();
                       scheduleNextRetry(RETRY_DELAY_NO_FILL, 'master timeout');
                   }, MASTER_TIMEOUT);
               } else {
                   if (masterTimeoutId) {
                       clearTimeout(masterTimeoutId);
                       masterTimeoutId = null;
                   }
                   if (creativeCheckTimeoutId) {
                       clearTimeout(creativeCheckTimeoutId);
                       creativeCheckTimeoutId = null;
                   }
                   hideAdLoader();
               }
           }

           function checkInitialization() {
    const adContainer = document.getElementById('my-video_ima-ad-container');
    if (adContainer) {
        isAdContainerReady = true;
    }

    const isReady = isPlayerReady && isVideoPlaying && isAdContainerReady;

    return isReady;
}

           function waitForInitAndRequestAd() {
    if (firstAdRequested) {
        return;
    }

    const elapsed = Date.now() - initStartTime;

    if (checkInitialization()) {

        firstAdRequested = true;

        if (initCheckIntervalId) {
            clearInterval(initCheckIntervalId);
            initCheckIntervalId = null;
        }

        setTimeout(function() {
            requestAd();
        }, 5000);

    } else if (elapsed > MAX_INIT_WAIT) {

        firstAdRequested = true;

        if (initCheckIntervalId) {
            clearInterval(initCheckIntervalId);
            initCheckIntervalId = null;
        }

        requestAd();
    }
}

           function requestAd() {

    if (imaIsBusy) {
        return;
    }

    if (adIsPlaying) {
        return;
    }

    if (!firstAdRequested) {
        return;
    }

    if (isTabHidden) {
        return;
    }

    if (typeof player.ima === 'undefined') {
        return;
    }

    resetAdState();

    setImaBusy(true, 'request started');

    showAdLoader();

    try {
        var vastUrl = getVastUrl();

        player.ima.changeAdTag(vastUrl);
        player.ima.requestAds();

    } catch (e) {
        setImaBusy(false, 'request exception');
        resumeMainVideo();
        scheduleNextRetry(RETRY_DELAY_NO_FILL, 'exception');
    }
}

           function startCreativeLoadCheck() {
               if (creativeCheckTimeoutId) {
                   clearTimeout(creativeCheckTimeoutId);
               }

               creativeCheckTimeoutId = setTimeout(function() {
                   creativeCheckTimeoutId = null;

                   if (vastResponseReceived && !creativeLoaded && !adIsPlaying) {

                       setImaBusy(false, 'empty creative detected');
                       resumeMainVideo();

                       scheduleNextRetry(RETRY_DELAY_NO_FILL, 'empty creative');
                   }
               }, CREATIVE_LOAD_TIMEOUT);
           }

           var initW = document.documentElement.clientWidth || dimensions.width;
           var initH = document.documentElement.clientHeight || (dimensions.height );

           const player = videojs('my-video', {
               autoplay: 'muted',
               muted: true,
               loop: true,
               bigPlayButton: false,
               techOrder: ['html5'],
               width: initW,
               height: initH,
               html5: {
    vhs: {
        overrideNative: true,

        enableLowInitialPlaylist: true,
        smoothQualityChange: false,
        fastQualityChange: true,
        limitRenditionByPlayerDimensions: true,

        maxPlaylistRetries: 3
    },

    preload: 'auto'
}
           });

           if (isFirefox) {
               player.on('durationchange', function() {
                   try {
                       var d = player.duration();
                       if (!isFinite(d) || d === 0) {
                           var tech = player.tech({ IWillNotUseThisInProduction: true });
                           if (tech && tech.vhs && tech.vhs.playlists && tech.vhs.playlists.media) {
                               var media = tech.vhs.playlists.media();
                               if (media && media.segments && media.segments.length > 0) {
                                   var totalDuration = 0;
                                   for (var i = 0; i < media.segments.length; i++) {
                                       totalDuration += (media.segments[i].duration || 0);
                                   }
                                   if (totalDuration > 0 && isFinite(totalDuration)) {
                                       var originalDuration = player.duration.bind(player);
                                       player.duration = function() {
                                           var dd = originalDuration();
                                           return (!isFinite(dd) || dd === 0) ? totalDuration : dd;
                                       };
                                       player.removeClass('vjs-live');
                                       player.removeClass('vjs-liveui');
                                   }
                               }
                           }
                       }
                   } catch(e) {}
               });
           }

           player.on('error', function() {
               var err = player.error();

               if (!err) return;

               if (err.code === 3 || err.code === 4) {

                   try {
                       var currentTime = player.currentTime();

                       player.pause();

                       setTimeout(function() {
                           player.src(player.currentSource());
                           player.currentTime(currentTime || 0);

                           player.play().then(function() {
                           }).catch(function(){});

                       }, 500);

                   } catch (e) {
                   }
               }
           });

           function pauseVhsSegmentLoader() {
               try {
                   var tech = player.tech({ IWillNotUseThisInProduction: true });
                   if (tech && tech.vhs && tech.vhs.masterPlaylistController_) {
                       var mpc = tech.vhs.masterPlaylistController_;
                       if (mpc.mainSegmentLoader_) {
                           mpc.mainSegmentLoader_.abort();
                           mpc.mainSegmentLoader_.pause();
                           if (mpc.mainSegmentLoader_.pendingSegment_) {
                               mpc.mainSegmentLoader_.pendingSegment_ = null;
                           }
                       }
                       if (mpc.audioSegmentLoader_) {
                           mpc.audioSegmentLoader_.abort();
                           mpc.audioSegmentLoader_.pause();
                           if (mpc.audioSegmentLoader_.pendingSegment_) {
                               mpc.audioSegmentLoader_.pendingSegment_ = null;
                           }
                       }
                   }
               } catch(e) {}
           }

           function resumeVhsSegmentLoader() {
               try {
                   var tech = player.tech({ IWillNotUseThisInProduction: true });
                   if (tech && tech.vhs && tech.vhs.masterPlaylistController_) {
                       var mpc = tech.vhs.masterPlaylistController_;
                       if (mpc.mainSegmentLoader_) mpc.mainSegmentLoader_.load();
                       if (mpc.audioSegmentLoader_) mpc.audioSegmentLoader_.load();
                   }
               } catch(e) {}
           }

           var wasPlayingBeforeHidden = false;

           function handleVisibilityChange() {
               try {
                   var isHidden;
                   if (handleVisibilityChange.__forceHidden) {
                       isHidden = true;
                   } else if (handleVisibilityChange.__forceVisible) {
                       isHidden = false;
                   } else {
                       try {
                           isHidden = (window.parent && window.parent.document) ? window.parent.document.hidden : document.hidden;
                       } catch(e) {
                           isHidden = document.hidden;
                       }
                   }

                   if (isHidden) {
                       isTabHidden = true;
                       if (retryTimeoutId) {
                           clearTimeout(retryTimeoutId);
                           retryTimeoutId = null;
                       }
                       if (player && !player.isDisposed()) {
                           wasPlayingBeforeHidden = !player.paused();
                           player.pause();
                           pauseVhsSegmentLoader();
                           if (adsManager && adIsPlaying) {
                               try { adsManager.pause(); } catch(e) {}
                           }
                       }
                   } else {
                       isTabHidden = false;
                       if (player && !player.isDisposed()) {
                           resumeVhsSegmentLoader();
                           if (adsManager && adIsPlaying) {
                               try { adsManager.resume(); } catch(e) {}
                               return;
                           }
                           if (wasPlayingBeforeHidden && !userManuallyPaused) {
                               player.play().catch(function(){});
                           }
                           if (!imaIsBusy && !adIsPlaying && firstAdRequested && !retryTimeoutId) {
                               scheduleNextRetry(getRetryDelay(), 'tab became visible');
                           }
                       }
                   }
               } catch(e) {}
           }
           handleVisibilityChange.__forceHidden = false;
           handleVisibilityChange.__forceVisible = false;

           document.addEventListener('visibilitychange', handleVisibilityChange);

           window.addEventListener('message', function(event) {
               if (!event.data || event.data.type !== 'ix_tab_visibility') return;
               if (event.data.hidden && !isTabHidden) {
                   handleVisibilityChange.__forceHidden = true;
                   handleVisibilityChange();
                   handleVisibilityChange.__forceHidden = false;
               } else if (!event.data.hidden && isTabHidden) {
                   handleVisibilityChange.__forceVisible = true;
                   handleVisibilityChange();
                   handleVisibilityChange.__forceVisible = false;
               }
           });

           (function() {
               var lastHiddenState = false;
               setInterval(function() {
                   try {
                       var parentHidden = false;
                       try {
                           if (window.parent && window.parent !== window && window.parent.document) {
                               parentHidden = window.parent.document.hidden;
                           }
                       } catch(e) {
                           parentHidden = document.hidden;
                       }
                       if (!parentHidden) parentHidden = document.hidden;

                       if (parentHidden !== lastHiddenState) {
                           lastHiddenState = parentHidden;
                           if (parentHidden && !isTabHidden) {
                               handleVisibilityChange.__forceHidden = true;
                               handleVisibilityChange();
                               handleVisibilityChange.__forceHidden = false;
                           } else if (!parentHidden && isTabHidden) {
                               handleVisibilityChange.__forceVisible = true;
                               handleVisibilityChange();
                               handleVisibilityChange.__forceVisible = false;
                           }
                       }
                   } catch(e) {}
               }, 500);
           })();

           player.ima({
               debug: false,
               numRedirects: 10,
           });

           player.on('ads-manager', function(response) {
               adsManager = response.adsManager;
               isImaInitialized = true;

               if (adsManager) {
                   vastResponseReceived = true;

                   startCreativeLoadCheck();

                   adsManager.addEventListener(
                       google.ima.AdEvent.Type.LOADED,
                       function(e) {
                           creativeLoaded = true;

                           if (creativeCheckTimeoutId) {
                               clearTimeout(creativeCheckTimeoutId);
                               creativeCheckTimeoutId = null;
                           }
                       }
                   );
                   adsManager.addEventListener(
                       google.ima.AdEvent.Type.STARTED,
                       function(e) {
                           creativeLoaded = true;
                           adIsPlaying = true;
                           hideAdLoader();

                           if (creativeCheckTimeoutId) {
                               clearTimeout(creativeCheckTimeoutId);
                               creativeCheckTimeoutId = null;
                           }
                       }
                   );

                   adsManager.addEventListener(
                       google.ima.AdEvent.Type.IMPRESSION,
                       function(e) {
                           creativeLoaded = true;
                           adIsPlaying = true;
                           hideAdLoader();
                       }
                   );

                   adsManager.addEventListener(
                       google.ima.AdEvent.Type.FIRST_QUARTILE,
                       function(e) {
                           if (!adIsPlaying) {
                               adIsPlaying = true;
                               hideAdLoader();
                           }
                       }
                   );

                   adsManager.addEventListener(
                       google.ima.AdEvent.Type.COMPLETE,
                       function(e) {
                           adIsPlaying = false;
                           setImaBusy(false, 'ad complete');
                           resumeMainVideo();
                           scheduleNextRetry(getRetryDelay(), 'ad complete');
                       }
                   );

                   adsManager.addEventListener(
                       google.ima.AdEvent.Type.ALL_ADS_COMPLETED,
                       function(e) {
                           adIsPlaying = false;
                           setImaBusy(false, 'all ads complete');
                           resumeMainVideo();
                           scheduleNextRetry(getRetryDelay(), 'all complete');
                       }
                   );

                   adsManager.addEventListener(
                       google.ima.AdEvent.Type.SKIPPED,
                       function(e) {
                           adIsPlaying = false;
                           setImaBusy(false, 'ad skipped');
                           resumeMainVideo();
                           scheduleNextRetry(RETRY_DELAY_NO_FILL, 'skipped');
                       }
                   );
                   adsManager.addEventListener(
                       google.ima.AdErrorEvent.Type.AD_ERROR,
                       function(e) {
                           const error = e.getError();
                           adIsPlaying = false;
                           setImaBusy(false, 'ad error');
                           resumeMainVideo();
                           scheduleNextRetry(RETRY_DELAY_NO_FILL, 'error');
                       }
                   );

                   adsManager.addEventListener(
                       google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
                       function(e) {
                           adIsPlaying = false;
                           hideAdLoader();
                           resumeMainVideo();
                       }
                   );
               }
           });

           player.on('adsready', function() {
               isImaInitialized = true;
           });

           player.on('adloaded', function() {
               creativeLoaded = true;
           });

           player.on('adstart', function() {
               creativeLoaded = true;
               adIsPlaying = true;
               hideAdLoader();

               if (masterTimeoutId) {
                   clearTimeout(masterTimeoutId);
                   masterTimeoutId = null;
               }
           });

           player.on('adend', function() {
               adIsPlaying = false;
               setImaBusy(false, 'ad ended');
               resumeMainVideo();
               scheduleNextRetry(getRetryDelay(), 'ad ended');
           });

           player.on('adskip', function() {
               adIsPlaying = false;
               setImaBusy(false, 'ad skipped');
               resumeMainVideo();
               scheduleNextRetry(RETRY_DELAY_NO_FILL, 'skipped');
           });

           player.on('aderror', function(e) {
               adIsPlaying = false;
               setImaBusy(false, 'ad error');
               resumeMainVideo();
               scheduleNextRetry(RETRY_DELAY_NO_FILL, 'error');
           });

           player.on('adtimeout', function() {
               adIsPlaying = false;
               setImaBusy(false, 'no fill');
               resumeMainVideo();
               scheduleNextRetry(RETRY_DELAY_NO_FILL, 'no fill');
           });

           player.on('contentresumed', function() {
               hideAdLoader();
               if (imaIsBusy && !adIsPlaying) {
                   setImaBusy(false, 'content resumed');
                   scheduleNextRetry(RETRY_DELAY_NO_FILL, 'content resumed');
               }
               resumeMainVideo();
           });

           player.on('adserror', function(e) {
               adIsPlaying = false;
               setImaBusy(false, 'ads error');
               resumeMainVideo();
               scheduleNextRetry(RETRY_DELAY_NO_FILL, 'ads error');
           });
           player.ready(function() {

    var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

    isPlayerReady = true;

    try {
        player.load();
    } catch(e) {
    }

    player.one('loadedmetadata', function() {

    setTimeout(function() {
        try {
            player.currentTime(0.01);
        } catch(e) {
        }
    }, 100); 

    if (isFirefox) {
        try {
            var tech = player.tech({ IWillNotUseThisInProduction: true });
            if (tech && tech.vhs && tech.vhs.playlists && tech.vhs.playlists.media) {
                var media = tech.vhs.playlists.media();
                if (media && media.segments && media.segments.length > 0) {
                    var totalDuration = 0;
                    for (var i = 0; i < media.segments.length; i++) {
                        totalDuration += (media.segments[i].duration || 0);
                    }
                    if (totalDuration > 0 && isFinite(totalDuration)) {

                        var originalDuration = player.duration.bind(player);
                        player.duration = function() {
                            var d = originalDuration();
                            return (!isFinite(d) || d === 0) ? totalDuration : d;
                        };

                        player.removeClass('vjs-live');
                        player.removeClass('vjs-liveui');
                        if (player.controlBar && player.controlBar.liveDisplay) {
                            player.controlBar.liveDisplay.hide();
                        }
                        if (player.controlBar && player.controlBar.progressControl) {
                            player.controlBar.progressControl.show();
                        }
                        if (player.controlBar && player.controlBar.durationDisplay) {
                            player.controlBar.durationDisplay.show();
                        }
                        if (player.controlBar && player.controlBar.currentTimeDisplay) {
                            player.controlBar.currentTimeDisplay.show();
                        }
                        player.trigger('durationchange');
                    }
                }
            }
        } catch(e) {
        }
    }
});

try {
    var videoEl = null;

    if (player && player.tech && player.tech({ IWillNotUseThisInProduction: true })) {
        var tech = player.tech({ IWillNotUseThisInProduction: true });
        videoEl = tech && tech.el && tech.el();
    }

    if (!videoEl) {
        videoEl = document.querySelector('#my-video_html5_api');
    }

    if (videoEl && typeof videoEl.play === 'function') {
    videoEl.muted = true;

    if (isSafari) {
        try {
            var p = videoEl.play();
            if (p && p.catch) p.catch(function(){});
        } catch(e) {
        }
    } else {
    }

} else {
}

} catch (e) {
}

player.ima.initializeAdDisplayContainer();

var playPromise;
if (isSafari) {
    setTimeout(function() {
        playPromise = player.play();
    }, 100);
} else {
    playPromise = player.play();
}

setTimeout(function() {
    try {

        player.trigger('playing');
        player.trigger('contentchanged');
        player.trigger('contentresumed');

        if (player.ads && player.ads.state !== 'content-set') {
            player.ads._contentEnded = false;
        }

    } catch(e) {
    }
}, 100);

player.trigger('adsready');

if (!isVideoPlaying) {
    isVideoPlaying = true;
}

if (playPromise && typeof playPromise.then === 'function') {
    playPromise.then(function() {
    }).catch(function(e) {
        player.muted(true);
        player.play().catch(function(){});
    });
}

    if (playPromise && typeof playPromise.then === 'function') {
        playPromise.then(function() {
        }).catch(function(e) {
            player.muted(true);
            player.play().catch(function(){});
        });
    }

    setTimeout(function() {
        if (!isVideoPlaying && player && !player.isDisposed() && player.readyState() >= 2) {
            isVideoPlaying = true;
        }
    }, 2000);

    initCheckIntervalId = setInterval(waitForInitAndRequestAd, INIT_CHECK_INTERVAL);

    try {
        var tech = player.tech({ IWillNotUseThisInProduction: true });

        if (tech && tech.vhs) {

            player.on('waiting', function() {

                setTimeout(function() {
                    if (!player.paused()) {
                        player.play().catch(function(){});
                    }
                }, 1000);
            });

            var lastTime = 0;

            setInterval(function() {
                var current = player.currentTime();

                if (current === lastTime && !player.paused()) {

                    try {
                        player.currentTime(current + 0.01);
                    } catch(e){}
                }

                lastTime = current;
            }, 2000);
        }

    } catch(e) {
    }

});

           player.on('playing', function() {
    isVideoPlaying = true;
});

player.on('canplay', function() {
    if (!isVideoPlaying) {
        isVideoPlaying = true;
    }
});

player.on('loadedmetadata', function() {
    if (!isVideoPlaying && player.readyState() >= 2) {
        isVideoPlaying = true;
    }
});

           setInterval(function() {
               if (isTabHidden) return;
               if (userManuallyPaused) return;
               if (!imaIsBusy && !adIsPlaying && firstAdRequested) {
                   if (player && !player.isDisposed() && player.paused()) {
                       resumeMainVideo();
                   }
               }
           }, 5000);
           let loopAdRequested = false;

           player.on('timeupdate', function() {
               const currentTime = player.currentTime();

               if (lastKnownTime > 5 && currentTime < 1) {
                   if (!loopAdRequested && !imaIsBusy && !adIsPlaying && firstAdRequested && !isTabHidden) {
                       loopAdRequested = true;
                       setTimeout(function() {
                           if (!imaIsBusy && !adIsPlaying && !isTabHidden) {
                               requestAd();
                           }
                       }, 300);
                   }
               }

               if (currentTime > 2) {
                   loopAdRequested = false;
               }

               lastKnownTime = currentTime;
           });

           player.on('pause', function() {
               if (!adIsPlaying && !imaIsBusy && !isTabHidden) {
                   userManuallyPaused = true;
               }
           });

           player.on('play', function() {
               userManuallyPaused = false;
           });

           if (mbEnabled) {
               const videoContainer = document.getElementById('incrx-video-container');
               const observer = new IntersectionObserver(function(entries) {
                   entries.forEach(function(entry) {
                       if (entry.isIntersecting && entry.intersectionRatio > 0.5) {
                           hasViewedMainVideo = true;
                           observer.disconnect();
                       }
                   });
               }, { threshold: 0.5 });
               observer.observe(videoContainer);
           } else {
               hasViewedMainVideo = true;
           }

           if (window.parent !== window) {
               window.parent.postMessage({ type: 'ix_player_ready', hasViewedMainVideo: hasViewedMainVideo }, '*');
           }

           if (mbEnabled) {
               const viewCheck = setInterval(function() {
                   if (hasViewedMainVideo) {
                       if (window.parent !== window) {
                           window.parent.postMessage({ type: 'ix_player_viewed', hasViewedMainVideo: true }, '*');
                       }
                       clearInterval(viewCheck);
                   }
               }, 500);
           }

           window.addEventListener('message', function(event) {
               if (!event.data) return;

               if (event.data.type === 'ix_player_set_floating') {
                   const isFloating = event.data.isFloating;
                   const width = event.data.dimensions.width;
                   const height = event.data.dimensions.height;

                   const wasPlaying = adIsPlaying && adsManager;
                   if (wasPlaying) { try { adsManager.pause(); } catch(e) {} }

                   requestAnimationFrame(function() {
                       const floatingEls = document.querySelectorAll('#incrx-video-container, #my-video, .vjs-tech, .video-js');
                       floatingEls.forEach(function(el) {
                           if (isFloating) {
                               el.classList.add('ix_ipl_floating');
                           } else {
                               el.classList.remove('ix_ipl_floating');
                           }
                       });

                       const container = document.getElementById('incrx-video-container');
                       if (container) {
                           container.style.width = '100%';
                           container.style.height = '100%';
                       }

                       player.width(width);
                       player.height(height);

                       if (adsManager && adIsPlaying) {
                           try { adsManager.resize(width, height, google.ima.ViewMode.NORMAL); } catch(e) {}
                       }

                       if (wasPlaying) { try { adsManager.resume(); } catch(e) {} }
                   });
               }

               if (event.data.type === 'ix_player_resize') {
                   const width = event.data.dimensions.width;
                   const height = event.data.dimensions.height;

                   player.width(width);
                   player.height(height);

                   if (adsManager && adIsPlaying) {
                       try { adsManager.resize(width, height, google.ima.ViewMode.NORMAL); } catch(e) {}
                   }
               }
           });

           window.addEventListener('beforeunload', function() {
               clearAllTimeouts();
           });

       })();
   </script>
</body>
</html>
   `;

    if (isSafari) {
        const blob = new Blob([iframeHTML], { type: 'text/html' });
        const blobUrl = URL.createObjectURL(blob);
        playerIframe.src = blobUrl;
        playerIframe.onload = function () { URL.revokeObjectURL(blobUrl); };
    } else {
        iframeDoc.open();
        iframeDoc.write(iframeHTML);
        iframeDoc.close();
    }
}

function getFloatingDimensions() {
    return {
        width: 260,
        height: 150,
        totalHeight: 150
    };
}

function setupFloatingBehavior(containerDiv, closeButton) {
    var floatingClosed = false;
    var isFloating = false;

    var floatingDimensions = getFloatingDimensions();
    var floaterMode = ix_ipl_floaterParam || 'r';
    var isFloatingEnabled = floaterMode !== '0';

    if (!isFloatingEnabled) return;

    var playerIframe = containerDiv.querySelector('iframe');
    var posRight = floaterMode === 'l' ? 'auto' : '20px';
    var posLeft = floaterMode === 'l' ? '20px' : 'auto';

    var sentinelStyle =
        'width: 1px; ' +
        'height: 1px; ' +
        'margin: 0; ' +
        'padding: 0; ' +
        'border: none; ' +
        'background: transparent; ' +
        'visibility: hidden; ' +
        'pointer-events: none; ' +
        'position: relative; ' +
        'display: block;';

    var sentinelTop = document.createElement('div');
    sentinelTop.id = 'ix-sentinel-top-' + ix_ipl_cB;
    sentinelTop.setAttribute('style', sentinelStyle);
    containerDiv.parentNode.insertBefore(sentinelTop, containerDiv);

    var sentinelBottom = document.createElement('div');
    sentinelBottom.id = 'ix-sentinel-bottom-' + ix_ipl_cB;
    sentinelBottom.setAttribute('style', sentinelStyle);
    if (containerDiv.nextSibling) {
        containerDiv.parentNode.insertBefore(sentinelBottom, containerDiv.nextSibling);
    } else {
        containerDiv.parentNode.appendChild(sentinelBottom);
    }

    var placeholder = document.createElement('div');
    placeholder.id = 'ix-placeholder-' + ix_ipl_cB;
    placeholder.setAttribute('style',
        'display: none; ' +
        'margin: 0; ' +
        'padding: 0; ' +
        'border: none; ' +
        'background: transparent; ' +
        'pointer-events: none;'
    );

    var hasVisitedContainer = false;
    var topVisible = false;
    var bottomVisible = false;

    var dockedContainerStyle = containerDiv.getAttribute('style');

    function updateFloatingState() {
        if (floatingClosed) return;
        if (!hasVisitedContainer) return;

        if (!topVisible && !bottomVisible && !isFloating) {
            goFloat();
        } else if ((topVisible || bottomVisible) && isFloating) {
            goDock();
        }
    }

    function goFloat() {
        if (isFloating || floatingClosed) return;
        isFloating = true;

        var currentWidth = containerDiv.offsetWidth;
        var currentHeight = containerDiv.offsetHeight;
        var currentMarginTop = window.getComputedStyle(containerDiv).marginTop;

        containerDiv.parentNode.insertBefore(placeholder, containerDiv);
        placeholder.setAttribute('style',
            'display: block; ' +
            'width: ' + currentWidth + 'px; ' +
            'height: ' + currentHeight + 'px; ' +
            'margin: 0; ' +
            'margin-top: ' + currentMarginTop + '; ' +
            'padding: 0; ' +
            'border: none; ' +
            'background: transparent; ' +
            'pointer-events: none;'
        );

        containerDiv.classList.add('ix-player-floating');
        containerDiv.setAttribute('style',
            'position: fixed; ' +
            'bottom: 120px; ' +
            'right: ' + posRight + '; ' +
            'left: ' + posLeft + '; ' +
            'width: ' + floatingDimensions.width + 'px; ' +
            'height: ' + floatingDimensions.totalHeight + 'px; ' +
            'z-index: 2147483647; ' +
            'box-shadow: 0 4px 12px rgba(0,0,0,0.3); ' +
            'margin: 0; ' +
            'padding: 0; ' +
            'border: none; ' +
            'overflow: visible; ' +
            'display: block; ' +
            'background: transparent; ' +
            'box-sizing: border-box;'
        );

        closeButton.style.display = 'block';

        if (playerIframe.contentWindow) {
            playerIframe.contentWindow.postMessage({
                type: 'ix_player_set_floating',
                isFloating: true,
                dimensions: {
                    width: floatingDimensions.width,
                    height: floatingDimensions.height
                }
            }, '*');
        }
    }

    function goDock() {
        if (!isFloating) return;
        isFloating = false;

        containerDiv.classList.remove('ix-player-floating');
        containerDiv.setAttribute('style', dockedContainerStyle);

        if (placeholder.parentNode) {
            placeholder.parentNode.removeChild(placeholder);
        }

        closeButton.style.display = 'none';

        if (playerIframe.contentWindow) {
            var w = containerDiv.offsetWidth || dimensions.width;
            var h = containerDiv.offsetHeight || IX_DESKTOP_CONTENT_HEIGHT;
            playerIframe.contentWindow.postMessage({
                type: 'ix_player_set_floating',
                isFloating: false,
                dimensions: { width: w, height: h }
            }, '*');
        }
    }

    closeButton.addEventListener('click', function () {
        floatingClosed = true;
        goDock();
    });

    if (window.IntersectionObserver) {
        var topObserver = new IntersectionObserver(function (entries) {
            var entry = entries[0];
            if (!entry) return;

            topVisible = entry.isIntersecting;

            if (!hasVisitedContainer && topVisible) {
                hasVisitedContainer = true;
            }

            updateFloatingState();
        }, { root: null, rootMargin: '0px', threshold: 0 });

        var bottomObserver = new IntersectionObserver(function (entries) {
            var entry = entries[0];
            if (!entry) return;

            bottomVisible = entry.isIntersecting;

            if (!hasVisitedContainer && bottomVisible) {
                hasVisitedContainer = true;
            }

            updateFloatingState();
        }, { root: null, rootMargin: '0px', threshold: 0 });

        topObserver.observe(sentinelTop);
        bottomObserver.observe(sentinelBottom);

        var topRect = sentinelTop.getBoundingClientRect();
        var bottomRect = sentinelBottom.getBoundingClientRect();
        topVisible = topRect.top >= 0 && topRect.top < window.innerHeight;
        bottomVisible = bottomRect.top >= 0 && bottomRect.top < window.innerHeight;

        if (topVisible || bottomVisible) {
            hasVisitedContainer = true;
        }
    }

    var lastKnownWidth = window.innerWidth;
    window.addEventListener('resize', function () {
        var newWidth = window.innerWidth;
        if (newWidth !== lastKnownWidth) {
            lastKnownWidth = newWidth;
            if (isFloating) goDock();
        }
    });
}

function setupParentVisibilityBridge(playerIframe) {
    document.addEventListener('visibilitychange', function () {
        try {
            if (playerIframe && playerIframe.contentWindow) {
                playerIframe.contentWindow.postMessage({
                    type: 'ix_tab_visibility',
                    hidden: document.hidden
                }, '*');
            }
        } catch (e) { }
    });
}

function ix_ipl_start() {
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            if (!ix_ipl_prnElmnt || ix_ipl_prnElmnt === document.documentElement) {
                ix_ipl_prnElmnt = getParentElement();
            }

            const { containerDiv, playerIframe, closeButton } = createPlayerIframe();
            setupFloatingBehavior(containerDiv, closeButton);
            setupParentVisibilityBridge(playerIframe);

            var isSafariBrowser = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
            if (isSafariBrowser) {
                initializePlayerInIframe(playerIframe);
            } else {
                playerIframe.onload = function () {
                    initializePlayerInIframe(playerIframe);
                };
                if (playerIframe.contentDocument && playerIframe.contentDocument.readyState === 'complete') {
                    initializePlayerInIframe(playerIframe);
                }
            }
        });
    } else {
        if (!ix_ipl_prnElmnt || ix_ipl_prnElmnt === document.documentElement) {
            ix_ipl_prnElmnt = getParentElement();
        }

        const { containerDiv, playerIframe, closeButton } = createPlayerIframe();
        setupFloatingBehavior(containerDiv, closeButton);
        setupParentVisibilityBridge(playerIframe);

        var isSafariBrowser = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
        if (isSafariBrowser) {
            initializePlayerInIframe(playerIframe);
        } else {
            playerIframe.onload = function () {
                initializePlayerInIframe(playerIframe);
            };
            setTimeout(function () {
                initializePlayerInIframe(playerIframe);
            }, 0);
        }
    }
}

ix_ipl_start();