; (function () {

    var pixelQueue = {};
    var domain = 'console.brightmountainmedia.com';

    setTimeout(function () {
        if (Object.keys(pixelQueue).length > 0) {
            var pixelKeyArr = Object.keys(pixelQueue);
            pixelKeyArr.forEach(ele => {
                createPixel(pixelQueue[ele], "imp");
                delete pixelQueue[ele];
            });
        }
    }, 1000 * 7)

    // your JS code
    // var zoneID = '12345';
    // var cookieName = 'zone' + zoneID
    // var ad = '[{"creative_id":"f6c95039-c9fa-43bb-b828-100b0d7259aa","campaign_id":"2211f26e-a68c-4101-b247-20881063fcea","name":"CGN 300x600_S_D AdSense","width":300,"height":600,"path":"","html":"<script async src=\\"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\\"></script> <!-- CGN 300x600_S_D AdSense --> <ins class=\\"adsbygoogle\\"      style=\\"display:block\\"      data-ad-format=\\"auto\\"      data-full-width-responsive=\\"true\\"></ins> <script>      (adsbygoogle = window.adsbygoogle || []).push({}); </script>","type":"html","content_type":"","tracking_pixel":"","target_url":"","target_window":"","alt_text":"","campaign_name":"AdSense ","advertiser_name":"Google AdSense","publisher_name":"Bright Mountain Media","publisher_id":"3a7772a7-b965-476f-b7c9-0edb001fa23a","advertiser_id":"ad785ad7-1d8a-4756-bfb5-46c9fff570bf","freq_cap":2000000000,"freq_cap_hour":24,"traffic_scan_pixel":"","traffic_scan_percentage":0,"location":[],"device_type":[],"browser":[],"os":[],"cities":[],"cap_list":null,"rate":0.5,"zone_name":"CGN 300x600_S_D","zone_cpm":0,"remaining_budget":2000000000,"remaining_daily_budget":2000000000,"capping_counter":1953759886,"daily_capping_counter":1999749691},{"creative_id":"1", "html":"<h1>ad1</h1>"}, {"creative_id":"2","html":"<h1>ad2</h1>"}]';


    var zoneID = '34098a0b-c229-41b0-9fba-347946e9f6a4';
    var cookieName = 'zone-' + '34098a0b-c229-41b0-9fba-347946e9f6a4'
    var ad = '[{"creative_id":"e0294233-02cb-46aa-8146-956b98a47b61","campaign_id":"ed9a6f91-27bb-4baa-8c80-46c3eacedb66","name":"BMM Undertone Page Grabber","width":1,"height":1,"path":"","html":"<!-- begin Undertone Ad Tag for INT3832 --> <script type=\'text/javascript\'>      document.MAX_ct0 =\'INSERT_CLICKURL_HERE\';          var ut_ju = (\'https:\'==document.location.protocol?\'https:\':\'http:\') + \\"//ads.undertone.com/dj\\";      ut=new Object();      ut.pid=3832;      ut.domain=\'%%SITE%%\';      ut.placementid=3832008;      ut.gdpr=\'REPLACE_WITH_GDPR_MACRO\';      ut.gdprstr=\'REPLACE_WITH_GDPR_CONSENT_STRING\';      ut.ccpa=\'REPLACE_WITH_CCPA_CONSENT_STRING\';      ut.schain=\'REPLACE_WITH_SERIALIZED_SCHAIN\';  </script>  <script type=\\"text/javascript\\" src=\\"//cdn.undertone.com/js/ajs.js\\"></script>  <!-- end Undertone Ad Tag -->","type":"html","content_type":"","tracking_pixel":"","target_url":"","target_window":"","alt_text":"","campaign_name":"Undertone page grabber","advertiser_name":"Undertone","publisher_name":"Bright Mountain Media","publisher_id":"3a7772a7-b965-476f-b7c9-0edb001fa23a","advertiser_id":"feca07cf-10ec-48fa-9671-cc22d9fc45d0","freq_cap":2000000000,"freq_cap_hour":24,"traffic_scan_pixel":"","traffic_scan_percentage":0,"location":[],"device_type":[],"browser":[],"os":[],"cities":[],"cap_list":null,"rate":5,"zone_name":"1x1 Page Grabber","zone_cpm":0,"remaining_budget":1999999999.8,"remaining_daily_budget":2000000000,"capping_counter":1999999960,"daily_capping_counter":2000000000}]';
    var domain = 'console.brightmountainmedia.com';

    init();
    function init() {
        var index = checkCookie()
        var divElement = document.querySelector('[adrtrgt-cont="' + zoneID + '"]');;
        // var divElement = document.getElementById(zoneID);
        if (JSON.parse(ad)[index] == undefined) {
            // reset index to 0
            setCookie(cookieName, 0, 7);
            index = 0;
        }

        var iframe = document.createElement('iframe');

        var html =
            '<body><div id="anc-wrap">' + decodeHTML(JSON.parse(ad)[index]["html"]) + '<div></body>';

        iframe.setAttribute("zid", zoneID);
        iframe.setAttribute("title", JSON.parse(ad)[index]["name"]);
        iframe.setAttribute("name", JSON.parse(ad)[index]["name"]);
        iframe.setAttribute("scrolling", "no");
        iframe.setAttribute("frameborder", "0");
        iframe.setAttribute("width", JSON.parse(ad)[index]["width"]);
        iframe.setAttribute("height", JSON.parse(ad)[index]["height"]);

        iframe.style.width = JSON.parse(ad)[index]["width"] + 'px';
        iframe.style.height = JSON.parse(ad)[index]["height"] + 'px';
        iframe.style.overflowX = 'hidden';
        iframe.style.overflowY = 'hidden';
        iframe.style.border = '0';


        divElement.innerHTML = "";
        divElement.appendChild(iframe);
        iframe.contentWindow.document.open();
        iframe.contentWindow.document.write(html);       
        iframe.contentWindow.document.close();
        // divElement.innerHTML = "<div id='anc-wrap'>" + decodeHTML(JSON.parse(ad)[index]["html"]) + "</div>";
        // divElement.innerHTML = JSON.parse(ad)[index]["html"];

        appendPixel(index);
    }

    function appendPixel(index) {
        var obj = {};
        obj["zoneID"] = zoneID;
        obj["creativeID"] = JSON.parse(ad)[index]["creative_id"];

        //Fire Response Pixel HERE
        createPixel(obj, "resp")

        pixelQueue[zoneID] = obj;
    }

    function getCookie(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    function setCookie(cname, cvalue, ctime) {
        var d = new Date();
        d.setTime(d.getTime() + (ctime * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    }

    function checkCookie() {
        var ckVal = getCookie(cookieName);
        if (ckVal != "") {
            var val = parseInt(ckVal) + 1
            setCookie(cookieName, val, 7);
            return val
        } else {
            setCookie(cookieName, 0, 7);
            //Fire Response Pixel HERE
            obj = {}
            obj["zoneID"] = zoneID;
            obj["creativeID"] = "Hidden"
            createPixel(obj, "req")
            return 0
        }
    }

    function createPixel(obj, pixelType) {
        try {
            var img = document.createElement('img');
            img.setAttribute('id', pixelType + obj["zoneID"]);
            img.setAttribute('src', "https://" + domain + "/api/wsync-pixel?zid=" + obj["zoneID"] + "&cid=" + obj["creativeID"] + "&type=" + pixelType);
            img.style.width = "0px";
            img.style.height = "0px";
            img.style.display = "none";

            var divElement = document.querySelector('[adrtrgt-cont="' + zoneID + '"]');
            // var divElement = document.getElementById(obj["zoneID"])
            divElement.appendChild(img);
        } catch{
            console.log("pixel not fired error")
        }
    }


    function decodeHTML(html) {
        var txt = document.createElement("textarea");
        txt.innerHTML = html;
        return txt.value;
    }

})()