

/**
 * Wait for 1 sec of viewability and send event
 */
var waitForViewable = (function() {
    var element;
    var viewability;
    // utils
    var dom = {
        screen: {
            orientation: function () {
                if (typeof window.orientation !== 'undefined') {
                    return {
                        short: (Math.abs(window.orientation) === 90) ? 'landscape' : 'portrait'
                    };
                }
                if (screen.orientation && screen.orientation.type) {
                    return {
                        short: screen.orientation.type.split('-')[0]
                    };
                }
                return {};
            }
        },
        element: {
            /* jshint ignore:start */
            matches: function (elm, selector) {
                var matches = document.querySelectorAll(selector);
                var i = matches.length;
                while (--i >= 0 && matches[i] !== elm) {}
                return i > -1;
            },
            /* jshint ignore:end */
            observe: function (selector, configuration, cb) {
                if (!window.MutationObserver || !selector) {
                    return;
                }

                var fnCallback = function (mutations) {
                    mutations.forEach(function (mutation) {
                        //if (mutation && mutation.addedNodes && mutation.addedNodes.length) {
                        cb(mutation);
                        //}
                    });
                };

                var observer = new MutationObserver(fnCallback);
                var elTarget = document.querySelector(selector);
                var objConfig = configuration || {
                    childList: true,
                    subtree: false,
                    attributes: false,
                    characterData: false
                };
                if (elTarget) {
                    observer.observe(elTarget, objConfig);
                }
            }
        },
        window: (function () {
            var windowMain = (function () {
                return isWinTopRestrictedFrame() ? window.self : window.top;
            })();

            function isRestrictedFrame() {
                return isWinTopRestrictedFrame() && isGoogleSafeFrame();
            }

            function isWinTopRestrictedFrame() {
                try {
                    window.top.location.href;
                } catch (e) {
                    return true;
                }
                return false;
            }

            function isGoogleSafeFrame() {
                return window.sfAPI || (window.$sf && window.$sf.ext);
            }

            function isFriendlyFrame() {
                return !isRestrictedFrame();
            }

            function isInFrame() {
                return window.self !== window.top;
            }

            function getWindowLocation() {
                function getFromDFPframe(urlObject) {
                    return url_query_parse(urlObject.fragment).p;
                }

                if (isFriendlyFrame()) {
                    return windowMain.location.href;
                }
                var urlObject = url_parse(windowMain.location.href);

                return getFromDFPframe(urlObject) || window.document.referrer || windowMain.location.href;
            }

            return {
                main: windowMain,
                isRestrictedFrame: isRestrictedFrame,
                isFriendlyFrame: isFriendlyFrame,
                isInFrame: isInFrame,
                locationString: getWindowLocation,
                isWinTopRestrictedFrame: isWinTopRestrictedFrame
            }
        })()
    };
    // viewability class, taken from infeed
    var Viewability = function (windowMain, creativeDocument) {
        var self = this;
        var pool = {};
        var timeoutId;
        var maxCounter = 0;
        var seen_time = 2000;
        var viewablePercent = 50;
        var sfAPIInterval;

        if (dom.window.isRestrictedFrame()) {
            var sfAPI = window.sfAPI || (window.$sf && window.$sf.ext);
            sfAPI.register(window.innerWidth, window.innerHeight, function (status, data) {
                if (status === 'geom-update') {
                    if (sfAPIInterval) {
                        clearInterval(sfAPIInterval);
                    }
                    checkViewability();
                }
            });
            sfAPIInterval = setInterval(checkViewability, 200);
        } else if (dom.window.isWinTopRestrictedFrame()) {
            sfAPIInterval = setInterval(checkViewability, 200);
        } else {
            windowMain.addEventListener('scroll', checkViewability);
        }

        function checkViewability() {
            maxCounter = 0;
            var visibleElements = 0;

            for (var key in pool) {
                if (pool.hasOwnProperty(key)) {
                    // in case of inapp no need for isVisible
                    if (isVisible(key, creativeDocument)) {
                        visibleElements++;

                        if (!pool[key].timestamp) {
                            pool[key].timestamp = (new Date()).valueOf();
                        } else {
                            pool[key].counter += ((new Date()).valueOf() - pool[key].timestamp);
                            pool[key].timestamp = (new Date()).valueOf();
                        }
                        maxCounter = Math.max(maxCounter, pool[key].counter);

                        if (isVisibleReached(pool[key]) && window.cfaux && window.cfaux.u) {
                            window.cfaux.view(`https://sns-p-search-event-tracker-us-east-1-k8s.seccint.com`)
                            self.remove(key);
                            visibleElements--;
                            if (!Object.keys(pool).length) {
                                if (!dom.window.isRestrictedFrame()) {
                                    windowMain.removeEventListener('scroll', checkViewability);
                                } else {
                                    if (sfAPIInterval) {
                                        clearInterval(sfAPIInterval);
                                    }
                                }
                            }
                        }
                    } else {
                        pool[key].counter = 0;
                        pool[key].timestamp = 0;
                    }
                }
            }

            if (visibleElements) {
                timeoutId = setTimeout(checkViewability, seen_time - maxCounter);
            }
        }

        function isVisible(key, doc) {
            var el;

            if (dom.window.isRestrictedFrame()) {
                var sfAPI = window.sfAPI || (window.$sf && window.$sf.ext);
                if (sfAPI && sfAPI.inViewPercentage) {
                    return (sfAPI.inViewPercentage() >= 50);
                }
            }

            if (typeof key == 'string') {
                el = doc.getElementById(key);
            } else {
                el = key;
            }

            if (!el || (!(el.nodeType && el.nodeType === 1))) {
                return false;
            }
            var rect = el.getBoundingClientRect();
            var item = {
                el: el,
                x: rect.left,
                y: rect.top,
                w: el.offsetWidth,
                h: el.offsetHeight
            };

            var windowHeight = getWindowHeight();

            var center = item.y + (item.h * viewablePercent / 100);
            return ((center > 0) && (center < windowHeight) && !document.hidden);
        }

        function getWindowHeight() {
            let res
            try {
                res = windowMain.innerHeight ? windowMain.innerHeight : windowMain.document.documentElement.offsetHeight;
            }catch(e) {
                res = null;
            }
            return res
        }

        function isVisibleReached(obj) {
            return obj.counter && (obj.counter >= seen_time);
        }

        self.add = function (obj) {
            if (!obj) {
                return;
            }

            pool[obj.id] = {
                counter: 0,
                timestamp: 0
            };
            //self.run();
        };

        self.remove = function (id) {
            if (pool[id]) {
                delete pool[id];
            }
        };

        self.clear = function () {
            pool = {};
        };

        self.run = function () {
            if (timeoutId) {
                self.stop();
            }
            checkViewability();
        };

        self.stop = function () {
            clearTimeout(timeoutId);
        };
        return self;
    };

    var run = function() {
        viewability && viewability.run();
    };

    var init = function(tagid) {
        // function content will run only once
        // if (element) {
        //     return;
        // }
        element = document.querySelector('#'+tagid);

        viewability = new Viewability(dom.window.main, element.ownerDocument);
        viewability.add(element);
        viewability.run();
    };

    return {
        init: init,
        run: run,
        dom: dom
    };
})();

waitForViewable.init('tagId1')


window.cfaux = window.cfaux || {
    u: null,
    imp: function (ep, u, contName) {

        const normalizeDim = (original, anchors) => {

            const distances = anchors.map((anchor, idx) => [Math.abs(original - anchor), idx]);
            const DISTANCE = 0;
            const IDX = 1;
            let min = distances[0];
            for(let i=0; i<distances.length; i++){
                if(distances[i][DISTANCE] < min[DISTANCE]) {
                    min = distances[i]
                }
            }

            return String(anchors[min[IDX]]);
        }

        const widthAnchors=  [300, 728, 160, 970, 180, 320, 970, 336, 120, 200, 250, 336, 600, 265];
        const heightAnchors = [250, 90, 600, 150, 280, 50, 100, 160, 300, 455];

        this.u = u
        var eu = JSON.parse(u);
        if(document.querySelector(`.${contName}`)) {
            try{

                eu.displayWidth = parseFloat(document.querySelector(`.${contName}`).getBoundingClientRect().width).toFixed(2);
                eu.displayHeight = parseFloat(document.querySelector(`.${contName}`).getBoundingClientRect().height).toFixed(2);
            }catch (e) {
                eu.displayWidth = 0;
                eu.displayHeight = 0;
            }
            try{
                eu.normalizedWidth = normalizeDim(Number.parseInt(eu.displayWidth), widthAnchors);
                eu.normalizedHeight = normalizeDim(Number.parseInt(eu.displayHeight), heightAnchors);
            }catch (e) {
                eu.normalizedWidth = 0;
                eu.normalizedHeight = 0;
            }
        }
        eu.UtcTime = (()=> Date.now())();
        eu.encUrlClientValue = decodeURIComponent(this.encurlSource.encUrlClientValue);
        eu.encUrlMacroValue = decodeURIComponent(this.encurlSource.encUrlMacroValue);
        eu.encurlSource = this.encurlSource.source;
        eu.referrer = document.referrer;
        fetch(`${ep}?eventtype=idp_impression&src=5`, {
            method: 'POST',
            body: JSON.stringify(eu),
            headers: {
                'Content-Type': 'application/json'
            }
        } )
    },
    clc: function (event, ep, t, idx, u, imageUrl) {
        
        
        
        if ((event.which === 1 || event.which === 2 || event.which === 3)) {
            try{
                var effectiveEp;
                var eu = JSON.parse(u);
                eu.ClickKeyword = t;
                eu.imageUrl = imageUrl;
                eu.KwPosition = idx;
                eu.UtcTime = (() => Date.now())();
                if (event.which === 3) {
    
                    effectiveEp = `${ep}?eventtype=idp_r_click_client&src=5`
                } else {
    
                    effectiveEp = `${ep}?eventtype=idp_click_client&src=5`
    
                }
                eu.referrer = document.referrer;
                eu = JSON.stringify(eu);
    
                fetch(effectiveEp, {
                    method: 'POST',
                    body: eu,
                    headers: {
                        'Content-Type': 'application/json'
                    }
                } )
            } catch(e){
                console.log(e)

            }
        }
    },
    view: function(ep){

        var eu = JSON.parse(this.u)
        eu.event = 'idp_viewability';
        eu.SearchAction= 'idp_viewability';
        eu.UtcTime = (()=> Date.now())();
        eu.referrer = document.referrer;

        fetch(`${ep}?eventtype=idp_viewability&src=5`, {
            method: 'POST',
            body: JSON.stringify(eu),
            headers: {
                'Content-Type': 'application/json'
            }
        } )
    },
    script: function(src, onSucc, onErr) {

        return new Promise( function(onSucc, onErr) {
            var script = document.createElement('script');
            document.body.appendChild(script);
            script.onload = onSucc || '';
            script.onerror = onErr || '';
            script.async = true;
            script.src = src;
            script.id = 'pm';
            script.type = 'text/javascript'
        });
    },
    url: {
        _isWinTopRestrictedFrame: function() {
            try {
                window.top.location.href;
            } catch (e) {
                return true;
            }
            return false;
        },
        getEffectiveUrl: function () {

            let temp = this._isWinTopRestrictedFrame()
                ? encodeURIComponent(document.referrer || window.location.href) // safe frame || google safe-frame
                : encodeURIComponent(window.top.location.href) // iframe

            return temp
                .replace(/'/g, "%27")
                .replace(/"/g, "%22")
                .replace(/`/g, "%60")
        }
    }
}

try {



    const querySearchParams = new URLSearchParams({"fd":"www.suggest-4you.com","gd":"ap1007673","tagid":"tagId1","encurl":null,"isautomation":"0","encurlsource":"client","encurlmacrovalue":"undefined","click":null})
    const encUrlClientValue = window.cfaux.url.getEffectiveUrl();
    window.cfaux.encurlSource = {
        encUrlClientValue: decodeURIComponent(encUrlClientValue),
        encUrlMacroValue: decodeURIComponent(querySearchParams.get('encurlmacrovalue')),
        source: querySearchParams.get('encurlsource')
    };

    if(!'') {
        querySearchParams.set('encurl', encUrlClientValue);
    }
    querySearchParams.delete('encurlmacrovalue')
    querySearchParams.delete('encurlsource')
    // decode completely (querySearchParams.toString() encodes).
    querySearchParams.set('encurl', decodeURIComponent(querySearchParams.get('encurl')));
    querySearchParams.set('click', decodeURIComponent(querySearchParams.get('click')));
    querySearchParams.set('referrer', document.referrer);
    
    (async ()=> {

                
                var wrapper = document.querySelector('#tagId1');
        var res = await fetch('https://www.idp-cf.com/serve?'+querySearchParams.toString())
        var html = await res.text();
        setInnerHTML(wrapper, html);
    })()

}catch (e) {

    document.querySelector('#tagId1').innerHTML = `<a target="_blank" href='https://privado.com?r=999'><img src='https://se-p-static-content.seccint.com/contextual-demo/privado_banner.png'></a>`
}

var setInnerHTML = function(elm, html, isAppend) {

    if(isAppend){

        const temp = document.createElement("div")
        temp.innerHTML = html;
        elm.appendChild(temp)
    }else {

        elm.innerHTML = html;
    }
    Array.from(elm.querySelectorAll("script")).forEach( oldScript => {
        const newScript = document.createElement("script");
        Array.from(oldScript.attributes)
            .forEach( attr => newScript.setAttribute(attr.name, attr.value) );
        newScript.appendChild(document.createTextNode(oldScript.innerHTML));
        oldScript.parentNode.replaceChild(newScript, oldScript);
    });
}


