/****** base class for showing ads based on frequency using cookies for tracking/persistence ******/
function adDisplayManager (id, adType, duration, days, hours, minutes, setCookieIncludeIframe, redirectUrl) {
    if ( arguments.length > 0 ) {
        this.init(id, adType, duration, days, hours, minutes, setCookieIncludeIframe, redirectUrl);
    }
    adDisplayManager.hiddenAds = null;
}
// init method
adDisplayManager.prototype.init = function (id, adType, duration, days, hours, minutes, setCookieIncludeIframe, redirectUrl) {
    this.id = id;
    this.adType = adType;
    this.duration = duration;
    this.intDays = days;
    this.intHours = hours;
    this.intMinutes = minutes;
    this.intMStoExpire = (days * 86400000) + (hours * 3600000) + (minutes * 60000);
    this.setCookieIncludeIframe = setCookieIncludeIframe;
    if(redirectUrl){
    	this.redirectUrl=redirectUrl;
    }
    this.disabled = false;
    // timer housekeeping
    this.intCurrentTime = new Date().getTime();
    this.timer = null;
    // cookie members
    this.cookieName = 'adDisplayManager';
    this.cookieKey = this.id;
    this.cookieDelim = '&';
    this.cookieExpires = 30;
    // ad types and div ids to suppress
    this.adTypesToSuppress = null;
    this.divIdsToHide = null;
    this.handlers = null;
}
// try to show the ad and 
adDisplayManager.prototype.setItemsToSuppress = function(adTypes, divIds) {
    if ( adTypes != null && adTypes.length > 0 ) {
        this.adTypesToSuppress = adTypes;
    }
    if ( divIds != null && divIds.length > 0 ) {
        this.divIdsToHide = divIds;
    }
}
// set a display handler object
adDisplayManager.prototype.setHandler = function(handler) {
    if ( this.handlers == null ) {
        this.handlers = new Array();
    }
    this.handlers[this.handlers.length] = handler;
}
// set a display handler object
adDisplayManager.prototype.setGlobalAdSrcType = function(globAdSrc) {
  if (this.isAdNeeded()) {
    AD_TRACKER.globalAdSrcType = globAdSrc;
  }
}
// run the ad logic
adDisplayManager.prototype.run = function() {
  if (!this.disabled) {
    if (this.isAdNeeded()) {
        this.saveState();
	this.start();
    } else {
        if(this.duration!=null && this.duration != '' && this.duration != -1)
            this.finish();
    }
  }
}
// determine whether or not to show ad
adDisplayManager.prototype.isAdNeeded = function() {
  if (!this.disabled) {
    if (typeof (hideAllAds) == 'undefined' || hideAllAds == false) {
        var lastRunDate = this.readCookieValue();
        if (null != lastRunDate) {
            if ((this.intCurrentTime - lastRunDate) > this.intMStoExpire) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
  }
  return false;
}
// save the ad state into the cookie
adDisplayManager.prototype.saveState = function() {
  if (!this.disabled) {
    this.setCookieValue(this.intCurrentTime);
    if (this.setCookieIncludeIframe && this.setCookieIncludeIframe.length > 0) {
      var iframe = document.createElement('iframe');
      iframe.src = this.setCookieIncludeIframe;
      iframe.style.width='0px';
      iframe.style.height='0px';
      var introDiv = document.getElementById(this.id);
      if (introDiv) {
        introDiv.appendChild(iframe);
      }
    }
  }
}
// "start" or "show" the ad
//    - start is semantically associated with duration
//    - think of this method as "show" when no duration is specified)
adDisplayManager.prototype.start = function() {
    document.getElementById(this.id).style.display = 'block';
    if(this.duration != null && this.duration != '' && this.duration != -1) {
        this.timer = window.setTimeout(this.id+'.finish()', this.duration);
    }
    // suppress items that "conflict" with this managed ad
    if ( this.adTypesToSuppress != null ) {
        var adTypes = this.adTypesToSuppress.split(',');
        for ( var i=0; i<adTypes.length; i++ ) {
            AD_TRACKER.addToHidden(adTypes[i]);
        }
    }
    if ( this.divIdsToHide != null ) {
        var divIds = this.divIdsToHide.split(',');
        for ( var i=0; i<divIds.length; i++ ) {
            document.write('<style type=\"text/css\">div#' + divIds[i] + ' { display: none; }</style>');
        }
    }
    if ( this.handlers != null ) {
        for ( var i=0; i<this.handlers.length; i++ ) {
            if ( !this.handlers[i].makeRoom.call(this) ) {
                AD_TRACKER.addDeferredHandler(this.handlers[i]);
            }
        }
    }
}
// "finish" or "hide" the ad
adDisplayManager.prototype.finish = function() {
    if(this.redirectUrl){
    	window.location = this.redirectUrl;
    	return;
    }

    document.getElementById(this.id).style.display = 'none';
    if (this.timer) {
        window.clearTimeout(this.timer);
    }
    // ad is finished, re-enable the "conflicting" items
    if ( this.divIdsToHide != null ) {
        var divIds = this.divIdsToHide.split(',');
        for ( var i=0; i<divIds.length; i++ ) {
	    if (document.getElementById(divIds[i]) != null) 
	        document.getElementById(divIds[i]).style.display = 'block';
        }
    }
    if ( this.handlers != null ) {
        for ( var i=0; i<this.handlers.length; i++ ) {
            handler[i].revert.call(this);
        }
    }
}
// set a value in the cookie
adDisplayManager.prototype.setCookieValue = function(newValue) {
    var newvals = '';
    var keyExists = false;
    var cook = getCookie(this.cookieName);
    if ( cook != null ) {
        var vals = cook.split(this.cookieDelim);
        for (var i=0; i<vals.length; i++) {
            var val = vals[i].split('=');
            newvals += (i==0) ? '' : '&';
            if ( val != null && val.length > 1 ) {
                if ( val[0] == this.cookieKey) {
                    newvals += val[0] + '=' + escape(newValue);
                    keyExists = true;
                } else {
                    newvals += val[0] + '=' + escape(val[1]);
                }
            }
        }
    }
    if (!keyExists) {
        newvals += (newvals.length == 0) ? '' : '&';
	newvals += this.cookieKey + '=' + escape(newValue);
    }
    setCookie(this.cookieName, newvals, this.cookieExpires);
}
// read a value from the cookie
adDisplayManager.prototype.readCookieValue = function() {
    var cook = getCookie(this.cookieName);
    if ( cook != null ) {
        var vals = cook.split(this.cookieDelim);
        for (var i=0; i<vals.length; i++) {
            var val = vals[i].split('=');
	    if ( val != null && val.length > 1 && val[0] == this.cookieKey) {
               return val[1];
	    }
        }
    }
    return null;
}



/****** static ad tracking class, keeps state of ads to hide for all loaded adDisplayManager implementations ******/
function adDisplayTracker () {
    this.hiddenAds = null;
    this.handlers = null;
    this.timer = null;
    this.interval = 750;
    this.maxRunCount = 15;
    this.globalAdSrcType = null;
}
// static method to keep track of ads to hide
adDisplayTracker.prototype.addToHidden = function(adType) {
    if ( this.hiddenAds == null ) {
        this.hiddenAds = new Array();
    }
    this.hiddenAds[this.hiddenAds.length] = adType;
}
// static method to keep track of ads to hide
adDisplayTracker.prototype.isAdHidden = function(adType) {
    if ( this.hiddenAds != null ) {
        for( var i=0; i<this.hiddenAds.length; i++ ) {
            if ( this.hiddenAds[i] == adType ) {
                return true;
                break;
            }
        }
    }
    return false;
}
adDisplayTracker.prototype.addDeferredHandler = function(hand) {
    this.ensureSetup();
    this.handlers[this.handlers.length] = hand;
}
adDisplayTracker.prototype.ensureSetup = function() {
    if ( this.timer == null ) {
        this.timer = setTimeout('AD_TRACKER.processHandlers()', this.interval);
    }
    if ( this.handlers == null ) {
        this.handlers = new Array();
    }
}
adDisplayTracker.prototype.processHandlers = function() {
    if ( this.handlers == null || this.handlers.length == 0 ) {
        this.timer = null;
    } else {
        var newHandlers = new Array();
        for( var i=0; i<this.handlers.length; i++ ) {
            if ( !this.handlers[i].makeRoom.call(this) && this.handlers[i].runCount < this.maxRunCount) {
                this.handlers[i].runCount++;
                newHandlers[newHandlers.length] = this.handlers[i];
            }
        }
        if ( newHandlers.length > 0 ) {
            this.handlers = newHandlers;
            this.timer = setTimeout('AD_TRACKER.processHandlers()', this.interval);
        } else {
            this.timer = null;
            this.handlers = null;
        }
    }
}
var AD_TRACKER = new adDisplayTracker();



/****** ad handler class, these can be registered with the adDisplayManager to account for specific functionality ******/
function adDisplayHandler () {
    this.runCount = 0;
}
// make room for the ad
adDisplayHandler.prototype.makeRoom = function() {
    return true;
}
// revert the "make room" operation
adDisplayHandler.prototype.revert = function() {}



/****** intro message manager ******/
function introMessageManager (id, adType, duration, days, hours, minutes, setCookieIncludeIframe, redirectUrl) {
    if ( arguments.length > 0 ) {
        this.init(id, adType, duration, days, hours, minutes, setCookieIncludeIframe, redirectUrl);
    }
}
introMessageManager.prototype = new adDisplayManager();
introMessageManager.superclass = adDisplayManager.prototype;
introMessageManager.prototype.init = function(id, adType, duration, days, hours, minutes, setCookieIncludeIframe, redirectUrl) {
    introMessageManager.superclass.init.call(this, id, adType, duration, days, hours, minutes, setCookieIncludeIframe, redirectUrl);
}
introMessageManager.prototype.start = function() {
    introMessageManager.superclass.start.call(this);
    if (this.adType=='intromessage') {
        document.write('<style type="text/css">div#maincontent, div#banner, div#Footer1 { display: none; }</style>');
    } else if (this.adType=='ssintromessage') {
        document.write('<style type="text/css">div#thumbFrame, div#multimedia, div#photoFrame, div#photoCaption, div#slideshowToolbar, div#slideshowAd, iframe#ReutersAd1 { display: none; }</style>');
    }
}
introMessageManager.prototype.finish = function() {
    introMessageManager.superclass.finish.call(this);

    if(this.adType == 'intromessage') {

        if (document.getElementById("maincontent") != null)
            document.getElementById("maincontent").style.display = 'block';
        if (document.getElementById("banner") != null)
            document.getElementById("banner").style.display = 'block';
        if (document.getElementById("Footer1") != null)
            document.getElementById("Footer1").style.display = 'block';

    } else if (this.adType == 'ssintromessage') {
    
        if (document.getElementById("section1") != null)
            document.getElementById("section1").style.display = 'block';
        if (document.getElementById("thumbFrame") != null) 
            document.getElementById("thumbFrame").style.display = 'block';
        if (document.getElementById("photoFrame") != null) 
            document.getElementById("photoFrame").style.display = 'block';
        if (document.getElementById("photoCaption") != null) 
            document.getElementById("photoCaption").style.display = 'block';
        if (document.getElementById("slideshowToolbar") != null) 
            document.getElementById("slideshowToolbar").style.display = 'block';
        if (document.getElementById("slideshowAd") != null) 
            document.getElementById("slideshowAd").style.display = 'block';
        if (document.getElementById("ReutersAd1") != null) 
            document.getElementById("ReutersAd1").style.display = 'block';

        var allDivs = document.getElementsByTagName("div");
        if (allDivs) {
            for (i=0; i<allDivs.length; i++) {
                if (allDivs[i].getAttribute('id') && allDivs[i].getAttribute('id') == 'slideshowAd')
                    allDivs[i].style.display = 'block';
            }
        }
    }
}



/****** poeArticlePage handler ******/
function poeArticlePageHandler () {}
poeArticlePageHandler.prototype = new adDisplayHandler();
poeArticlePageHandler.superclass = adDisplayHandler.prototype;
poeArticlePageHandler.prototype.makeRoom = function() {
    if ( document.getElementById('crumbsBand') != null ) {
        var crumb = document.getElementById('crumbsBand');
        crumb.parentNode.removeChild(crumb);
        document.getElementById('prebanner').appendChild(crumb);
        crumb.style.display = 'block';
        this.crumbRes = true;
    } else if ( document.getElementById('crumbsBand') == null && this.runCount == 0 ) {
        document.write('<style type=\"text/css\">div#crumbsBand { display: none; }</style>');
    }
    if ( document.getElementById('rhsPOEtarget') != null ) {
        var rhst = document.getElementById('rhsPOEtarget');
        var rhstp = rhst.parentNode;
        // shift up one level if module level tracking is on
        if ( rhstp.getAttribute('name') == 'trackingEnabledModule') {
            rhst = rhstp;
            rhstp = rhstp.parentNode;
        }
        var thirdStone = rhst.nextSibling.nextSibling.nextSibling;
        rhstp.removeChild(rhst);
        rhstp.insertBefore(rhst, thirdStone);
        this.adRes = true;
    } else if ( document.getElementById('rhsPOEtarget') == null && this.runCount == 0 ) {
        document.write('<style type=\"text/css\">div#rhsPOEtarget { display: none; }</style>');
    }
    return this.crumbRes * this.adRes;
}
poeArticlePageHandler.prototype.revert = function() {}


/****** poeLandingPageHandler handler ******/
function poeLandingPageHandler () {}
poeLandingPageHandler.prototype = new adDisplayHandler();
poeLandingPageHandler.superclass = adDisplayHandler.prototype;
poeLandingPageHandler.prototype.makeRoom = function() {
    var res = false;
    if ( document.getElementById('oldPageTitle') != null && document.getElementById('newPageTitle') != null) {
        var opt = document.getElementById('oldPageTitle');
        opt.parentNode.removeChild(opt);
        document.getElementById('newPageTitle').appendChild(opt);
        res = true;
    }
    return res;
}
poeLandingPageHandler.prototype.revert = function() {}


