var cnnad_tileID = cnnad_getID();
var cnnad_enabled = true;
function cnnad_getID() {
	return (new Date().getTime());
}

//ADM send functionality
//pagemodes - 1(all tags) - DM_cat(), DM_addToLoc(), DM_tag();
//pagemodes - 2(health) -  DM_tag();
//pagemodes - 3(none);
var cnnad_pageMode = 1;
var cnnad_calledURLs = new Array(); //associative array
var cnnad_successfulSend = 0;
var cnnad_resultArray = new Array();

function cnnad_sendADMData() {
	var cnnad_ADMSizes = new Array();
	var finalExpression = "";
	cnnad_ADMSizes = ["728x90","300x250","336x280","160x600","234x60","125x125"];

	for(as=0;as<cnnad_ADMSizes.length;as++){
		var calledURL = cnnad_calledURLs[cnnad_ADMSizes[as]];

		if(calledURL && cnnad_successfulSend == 0){

			if(cnnad_pageMode != 3){
				finalExpression += '<scr' + 'ipt> \n ';
				if(cnnad_pageMode == 1){
					finalExpression += '	A09801.DM_cat("';
					var site = cnnad_getParamValue(calledURL, "site=","&");
					var rollup = cnnad_getParamValue(calledURL, "_rollup=","&");
					var section = cnnad_getParamValue(calledURL, "_section=","&");
					var subsection = cnnad_getParamValue(calledURL, "_subsection=","&");

					finalExpression += site;
					if((site!="") && ((rollup!="") || (section!="") || (subsection!=""))){
						finalExpression += " > ";
					}
					finalExpression += rollup;
					if((rollup!="") && ((section!="") || (subsection!=""))){
						finalExpression += " > ";
					}
					finalExpression += section;
					if((section!="") && (subsection!="")){
						finalExpression += " > ";
					}
					finalExpression += subsection;
					finalExpression += '"); \n ';
					finalExpression += '	A09801.DM_addEncToLoc(); \n ';
				}
				finalExpression += '	A09801.DM_tag(); \n ';
				finalExpression += '</scr' + 'ipt> \n ';



				document.write(finalExpression);

			}

			cnnad_successfulSend = 1;
			break;
		}
	}
}


function cnnad_getParamValue(paramString, parameter, endCharacter){
	if(paramString.match(parameter)){
		var startOfString = paramString.indexOf(parameter)+parameter.length;
		var endOfString = paramString.indexOf(endCharacter,startOfString);
	 	var parameterValue = paramString.substring(startOfString,endOfString);
	 	return parameterValue;
	 }
	 else{
	 	return "";
	 }
}
// end ADM send functionality


function cnnad_renderAd(cnnad_url) {
// this function is deprecated in failsafe ads solution. -sg
	if(cnnad_enabled == true) {
		document.write("<script type=\"text/javascript\"");
		document.write(" src=\""+cnnad_url+"&tile="+cnnad_tileID+"\"></scr");
		document.write("ipt>");
	}
	// ADM functionality
		var adSize = new String();

		if(cnnad_url.match("_position=") ){
			adSize = cnnad_getParamValue(cnnad_url, "_position=", "_");
		}
		else if(cnnad_url.match("_pos=")){
			adSize = cnnad_getParamValue(cnnad_url, "_pos=", "_");
		}
		else {
			adSize = "";
		}

		cnnad_calledURLs[adSize] = cnnad_url;
	// END ADM functionality

}

function cnnad_createAd(adId,cnnad_url,cnnad_height,cnnad_width) {
	document.write('<iframe hspace="0" vspace="0" marginHeight="0" marginWidth="0" src="' + cnnad_url + '&tile=' + cnnad_tileID + '&page.allowcompete=yes&domId=' + adId + '" border="0" frameBorder="0" height="0" width="0" scrolling="no"  id="'+adId+'" style="position: absolute; visibility: hidden;" ></iframe>');
}

function cnnad_writeAd(cnnad_callid,cnnad_url) {
        if(cnnad_enabled == true) {
                document.write("<script id=\"" + cnnad_callid + "\" type=\"text/javascript\" onload=\"cnnSendData();\"");
                document.write(" src=\""+cnnad_url+"&tile="+cnnad_tileID+"\"></scr");
                document.write("ipt>");
        }
}

function cnnad_showAd(cnnad_id) {
	if (document.getElementById(cnnad_id))
	{
		document.getElementById(cnnad_id).style.position = 'relative';
		document.getElementById(cnnad_id).style.visibility = 'visible';
	} else
	{
		//alert("Error displaying ad component: " + cnnad_id);
		// just do not display the ad. -sg
	}
}


function cnnad_setAdSize(docId,height,width) {
        if (document.getElementById(docId)) {
                document.getElementById(docId).height = height;
                document.getElementById(docId).width = width;
        }
}


//-- the following migrated from the include

function CNN_getCookies() {
	var hash = new Array;
	if ( document.cookie ) {
		var cookies = document.cookie.split( '; ' );
		for ( var i = 0; i < cookies.length; i++ ) {
			var namevaluePairs = cookies[i].split( '=' );
			hash[namevaluePairs[0]] = unescape( namevaluePairs[1] ) || null;
		}
	}
	return hash;
}

function CNN_parseCookieData( cookieDataString ) {
	var cookieValues = new Object();
	var separatePairs = cookieDataString.split( '&' );
	for ( var i = 0; i < separatePairs.length; i++  ) {
		var separateValues = separatePairs[i].split( ':' );
		cookieValues[separateValues[0]] = separateValues[1] || null;
	}
	return cookieValues;
}

function getAdHeadCookie( imageRef ) {
	//alert( "isClassAndOffsetValid=" + isClassAndOffsetValid + "\nadHeadOffset=" + adHeadOffset + "\nadHeadClass=" + adHeadClass);
	var newSrc = "http://cnn.dyn.cnn.com/1.gif?" + new Date().getTime();
	if ( !alreadySwappedTargetImage && !isClassAndOffsetValid && WM_browserAcceptsCookies() ) {
		//alert( "getAdHeadCookie\nalreadySwappedTargetImage=" + alreadySwappedTargetImage + "\nisClassAndOffsetValid=" + isClassAndOffsetValid );
		imageRef.src = newSrc;
		alreadySwappedTargetImage = true;
	}
}

function getDEAdHeadCookie( imageRef ) {
	if (typeof(WM_readCookie) != "undefined") {
		cnnDEadDEonCookie = WM_readCookie( 'adDEon' );
	}
	var newSrc = "http://gdyn.cnn.com/1.1/1.gif?" + new Date().getTime();
	if ( !alreadySwappedDETargetImage && !cnnDEadDEonCookie) {
		imageRef.src = newSrc;
		alreadySwappedDETargetImage = true;
	}
}


function cnnad_getDEAdHeadCookie( imageRef ) {
	if (typeof(cnnad_readCookie) != "undefined") {
		cnnDEadDEonCookie = cnnad_readCookie( 'adDEon' );
	}
	var newSrc = "http://gdyn." + cnnad_getTld(location.hostname) + "/1.1/1.gif?" + new Date().getTime();
	if ( !alreadySwappedDETargetImage && !cnnDEadDEonCookie) {
		imageRef.src = newSrc;
		alreadySwappedDETargetImage = true;
	}
}

function cnnad_getTld (hostname)
{
	var data = hostname.split(".");
	if (data.length >= 2)
	{
		return (data[data.length-2] + "." + data[data.length-1]);
	}
	return(null);
}

// This next little bit of code tests whether the user accepts cookies.
function WM_browserAcceptsCookies() {
	var WM_acceptsCookies = false;
	if ( document.cookie == '' ) {
		document.cookie = 'WM_acceptsCookies=yes'; // Try to set a cookie.
		if ( document.cookie.indexOf( 'WM_acceptsCookies=yes' ) != -1 ) {
			WM_acceptsCookies = true;
		} // If it succeeds, set variable
	} else { // there was already a cookie
		WM_acceptsCookies = true;
	}

	return ( WM_acceptsCookies );
}

function WM_setCookie( name, value, hours, path, domain, secure ) {
	if ( WM_browserAcceptsCookies() ) { // Don't waste your time if the browser doesn't accept cookies.
		var numHours = 0;
		var not_NN2 = ( navigator && navigator.appName
					&& (navigator.appName == 'Netscape')
					&& navigator.appVersion
					&& (parseInt(navigator.appVersion) == 2) ) ? false : true;

		if ( hours && not_NN2 ) { // NN2 cannot handle Dates, so skip this part
			if ( (typeof(hours) == 'string') && Date.parse(hours) ) { // already a Date string
				numHours = hours;
			} else if ( typeof(hours) == 'number' ) { // calculate Date from number of hours
				numHours = ( new Date((new Date()).getTime() + hours*3600000) ).toGMTString();
			}
		}

		document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'') + ((secure && (secure == true))?'; secure':''); // Set the cookie, adding any parameters that were specified.
	}
} // WM_setCookie

function WM_readCookie( name ) {
	if ( document.cookie == '' ) { // there's no cookie, so go no further
	    return false;
	} else { // there is a cookie
	    var firstChar, lastChar;
		var theBigCookie = document.cookie;
		firstChar = theBigCookie.indexOf(name);	// find the start of 'name'
		var NN2Hack = firstChar + name.length;
		if ( (firstChar != -1) && (theBigCookie.charAt(NN2Hack) == '=') ) { // if you found the cookie
			firstChar += name.length + 1; // skip 'name' and '='
			lastChar = theBigCookie.indexOf(';', firstChar); // Find the end of the value string (i.e. the next ';').
			if (lastChar == -1) lastChar = theBigCookie.length;
			return unescape( theBigCookie.substring(firstChar, lastChar) );
		} else { // If there was no cookie of that name, return false.
			return false;
		}
	}
} // WM_readCookie

function WM_killCookie( name, path, domain ) {
	var theValue = WM_readCookie( name ); // We need the value to kill the cookie
	if ( theValue ) {
		document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:''); // set an already-expired cookie
	}
} // WM_killCookie
