(function() {
    var name = '';
    var isIE = (function() {
        var ver = navigator.userAgent.match(/MSIE ([0-9]{1,}[\\.0-9]{0,})|Trident\/.*rv:([0-9]{1,}[\\.0-9]{0,})/);
        if (!ver) {
            return false;
        }
        ver.shift();
        return ver.filter(function(str) { return str != undefined; }).pop();
    });
    var logger = function () {
        if (window.localStorage && window.localStorage.getItem('can_debug') == 'true') {
            if (window._canStore && !window._canStore.debugLogsPrinted) {
                window._canStore.debugLogsPrinted = true;

                if (isIE()) {
                    console.debug(
                        "[CAN] If you can see this, CAN debug logs are turned ON"
                    );
                } else {
                    console.debug(
                        "%c[CAN] %cIf you can see this, CAN debug logs are turned ON",
                        "font-size: 3em; color: #267cae; font-weight: bolder; font",
                        "font-size: 3em; color: #f47401; font-weight: bold"
                    );
                }
            }
            for (var msgKey in arguments) {
                var msg = arguments[msgKey];
                console.debug("[can] [" + name + "]: "+msg);
            }
        }
    };

    (function(currentScript) {
    if (!window._canStore) {
        window._canStore = {};
    }
    name = "div-gpt-ad-sheffieldcc-ibar";
    var isRTBEnabled = false;
    var consentDecisionMade = false;
    var consentManagement = false;

    if (consentManagement) {
        logger('waiting for IAB CMP to provide consent info');
        var checkForConsent = function (delay) {
            if (!window.__cmp) {
                var nextDelay = delay + 100;
                setTimeout(checkForConsent, nextDelay, nextDelay);
                return;
            }

            window.__cmp('getVendorConsents', null, function(consent, success) {
                var sovrnRaceConditionTimer = setTimeout(function () {
                    var qcRaceConditionInterval = setInterval(function() {
                        window.__cmp('getVendorConsents', null, function(consent, success) {
                            if (consent.metadata === null) {
                                return;
                            }
                            clearInterval(qcRaceConditionInterval);
                            consentDecisionMade = true;

                            var vendorsWithConsent = Object
                                .keys(consent.vendorConsents)
                                .map(function (key) { return parseInt(key); })
                                .filter(function (key) {
                                    return consent.vendorConsents[key] === true;
                                });
                            var purposesWithoutConsent = Object
                                .keys(consent.purposeConsents)
                                .map(function (key) { return parseInt(key); })
                                .filter(function (key) {
                                    return consent.purposeConsents[key] === false
                                    && key <= 5; // QC report non-existent purposes
                                });

                            if (vendorsWithConsent.length > 0 && purposesWithoutConsent.length === 0) {
                                logger('consent granted; continuing');
                                beginInit();
                            } else {
                                logger('consent not granted; exiting');
                                window._canStore.consent = {
                                    vendorsWithConsent: vendorsWithConsent,
                                    purposesWithoutConsent: purposesWithoutConsent,
                                };
                            }
                        });
                    }, 50);
                }, 1000);
            });
        };
        setTimeout(checkForConsent, 0, 0);
    } else {
        setTimeout(function () { beginInit() }, 0);
    }

    var validateRTBResponse = function (xhr) {
        if (xhr.status != 200) {
            logger('RTB is disabled: a failure occurred resolving the RTB check for ' + window.location.href, xhr.status, xhr.statusText, xhr.responseText);
            return false;
        }
        var responseJson;
        try {
            responseJson = JSON.parse(xhr.responseText);
        } catch (err) {
            logger('RTB is disabled: a failure occurred parsing the RTB response', err);
            return false;
        }

        if (responseJson.blocked) {
            logger('RTB is disabled: endpoint blocked');
            return false;
        }

        logger('RTB is enabled');
        return true;
    };

    var beginInit = function () {
        logger('checking RTB state');

        var windowURL = window.location.hostname + window.location.pathname;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', "https:\/\/ads.counciladvertising.net\/tag\/rtb\/check" + "?url=" + encodeURIComponent(windowURL));
        xhr.setRequestHeader('Accept', 'application/json');

        xhr.onload = function() {
            isRTBEnabled = validateRTBResponse(xhr);
            start();
        };
        xhr.onerror = function() {
            logger('a failure occurred resolving the RTB check for ' + window.location.href);
            start();
        };

        xhr.send();
    };
    var start = function() {
        var blacklist = ["@","%2540","%40","user=","email=","emailaddress=","password=","pw=","un=","username="];

var shouldAbortDueToPII = function () {
    var url = (window.location.search || window.location.href).toLowerCase();
    for (var i = 0; i < blacklist.length; i++) {
        var word = blacklist[i];
        if (url.indexOf(word) !== -1 || decodeURIComponent(url).indexOf(word) !== -1) {
            logger("aborted load after finding "+word);
            return true;
        };
    };

    return false;
}

if (shouldAbortDueToPII()) {
    return;
}

var gdpr = null;
var addScript = function(url) {
    var script = document.createElement("script");

    script.type = "text/javascript";
    script.src = url;

    var head = document.body || document.getElementsByTagName('body')[0];
    head.appendChild(script);
    return script;
};
var gpt_slot = null;

var load = function () {
    var div = document.createElement('div');
    div.id = "div-gpt-ad-sheffieldcc-ibar";
    document.body.appendChild(div);

    if (!window.googletag) {
        addScript('https://www.googletagservices.com/tag/js/gpt.js');
    }
    window.googletag = window.googletag || {};
    window.googletag.cmd = window.googletag.cmd || [];

    window.googletag.cmd.push(function () {
        gpt_slot = window.googletag.defineOutOfPageSlot('/31781941/can_sheffieldcc', "div-gpt-ad-sheffieldcc-ibar").addService(window.googletag.pubads());
        window.googletag.pubads().enableAsyncRendering();
        window.googletag.pubads().enableSingleRequest();
        window.googletag.pubads().disableInitialLoad();
        window.googletag.enableServices();
    });

    window.googletag.cmd.push(function () {
        window.googletag.display("div-gpt-ad-sheffieldcc-ibar");
        window.googletag.pubads().refresh([gpt_slot]);
    });
};

if (gdpr == null) {
    load();
} else {
    window._canStore = window._canStore || {};
    if (!window._canStore['gdpr']) {
        addScript(gdpr);
        window._canStore['gdpr'] = true;
    };
    window.addEventListener('canGdprConsent', function (e) {
        if (e.consent) {
            load();
        }
    });
}
    };
})(document.currentScript);
})();
