
(function () {
    if (window.ImpulseFrameLoop) return;   

    function startOne(el) {
        if (el.__flStarted) return;
        var base = el.getAttribute('data-frameloop-base') || '';
        var N    = parseInt(el.getAttribute('data-frameloop-frames'), 10) || 0;
        var fps  = parseInt(el.getAttribute('data-frameloop-fps'), 10) || 12;
        var ver  = el.getAttribute('data-frameloop-ver') || '';
        if (!base || N < 1) return;
        el.__flStarted = true;

        

        var frames = [], ready = 0, started = false;
        var idx = 0, last = 0, step = 1000 / Math.max(1, fps);

        function tick(t) {
            if (!el.isConnected) { el.__flStarted = false; return; } 
            if (!last) last = t;
            if (t - last >= step) {
                last = t;
                var f = frames[idx];
                if (f && f.complete && f.naturalWidth) el.src = f.src;
                idx = (idx + 1) % N;
            }
            requestAnimationFrame(tick);
        }
        function go() { if (started) return; started = true; requestAnimationFrame(tick); }
        function tally() { if (++ready >= N) go(); }

        for (var i = 1; i <= N; i++) {
            var im = new Image(); im.decoding = 'async';
            im.src = base + i + '.webp' + ver;

            

            if (im.decode) { im.decode().then(tally, tally); }
            else { im.onload = tally; im.onerror = tally; }
            frames.push(im);
        }
        setTimeout(go, 7000); 
    }

    function scan() {
        var els = document.querySelectorAll('img[data-frameloop]');
        for (var i = 0; i < els.length; i++) startOne(els[i]);
        return els.length;
    }

    function boot() {
        scan();

        var tries = 0, iv = setInterval(function () { tries++; scan(); if (tries > 20) clearInterval(iv); }, 300);
    }

    if (document.readyState !== 'loading') boot();
    else document.addEventListener('DOMContentLoaded', boot);

    window.ImpulseFrameLoop = { scan: scan, start: startOne };
})();
