console.log("THETA DISPLAY");

let evianews300x250atf = {}

evianews300x250atf.pel = document.createElement('script')
evianews300x250atf.pel.src =
'https://securepubads.g.doubleclick.net/tag/js/gpt.js'
evianews300x250atf.pel.async = true
document.head.appendChild(evianews300x250atf.pel)

evianews300x250atf.pel = document.createElement('script')
evianews300x250atf.pel.src =
`https://static.thetamedia.gr/prebid.js?t=1721893586`
evianews300x250atf.pel.async = true
document.head.appendChild(evianews300x250atf.pel)

evianews300x250atf.PREBID_TIMEOUT = 1500;
evianews300x250atf.FAILSAFE_TIMEOUT = 3000;

evianews300x250atf._theta_head =
    window.parent.document.head || window.parent.document.getElementsByTagName('head')[0]
evianews300x250atf.conf = JSON.parse('{"mediaTypes":{"banner":{"sizes":[300,250]}},"bidders":[{"bidder":"adform","params":{"mid":1718518}},{"bidder":"adform","params":{"mid":2019349}},{"bidder":"rubicon","params":{"accountId":26556,"siteId":544462,"zoneId":3385356}}]}'.replaceAll('"', '"'))
evianews300x250atf.sellerId = "29"
evianews300x250atf.gam = false
evianews300x250atf.passbackuri = "https://thetamarketplace.com/passback/evianews300x250atf"
evianews300x250atf.hituri = "https://thetamarketplace.com/hit/evianews300x250atf/host/false"
evianews300x250atf.dmp = false
evianews300x250atf.position = 'thetadisplay'

if(typeof evianews300x250atf.conf.position !== "undefined")
    evianews300x250atf.position = evianews300x250atf.conf.position

evianews300x250atf.adUnits = [
    {
        code: 'thetadisplay',
        mediaTypes: evianews300x250atf.conf.mediaTypes,
        bids: evianews300x250atf.conf.bidders
    }
];

var pbjs = pbjs || {};
pbjs.que = pbjs.que || [];

evianews300x250atf.passback = function() {
    var script_tag = document.createElement('script')
    script_tag.src = evianews300x250atf.passbackuri
    script_tag.async = true
    script_tag.defer = true
    evianews300x250atf.passbackins.appendChild(script_tag)
}

evianews300x250atf.pbjsconfig = {
    enableTIDs: true,
    currency: { adServerCurrency: 'EUR' },
    ortb2: {
        site: {
            publisher: {
                domain: location.hostname
            }
        },
    },
    schain: {
        validation: "strict",
        config: {
            ver: "1.0",
            complete: 1,
            nodes: [
                {
                    asi: "thetamarketplace.com",
                    sid: evianews300x250atf.sellerId,
                    hp:1
                }
            ]
        }
    },
    userSync: {
        aliasSyncEnabled: true,
        syncsPerBidder: 3,
        iframeEnabled: true,
        filterSettings: {
          iframe: {
            bidders: '*',
            filter: 'include',
          },
        },
        userIds: [],
        auctionDelay: 1000,
        syncDelay: 3000,
        syncEnabled: true
    }
}

if(window.parent.document !== document) {
    evianews300x250atf.passbackins = document.body
    evianews300x250atf.ins = document
} else {
    evianews300x250atf.passbackins = document.currentScript.parentElement
    let t = document.createElement('iframe')
    t.setAttribute('frameBorder', 0)
    t.setAttribute('id', `thetadisplay_evianews300x250atf`)
    t.setAttribute('style', 'width:330px; height: 600px;')
    document.currentScript.parentElement.append(t)
    evianews300x250atf.ins = t.contentWindow.document;
    evianews300x250atf.passbackins = t.contentWindow.document.body;
}

evianews300x250atf.initAdserver = function() {
    if (evianews300x250atf.initAdserverSet) return;
    evianews300x250atf.initAdserverSet = true;

    let adServerTargeting = pbjs.getAdserverTargetingForAdUnitCode('thetadisplay');

    // If any bidders return any creatives
    if (adServerTargeting && adServerTargeting['hb_adid']) {
        pbjs.renderAd(evianews300x250atf.ins, adServerTargeting['hb_adid']);
    } else {
        evianews300x250atf.passback()
    }
}

if(location.hostname === 'localhost' || location.hostname === '127.0.0.1' || location.hostname == 'cypress.tester' || location.hostname == '192.168.84.32') {
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    if(urlParams.get('passback') === 'true') {
        evianews300x250atf.passback()
    } else {
        pbjs.que.push(function() {
            pbjs.addAdUnits(evianews300x250atf.adUnits);
            pbjs.setConfig(evianews300x250atf.pbjsconfig)
            pbjs.setBidderConfig({
                bidders: ['oftmedia'],
                config: {
                    schain: {
                        validation: "relaxed",
                        config: {
                            ver: "1.0",
                            complete: 1,
                            nodes: [
                                {
                                    "asi": "152media.info",
                                    "sid": "152M1021",
                                    "hp": 1
                                }
                            ]
                        }
                    }
                }
            });
            pbjs.requestBids({
                timeout: evianews300x250atf.PREBID_TIMEOUT,
                bidsBackHandler: evianews300x250atf.initAdserver
            });
        });
    }
} else {

    fetch(evianews300x250atf.hituri.replace('/host', '/' + window.location.host), {
        method: 'GET',
    })

    evianews300x250atf.pbjsconfig.consentManagement = {
        gdpr: {
            cmpApi: 'iab',
            timeout: 1000,
            actionTimeout: 10000,
            defaultGdprScope: true
        }
    }

    window.parent.__tcfapi('addEventListener', 2, function (tcData, success) {
        if (success) {
            const queryString = window.location.search;
            const urlParams = new URLSearchParams(queryString);
            if(urlParams.get('passback') === 'true') {
                evianews300x250atf.passback()
                return
            }

            if (tcData.eventStatus == 'useractioncomplete' || tcData.eventStatus == 'tcloaded') {
                if(tcData.purpose.consents[1]
                && tcData.purpose.consents[3]
                && tcData.purpose.consents[5]
                && tcData.purpose.consents[7]
                && tcData.purpose.consents[8]
                && tcData.purpose.consents[9]
                && tcData.purpose.consents[10]) {
                    if (tcData.vendor.consents[131]) {
                        evianews300x250atf.pbjsconfig.userSync.userIds.push({
                            name: "id5Id",
                            params: {
                                partner: 1653,
                                externalModuleUrl: 'https://cdn.id5-sync.com/api/1.0/id5PrebidModule.js',
                            },
                            storage: {
                                type: "html5",
                                name: "id5id",
                                expires: 90,
                                refreshInSeconds: 8 * 3600
                            }
                        })
                    }
                    if (tcData.vendor.consents[95]) {
                        evianews300x250atf.pbjsconfig.userSync.userIds.push({
                            name: "lotamePanoramaId",
                            params: {
                                clientId: 17773
                            }
                        })
                    }
                    evianews300x250atf.pbjsconfig.userSync.userIds.push({
                        name: "sharedId",
                        storage: {
                            name: "_sharedID",
                            type: "html5",
                            expires: 30
                        }
                    })

                    evianews300x250atf.pbjsconfig.userSync.userIds.push({
                        name: "criteo"
                    })
                }
                pbjs.que.push(function() {
                    pbjs.addAdUnits(evianews300x250atf.adUnits);
                    pbjs.setConfig(evianews300x250atf.pbjsconfig)
                    pbjs.setBidderConfig({
                        bidders: ['oftmedia'],
                        config: {
                            schain: {
                                validation: "relaxed",
                                config: {
                                    ver: "1.0",
                                    complete: 1,
                                    nodes: [
                                        {
                                            "asi": "152media.info",
                                            "sid": "152M1021",
                                            "hp": 1
                                        }
                                    ]
                                }
                            }
                        }
                    });
                    pbjs.requestBids({
                        timeout: evianews300x250atf.PREBID_TIMEOUT,
                        bidsBackHandler: evianews300x250atf.initAdserver
                    });
                });

                setTimeout(function() {
                    evianews300x250atf.initAdserver();
                }, evianews300x250atf.FAILSAFE_TIMEOUT);


                if(evianews300x250atf.dmp === true) {
                    const stringToUuid = (str) => {
                        str = str.replace('-', '');
                        return 'xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c, p) {
                            return str[p % str.length];
                        });
                    }

                    navigator.mediaDevices
                    .enumerateDevices()
                    .then((devices) => {
                        const uuid = JSON.parse(decodeURIComponent(localStorage.id5id)).universal_uid

                        const source = window.location.host
                        const atype = 1
                        const text = window.parent.document.body.innerText

                        var formdata = new FormData();
                        formdata.append('t', text)
                        var requestOptions = {
                            method: 'POST',
                            body: formdata,
                            redirect: 'follow'
                        };

                        fetch('https://contextual.thetamarketplace.com/', requestOptions)
                        .then(response => response.json())
                        .then(data => {
                            const key = data.key
                            let ns = document.createElement('noscript')
                            let img = document.createElement('img')
                            img.src = `//dmp.adform.net/dmp/profile/?pid=12269&sg=${key}&eid_${source}_${atype}=${uuid}`
                            img.setAttribute('style', 'display:none !important')
                            ns.appendChild(img)
                            evianews300x250atf._theta_head.appendChild(ns)
                        })
                    })
                    .catch((err) => {
                        console.log(`${err.name}: ${err.message}`);
                    });
                }
            }
        }
    });
}