
secondsBeforeBannerFlip = 30; // How many seconds should we wait before flipping the ads?
var mspause = 1000 * secondsBeforeBannerFlip; // This converts the seconds to milliseconds.
var ads = new Array(); //  // Build up the arrays that contain the rotating ad information.
var aAdLinkLocations; // This will keep track of where our links are on the page that we want to manipulate.
// This will scan though the ad positions that are registered to rotate ads and call the rotation 
// function for each of them.
function flipAds() {
	// At this point, we know that "ads" is a variable which contains an entry
	// for each of the banner positions that have rotating ads.
	for (position in ads) {
		attemptFlip(position);
	}
	timerID = setTimeout("flipAds()", mspause);
}
// Pass in a number and this will return a random number between 0 and the whole integer you pass.
// This is useful for picking a random entry on an array.
function randomIndex(topRange) {
	return Math.round(Math.random()*topRange);
}

// This will instruct all compatible banner positions on the page to show
// the next banner in the rotation without refreshing the page.
function attemptFlip(position) {
	
	// Reset this variable just in case something else changed this variable.
	var aAdLinkLocations = lookUpAdLinks();
	
	// What ad is currently displayed in this position's inventory?
	// currentlyDisplayedAdIndex = ads[position][1];
	
	// Determine how many *still* images are available for this position. We'll use this when deciding whether or not we want to 
	// try to rotate below.
	numberOfStillImagesForThisPosition = 0;
	
	// Loop over each ad in this position.
	for (i=0; i < ads[position][0].length;i++) {
		adTypeInThisPosition = ads[position][0][i][3];
		if(adTypeInThisPosition == 'stillimage') {
			numberOfStillImagesForThisPosition++;
		}
	}
	
	// If there are at least 2 ads to rotate through (AND the ad tag is on the page), we'll try to flip them here...
	// Also, only flip if we have not done the entire set 3 times yet. If there were mixed advertising types (rich media and still image ads)
	// placed in this position, we'll have a rotation problem. We will only rotate to the next ad if the current one was a still image.
	// That's why we only proceed if the DOM image name is defined. In other words, when the ad that got spit out was a rich media ad, 
	// no DOM image name gets defined. When they are defined, they are named like "cpstillad1", "cpstillad2" etc.
	// Further, we can only flip if there are at least 2 still images.
	//if (ads[position][2] < 3 && ads[position][0].length > 1 && eval("typeof document.cpstillad" + position + " != 'undefined'") && numberOfStillImagesForThisPosition > 1) {
	if (ads[position][2] < 3 && eval("typeof document.cpstillad" + position + " != 'undefined'") && numberOfStillImagesForThisPosition > 1) {
		
		// We now know that there is another still image that we can rotate to. Find the "next" still image in our array.
		// If we have not reached the end of the list of ads for this position, increment the ad index we're on by 1.
		// As a reminder, "ads[position][1]" is the index of the "current" ad we're displaying in this position.
		if (ads[position][1] < ads[position][0].length-1) {
			ads[position][1]++;
		} else {
			ads[position][1] = 0;
		}
		
		// If the "next" ad we just picked above is not a still image, keep trying to find the next still image.
		while(ads[position][0][ads[position][1]][3] != 'stillimage') {
			if (ads[position][1] < ads[position][0].length-1) {
				ads[position][1]++;
			} else {
				ads[position][1] = 0;
			}
		}
		
		// Remember the fact we have iterated through this set another time.
		ads[position][2]++;
		
		// The next 3 lines will call back to the banner ad server and cache bust and allow you to count this view.
		tmpImg = new Image();
		tmpImg.src = ads[position][0][ads[position][1]][2] + cacheBust();
		eval("document.cpstillad" + position + ".src = ads[position][0][ads[position][1]][0];");
		
		// This will set the click through URL for the ad we just flipped to the appropriate click through URL.
		document.links[aAdLinkLocations[position]].href = ads[position][0][ads[position][1]][1];
	}
}

// This function will return a new number every time you call it. Good for cache busting.
function cacheBust() {
	x = new Date();
	return x.getTime() + '' + randomIndex(1000);
}
// This will start the image flipping process.
function Start() {
	Reset();
	aAdLinkLocations = lookUpAdLinks(); // This defines the ads.
	tStart   = new Date();
	timerID  = setTimeout("flipAds()", mspause);
}
// The page first needs to build before we can analyize the links so we'll start this after a few 
// seconds.
function DelayedStart() {
	Reset();// Initialize the timer.
	tStart   = new Date();
	timerID  = setTimeout("Start()", 2000);
}
function Reset() {
	// This kills the timer object.
	var timerID = 0;
	var tStart = null;
}
// In order to be able to change the click through URL's, we'll need to find the link
// index of each of the ads. This function will build an associative array of the ad link
// locations. The key is the banner position and the value is the link index on the page.
function lookUpAdLinks() {
	aLinkLocationsX = new Array();
	// Loop over each of the links on this page 
	// searching for the rotating ad positions.
	for (i=1;i<=document.links.length;i++) {
		// If this image object appears to be one of the banner positions, try to figure out which it is.
		if (typeof(document.links[i-1].name) != 'undefined' && document.links[i-1].name.indexOf('cpstilladclick') > -1) {
			aLinkLocationsX['' + document.links[i-1].name.substring(14,document.links[i-1].name.length+1)] = i-1;
		}
	}
	return aLinkLocationsX;
}
// This stops the banner rotations.
function Stop() {
   if (typeof timerID != 'undefined' && timerID) {
      clearTimeout(timerID);
      timerID  = 0;
   }
   tStart = null;
}
// Takes a url like "http://www.example.com:81/" and returns "www.example.com:81"
function cleanBaseHref(baseHrefIn){ 
	baseHrefOut = baseHrefIn;
	baseHrefOut =  replaceSubstring(baseHrefOut, "http://", "");
	baseHrefOut =  replaceSubstring(baseHrefOut, "/", "");	
	return escape(baseHrefOut);
}	
function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function
// Pass an array of ads to this function and the SRC of the ad currently running. This function
// will find the index of the current ad..
function findRotationIndex(aAds, position) {
	if (aAds.length == 0 || aAds.length == 1 || eval("typeof document.cpstillad" + position + " == 'undefined'")) {
		return 0;
	} else {
		chosenIndex = null;
		// Find the index of the currently displayed ad.
		for (i=0;i<aAds.length;i++) {
			if (aAds[i][0] == eval("document.cpstillad" + position + ".src")) {
				chosenIndex = i;
				break;
			}
		}
		return chosenIndex;
	}
}
// This will start the rotations after a small amount of time passes.
DelayedStart();

// Resolves timestamp variable in addition to resolving values for all of the other optional values that you pass after richmedia.
function resolveSimpleVars(richmedia, redirectURL, ibanner_ad_id, ipaper_id) {
	argv = resolveSimpleVars.arguments;
	argc = resolveSimpleVars.arguments.length;
	redirectURL = (argc > 1) ? argv[1] : '';
	ibanner_ad_id = (argc >2) ? argv[2] : '';
	ipaper_id = (argc >3) ? argv[3] : '';
	stringout = richmedia; // This input param is the only required input. If you don't pass the other optional values, they won't get resolved.
	
	basicClickThrough = redirectURL;
	
	stringout = replaceSubstring(stringout, "[BAS-CLICKTHROUGH]", escape(basicClickThrough));
	stringout = replaceSubstring(stringout, "[BAS-CLICKTHROUGH-PLAIN]", basicClickThrough);
	stringout = replaceSubstring(stringout, "[BAS-FLASHCLICKTHROUGH]", replaceSubstring(basicClickThrough, "&", "!"));
	stringout = replaceSubstring(stringout, "[ID]", ibanner_ad_id);
	stringout = replaceSubstring(stringout, "[paperid]", ipaper_id);
	stringout = replaceSubstring(stringout, "[timestamp]", makeTimeStamp());
	return stringout;
}

function makeTimeStamp() {
	pcdateobject=new Date();
	timestamp=pcdateobject.getTime();
	return timestamp.toString();
}

// Pick a banner ad that should be running for the given position. This will randomly pick one out of the array.
// It will output plain <IMG> tags for plain image display or output direct rich media source code.
function pickAnAdForThisPositionAndDisplayIt(aAdsForPosition, position) {
	 indexOfBannerToStartWith = randomIndex(aAdsForPosition.length-1);
	 chosenBanner = aAdsForPosition[indexOfBannerToStartWith];
	 stillCreative = chosenBanner[0];
	 clickThrough = chosenBanner[1];
	 impressionLink = chosenBanner[2];
	 type = chosenBanner[3];
	 richmediacode = chosenBanner[4];
	 pbaid = chosenBanner[5];
	 ibanner_ad_id = chosenBanner[6];
	 ipaper_id = chosenBanner[7];
	if (type == 'stillimage') {
	 	document.write('<img src="http://media.collegepublisher.com/media/images/blank.gif" border="0" height="2"><br>');
		document.write('<a href="' + resolveSimpleVars(clickThrough, clickThrough, ibanner_ad_id, ipaper_id) + '" target="_blank" name="cpstilladclick' + position + '"><img src="' + resolveSimpleVars(stillCreative, clickThrough, ibanner_ad_id, ipaper_id) + '" border="0" name="cpstillad' + position + '"></a>');
		document.write('<br><img src="http://media.collegepublisher.com/media/images/blank.gif" border="0" height="2"><br>');
	} else {
		document.write(resolveSimpleVars(richmediacode, clickThrough, ibanner_ad_id, ipaper_id));
		//resolveSimpleVars(richmediacode, paperBannerAdId, redirectURL, ibanner_ad_id, ipaper_id)
	}
	
	// Increment the impressions counter for this ad. 
	newimageobject = new Image();
	eval('impressionIMG' + position + '= newimageobject');
	eval('impressionIMG' + position + '.src = "http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=' + pbaid + '&random=" + cacheBust()');
	
}
		
// This function is is called directly by the newspaper website. A number is passed into this function which represents
// which national ad position the front end needs an advertisement for.
function showNetworkBanner (iposition) {
	switch (iposition) {
	
		case 6:
			// This array will take up a collection of each still ad for this position. 
			aAdsForPosition6 = new Array();

			//Each array added below will contain STILL CREATIVE,STILL CLICKTHROUGH, IMPRESSION LINK, TYPE (richmedia|still), RICHMEDIA CODE, IBANNER_AD_ID, ipaper_id in that order.
			aAdsForPosition6[0] = new Array('http://', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=30591&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=http%3A%2F%2F', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=30591&random=' + cacheBust() + '', 'richmedia', '<!-- JavaScript Only --><scr'+'ipt language="JavaScript1.1" src="http://altfarm.mediaplex.com/ad/js/4834-26205-6416-0?mpt=[timestamp]&mpvc="></scr'+'ipt><noscript>  <a href="http://altfarm.mediaplex.com/ad/ck/4834-26205-6416-0?mpt=[timestamp]">    <img src="http://altfarm.mediaplex.com/ad/bn/4834-26205-6416-0?mpt=[timestamp]"alt="Click Here" border="0"></a></noscript>', 30591, '589', '660');

			// Call the command that will select an ad in this position and draw it to the screen.
			pickAnAdForThisPositionAndDisplayIt(aAdsForPosition6, 6);

			// The array we register in the 'ads' array contains the following items on each index:
			// [0] - The array of ads for this position number
			// [1] - The index of the ad that we will *begin* the rotation with. It is a stateful way of remember the current ad in this position.
			// [2] - A zero. This becomes a counter for how many times we've rotated ads in this position.
			ads['6'] = new Array(aAdsForPosition6, findRotationIndex(aAdsForPosition6, 6), 0);
			
			break;

		case 8:
			// This array will take up a collection of each still ad for this position. 
			aAdsForPosition8 = new Array();

			//Each array added below will contain STILL CREATIVE,STILL CLICKTHROUGH, IMPRESSION LINK, TYPE (richmedia|still), RICHMEDIA CODE, IBANNER_AD_ID, ipaper_id in that order.
			aAdsForPosition8[0] = new Array('http://media.collegepublisher.com/media/ncbar/ads/STAtravel2.swf?v9', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=29454&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=main%2Ecfm%3Finclude%3DviewChannel%26channel%5Fid%3D59', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=29454&random=' + cacheBust() + '', 'stillimage', '', 29454, '565', '660');

			// Call the command that will select an ad in this position and draw it to the screen.
			pickAnAdForThisPositionAndDisplayIt(aAdsForPosition8, 8);

			// The array we register in the 'ads' array contains the following items on each index:
			// [0] - The array of ads for this position number
			// [1] - The index of the ad that we will *begin* the rotation with. It is a stateful way of remember the current ad in this position.
			// [2] - A zero. This becomes a counter for how many times we've rotated ads in this position.
			ads['8'] = new Array(aAdsForPosition8, findRotationIndex(aAdsForPosition8, 8), 0);
			
			break;

		case 9:
			// This array will take up a collection of each still ad for this position. 
			aAdsForPosition9 = new Array();

			//Each array added below will contain STILL CREATIVE,STILL CLICKTHROUGH, IMPRESSION LINK, TYPE (richmedia|still), RICHMEDIA CODE, IBANNER_AD_ID, ipaper_id in that order.
			aAdsForPosition9[0] = new Array('http://', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=34600&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=http%3A%2F%2Fwww%2Elglifeisgood%2Ecom', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=34600&random=' + cacheBust() + '', 'richmedia', '<OBJECT classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0 ID=FLASH_AD WIDTH=120 HEIGHT=240><PARAM NAME=movie VALUE=http://media.collegepublisher.com/media/Images/ads/LG/LG-SH2-120x240-revised2.swf?clickthrough=[BAS-FLASHCLICKTHROUGH]> <PARAM NAME=bgcolor VALUE=#FFFFFF> <PARAM NAME=quality VALUE=autohigh> <embed src=http://media.collegepublisher.com/media/Images/ads/LG/LG-SH2-120x240-revised2.swf?clickthrough=[BAS-FLASHCLICKTHROUGH] quality=high bgcolor=#FFFFFF pluginspage=http://www.macromedia.com/go/getflashplayer type=application/x-shockwave-flash width=120 height=240 salign=tl menu=0> </embed> </OBJECT>', 34600, '606', '660');

			// Call the command that will select an ad in this position and draw it to the screen.
			pickAnAdForThisPositionAndDisplayIt(aAdsForPosition9, 9);

			// The array we register in the 'ads' array contains the following items on each index:
			// [0] - The array of ads for this position number
			// [1] - The index of the ad that we will *begin* the rotation with. It is a stateful way of remember the current ad in this position.
			// [2] - A zero. This becomes a counter for how many times we've rotated ads in this position.
			ads['9'] = new Array(aAdsForPosition9, findRotationIndex(aAdsForPosition9, 9), 0);
			
			break;

		case 10:
			// This array will take up a collection of each still ad for this position. 
			aAdsForPosition10 = new Array();

			//Each array added below will contain STILL CREATIVE,STILL CLICKTHROUGH, IMPRESSION LINK, TYPE (richmedia|still), RICHMEDIA CODE, IBANNER_AD_ID, ipaper_id in that order.
			aAdsForPosition10[0] = new Array('http://media.collegepublisher.com/media/Images/ads/brokescholar/scholarshipchannel120x240.gif', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=34479&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=http%3A%2F%2Fbrokescholar%2Ecom', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=34479&random=' + cacheBust() + '', 'stillimage', '', 34479, '605', '660');
			aAdsForPosition10[1] = new Array('http://media.collegepublisher.com/media/Images/ads/SLCP/ratealert120x240.gif', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=34156&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=http%3A%2F%2Fwww%2Eslcp%2Ecom%2Findex%2Ecfm%3FCMP%3DBAC%2DX2K469914436', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=34156&random=' + cacheBust() + '', 'stillimage', '', 34156, '604', '660');
			aAdsForPosition10[2] = new Array('http://media.collegepublisher.com/media/images/ads/statravel/120x240_travelchannel.gif', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=33520&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=http%3A%2F%2F%5BcallingSite%5D%2Fmain%2Ecfm%3Finclude%3DviewChannel%26channel%5Fid%3D59', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=33520&random=' + cacheBust() + '', 'stillimage', '', 33520, '601', '660');
			aAdsForPosition10[3] = new Array('http://', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=33837&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=33837&random=' + cacheBust() + '', 'richmedia', '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="120" height="240">  <param name="movie" value="http://media.collegepublisher.com/media/Images/ads/ford/Ford/1stHalf2005/y2m02.swf"/>  <param name="quality" value="high" />  <embed src="http://media.collegepublisher.com/media/Images/ads/ford/Ford/1stHalf2005/y2m02.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="120" height="240"></embed></object>', 33837, '602', '660');

			// Call the command that will select an ad in this position and draw it to the screen.
			pickAnAdForThisPositionAndDisplayIt(aAdsForPosition10, 10);

			// The array we register in the 'ads' array contains the following items on each index:
			// [0] - The array of ads for this position number
			// [1] - The index of the ad that we will *begin* the rotation with. It is a stateful way of remember the current ad in this position.
			// [2] - A zero. This becomes a counter for how many times we've rotated ads in this position.
			ads['10'] = new Array(aAdsForPosition10, findRotationIndex(aAdsForPosition10, 10), 0);
			
			break;

		}
}
var admanagerIsAvailable = 1;