// --------------------------
// Cookie releated functions - taken from Jonathan Glassman's code - function names made unique to avoid collision with existing javascript
// --------------------------
function readCbsiAdCookie(name) {
//    if( document.cookie.length > 0) {
//     return false;
//    } else {
     var firstChar, lastChar;
     var theBigCookie = document.cookie;
     name = name + '=';
     firstChar = theBigCookie.indexOf(name);
     if (firstChar != -1) {
         firstChar += name.length;
         lastChar = theBigCookie.indexOf(';', firstChar);
         if(lastChar == -1) lastChar = theBigCookie.length;
         return unescape(theBigCookie.substring(firstChar, lastChar));
     } else {return false;}
//    }
}

function mCbsiAdTrack(mTrackName,mTrackMax,cName,cExpires) {

    if (arguments.length == 2) {
		var cName='mediaTrack';
	}
	
    var newExp = (cExpires) ? ';expires='+cExpires : '';
    var showAd=true;

    if (!readCbsiAdCookie(cName)) {
        newCook=mTrackName +'|' +1;
       //document.cookie=(cName +'='  + newCook +";domain=.ncaa.com;path=/" +newExp);
        document.cookie=(cName +'='  + newCook + newExp);
     }
    else if (readCbsiAdCookie(cName)) {
        oldCook = readCbsiAdCookie(cName);
        var thisAH = oldCook.indexOf(mTrackName);
        if (thisAH==-1) {
            newCook=oldCook +'|' +mTrackName +'|' +1;
            //document.cookie=(cName +'=' + newCook +";domain=.ncaa.com;path=/" +newExp);
            document.cookie=(cName +'=' + newCook + 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=.ncaa.com;path=/" +newExp );
            document.cookie=(cName +'=' + newCook + newExp );
            }
        }
    return showAd;
    }
///////////////////////////////////////////////////////////////////////////////////////////////////////
// Begin flashObj

var flashObj                            = new Object();
    flashObj.settings                   = new Object();
    flashObj.settings.objectAttributes  = ['id','width','height','style'];
    flashObj.template                   = new Object();
    flashObj.template.takeover          = { width:985, height:300, loop:'false', menu:'false', quality:'autohigh', scale:'exactfit', wmode:'opaque', id:'expandingAd', swLiveConnect:'true', name:'expandingAd', allowScriptAccess:'always' };
    flashObj.template.takeover981       = { width:981, height:300, loop:'false', menu:'false', quality:'autohigh', scale:'exactfit', wmode:'opaque', id:'expandingAd', swLiveConnect:'true', name:'expandingAd', allowScriptAccess:'always' };
    flashObj.template.takeover100       = { width:985, height:100, loop:'false', menu:'false', quality:'autohigh', scale:'exactfit', wmode:'opaque', id:'expandingAd', swLiveConnect:'true', name:'expandingAd', allowScriptAccess:'always' };
    flashObj.template.takeover981x100   = { width:981, height:100, loop:'false', menu:'false', quality:'autohigh', scale:'exactfit', wmode:'opaque', id:'expandingAd', swLiveConnect:'true', name:'expandingAd', allowScriptAccess:'always' };
    flashObj.template.basic             = { width:32, height:32, menu:'false', quality:'autohigh', wmode:'opaque' };
    flashObj.template.printable         = { width:650, height:875, loop:'false', menu:'false', quality:'autohigh', scale:'exactfit', wmode:'opaque', id:'bracket' };
    flashObj.template.viewable          = { width:875, height:650, loop:'false', menu:'false', quality:'autohigh', scale:'exactfit', wmode:'opaque', id:'bracket' };

	flashObj.display = function( swfPath, swfVersion, swfOptions, imgPath, imgObj ){
		// This is the primary function in this Object Class
		//
		// Functions
		//  1. IF swfOptions._debug is true, <textarea> tags are added before and after Output for debugging purposes.
		//  2. Attaches Template to current Operation (If Applicable)
		//	3. Decides whether FLASH or IMG will be written based on user's Supported Flash/Fash Version
		//	4. doc.writes or returns HTML depending on swfOptions._return (true/false)
		var html = '';
		if( !imgObj ) imgObj = {};
		
		// If _debug true, Open Textarea Tag
		if( swfOptions['_debug'] ) html += '<textarea style="width:985px; height:300px" wrap="off">';
		
		// Import Template
		var template = ( typeof(this.template[swfOptions._template]) == 'object' )
					? this.template[swfOptions._template]
					: this.template.basic;

		// Generate HTML or IMG
		//html += ( this.getVersion() >= swfVersion )
		if( this.isSupported( swfVersion ) ){
			// Flash/FlashVersion Supported, Processes for Flash Object/Embed Output
			html += this.outputFlash( swfPath, swfVersion, swfOptions, template );
		}else{
			if( !imgObj.height ) imgObj.height = ( !swfOptions ) ? template.height : swfOptions.height;
			if( !imgObj.width  ) imgObj.width  = ( !swfOptions ) ? template.width  : swfOptions.width ;
			html += this.outputImg( imgPath, imgObj, template );
		}
		
		// If _debug true, Close Textarea Tag
		if( swfOptions['_debug'] ) html += '</textarea>';
		
		if( swfOptions['_return'] ){
			// Returns HTML
			return html;
		}else{
			document.write(html);		// Writes HTML to DOM
			return ( this.isSupported( swfVersion ) ) ? 'flash' : 'image';	// Returns Flash/Image depending on what was written
		}
	}
	
	flashObj.outputFlash = function( swfPath, swfVersion, swfOptions, template ){
		var oAttributes = new Object(); // Object Tag Attributes
		var oParameters = new Object(); // Object Tag Parameters
		var eAttributes = new Object(); // Embed  Tag Attributes
				
		// -Over-write Template with User Specified Information
		// -For Each Property User provided in swfOptions
		//  Write Option to Template.
		for( var key in swfOptions ) if( key.substr(0,1) != '_' ) template[key] = swfOptions[key];
		
		// Static Non Changing Flash classid & codebase
		oAttributes['classid'] = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
		oAttributes['codebase'] = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+ this.objectVersionString(swfVersion);
		
		// Set Object Movie Parameter
		oParameters['movie'] = swfPath;
		
		// Set Embed Standard/Src Attributes
		eAttributes['type'] = 'application/x-shockwave-flash';
		eAttributes['pluginspage'] = 'http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash';
		eAttributes['src'] = swfPath;
		
		// Build Object/Embed Attributes based on non flash Attributes such as ID, STYLE
		//  Users flashObj.settings.objectAttributes for list of Object Attributes
		for( var index=0; index<this.settings.objectAttributes.length; index++ ){
			var templateKey = this.settings.objectAttributes[index];
			if( typeof template[templateKey] != 'undefined' ){
				oAttributes[templateKey] = template[templateKey];
				eAttributes[templateKey] = template[templateKey];
				delete template[templateKey];
			}
		}
		
		// Build Parameters and Embed
		for( var key in template ){
			oParameters[key] = template[key];
			eAttributes[key] = template[key];
		}

		// Build HTML
		var html  = '';
			// Object
			html += '<OBJECT';		// Open Object Tag
			for( var key in oAttributes ) html += '\n ' + key + '="' + oAttributes[key] + '"';	// Build Object Attributes
			html += '>';			// Close the Start Object Tag
			// Parameters
			for( var key in oParameters ) html += '\n  <PARAM NAME="' + key + '" VALUE="' + oParameters[key] + '" />';	// Build Ojbect Parameters
			// Embed
			html += '\n<EMBED';		// Open Embed Tag
			for( var key in eAttributes ) html += '\n ' + key + '="' + eAttributes[key] + '"';	// Build Embed Attributes
			html += ' />';			// Close Embed Tag
			html += '\n</OBJECT>';	// Close Object Tag
		return html;
	}
	
	flashObj.isSupported = function( swfVersion ){
		// Checks if Necessary Flash Version is Supported by browser.
		return(   this.juxtVersion( this.getVersionString() )   >=   this.juxtVersion( swfVersion )   );		
		// this.juxtVersion
		// Converts Flash Version Information whether it be (Integer, String, or Array) into a Comparable string of numbers.
	}
	
	flashObj.juxtVersion = function( version ){
		// Converts Flash Version Information whether it be (Integer, String, or Array) into a Comparable string of numbers.
		var vString = '';	// Return Variable
		
		if( typeof(version) == 'string' || typeof(version) == 'number' ){
			version = parseInt(version);
			// Convert String/Number into 3 character string. Padded by zeros
			if( version < 10 ) vString += '00'+ version;
			if( version >= 10 && version < 100 ) vString += '0'+ version;
			if( version >= 100 ) vString += version;
			vString += '000000000';
		}else if( typeof(version) == 'object' ){
			for( i=0; i<=3; i++ ){
				if( typeof(version[i]) == 'undefined' || version[i] == 0 ){
					vString += '000';
				}else{
					if( version[i] < 10 ) vString += '00'+ version[i];
					if( version[i] >= 10 && version[i] < 100 ) vString += '0'+ version[i];
					if( version[i] >= 100 ) vString += version[i];
				}
			}
		}
		return vString;
	}
	
	flashObj.objectVersionString = function( version ){
		// Converts juxtVersion String of 12 characters into an Array Object.
		var version = this.juxtVersion(version);
		var objVersion = new Array();
		var segmentCount = 0;
		var group = '';
		for( var i=0; i<version.length; i++ ){
			segmentCount ++;
			group += ( parseInt(version.substr(i,1)) )
				   ? (version.substr(i,1)+'')
				   : '';
			if( segmentCount == 3 ){
				if( !group ) group = 0;
				segmentCount = 0;
				objVersion.push( group );
				group = '';
			}
		}		
		return objVersion;
	}

	flashObj.outputImg = function( imgPath, imgObj, template ){		
		// If no imgPath Provided
		if( ! imgPath ) return '';
		
		var oImg = new Object();		// Holds Image Tag Attributes
		var oAnchor = new Object();		// Holds Anchor Tat Attributes
		var anchorFlag = false;			// Boolean: IF Any Anchor Tag Attributes Exits (true)
		
		oImg['src'] = imgPath;
		oImg['height'] = template.height;
		oImg['width'] = template.width;
		oImg['border'] = 0;
		
		// Overwrite/Build Image and Anchor Tags
		for( var key in imgObj ){			
			if( key.substr(0,1) == '_' ){
				oAnchor[key.substr(1)] = imgObj[key];
				anchorFlag = true;
			}else{
				oImg[key] = imgObj[key];
			}
		}
		
		// Build HTML
		var html = '';
		
			if( anchorFlag ){
				html += '<a';		// Open Achor Tag
				for( var key in oAnchor ) html += '\n ' + key + '="' + oAnchor[key] + '"';	// Build Anchor Attributes
				html += '>';		// Close the Start Object Tag
			}

			html += '<img';		// Open Achor Tag
			for( var key in oImg ) html += '\n ' + key + '="' + oImg[key] + '"';	// Build Anchor Attributes
			html += '/>';		// Close the Start Object Tag

			if( anchorFlag ) html += '</a>';	// Close Achor Tag
			
		return html;
	}
	
	flashObj.detectFlash = function(){
		this.detectedFlag = true;
		if(navigator.plugins && navigator.mimeTypes.length){
			// Non IE
			var x = navigator.plugins["Shockwave Flash"];
			if(x && x.description){
				//PlayerVersion = new com.deconcept.PlayerVersion();
				this.versionString = x.description.replace(/([a-z]|[A-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split(".")
				this.version = this.versionString[0];
			}			
		}else{
			// IE
			try{
				var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
				for(var i=3; axo!=null; i++){
					axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
					if (i==6){
						axo.AllowScriptAccess = "always"; // throws if player version < 6.0.47
					}
				}
			}catch(e){}
			
			if (axo != null) {
				this.version = axo.GetVariable("$version").split(" ")[1].split(',')[0];
				//this.versionString = axo.GetVariable("$version").split(" ")[1];
				this.versionString = axo.GetVariable("$version").split(' ')[1].split(',');
			}
		}
		return;
	}
	
	flashObj.getVersion = function(){
		if( ! this.detectedFlag ) this.detectFlash();
		return this.version;
	}
	
	flashObj.getVersionString = function(){
		if( ! this.detectedFlag ) this.detectFlash();
		return this.versionString;
	}

// END flashObj

///////////////////////////////////////////////////////////////////////////////////////////////////////////
// FROM Jonathan Glassman's CBSi Ad Code - modified to avoid global js function naming collisions //
//------------------------------------------------------------------------------------//
// On CBSsports.com, we have the ad set to display twice per each day-part.           //
// The day-parts are from 3am-3pm and 3pm-3am.  We set a cookie and only write the ad //
// tag when necessary. We do not serve ad impressions when the ad should not be seen. //
//------------------------------------------------------------------------------------//
/* EXCEPTION TO DENY THE AD FROM MAC/SAFARI //
var ua=navigator.userAgent;  
var FFMac = ((ua.indexOf("Mac") > 0) && ( (ua.indexOf("Firefox") > 0) ) || (ua.indexOf("Opera") > 0) ) ? 1 : 0;
if (FFMac==0){
//        document.write('YOUR AD TAG GOES HERE')  //
}*/

tracker=function(periods) {
 
     var curDate = new Date();
     var toHour24 = curDate.getUTCHours() - 5;
     if (toHour24 < 0) {
		toHour24 += 24;
	 }
 
     // determine which period is now     
     var getPeriod = function() {
           count=0;
           while (periods[count] <= toHour24) {count++;}
           return count;
     }
 
     var holder = getPeriod();
     //adjust for daypart zero
     if (holder==0) { 
		holder=2;
	 }
 
     this.currentPeriod=holder;
 
     // determine expire for current period
     var expireDate = new Date();
     expireDate.setHours(periods[this.currentPeriod]-1);
     expireDate.setMinutes(59);
     expireDate.setSeconds(59);
//alert(periods[this.currentPeriod])
        
     var msToExpire = expireDate-curDate;
     var test_lifetime=function(){
        var testExpires=new Date();
        testExpires.setTime(testExpires.getTime()+msToExpire);
		//alert(msToExpire)
		//alert(testExpires)
        return testExpires;
     }

     this.expires = test_lifetime();
     
}
 
// begin first day-part then end times of each day-part. 
// Final value must be first plus 24
var takeover=new tracker([3,15,27]);  
 
// the vTag allows specific targeting. You may not use it. You will want to include ';dpart=' +(takeover.currentPeriod); in you ad tag though.
// since that is how Ad Operations traffics for morning/night day-parts.
var vTag = 'dpart=' +(takeover.currentPeriod);
 
/* as noted, Firefox on the Pac
var ua=navigator.userAgent;  
var FFMac = ((ua.indexOf("Mac") > 0) && ( (ua.indexOf("Firefox") > 0) ) || (ua.indexOf("Opera") > 0) ) ? 1 : 0;*/
 
// at CBSSports.com, we segment the ad to either the site home page or specific sections (arenas) of the site:
// var toSegment=( ("$arena"=="other") && ("$feature"=="home") ) ? 'home' : "$arena";
var toSegment= 'home';
 
// mCbsiAdTrack is a function that lets us use the same cookie for tracking all the takeover ads in the same cookie. It will be included below.

var showTakeover=mCbsiAdTrack(toSegment,2,'toTrack',takeover.expires);
//alert("showTakeover = " + showTakeover);
//alert("toSegment = " + toSegment);
//alert("expireDate = " + expireDate);
//alert("oldCook = " + oldCook);
//alert("newCook = " + newCook);
//alert(readCbsiAdCookie());

var sportCodeUpper = schoolCode;
var sportCodeInsert = sportCodeUpper.toUpperCase();

if (showTakeover==true) {
    // construct the ad tag for your site, but be sure to pass the day-part (part of our vTag).
    procad("http://ad.doubleclick.net/adj/CSTV."+sportCodeInsert+"/FRONTPAGE;sect=frontpage;pos=;sz=981x300;dcopt=ist;",0);	
}