var cnnad_tileID = cnnad_getID();
var cnnad_enabled = true;
var cnnad_adIframes = new Array();
// browser detection
var cnnad_IE = (document.all) ? 1 : 0;
var cnnad_DOM = (document.getElementById) ? 1 : 0;
var cnnad_NS4 = (document.layers) ? 1 : 0;
var cnnad_MAC = ( (navigator.appVersion.indexOf("PPC") >0) || (navigator.appVersion.indexOf("Mac") >0) ) ? 1 : 0;
var cnnad_ua = '$User_Agent';
var cnnad_OPERA = (cnnad_ua.indexOf("Opera") > 0) ? 1 : 0;

// flag for geo targetting image
alreadySwappedDETargetImage = false;
var cnnDEadDEonCookie = false;

// document domain security issues
var cnnDocDomain = cnnad_getTld(location.hostname);
if(cnnDocDomain) {document.domain = cnnDocDomain;}

function reverseString (input)
{
	// convert everything to a string
	input = "" + input;
	var output = '';

	if (input.length)
	{
		var i;
		for (i = input.length; i > 0; i--)
		{
			output += input.charAt(i-1);
		}
	}
	return(output);
}

function cnnad_getID() {
	return (reverseString(new Date().getTime()));
}

function cnnad_renderAd(cnnad_url) {
	if(cnnad_enabled == true) {
		document.write("<script type=\"text/javascript\"");
		document.write(" src=\""+cnnad_url+"&tile="+cnnad_tileID+"\"></scr");
		document.write("ipt>");
	}
}

function cnnad_preview(cnnad_adstring) {
	if ( location.host.indexOf("turner.com") > -1) {
		// we are on preview (or on local subnet, so we have to use internal names)
		cnnad_adstring = cnnad_adstring.replace(new RegExp("ads\..*?\.com","gi"),"ads.turner.com");
	}
	return cnnad_adstring;
}

function cnnad_createAdNoTileId(adId,cnnad_url,cnnad_height,cnnad_width) {
	cnnad_url = cnnad_preview(cnnad_url);
	document.write('<iframe ALLOWTRANSPARENCY="true" hspace="0" vspace="0" marginHeight="0" marginWidth="0" src="' + cnnad_url + '&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_createAdTransNoTileId(adId,cnnad_url,cnnad_height,cnnad_width) {
	cnnad_url = cnnad_preview(cnnad_url);
	document.write('<iframe ALLOWTRANSPARENCY="true" hspace="0" vspace="0" marginHeight="0" marginWidth="0" src="' + cnnad_url + '&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_createAd(adId,cnnad_url,cnnad_height,cnnad_width) {
	cnnad_url = cnnad_preview(cnnad_url);
	document.write('<iframe ALLOWTRANSPARENCY="true" 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_createAdTrans(adId,cnnad_url,cnnad_height,cnnad_width) {
	cnnad_url = cnnad_preview(cnnad_url);
	document.write('<iframe ALLOWTRANSPARENCY="true" 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_createAdCompanion(adId, url, height, width, tileId) {
	url = cnnad_preview(url);
	document.write('<iframe ALLOWTRANSPARENCY="true" hspace="0" vspace="0" marginHeight="0" marginWidth="0" src="' + url + '&tile=' + 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;
        }
}

function cnnad_readCookie( name ) {
        if ( document.cookie == '' ) { // there is 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;
                }
        }
}

function cnnad_getTld (hostname)
{
	var data = hostname.split(".");
	if (data.length >= 2)
	{
		return (data[data.length-2] + "." + data[data.length-1]);
	}
	return(null);
}

function cnnad_refreshAds ()
{
    if (! cnnad_adIframes)
    {
        return;
    }

    for (var i = 0; i < cnnad_adIframes.length; i++)
    {
        var cnnad_id = cnnad_adIframes[i];
        if (document.getElementById(cnnad_id))
        {
            var elem = document.getElementById(cnnad_id);
            if (elem.width > 0 && elem.height > 0)
            {
                elem.contentWindow.location.reload();
            }
        }
    }
}

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_psuedoGetElementById(elm,d) { 
    var p,i,x; if(!d) d=document; if((p=elm.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; elm=elm.substring(0,p);
        }
    if(!(x=d[elm])&&d.all) x=d.all[elm]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][elm];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=document.getElementById(elm,d.layers[i].document);
    return x;
}
	
function cnnad_getCoordinates(obj) {
    var point = { x: 0, y: 0 };
    while(obj) {
        point.x += obj.offsetLeft;
        point.y += obj.offsetTop;
        obj = obj.offsetParent;
        }
    return point;
}

function cnnad_whereami(anchorid) {
    var locarr = new Array();
    if(cnnad_NS4) {
        if (document.anchors[anchorid]){
            locarr[0] = document.anchors[anchorid].x;
            locarr[1] = document.anchors[anchorid].y;
            }
        }
    else if(cnnad_DOM) {
        var myanchor = document.getElementById(anchorid);
        var coordinates = cnnad_getCoordinates(myanchor)
        if (myanchor){
            locarr[0] = coordinates.x;
            locarr[1] = coordinates.y;
            }
        }
    else {
	var myanchor = cnnad_psuedoGetElementById(anchorid);
    var coordinates = cnnad_getCoordinates(myanchor)
    if(myanchor.offsetLeft&&myanchor.offsetTop){
        locarr[0] = coordinates.x;
        locarr[1] = coordinates.y;
        }
    }
	return locarr;
}

function cnnad_mTrack(mTrackName,mTrackMax,cName,cExpires) {
	// function for storing float ad views per user, one cookie for all ad spaces.  
  if (arguments.length == 2) {var cName='mediaTrack';}
    var newExp = (cExpires) ? ';expires='+cExpires : '';

    var showAd=true;
    if (!cnnad_readCookie(cName)) {
        newCook=mTrackName +'|' +1;
        document.cookie=(cName +'='  + newCook +";domain=" +cnnDocDomain +";path=/" +newExp);
    	}
    else if (cnnad_readCookie(cName)) {
        oldCook = cnnad_readCookie(cName);
        var thisAH = oldCook.indexOf(mTrackName);
        if (thisAH==-1) {
            newCook=oldCook +'|' +mTrackName +'|' +1;
            document.cookie=(cName +'=' + newCook +";domain=" +cnnDocDomain +";path=/" +newExp);
            }
        else {
            var splitCook = oldCook.split('|');
            var cookPlus; var plusOne;
            for (i=0; i < splitCook.length; i+=2 ) {
                plusOne = i+1;
                if (splitCook[i]==mTrackName) {
                    cookPlus = parseInt(splitCook[plusOne])+1;
                    splitCook[plusOne]=cookPlus;
                    if (cookPlus > mTrackMax) showAd = false;
                    }
                }
            newCook="";
            for (var j=0; j < splitCook.length-1; j+=2) {
                newCook += splitCook[j] + '|' +splitCook[j+1];
                if (j+2 < splitCook.length) {newCook += '|';}
                }
            document.cookie=(cName +'=' + newCook +";domain=" +cnnDocDomain +";path=/" +newExp );
            }
        }
    return showAd;
}

function cnnad_showActiveHeader (numViews, cName, swfFile, clickThrough, flashVersion, left, top) {
	// BEGIN variables
	var domain = ".pgatour.com";
	var ahY=0;
	left = (left ? left : 0);
	top  = (top ? top : 0);
	var hdrPosition = cnnad_whereami('hdr_anchor'); 
	ahY = parseInt(hdrPosition[1]);
	flashVersion = ( flashVersion ? flashVersion : 6 );
	var showHdr = cnnad_mTrack(cName,numViews);
	var writeMe = "";
	var cnnad_hasFlash = detectFlash();
	var cnnad_plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
	if (cnnad_plugin)
	{
		cnnad_plugin = parseInt(cnnad_plugin.description.substring(cnnad_plugin.description.indexOf(".")-1)) >= flashVersion;
		
	}
	else if ( navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 
	   && (navigator.userAgent.indexOf("Windows 95")>=0 || navigator.userAgent.indexOf("Windows 98")>=0 || navigator.userAgent.indexOf("Windows NT")>=0)) {
		writeMe='<SCRIPT LANGUAGE=VBScript\> \n'
	    +'on error resume next \n'
	    +'cnnad_plugin = ( IsObject(CreateObject(\"ShockwaveFlash.ShockwaveFlash.' + flashVersion +'\")))\n'
	    +'<\/SCRIPT\> \n';
	    document.write(writeMe);
	    }
//	if (IE && !MAC && cnnad_plugin && showHdr) {
	if (IE && !MAC && cnnad_hasFlash && showHdr) {		
		//  top:' + (ahY+23)
	    writeMe='<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'
	    +' codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' +flashVersion +',0,0,0\" '
	    +' STYLE="position: absolute; left:' + left + '; top:' + top +';z-index:3;" '
	    +' ID=act_header WIDTH=985 HEIGHT=100>'
	    +' <PARAM NAME=movie VALUE=\"' + swfFile + '?clickTag=' + clickThrough + '\"><PARAM NAME=loop VALUE=false><PARAM NAME=menu VALUE=true><PARAM NAME=quality VALUE=autohigh><PARAM NAME=scale VALUE=exactfit><PARAM NAME=wmode VALUE=transparent><PARAM NAME=bgcolor VALUE=#FFFFFF> '
	    +' </OBJECT>';
	    document.write(writeMe);
	    }
}

function detectFlash() {
	pluginFound = detectPlugin( 'Shockwave', 'Flash' );
	// if not found, try to detect with VisualBasic
	if ( !pluginFound && detectableWithVB ) {
		pluginFound = detectActiveXControl( 'ShockwaveFlash.ShockwaveFlash.1' );
	}
	return pluginFound;
}

function getShockwaveVersion() {
  // Set local variables to avoid crashing bug
  var thearray = navigator.plugins;
  var arraylength = thearray.length;
  for (i=0; i<arraylength; i++)
  {
    theplugin = thearray[i];
    // Retrieve the plugin
    thename   = theplugin.name;
    // Get the plugin name
    thedesc   = theplugin.description;
    // Get the plugin description
      // If the plugin is the Shockwave Player...
      if (thedesc.indexOf("Shockwave")
        != -1 && thedesc.indexOf("Director") != -1)
        { 
        // ...parse out the version...
        versionString = thedesc.substring(thedesc.indexOf("version ") + 8);
        // ...pet the major version...
        majorVersion = parseInt(versionString);
        // ...and return it.
        return majorVersion;
        } 
   }
   // If we've went through the whole list of plugins without
   // finding Shockwave, we return zero.
   return 0;
}

