truste = window.truste || {};
truste.util = truste.util || {};
truste.util.isBinding = function(value) {
    var bindReg = RegExp(/\${.*}/);
    return bindReg.test(value);
};
truste.util.getValue = function(bindingVal, defaultVal) {
    return truste.util.isBinding(bindingVal) ? defaultVal : bindingVal;
};

truste.pm = {
    version: '1.0.2',
    minWidthMobile: 890,
    popDiv: ('pop-div' + Math.random()).replace('.', ''),
    popDiv2: ('pop-div2' + Math.random()).replace('.', ''),
    popDiv3: ('pop-div3' + Math.random()).replace('.', ''),
    popFrame: ('popFrame' + Math.random()).replace('.', ''),
    closeBtn: ('closeBtn' + Math.random()).replace('.', ''),
    closeBtnImage: ('closeBtnImage' + Math.random()).replace('.', ''),
    trusteId: '163',
    frameWidth: 930,
    frameHeight: 650,
    closeBtn: {
        url: 'https://preferences.trustarc.com/images/close.png',
        top: truste.util.getValue('${CLOSE_TOP}', '-20px'),
        right: truste.util.getValue('${CLOSE_RIGHT}', '-20px'),
    },
    closeBtnMob: {
        url: truste.util.getValue('${CLOSE_URL_MOBILE}', 'https://choices.trustarc.com/get?name=close_mobile.png'),
        top: truste.util.getValue('${CLOSE_TOP_MOBILE}', '-3px'),
        right: truste.util.getValue('${CLOSE_RIGHT_MOBILE}', '-3px')
    },
    paddingSize: '10px',
    borderRadius: '5px',
    borderColor: '#92c53f',
    preferenceUrl: 'http://preferences-mgr.trustarc.com/?type=webmd_popnew&affiliateId=163',
    zindex: parseInt('${ZINDEX}')
};

truste.util.getStyle = function(el, cssprop) {
    if (el.currentStyle) //IE
        return el.currentStyle[cssprop];
    else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
        return document.defaultView.getComputedStyle(el, null).getPropertyValue(cssprop);
    else //try and get inline style
        return el.style[cssprop];
};

truste.util.findHighestZIndex = function(elem) {    
    var elems = document.getElementsByTagName(elem);
    var highest = 0;
    for(var i = 0; i < elems.length; i++) {
        var zindex = parseInt(truste.util.getStyle(elems[i],"z-index"), 10);

        if(zindex > highest && !isNaN(zindex)) {
            highest = zindex;
        }
    }
    return parseFloat(highest);
};

truste.pm.changeProtocol = function(b) {
    var proto = window.location.protocol;
    for (var s in b)
        if (b[s] && b[s].replace) b[s] = b[s].replace(/^.{3,5}:/, proto);
};

truste.pm.changeProtocol(truste.pm);

truste.pm.prefview = function(affliateId) {
    var pop = document.getElementById(truste.pm.popDiv);
    if (pop) return;

    var hZindex = truste.pm.zindex || (truste.util.findHighestZIndex('div') + 1);

    //set overlay styles
    var o = document.createElement('div');
    o.setAttribute('id', truste.pm.popDiv);
    o.className = 'overlay';
    o.style.backgroundColor = '#000';
    o.style.opacity = '0.8';
    o.style.position = 'fixed';
    o.style.setProperty('position', 'fixed', 'important');
    o.style.zIndex = hZindex;
    o.style.width = '100%';
    o.style.height = '100%';
    o.style.top = '0';
    o.style.left = '0';
    o.style.overflow = 'hidden';
    o.style.filter = 'Alpha(Opacity: 80)'; //ie fix

    // Create scrolling container wrapper
    var scrollContainer = document.createElement('div');
    scrollContainer.setAttribute('id', truste.pm.popDiv + '_scroll');
    scrollContainer.className = 'scroll_container';
    scrollContainer.style.position = 'fixed';
    scrollContainer.style.setProperty('position', 'fixed', 'important');
    scrollContainer.style.zIndex = hZindex + 1;
    scrollContainer.style.top = '0';
    scrollContainer.style.left = '0';
    scrollContainer.style.width = '100%';
    scrollContainer.style.height = '100%';
    scrollContainer.style.overflowY = 'auto';
    scrollContainer.style.overflowX = 'hidden';
    scrollContainer.style.backgroundColor = 'transparent';
    scrollContainer.style.paddingTop = '20px';
    scrollContainer.style.paddingBottom = '20px';
    scrollContainer.style.boxSizing = 'border-box';

    //set box_overlay styles - modified for scroll container
    var b = document.createElement('div');
    b.setAttribute('id', truste.pm.popDiv2);
    b.className = 'box_overlay';
    b.style.position = 'relative';
    b.style.setProperty('position', 'relative', 'important');
    b.style.zIndex = 'inherit';
    b.style.width = "100%";
    b.style.maxWidth = truste.pm.frameWidth + 'px';
    b.style.minWidth = "300px";
    b.style.height = truste.pm.frameHeight + 'px';
    b.style.margin = "0 auto";
    b.style.backgroundColor = 'transparent';

    var c = truste.pm.createCloseBtn();

    //set box_overlay_inner styles
    var i = document.createElement('div');
    i.setAttribute("id", truste.pm.popDiv3);
    i.style.backgroundColor = '#fff';
    i.style.position = 'relative';
    i.style.setProperty('position', 'relative', 'important');
    i.className = 'box_overlay_inner';
    i.style.border = truste.pm.borderRadius + ' solid ' + truste.pm.borderColor;
    i.style.width = "100%";
    i.style.height = truste.pm.frameHeight + parseInt(truste.pm.paddingSize) + 'px';
    i.style.boxSizing = "border-box";

    // set iframe attributes - modified for better content handling
    var f = document.createElement('iframe');
    var hasAidPid = new RegExp(/pid=.*?aid=.*?|aid=.*?pid.*?/);
    f.setAttribute("id", truste.pm.popFrame);
    f.src = hasAidPid.test(truste.pm.preferenceUrl) ? truste.pm.preferenceUrl.replace('affiliateId=', '') : truste.pm.preferenceUrl;
    f.scrolling = 'auto'; // Allow iframe scrolling if needed
    f.style.border = '0';
    f.style.overflow = 'auto'; // Allow content overflow scrolling
    f.style.display = 'block';
    f.style.position = 'absolute';
    f.style.setProperty('position', 'absolute', 'important');
    f.style.top = "0";
    f.style.left = "0";
    f.style.width = "100%";
    f.style.height = "100%";
    f.style.minHeight = truste.pm.frameHeight + 'px'; // Ensure minimum height

    //append elements to document - modified structure
    document.body.appendChild(o);
    document.body.appendChild(scrollContainer);
    scrollContainer.appendChild(b);
    b.appendChild(i);
    i.appendChild(c);
    i.appendChild(f);

    // Force iframe content to expand after load
    f.onload = function() {
        truste.pm.expandIframeContent(f);
    };

    var objects = document.getElementsByTagName('object');

    for (var j = 0; j < objects.length; ++j) {
        var obj = objects[j];
        obj.style.visibility = 'hidden';
    }
    //scrollTo(0, 0);
};

// Force iframe content to expand to full height
truste.pm.expandIframeContent = function(iframe) {
    try {
        // Only works if iframe is same-origin
        var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
        if (iframeDoc) {
            // Set iframe document styles to ensure full height usage
            var style = iframeDoc.createElement('style');
            style.innerHTML = `
                html, body {
                    height: 100% !important;
                    min-height: 100% !important;
                    margin: 0 !important;
                    padding: 0 !important;
                    overflow-x: hidden !important;
                    overflow-y: auto !important;
                }
                body > * {
                    min-height: 100%;
                }
            `;
            iframeDoc.head.appendChild(style);
            
            // Force immediate reflow
            iframeDoc.body.style.height = '100%';
            iframeDoc.documentElement.style.height = '100%';
        }
    } catch (e) {
        // Cross-origin restriction - try alternative approach
        console.log('Cross-origin iframe detected, using postMessage approach');
        truste.pm.requestIframeExpansion(iframe);
    }
};

// Alternative approach for cross-origin iframes
truste.pm.requestIframeExpansion = function(iframe) {
    // Send message to iframe to expand its content
    try {
        iframe.contentWindow.postMessage({
            action: 'expand_content',
            height: truste.pm.frameHeight
        }, '*');
    } catch (e) {
        console.log('Could not send expansion message to iframe');
    }
};

truste.pm.prefclose = function() {
    try {
        document.body.removeChild(document.getElementById(truste.pm.popDiv));
        document.body.removeChild(document.getElementById(truste.pm.popDiv + '_scroll'));
        var objects = document.getElementsByTagName('object');

        for (var i = 0; i < objects.length; ++i) {
            var obj = objects[i];
            obj.style.visibility = 'visible';
        }
    } catch (e) {
        console.log(e);
    };
};

truste.pm.resizeFrame = function(w, h) {
    // Update frameHeight for future reference
    truste.pm.frameHeight = parseInt(h);
    
    var inner = document.getElementById(truste.pm.popFrame);
    if (inner && inner.style) {
        inner.style.height = h;
        inner.style.minHeight = h; // Ensure minimum height is maintained
        
        // Force iframe content expansion after resize
        setTimeout(function() {
            truste.pm.expandIframeContent(inner);
        }, 100);
    }

    var div2 = document.getElementById(truste.pm.popDiv2)
    if (div2 && div2.style) {
        div2.style.height = h;
        div2.style.minHeight = h;
    }

    var div3 = document.getElementById(truste.pm.popDiv3)
    if (div3 && div3.style) {
        var iH = parseInt(h);
        iH = iH + parseInt(truste.pm.paddingSize);
        div3.style.height = iH + 'px';
        div3.style.minHeight = iH + 'px';
    }

    // Update scrolling container height if needed
    var scrollContainer = document.getElementById(truste.pm.popDiv + '_scroll');
    if (scrollContainer && scrollContainer.style) {
        // The scroll container maintains full viewport height for proper scrolling
        scrollContainer.style.height = '100%';
    }

    var btnDiv = document.getElementById(truste.pm.closeBtn);
    var btnImg = document.getElementById(truste.pm.closeBtnImage);

    if (window.innerWidth && window.innerWidth <= truste.pm.minWidthMobile) {
        btnImg.src = truste.pm.closeBtnMob.url;
        btnDiv.style.top = truste.pm.closeBtnMob.top;
        btnDiv.style.right = truste.pm.closeBtnMob.right;
    } else {
        btnImg.src = truste.pm.closeBtn.url;
        btnDiv.style.top = truste.pm.closeBtn.top;
        btnDiv.style.right = truste.pm.closeBtn.right;
    }
};

truste.pm.createCloseBtn = function() {
    var cHref = document.createElement('a');
    cHref.href = 'javascript:truste.pm.prefclose();';
    cHref.style.cursor = 'pointer';

    var imgSrc, top, right;
    if (window.innerWidth && window.innerWidth <= truste.pm.minWidthMobile) {
        imgSrc = truste.pm.closeBtnMob.url;
        top = truste.pm.closeBtnMob.top;
        right = truste.pm.closeBtnMob.right;
    } else {
        imgSrc = truste.pm.closeBtn.url;
        top = truste.pm.closeBtn.top;
        right = truste.pm.closeBtn.right;
    }

    var cImgHref = document.createElement('img');
    cImgHref.setAttribute('id', truste.pm.closeBtnImage);
    cImgHref.src = imgSrc;
    cImgHref.border = 0;

    cHref.appendChild(cImgHref);

    var c = document.createElement('div');
    c.setAttribute('id', truste.pm.closeBtn);
    c.className = 'close';
    c.style.position = 'absolute';
    c.style.top = top;
    c.style.right = right;
    c.appendChild(cHref);
    c.style.zIndex = '3000000';

    return c;
};

truste.pm.addEvent = function(obj, etype, fn, autorun) {
    try {
        if (obj.addEventListener) {
            obj.addEventListener(etype, fn, false);
            return true;
        } else if (obj.attachEvent) {
            return obj.attachEvent("on" + etype, fn);
        } else if (autorun) {
            fn();
            return true;
        }
    } catch (e) {
        if (window.console) {
            console.log(e.message)
        } else throw e;
    }
    return false;
};

truste.pm.actmessage = function(prefData) {
    if (prefData && prefData.source == 'preference_manager') {
        switch (prefData.message) {
            case 'change_panel':
                var split = prefData.data.split('x');
                truste.pm.frameHeight = parseInt(split[0]);
                truste.pm.resizeFrame(truste.pm.frameWidth + "px", truste.pm.frameHeight + "px");
                break;
            default:
                console.log('Post message from preference_manager: ' + prefData.message);
        }
    }
};

truste.pm.msgListener = function(e) {
    var urls = [(truste.pm.preferenceUrl.match(/^.{3,5}:\/\/[^\/]*/) || ["*"])[0],
        window.location.protocol + '//preferences-dev-sf.truste-svc.net',
        window.location.protocol + '//adchoices-prefmgr-staging.trustarc.com',
        window.location.protocol + '//preferences-qa-sf.truste-svc.net',
        window.location.protocol + '//preferences-mgr.truste.com',
        window.location.protocol + '//preferences-mgr.trustarc.com'
    ];
    if (e.data) {
        for (var i = urls.length; i-- > 0;) {
            if (urls[i] == e.origin) {
                var prefData = null;
                try {
                    if (typeof e.data == "string")
                        prefData = JSON.parse(e.data);
                    else if (typeof e.data == "object")
                        prefData = e.data;
                } catch (f) {
                    prefData = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(e.data.replace(/"(\\.|[^"\\])*"/g, ''))) && eval('(' + e.data + ')');
                }
                truste.pm.actmessage(prefData);
                return;
            }
        }
    }
};

if (window.postMessage) {
    truste.pm.addEvent(window, "message", truste.pm.msgListener);
}

//for backward compatibility with old version
trusteId = truste.pm.trusteId;
view = truste.pm.prefview;

TRUSTeWidget = window.TRUSTeWidget || {};
TRUSTeWidget.Tab = TRUSTeWidget.Tab || {
    id: "TRUSTeWidget-feedback-tab",
    link: function(options) {
        truste.pm.prefview(trusteId);
    },
    close: function(options) {
        truste.pm.prefclose();
    }
};

truste.pm.detectAdblock = function() {
    var element = document.createElement('div');
    element.id = 'adbanner';
    element.setAttribute("trste", "trstebanner");
    if (!document.getElementById(element.id) && element.getAttribute("trste") == "trstebanner") {
        element.className = 'bottom-ad';
        element.style.position = 'absolute';
        element.style.height = '3px';
        element.style.top = '-300px';
        document.body.appendChild(element);
    }

    var _dablDone;
    if (!_dablDone && element.getAttribute("trste") == "trstebanner") {
        setTimeout(function() {
            _dablDone = true;
            el = document.getElementById('adbanner');
            if ((el != null) && (el.clientHeight < 1) && (typeof truste.pm.trusteId == 'string' || truste.pm.trusteId instanceof String)) {
                var sPid = (truste.pm.trusteId.indexOf('pid=') > -1) ? (truste.pm.trusteId.match(/pid=[^ &#]*/i)[0]).replace('pid=', '') : '';
                var sAid = (truste.pm.trusteId.indexOf('aid=') > -1) ? (truste.pm.trusteId.match(/aid=[^ &#]*/i)[0]).replace('aid=', '') : '';
                if ((sPid.length > 0 && sAid.length > 0) && (sPid == 'turnermedia01'))
                    (new Image(1, 1)).src = 'http://choices2.trustarc.com/cap?' + 'aid=' + sAid + '-ab' + '&pid=' + sPid + '&cid=' + sPid + '&w=1&h=1';
                document.body.removeChild(element);
            }
        }, 2000);
    }

};

if (document.body) {
    truste.pm.detectAdblock();
} else {
    window.onload = function() {
        truste.pm.detectAdblock();
    }
}