//gets revsci info
if (document.domain != '') {
document.write('<s\cript src="http://js.revsci.net/gateway/gw.js?csid=J05531"></s\cript>');
}

//generates random number (but not ord string) once for entire page
function RandomInt()
{
	if (typeof this.randReturnValue == 'undefined')
	{
		this.randReturnValue = Math.random() * 1000000000000000000;
    } 

	return this.randReturnValue
}

//generates ord string once for entire page
function ord()
{	
	if (typeof this.ordReturnValue == 'undefined')
	{	
		this.ordReturnValue = "ord=" + RandomInt()
    } 
	return this.ordReturnValue
}

//checks for dfpcomp variable. if it exists, return dfpcomp as a keyvalue.
function dfpComp()
{
	if(typeof this.dfpReturnValue == 'undefined' || this.dfpReturnValue == '')
	{	
		if(typeof dfpcomp != 'undefined')
		{	
			this.dfpReturnValue = 'dfpcomp=' + dfpcomp + ";";
		}
		else
		{
			this.dfpReturnValue = '';
		}
	}
	return this.dfpReturnValue;
}

function slateid()
{
	if(typeof this.idReturnValue == 'undefined')
	{
	var url = document.location.href;
	url = url.toLowerCase();
	var urlarray = url.split('/');
	var tail = urlarray[urlarray.length -1];
	if (tail.indexOf('nav=') != -1)
	{
		tail = tail.substring(0,tail.indexOf('nav='));
	}
	var illegals = ['?test_ads','?debugadcode','?slateidtest','?','=','/','\\',':',';',',','*','(',')','&','$','%','@','!','^','+',' ','[',']','{','}','.html','.htm','.',];
	for (i=0;i<illegals.length;i++)
	{
		sRE = new RegExp('(\\' + illegals[i] + ')', 'g');
		tail = tail.replace(sRE,"");
	}
	if (tail == 'index' || tail == '')
	{
		tail = urlarray[urlarray.length -2];
	}
	for(i=1;i<urlarray.length;i++)
	{
		if(urlarray[i] == 'entry')
		{
			tail = urlarray[urlarray.length -4]+'_'+tail;
		}
	}

	this.idReturnValue = 'slateid='+tail;
	if (this.idReturnValue.length > 55)
	{
		this.idReturnValue = this.idReturnValue.substring(0,55);
	}
	if(typeof(slateidTestCheck) == 'undefined')
	{
		slateidTestCheck = 0;
	}
	if (url.indexOf('?slateidtest') != -1 && slateidTestCheck != 1)
	{
		prompt('slateid',this.idReturnValue);
		slateidTestCheck = 1;
	}
	}
	return this.idReturnValue + ";"
}



//if revsci array exists, creates revsci keyvalues
function revsci()
{	
	if (typeof rsinetsegs != 'undefined' && (typeof this.revsciReturnValue == 'undefined' || this.revsciReturnValue == '') )
	{
		this.revsciReturnValue='';
		for(i=0;i<rsinetsegs.length;i++)
		{
			this.revsciReturnValue += "rs="+rsinetsegs[i].replace("J05531_","j")+";"
		}
	}
	else if (typeof this.revsciReturnValue=='undefined')
	{
		this.revsciReturnValue='';
	}
	
	return this.revsciReturnValue
}

//creates debugAdCode box for each ad spot
function debugTextArea(ac)
{
  var re = new RegExp("\"","g") ;
  var ac = ac.replace(re,"\\\"") ;
  return '<form><textarea wrap=physical cols=\"+55+\" rows=\"+10+\">'+ac+'</textarea></form>';
}

//getCookie function
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

//returns size if it isn't a flex

function flex(flexBoolean,size)	
{	
	this.flexAndSizeReturnValue = '';
	if (flexBoolean==false)
	{
	this.flexAndSizeReturnValue = 'sz='+size+';'
	}
	return this.flexAndSizeReturnValue
}

//setcookie function
function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

//sets Point of Entry value--once for entire page
function poe()
{
	if(typeof this.poeReturnValue == 'undefined')
	{
		this.poeReturnValue = 'poe=no;';
		if (getCookie("slate_poe") == null || getCookie("slate_poe") == "false")
		{
			this.poeReturnValue = 'poe=yes;';
			setCookie("slate_poe","true","","/","",'')
		}
	}
	return this.poeReturnValue
}

//sets rss-user values--once for entire page
function rss()
{	
	if (typeof this.rssReturnValue == 'undefined')
	{
		if (location.href.indexOf('/fr/rss/') != -1)
		{
			this.rssReturnValue="fromrss=y;";
			setCookie('rss_now','true',''+thisDate().toString()+'','/','www.slate.com','');
			setCookie('rss','true',''+thisDate().toString()+'','/','www.slate.com','');
		}
		else
		{
			this.rssReturnValue="fromrss=n;";
			setCookie('rss_now','false',''+thisDate().toString()+'','/','www.slate.com','');
		}
		if (getCookie('rss') != null) 
		{
			this.rssReturnValue+='rss=y;'
		}
		else 
		{
			this.rssReturnValue += 'rss=n;'
		}
	}
	
	return this.rssReturnValue
}

//detects msn cobranding status--once a page
function msnCobrand()
{
	if (typeof this.msnReturnValue == 'undefined')
	{
		this.msnReturnValue='msn_refer=n;'
		if (typeof msn_cobrand != "undefined")
		{
			if (msn_cobrand != 0)
			{
				this.msnReturnValue='msn_refer=y;';
			}
		}
	}
	
	return this.msnReturnValue
}

function heavy()
{
	if (typeof this.heavyReturnValue == 'undefined')
	{
		this.heavyReturnValue = "heavy=n;"
		if (typeof document.referrer != "undefined")
		{
			if (document.referrer == '') this.heavyReturnValue = "heavy=y;"
		}
	}
	return this.heavyReturnValue
}

function tile(tileBoolean,dcCount)
{
	if (tileBoolean == true)
	{
		return "tile=" + dcCount + ";"
	}
}

function interstitial(interstitialCode,dcCount)
{	
	this.intReturnValue = ''
	if (dcCount=="1")
	{
		this.intReturnValue = interstitialCode
	}
	
	return this.intReturnValue
}

function thisDate()
{
	if (typeof this.dateReturnValue == 'undefined')
	{
		this.dateReturnValue = new Date()
	}
	return this.dateReturnValue
}

function dateToString()
{
	if (typeof this.dtsReturnValue == 'undefined')
	{
		var thisDateObj = thisDate()
		var yyyy = thisDateObj.getYear();
		var mm = thisDateObj.getMonth() + 1;
		var dd = thisDateObj.getDate();
		var hour = thisDateObj.getHours();
		var min = thisDateObj.getMinutes();
		if (mm < 10) mm = "0"+mm;
		if (dd < 10) dd = "0"+dd;
		if (hour < 10) hour = "0"+hour;
		if (min < 10) min = "0"+min;
		this.dtsReturnValue = ''+mm+dd+hour+min;
	}
	return this.dtsReturnValue
}

function dateCheck(when,now)
{
	this.dateCheckReturnValue=false;
	if (typeof when == "undefined")
	{
		this.dateCheckReturnValue = true;
	}
	else
	{
		dateSets = when.split(';')
		for (x=0;x<dateSets.length;x++)
		{
			if (now >= dateSets[x].split('/')[0] && now <= dateSets[x].split('/')[1])
			{
				this.dateCheckReturnValue=true
			}
		}
	}
	return this.dateCheckReturnValue	
}

function locationCheck(where,currentLoc)
{
	this.locCheckReturnValue=false;
	if (where == "undefined")
	{
		where = true;
	}
	if (where.indexOf('-') != -1 || where == '')
	{
		this.locCheckReturnValue = true
	}
	else
	{
		this.locCheckReturnValue = false
	}
		
	var nodes = where.split(';');
		
	for (x=0;x<nodes.length;x++)
	{
		if (currentLoc == nodes[x])
		{
			this.locCheckReturnValue = true;
		}
		if (('-' + currentLoc) == nodes[x])
		{
			this.locCheckReturnValue = false;
		}
	}
	return this.locCheckReturnValue
}

function getHighestValue()
{
	var longest = 0;
	var loop;
	for (loop=0;loop<arguments.length;loop++)
	{
		if (arguments[loop] > longest)
		{
			longest = arguments[loop];
		}
	}
return longest;
}

function AdInstance()
{	
	this.when = new Array()
	this.where = new Array()
	this.managerListLength = 0
	
	this.dateObject = new Date()
	this.now = dateToString(this.dateObject)
	
	this.tile = true
	this.flex = false
	
	
	this.interstitial = "dcopt=ist;"
	if (location.href.indexOf("g=1") != -1)
	{
		this.interstitial = "!category=nopops;";
	}
	
	this.doubleClickFlag = true;
	this.doubleClickAdType = "adj";
	
	this.dcCode = ''
	if (location.href.indexOf("test_ads") != -1) 
	{
		this.dcCode += 'kw=slate_test;'
	}
	
	this.dcCode += "dept=" + PStax + ";" + msnCobrand() + heavy() + slateid() + poe() + revsci() + dfpComp() + rss(this.dateObject);
	
	this.code = ''
	

	
	this.adExecute = function (currentLoc,dcCount,what,flexBoolean) {
		var doIt = true;
		
			this.isThisManaged = false
		
		if (this.isThisManaged == true)
		{
			doIt = false;
			for (loop=0;loop<this.managerListLength;loop++)
			{
				if (dateCheck(this.when[loop],this.now) && dateCheck(this.where[loop],currentLoc))
				{
					doIt = true;
				}
			}
		}
		
		
		if (doIt == true)
		{
			
			if (this.doubleClickFlag == true)
			{
				output="<s\cript language=\"JavaScript1.1\" src=\"http://ad.doubleclick.net/" + this.doubleClickAdType + "/" + currentLoc + ";" + this.code + flex(flexBoolean,this.size) + tile(this.tile,dcCount) + interstitial(this.interstitial,dcCount) + this.dcCode + "pos=" + what + ";" + ord() +  "?\"></s\cript>"
				if (location.href.indexOf('debugAdCode') != -1)
				{
				output+=debugTextArea(output)
				}
			}
		document.write(output)
		}
	}
}

function initAdType(what)
{
	thisAdType = new AdInstance()
	
	switch(what)
	{
		case 'toolbar':
			thisAdType.size = "120x60"
			thisAdType.code = "ad=120x60;"
			thisAdType.adExecute.isThisManaged = true
			thisAdType.when[0] = "09180000/10192359"
		break
		
		case 'leaderboard':
			thisAdType.size = "728x90"
			thisAdType.code = "ad=lb;kw=slate;"
		break
		
		case 'bigbox':
			thisAdType.size = "300x250"
			thisAdType.code = "ad=bb;"
		break
		
		case '120x240':
			thisAdType.size = "120x240"
			thisAdType.code = "ad=120x240;"
		break
		
		case 'skyscraper':
			thisAdType.size = "160x600"
			thisAdType.code = "ad=ss;"
		break
		
		case 'featurebar':
			thisAdType.size = "446x33"
			thisAdType.code = "ad=fb;"
		break
		
		case 'midarticleflex':
			thisAdType.code = "ad=fb;ad=bb;"
		break

		case '1x1':
			thisAdType.size = "1x1"
			thisAdType.code = "ad=onebyone;"
		break
		
		case 'tiffanytile':
			thisAdType.size = "264x120"
			thisAdType.code = "ad=tiff;"
		break
		
		case '120x60':
			thisAdType.size = "120x60"
			thisAdType.code = "ad=120x60;"
		break
		
		case 'rightflex':
			thisAdType.size = ""
			thisAdType.code = "ad=ss;ad=hp;ad=bb;"
		break
		
		case 'video':
			thisAdType.adServer = 'http://ad.doubleclick.net/pfadx/'
			thisAdType.code = "ad=video"
			thisAdType.adExecute = function (currentLoc,dcCount,what,flexBoolean)
			{
				if(typeof config == 'undefined')
				{
					config = new Array();
				}
				config['adServerURL'] = this.adServer + currentLoc + ";" + this.code + ";"  + this.dcCode
				if (location.href.indexOf('debugAdCode') != -1)
					{
						prompt("Brightcove Ad Code: ",config['adServerURL'])
					}

			}
		break

	}
	
	if (thisAdType.isThisManaged = true)
	{
	thisAdType.managerListLength = getHighestValue(thisAdType.when.length,thisAdType.where.length)
	}
	
	
return thisAdType
}

function placeAd2(currentLoc,what,flex)
{	
	//if no_ads is in the url, it bails
	if (location.href.match('no_ads'))
	{
	return
	}
	
	//if array adClasses doesn't exist, initializes it.
	if (typeof adClasses == "undefined")
	{
		adClasses = new Array()
	}

	//if the specified ad type (what) doesn't exist in the array adClasses, define it with initAdType
	
	if (typeof adClasses[what] == "undefined")
	{
		adClasses[what] = initAdType(what)
	}
	
	//if this is a doubleclick thing, iterate (or initialize) the tile number. 
	if (adClasses[what].doubleClickFlag == true)
	{
		if (typeof dcCount == 'undefined')
		{
			this.dcCount = 1
		}
		else
		{
			this.dcCount++
		}
	}
	
	//run this adtype's adExecute method, which actually does what has to be done.
	adClasses[what].adExecute(currentLoc,dcCount,what,flex)
}


//this translates from the old placeAd to the new one
function placeAd(spot,currentLoc)
{
	var transArray = new Array('','leaderboard','bigbox','120x240','skyscraper','featurebar','120x240','1x1','120x60','tiffanytile','','rightflex','rightflex','toolbar')
	flexVal=false;
	if (spot==11 || spot==12) {flexVal=true};
	placeAd2(currentLoc,transArray[spot],flexVal)
}
