var MediaSmart = {
    site: '',
    promoSite: '',
    areaPattern: '',
    area: '',
    subArea: 'OTHER',
    ads: [],
    keyword: '',
    pageId: '',
    adRemarket: true,
    skinActive: false,
    adsInserted: false,
    adDomain: '',
    adProtocol: 'http',
    innerHeight: 0,
    initialised: false,
        util: {
        polite: true,
        aboveBelowFold: false,
        island_expand: false,
        random: function () {
            return Math.round(Math.abs(Math.sin((new Date()).getTime())) * 1000000000000);
        },
        isEmpty: function (str) {
            if ((str === null) || (typeof(str) === 'undefined') || (str === '')) {
                return true;
            }
            return false;
        },
        notEmpty: function (str) {
            if ((str !== null) && (typeof(str) !== 'undefined') && (str !== '')) {
                return true;
            }
            return false;
        },
        makeURLSafe: function(str){
          if(this.notEmpty(str)){
            str = str.replace(/ |-|<|>|\/|\?|\+/g, '_');
            str = str.replace(/&/, 'AND');
            str = str.replace(/_+/g, '_');
            str = str.replace(/^_|_$/g, '');
          }
          return str;
        }
    },
    initialise: function () {
	    
        if (this.initialised === true) {return;}
        var zmsJson, i, zmsOutput = '',
            tmpStringArray = [];
        if (arguments.length > 0) {
            zmsJson = arguments[0];
            if ((zmsJson.site !== '') && (typeof(zmsJson.site) === 'string')) {
                this.site = this.util.makeURLSafe(zmsJson.site.toUpperCase());
            }
            if ((zmsJson.promoSite !== '') && (typeof(zmsJson.promoSite) === 'string')) {
                this.promoSite = this.util.makeURLSafe(zmsJson.promoSite.toUpperCase());
            }
            if ((zmsJson.area !== '') && (typeof(zmsJson.area) === 'string')) {
                this.subArea = this.util.makeURLSafe(zmsJson.area.toUpperCase());
            }
            if ((zmsJson.areaPattern !== '') && (typeof(zmsJson.areaPattern) === 'string')) {
                this.areaPattern = zmsJson.areaPattern.toUpperCase();
            }
        }
        tmpStringArray = this.areaPattern.split('$');
        for (i = 0; i < tmpStringArray.length - 1; i=i+1) {
                zmsOutput += tmpStringArray[i] + this.subArea;
            }
        zmsOutput += tmpStringArray[tmpStringArray.length - 1];
        this.area = zmsOutput;
        if (this.util.notEmpty(top.MediaSmart.pageId)) {
                this.pageId = top.MediaSmart.pageId;
            }
        else {
                this.pageId = this.util.random();
            }
        this.adProtocol = "http";
        if ((document.location + '').indexOf('https://') !== -1) {
                this.adProtocol += 's'; // BP_TS: Secure HTTPS as the protocol
                this.adRemarket = false;
            }
        this.adDomain = this.adProtocol + '://media.sensis.com.au';

        if ((document.location + '').indexOf('MSTOOTHPASTE') !== -1) {
                this.keyword = 'MSTOOTHPASTE';
            }
        if ((document.location + '').indexOf('zmstestingenvironment375') !== -1) {
                this.site = 'Z_ZORRO';
                this.area = 'MOB.TEST.DEMO';
            }
        if (this.util.polite === false) {
          this.keyword = 'EXPANDABLE';
        }
        this.initialised = true;
    },
    generateAdCall: function (ad) {
        var adHtml = '',
            polite = true,
            key;
        if (typeof(ad.cmd) === 'function') {
                ad.cmd();
            }
        if (typeof(ad.tags) === 'undefined') {
                ad.tags = [];
            }
        if (((typeof(ad.polite) !== 'undefined') && (ad.polite === false)) || (this.util.polite === false)) {
                polite = false;
            }
        if (polite) {
                adHtml = '<iframe scrolling="no" frameborder="0" marginwidth="0" marginheight="0" allowtransparency="yes" ';
                // BP_TS: Use CSS to style the iframe
                adHtml += 'style="margin:0;padding:0;border:none;height:';
                adHtml += this.util.notEmpty(ad.iframeHeight) ? ad.iframeHeight : ad.height;
                adHtml += 'px;width:';
                adHtml += this.util.notEmpty(ad.iframeWidth) ? ad.iframeWidth : ad.width;
                adHtml += 'px;" src="';
                // redirect to cookiefix for islands leaderboard and skys
                if ((this.adRemarket === true) && (((ad.width === 300) && (ad.height === 250)) || ((ad.width === 728) && (ad.height === 90)) || (((ad.width === 160) || (ad.width === 120)) && (ad.height === 600)))) {
                    adHtml += this.adProtocol + '://medrx.sensis.com.au/images/sensis/cookieFix.html?acc_random=';
                }
                else {
                    adHtml += this.adDomain + '/hserver/acc_random=';
                }
            }
        else {
                adHtml = '<scr' + 'ipt src="' + this.adDomain + '/jserver/acc_random=';
            }
        adHtml += this.util.random();
        adHtml += '/SITE=';
        adHtml += this.util.notEmpty(ad.site)? ad.site : this.site;
        adHtml += '/AREA=';
        adHtml += this.util.notEmpty(ad.area) ? ad.area : this.area;
        adHtml += '/AAMSZ=' + ad.width + 'x' + ad.height;
        if (this.util.notEmpty(ad.position)) {
                adHtml += '/POSITION=';
                if (ad.abf !== false) {
                    if (this.innerHeight - ad.top - 90 > 0 || typeof(ad.top) === 'undefined') {
                        adHtml += 'ABV';
                    }
                    else {
                        adHtml += 'BLW';
                    }
                }
                adHtml += ad.position;
            }
        if (this.util.notEmpty(ad.keyword)) {
                adHtml += '/KEYWORD=' + this.util.makeURLSafe(ad.keyword.toUpperCase());
            }
        else {
                if (this.util.notEmpty(this.keyword)) {
                    adHtml += '/KEYWORD=' + this.util.makeURLSafe(this.keyword.toUpperCase());
                }
            }
        for (key in this.tags) {
                if (typeof(ad.tags[key]) === 'undefined') {
                    if (this.tags[key] !== '') {
                        adHtml += '/' + this.util.makeURLSafe(key.toUpperCase()) + '=' + this.util.makeURLSafe(this.tags[key].toUpperCase());
                    }
                }
            }
        adHtml += '/pageid=' + this.pageId;
        adHtml += polite ? '"></iframe>\n' : '"></script>\n';
        return adHtml;
    },
    newAd: function (json) {
	    if(this.util.island_expand && json.width === 300 && json.height === 250 && json.position === 1)
	    {
		    json.polite = false; 
		    json.abf = false;
		    json.keyword = "EXPANDABLE";
	    }
        //Turn the top 728x90 into a 1220x90 on the HP when a skin is active. 
        if((this.skinActive === true) && (json.width === 728) && (json.height === 90) && (json.position === 1) && (this.subArea === "HOME")){
            json.width = 1220;
        }
        if (this.util.aboveBelowFold === false) {
            json.abf = false;
        }
        if (((typeof(json.polite) !== 'undefined') && (json.polite === false)) || (this.util.polite === false)) {
            document.write(this.generateAdCall(json));
        } else {
            this.ads[this.ads.length] = json;
            thisAdWidth = this.util.notEmpty(json.iframeWidth) ? json.iframeWidth : json.width;
            thisAdHeight = this.util.notEmpty(json.iframeHeight) ? json.iframeHeight : json.height;
            document.write('<div id="zMSplacement' + this.ads.length + '" style="width:' + thisAdWidth + 'px; height:' + thisAdHeight + 'px;"></div>');
        }
    },
    refreshAd: function () {this.insertAd(this.ads);},
    setRefresh: function (time) {
        if (time > 0) {
            setInterval(this.refreshAd(), (time * 1000));
        }
    },
    getAdById: function (id) {
        for (var i = 0; i < this.ads.length; i=i+1) {
            if (this.ads[i].id === id) {
                // BP_TS: Set adIndex within the ad object, so it can form unique association with the ad. Assigning it to util.adIndex as a secondary return value was not a safe practice
                this.ads[i].adIndex = i;
                return this.ads[i];
            }
        }
        return false;
    },
    insertAd: function (ad, elementId) {
        var i, adElement, tmpElement;
        if (typeof(ad) === 'string') {
            ad = this.getAdById(ad);
            if (ad) {
                adElement = document.getElementById(elementId);
                if (adElement) {
                    adElement = document.getElementById('zMSplacement' + ad.adIndex);
                    if (adElement) {
                        adElement = document.getElementById(ad.containerId);
                    }
                }
                if (adElement) {
                  adElement.innerHTML = this.generateAdCall(ad);
                }
            }
        } else {
            if (typeof(ad) === "object") {
                if ((typeof(ad.length) === 'number') && !(ad.propertyIsEnumerable('length')) && (typeof ad.splice === 'function')) {
                    for (i = 0; i < ad.length; i=i+1) {
                        adElement = document.getElementById(ad[i].containerId);
                        if (adElement) {
                            adElement.innerHTML = this.generateAdCall(ad[i]);
                        }
                    }
                } else {
                    tmpElement = document.getElementById(ad.containerId);
                    if (tmpElement) {
                      tmpElement.innerHTML = this.generateAdCall(ad);
                    }
                }
            }
        }
    },
    insertAllAds: function () {
        var adElement, tmpElement, i, zmsCount = 0;
        if (arguments.length > 0) {
            zmsCount = arguments[0];
        }
        if (typeof(window.innerWidth) === 'number') {
            this.innerHeight = window.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight) {
            this.innerHeight = document.documentElement.clientHeight;
        }
        else if (document.body && document.body.clientHeight) {
            this.innerHeight = document.body.clientHeight;
        }
        for (i = zmsCount; i < this.ads.length; i=i+1) {
            adElement = document.getElementById('zMSplacement' + (i + 1));
            this.ads[i].top = adElement.offsetTop;
            if (adElement && (adElement.offsetTop === adElement.offsetParent.offsetTop)) {
                if (this.ads[i].id.indexOf('300X250_2') !== -1) {
                      tmpElement = top.document.getElementById('sensis_island_ad_2');
                      if (tmpElement) {
                        this.ads[i].top = tmpElement.offsetTop;
                      }
                }
                else if (this.ads[i].id.indexOf('300X250_3') !== -1) {
                      tmpElement = top.document.getElementById('sensis_island_ad_3');
                      if (tmpElement) {
                        this.ads[i].top = tmpElement.offsetTop;
                      }
                }
            }
            if (adElement === adElement.offsetParent) {
                this.ads[i].top += adElement.offsetTop;
            }
            if (adElement) {
              adElement.innerHTML = this.generateAdCall(this.ads[i]);
            }
        }
        this.adsInserted = true;
    },
    checkInsertAllAds: function(){
        if(this.adsInserted === false){
            this.insertAllAds();
        }
    },
    waitInsertAllAds: function(){
        setTimeout(MediaSmart.checkInsertAllAds, 500);
    },
        newPromo: function (json) {
        json.site = this.promoSite;
        json.abf = false;
        if (((typeof(json.polite) !== 'undefined') && (json.polite === false)) || (this.util.polite === false)) {
            document.write(this.generateAdCall(json));
        } else {
            this.ads[this.ads.length] = json;
            document.write('<div id="zMSplacement' + this.ads.length + '" style="width:' + json.width + 'px;height:' + json.height + 'px;"></div>');
        }
    },
    // Redirect functions added for backwards compatibility
    bigpondPromotions: {
        newAd: function (json){
            MediaSmart.newPromo(json);
        }
    },
    Utilities: {
        initialise: function (){
            MediaSmart.initialise((arguments.length > 0)?arguments[0]:null);
        }
    }
};

MediaSmart.util.aboveBelowFold = true;
MediaSmart.site = 'TEL.BIGPOND.PORTAL.ENTERTAINMENT';
MediaSmart.promoSite = 'TEL.BPPROMO.PORTAL.ENTERTAINMENT';
MediaSmart.areaPattern = 'ENTERTAINMENT.BIGPOND.$';
MediaSmart.util.polite = true;
MediaSmart.util.island_expand = false;

if(window.addEventListener){ // Mozilla, Netscape, Firefox
    window.addEventListener('load', MediaSmart.waitInsertAllAds, false);
}else{ // IE
    window.attachEvent('onload', MediaSmart.waitInsertAllAds);
}