﻿__LOGGING_HOST__ = "maxpreps.com";
__MANTA_BEACON_SAMPLE_RATE__ = "100";

MaxPreps.Ads = {};
MaxPreps.Ads.AdManager = Class.create({

    adParams: {SITE:189, BRAND:64, NCAT:"MAXPREPS", STAGING:0},
    
    initialize: function(options, adParams) {
        
        if(adParams != null && adParams.PTYPE != null) {
            
            if(options == null) options = {};
            
            // figure out if we are goign to allow the page to recycle the ads
            if(options.asyncEnabled == null || !options.asyncEnabled) options.asyncEnabled = false;
            
            // figure out if we are loading ads at bottom of page
            if(options.loadedAtBottom == null || !options.loadedAtBottom) options.loadedAtBottom = false;
            
            // assumes all ad "cookies" are session cookies
            var cookie = this.cookie = new Cookie({name:"Ad_Manager"});
            this.ads = [];
            
            // mode we are using the ads in. values are 0-3. allow both server side sets and querystring set. higher values take precidence
            // 0 = production
            // 1 = production debug
            // 2 = staging
            // 3 = debug
            var mode = (options.mode != null) ? options.mode : 0;
            if(mode < 3 && location.hash.indexOf("#mad_debug") != -1) {
                mode = 3;
            }
            else if(mode < 2 && location.hash.indexOf("#mad_staging") != -1) {
                mode = 2;
            }
            else if(mode < 1 && location.hash.indexOf("#mad_production_debug") != -1) {
                mode = 1;
            }
            this.mode = mode;
            delete options.mode;
            
            this.options = options;
            
            // get ad cookies and add them to the adParams object.
            var allAdParams = {};
            Object.extend(allAdParams, MaxPreps.Ads.AdManager.adParams);
            Object.extend(allAdParams, adParams);
            Object.extend(allAdParams, MaxPreps.Ads.AdManager.getAdCookies(cookie));
            this.adParams = allAdParams;
                        
            this.debugDiv = new Element("div", {id: "ad_debug", style: "padding:10px; display:none; background:white;"});
        
            //this.trackBehavioral();
                        
            var bindedDocumentLoaded = this.bindedDocumentLoaded = this.documentLoaded.bindAsEventListener(this);
            document.observe("dom:loaded", bindedDocumentLoaded);
        }
    },
    
    documentLoaded: function(e) {
        var debugDiv = this.debugDiv;
        document.body.appendChild(debugDiv);
        
        if(this.mode % 2 == 1) {
            var adParams = this.adParams;
            var options = this.options;
            
            var adManagerInfo = new Element("div", {style:"border:blue 1px solid;padding:2px"});
            adManagerInfo.appendChild(document.createTextNode("AdManager Properties"));
            adManagerInfo.appendChild(document.createElement("br"));
            adManagerInfo.appendChild(document.createTextNode("--MP:AdManagerMode = " + this.mode));
            adManagerInfo.appendChild(document.createElement("br"));
            
            adManagerInfo.appendChild(document.createTextNode("--MP:AsyncEnabled = " + options.asyncEnabled));
            adManagerInfo.appendChild(document.createElement("br"));
            adManagerInfo.appendChild(document.createTextNode("--MP:LoadAtBottom = " + options.loadAtBottom));
            adManagerInfo.appendChild(document.createElement("br"));
            
            adManagerInfo.appendChild(document.createTextNode("--BRAND = " + adParams.BRAND));
            adManagerInfo.appendChild(document.createElement("br"));
            adManagerInfo.appendChild(document.createTextNode("--SITE = " + adParams.SITE));
            adManagerInfo.appendChild(document.createElement("br"));
            adManagerInfo.appendChild(document.createTextNode("--PTYPE = " + adParams.PTYPE));
            adManagerInfo.appendChild(document.createElement("br"));
            adManagerInfo.appendChild(document.createTextNode("--NCAT = " + adParams.NCAT));
            adManagerInfo.appendChild(document.createElement("br"));
            adManagerInfo.appendChild(document.createTextNode("--Session = " + adParams.DVAR_SESSION));
            adManagerInfo.appendChild(document.createElement("br"));
            adManagerInfo.appendChild(document.createTextNode("--FirstPage = " + adParams.DVAR_FIRSTPAGE));
            adManagerInfo.appendChild(document.createElement("br"));
            adManagerInfo.appendChild(document.createTextNode("--Cookies Enabled = " + adParams.cookiesOn));
            
            if(adParams.DVAR_STATE != null) {
                adManagerInfo.appendChild(document.createElement("br"));
                adManagerInfo.appendChild(document.createTextNode("--State = " + adParams.DVAR_STATE));
            }
            
            debugDiv.insert({top:adManagerInfo});
            debugDiv.setStyle({display:"block"});
        }
        
        
        this.ads.invoke("documentLoaded");
        
    },
    
    trackBehavioral: function() {
        var tracked = false;
        var track = null;
        var trackRate = -1;
        var trackTest = -1;
        if(window.__LOGGING_HOST__ != null && window.__MANTA_BEACON_SAMPLE_RATE__ != null) {
            
            trackTest = Math.floor(Math.random() * 100) + 1;
            trackRate = __MANTA_BEACON_SAMPLE_RATE__;
            
            if(trackTest <= trackRate) {
                var adParams = this.adParams;
                var cacheBuster = (Math.floor(Math.random()*100000) + 1);
                //These are tracked in lineId 299979
                
                // replace the tokens with values from the adObj (if present)
                track = "http://" + __LOGGING_HOST__ + "/adlog/i/r=7807&s=855140&h=cn&p=2&l=en_US";
                track += "&t=-1&x-rnd=" + cacheBuster.toString();
                track += "&b=" + ((adParams.BRAND == null) ? "" : adParams.BRAND);
                track += "&site=" + ((adParams.SITE == null) ? "" : adParams.SITE);
                track += "&ptype=" + ((adParams.PTYPE == null) ? "" : adParams.PTYPE);
                track += "&o=" + ((adParams.NCAT == null) ? "1:" : adParams.NCAT);
                
                // dont have next 2 values. always return string.empty
                track += "&pid=&cid="
                
                // dont have DVAR_MFG or DVAR_SELECTTAG removing that block
	            
	            // not sure what this is for...
                track += "/http://i.i.com.com/cnwk.1d/Ads/common/dotclear.gif";
                
                // not safe to insert to body here as document hasnt loaded yet
                document.write("<img src=\"" + track + "\" width=\"1\" height=\"1\" border=\"0\" />");
                
                // create a psedo ad that will call madison with the global ad params.
                // basically im just using the ad class to collect params and create the js call.
                this.createAd({behaviorAd:true}, {SP:-1, POS:-1});
                
                
                // deals with the asi stuff
                var bindedOnAsiLoaded = this.bindedOnAsiLoaded = this.onAsiLoaded.bindAsEventListener(this);
                var asi = this.asi = new Element("script", {type:"text/javascript"});
                asi.observe("load", bindedOnAsiLoaded);
                asi.observe("readystatechange", bindedOnAsiLoaded);
                asi.src = "http://js.revsci.net/gateway/gw.js?csid=K05540";
                document.getElementsByTagName("head")[0].appendChild(asi);
                
            }
        }
        
        // add debug info for the cbs behavioral tracking
        if(this.mode % 2 == 1) {
            var debugInfo = new Element("div", {style:"margin-top:5px;border:green 1px solid;padding:2px"});
            debugInfo.appendChild(document.createTextNode("CBS Behavior Tracking"));
            debugInfo.appendChild(document.createElement("br"));
            
            debugInfo.appendChild(document.createTextNode("--Sample % = " + trackRate));
            debugInfo.appendChild(document.createElement("br"));
            
            if(track != null) {
                debugInfo.appendChild(document.createTextNode("--Track Occured = Yes"));
                debugInfo.appendChild(document.createElement("br"));
                
                debugInfo.appendChild(document.createTextNode("--Track Url = " + track));
            }
            else {
                debugInfo.appendChild(document.createTextNode("--Track Occured = No"));
                debugInfo.appendChild(document.createElement("br"));
                
                var reason = null;
                if(window.__LOGGING_HOST__ == null || window.__MANTA_BEACON_SAMPLE_RATE__ == null) {
                    reason = "Missing global props(s)... __LOGGING_HOST__ = " + ((window.__LOGGING_HOST__ != null) ? window.__LOGGING_HOST__ : "null") + "  |  __MANTA_BEACON_SAMPLE_RATE__ = " + ((window.__MANTA_BEACON_SAMPLE_RATE__ != null) ? window.__MANTA_BEACON_SAMPLE_RATE__ : "null");
                }
                else {
                    reason = "Sample rate (not an error... just didn't need track for this pageview) " + trackTest;
                }
                debugInfo.appendChild(document.createTextNode("--No Track Reason = " + reason));
            }
            
            var debugDiv = this.debugDiv;
            debugDiv.appendChild(debugInfo);
            debugDiv.setStyle({display:"block"});
        }
    },
    
    onAsiLoaded: function(e) {
        var element = e.element();
        
        // if we have a readyState make sure its loaded or complete. if no ready state that means the loaded portion fired and were good to go.
        if( (element.readyState != null && (element.readyState == "loaded" || element.readyState == "complete")) || element.readyState == null) {
            var asi = this.asi;
            var bindedOnAsiLoaded = this.bindedOnAsiLoaded;
            asi.stopObserving("load", bindedOnAsiLoaded);
            asi.stopObserving("readystatechange", bindedOnAsiLoaded);
            
            var adParams = this.adParams;
            var paramLowerCased = null;
            var paramValue = null;
            for (var param in adParams)
            {
                paramValue = adParams[param];
                paramLowerCased = param.toLowerCase();
                if(paramLowerCased == "ncat" || paramLowerCased == "site" || paramLowerCased == "ptype")
                {   
                    K05540.DM_addEncToLoc(paramLowerCased, paramValue);
                }
            }
            K05540.DM_tag();
            
            // add the debug info for the asi loaded thingy
            if(this.mode % 2 == 1) {
                var debugInfo = new Element("div", {style:"margin-top:5px;border:green 1px solid;padding:2px"});
                debugInfo.appendChild(document.createTextNode("ASI Loaded"));
                var debugDiv = this.debugDiv;
                debugDiv.appendChild(debugInfo);
                debugDiv.setStyle({display:"block"});
            }
        }
    },
    
    createAd: function(adOptions, adParams) {
        if(adParams != null) {
            var ad = new MaxPreps.Ads.Ad(this, adOptions, adParams);
            if(ad.valid) {
                this.ads.push(ad);
                return ad;
            }
        }
        return null;
    },
    
    reloadAds: function() {
        if(this.options.asyncEnabled) {
            this.ads.invoke("reload");
        }
    },
    
    
    // remove this once the video shit is ready
    // Stuff for video ads
    addVideoAd: function(identifier, baseURL, zone, width, height, pos, isAjaxable) {
        var videoAd = this.videoAd = new MaxPreps.Ads.VideoAd(identifier, baseURL, zone, width, height, pos, isAjaxable, MaxPreps.Ads.AdManager.getAdCookies(this.cookie).DVAR_SESSION);
        this.hasVideoAd = true;
        return videoAd;
    },
    
    addCompanionAd: function(identifier, baseURL, zone, width, height, pos, isAjaxable) {
        var companionAd = this.companionAd = new MaxPreps.Ads.CompanionAd(identifier, baseURL, zone, width, height, pos, isAjaxable, MaxPreps.Ads.AdManager.getAdCookies(this.cookie).DVAR_SESSION);
        return companionAd;
    },
    
    getVideoAdURL: function() {
        if(this.hasVideoAd) {
            return this.videoAd.getAdURL();
        }
        return null;
    },
    
    getCompanionAdURL: function() {
        if(this.hasVideoAd) {
            return this.companionAd.getAdURL();
        }
        return null;
    }
});

Object.extend(MaxPreps.Ads.AdManager, {
    getAdCookies: function(cookie) {
        // get the session cookie
        var session = cookie.getData("session");
        if(session == null) {
            session = ["a","b","c","d"];
            session = session[Math.floor(Math.random() * session.length)];
            cookie.setData("session", session);
        }
        
        // is this the first page?
        var firstPage = cookie.getData("firstPage");
        if(firstPage == null) {
            firstPage = 1;
            cookie.setData("firstPage", 0);
        }
        
        // tes to see if cookies are enabled.
        var cookiesOn = 0;
        if(Cookie.CookiesEnabled()) {
            cookiesOn = 1;
        }
        return {DVAR_SESSION: session, DVAR_FIRSTPAGE: firstPage, cookiesOn:cookiesOn};
    }
});


var pageOrd = Math.round(Math.random() * 10000000);
MaxPreps.Ads.VideoAd = Class.create({
    initialize: function(identifier, baseURL, zone, width, height, pos, isAjaxable, session) {
        this.identifier = identifier;
        this.baseURL = baseURL;
        this.zone = zone;
        this.width = width;
        this.height = height;
        this.pos = pos;
        this.session = session;
    },
    
    getAdURL: function() {
        var baseURL = this.getPageTile() + ";adx=" + this.session + ";ord=" + pageOrd + "?";
        
        var indexOfType = baseURL.indexOf("#{type}");
        var adURL = baseURL.substring(0, indexOfType) + "adx" + baseURL.substring(indexOfType + 7, baseURL.length);
        return adURL;
    },
    
    getPageTile: function() {
        var tileAppend = ";tile=1";
        var adURL = this.baseURL;
        return adURL.substr(0, adURL.indexOf(";dcopt=ist")) + tileAppend + adURL.substr(adURL.indexOf(";dcopt=ist") + 10);
    }
});

MaxPreps.Ads.CompanionAd = Class.create({
    initialize: function(identifier, baseURL, zone, width, height, pos, isAjaxable, session) {
        this.identifier = identifier;
        this.baseURL = baseURL;
        this.zone = zone;
        this.width = width;
        this.height = height;
        this.pos = pos;
        this.isAjaxable = isAjaxable;
        this.session = session;
    },
    
    getAdURL: function() {
        var baseURL = this.getPageTile() + ";adx=" + this.session + ";ord=" + pageOrd + "?";
        var indexOfType = baseURL.indexOf("#{type}");
        var adURL = baseURL.substring(0, indexOfType) + "adj" + baseURL.substring(indexOfType + 7, baseURL.length);
        return adURL;
    },
    
    getPageTile: function() {
        var tileAppend = ";tile=2";
        var adURL = this.baseURL;
        return adURL.substr(0, adURL.indexOf(";dcopt=ist")) + tileAppend + adURL.substr(adURL.indexOf(";dcopt=ist") + 10);
    }
});



MaxPreps.Ads.Ad = Class.create({
    adParams: {POS:100},
    
    initialize: function(adManager, options, adParams) {
    
        if(adManager != null && adParams != null && adParams.SP != null) {
            this.valid = true;
            this.rendered = false;
            
            if(options == null) options = {};
            
            // figure out if we are loading ads at bottom of page
            if(options.loadedAtBottom == null || !options.loadedAtBottom) options.loadedAtBottom = false;
            // figure out if this ad is to participate in the async refreshes that the ad manager can request
            if(options.asyncEnabled == null || !options.asyncEnabled) options.asyncEnabled = false;
            
            if(isNaN(options.width)) options.width = -1;
            if(isNaN(options.height)) options.height = -1;
            
            this.options = options;
            
            // mode we are using for this ad. values are 0-3. allow both server side sets and querystring set. 
            // higher values take precidence.
            // 0 = production
            // 1 = staging
            // 2 = production debug
            // 3 = debug
            var mode = (options.mode != null) ? options.mode : 0;
            if(mode < 3 && location.hash.indexOf("#mad_debug") != -1) {
                mode = 3;
            }
            else if(mode < 2 && location.hash.indexOf("#mad_staging") != -1) {
                mode = 2;
            }
            else if(mode < 1 && location.hash.indexOf("#mad_production_debug") != -1) {
                mode = 1;
            }
            if(adManager.mode > mode) {
                mode = adManager.mode;
            }
            this.mode = mode;
            
            // build the adparams object
            var allAdParams = new Hash();
            allAdParams = allAdParams.merge(adManager.adParams);
            allAdParams = allAdParams.merge(MaxPreps.Ads.Ad.adParams);
            allAdParams = allAdParams.merge(adParams);
            this.adParams = allAdParams;
            
            this.adManager = adManager;
            
            this.render();
        }
    },
    
    documentLoaded: function() {
        var options = this.options;
        
        if(this.options.loadedAtBottom) {
            this.loadedAtBottom();
        }
        
        if(this.mode % 2 == 1) {
            this.outputDebug();
        }
    },
    
    loadedAtBottom: function() {
        var container = this.getContainer();
        var placeHolder = this.getPlaceHolder();
        
        if(container != null && placeHolder != null) {
       
            container.select("script").each(
                function(script, index) {
                    //script.src = null;
                    script.remove();
                }
            );
            
            container.remove();
            placeHolder.appendChild(container);
            container.setStyle({display: "block"});
            
            // In ie the iframes werent showing.
            // IE was giving the style hasLayout = -1; For some reason flagging it to 1 made the ads appear.
            if(Prototype.Browser.IE) {
                container.select("iframe").each(
                    function(iframe, index) {
                        iframe.setStyle({zoom:"1"});
                    }
                );
            }
        }
    },
    
    getContainer: function() {
        var container = this.container;
        if(container == null) {
            container = this.container = $("ad_" + this.options.id);
        }
        return container;
    },
    
    getPlaceHolder: function() {
        var placeHolder = this.placeHolder;
        if(placeHolder == null) {
            placeHolder = this.placeHolder = $("ad_ph_" + this.options.id);
        }
        return placeHolder;
    },
    
    render: function() {
        if(!this.rendered) {
            var src = this.src = this.getScriptUrl();
            this.rendered = true;
            
            document.write("<script type=\"text/javascript\" src=\"" + src + "\"></script>\n");
        }
    },
    
    reload: function() {
        var options = this.options;
        
        if(options.asyncEnabled && options.width != -1 && options.height != -1) {
            
            var container = this.getContainer();
            if(container == null) return;
            
            // +10px to allow for the ad feedback graphic
            var html = "<iframe width=\"" + options.width + "\" height=\"" + (options.height + 10) + "\"";
            html += "frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" allowtransparency=\"true\" style=\"background-color:transparent;\" ";
            html += "src=\"/utility/ad_proxy.aspx?scripturl=" + encodeURIComponent(this.getScriptUrl()) + "\" ></iframe>";
            
            container.innerHTML = html;
                
            // debug stuff for async ad
            if(this.mode % 2 == 1) {
                var asyncRefreshesSpan = this.asyncRefreshesSpan;
                
                if(asyncRefreshesSpan == null) {
                    var asyncRefreshes = new Element("div");
                    asyncRefreshesSpan = new Element("span");
                    asyncRefreshesSpan.appendChild(document.createTextNode("1"));
                    
                    asyncRefreshes.appendChild(document.createTextNode("MP:Async Refreshes: "));
                    asyncRefreshes.appendChild(asyncRefreshesSpan);
                    this.debugInfo.appendChild(asyncRefreshes);
                    
                    this.asyncRefreshesSpan = asyncRefreshesSpan;
                }
                else if(!isNaN(asyncRefreshesSpan.innerHTML)) {
                    asyncRefreshesSpan.innerHTML = (parseInt(asyncRefreshesSpan.innerHTML) + 1) + "";
                }
                else {
                    asyncRefreshesSpan.innerHTML = "Error in debug output (doesnt mean ad had an error).";
                }
            }
        }
    },
    
    outputDebug: function() {
        var debugDiv = this.adManager.debugDiv;
        
        var adParams = this.adParams;
        var options = this.options;
        
        var debugInfo = null;
        if(options.behaviorAd) {
            debugInfo = this.debugInfo = new Element("div", {style:"margin-top:5px;border:1px solid green; padding:2px;"});
        }
        else {
            debugInfo = this.debugInfo = new Element("div", {style:"margin-top:5px;border:1px solid red; padding:2px;"});
        }
        debugInfo.appendChild(document.createTextNode("MP:AsyncEnabled = " + options.asyncEnabled));
        
        debugInfo.appendChild(document.createElement("br"));
        debugInfo.appendChild(document.createTextNode("MP:LoadedAtBottom = " + options.loadedAtBottom));
        
        debugInfo.appendChild(document.createElement("br"));
        debugInfo.appendChild(document.createTextNode("SP = " + adParams.get("SP")));
        
        debugInfo.appendChild(document.createElement("br"));
        debugInfo.appendChild(document.createTextNode("POS = " + adParams.get("POS")));
    
        debugInfo.appendChild(document.createElement("br"));
        debugInfo.appendChild(document.createTextNode("NCAT = " + adParams.get("NCAT")));
        
        debugInfo.appendChild(document.createElement("br"));
        debugInfo.appendChild(document.createTextNode("Url = " + this.src));
        
        debugDiv.appendChild(debugInfo);
        debugDiv.setStyle({display:"block"});
    },
    
    getScriptUrl: function() {
        var domain = ( this.mode > 1) ? "madstage.cnet.com:8000" : "mads.maxpreps.com";
        
        var referrer = (window.location.protocol.indexOf("https") != -1) ? "&amp;referer=" + encodeURIComponent(window.location.href) : "";
        
        var adParams = this.adParams;
        // if this is the behavioral ad then remove the vars that aren't nessisary.
        if(this.options.behaviorAd) {
            adParams.unset("SP");
            adParams.unset("POS");
            adParams.unset("DVAR_SESSION");
            adParams.unset("DVAR_FIRSTPAGE");
        }
        
        return "http://" + domain + "/mac-ad?CLIENT:ID=SJS&amp;celt=js&amp;x-cb=" + Math.floor(Math.random() * 1000000) + "&amp;" + adParams.toQueryString();
    }
});


// shit pulled over from mantaray
// j = server to pull ad from.
// b = "".
// d = site id which get overridden by ""
// i = "js"
// h = random number
// g = referrer (if on a https page)
// k = all ad params + ad global params in string format.
//c = "http://" + j + b + d + "/mac-ad?CLIENT:ID=SJS&amp;celt=" + i + "&amp;x-cb=" + h + g + k;

/*
// manta ray version
http://madstage.cnet.com:8000/mac-ad?
CLIENT:ID=SJS&amp;
celt=js&amp;
x-cb=21294706&amp;
SITE=189&amp;
BRAND=64&amp;
NCAT=MAXPREPS&amp;
PTYPE=2000&amp;
SP=15&amp;
POS=100&amp;
DVAR_FIRSTPAGE=1

// my version
http://madstage.cnet.com:8000/mac-ad?
CLIENT:ID=SJS&amp;
celt=js&amp;
x-cb=28504&amp;
SITE=189&amp;
BRAND=64&amp;
NCAT=MAXPREPS&amp;
PTYPE=2000&amp;
DVAR_SESSION=d&amp;
DVAR_FIRSTPAGE=0&amp;
SP=15&amp;
POS=100
*/