if (typeof CtvAd == "undefined") {
    var CtvAd = function() {
        this.Height = 0;
        this.Width = 0;
        this.Path = "";
        this.Zone = "";
        this.Site = "";
        this.Tile = 0;

        this.ShouldDisplayInterstitials = false;

        CtvAd.__instance = this;

        if (!CtvAd.__OrdinalString) {
            var ordstr = CtvAd.GetOrdinalString();
            CtvAd.__OrdinalString = ordstr;
        }

        if (!CtvAd.__NumberOfAdsDisplayed) {

            CtvAd.__NumberOfAdsDisplayed = 0;
        }
    }

    CtvAd.GetInstance = function() {
        if (!CtvAd.__instance) {
            CtvAd.__instance = new CtvAd();
        }

        return CtvAd.__instance;
    }

    CtvAd.prototype.SetZone = function(zone) {
        this.Zone = zone.toLowerCase();
    }

    CtvAd.prototype.SetPath = function(path) {
        this.Path = this.Trim(path);
        this.Path = this.Path.toLowerCase();

        if (this.Path == '') {
            this.Path = "index";
        }

    }

    CtvAd.prototype.SetHeight = function(height) {
        this.Height = height;
    }

    CtvAd.prototype.SetWidth = function(width) {
        this.Width = width;
    }

    CtvAd.prototype.SetSite = function(site) {
        this.Site = site.toLowerCase();
    }

    CtvAd.prototype.SetTile = function(tile) {
        //Leaderboards should always be Tile=1. If it's not - it will break sync ad units that we have running on the site. 
        this.Tile = tile;
    }

    CtvAd.prototype.DisplayInterstitials = function(displayInterstitials) {
        this.ShouldDisplayInterstitials = displayInterstitials;
    }

    CtvAd.GetOrdinalString = function() {
        return Math.ceil(Math.random() * 1000000000).toString();
    }

    CtvAd.prototype.Trim = function(value) {
        var rvalue = value;

        if (value.length > 0) {
            var firstChar = rvalue[0];

            if (firstChar == "/") {
                rvalue = rvalue.substring(1, rvalue.length)
            }

            var lastChar = rvalue[rvalue.length - 1];

            if (lastChar == "/") {
                rvalue = rvalue.substring(0, rvalue.length - 1)
            }
        }

        return rvalue;
    }

    CtvAd.prototype.Render = function() {
		
        var istCode = "";
        if (this.ShouldDisplayInterstitials == true && CtvAd.__NumberOfAdsDisplayed == 0) {
            istCode = "dcopt=ist;";
        }

        var renderTile = "";
        if (this.Tile > 0) {
            renderTile = "tile=" + this.Tile + ";";
        }

        CtvAd.__NumberOfAdsDisplayed += 1;

        var adCode = '<scr' + 'ipt language="JavaScript" src="http://ad.doubleclick.net/adj/' + this.Site + '/' + this.Zone + '/' + this.Path + ';' + istCode + renderTile + 'sz=' + this.Width + 'x' + this.Height + ';ord=' + CtvAd.__OrdinalString + '\"' + ' type="tex' + 't/javascript"></sc' + 'ript>';

        document.write(adCode);
    }
}


