
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 used to count the number of ads that are registered in a given position.
function getAdsInTag (iposition) {
	switch(iposition) {
		case 1:
			return 1;
			break;
			case 7:
			return 1;
			break;
			case 9:
			return 1;
			break;
			case 10:
			return 2;
			break;
		
		default:
			return 0;
			break;
	}
}
// 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) {
	adDisplayed = 0;
	
	switch (iposition) {
	
		case 1:
			// This array will take up a collection of each still ad for this position. 
			aAdsForPosition1 = 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.
			aAdsForPosition1[0] = new Array('http://', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=30769&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=http%3A%2F%2F', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=30769&random=' + cacheBust() + '', 'richmedia', '<!-- JavaScript Only --><scr'+'ipt language="JavaScript1.1" src="http://altfarm.mediaplex.com/ad/js/4834-26205-6416-1?mpt=[timestamp]&mpvc="></scr'+'ipt><noscript>  <a href="http://altfarm.mediaplex.com/ad/ck/4834-26205-6416-1?mpt=[timestamp]">    <img src="http://altfarm.mediaplex.com/ad/bn/4834-26205-6416-1?mpt=[timestamp]"alt="Click Here" border="0"></a></noscript>', 30769, '590', '420');

			// Call the command that will select an ad in this position and draw it to the screen.
			pickAnAdForThisPositionAndDisplayIt(aAdsForPosition1, 1);

			// 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['1'] = new Array(aAdsForPosition1, findRotationIndex(aAdsForPosition1, 1), 0);
			
			adDisplayed=1;
			
			break;

		case 7:
			// This array will take up a collection of each still ad for this position. 
			aAdsForPosition7 = 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.
			aAdsForPosition7[0] = new Array('http://', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=39980&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=http%3A%2F%2F', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=39980&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/2ndHalf2005/y2m01.swf"/>  <param name="quality" value="high" />  <embed src="http://media.collegepublisher.com/media/Images/ads/ford/Ford/2ndHalf2005/y2m01.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="120" height="240"></embed></object>', 39980, '620', '420');

			// Call the command that will select an ad in this position and draw it to the screen.
			pickAnAdForThisPositionAndDisplayIt(aAdsForPosition7, 7);

			// 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['7'] = new Array(aAdsForPosition7, findRotationIndex(aAdsForPosition7, 7), 0);
			
			adDisplayed=1;
			
			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=49806&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=http%3A%2F%2F', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=49806&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">\n <param name="movie" value="http://media.collegepublisher.com/media/Images/ads/studyloft/banner_120x240.looping.swf">\n <param name="quality" value="high">\n <embed src="http://media.collegepublisher.com/media/Images/ads/studyloft/banner_120x240.looping.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="120" height="240"></embed>\n</object>\n', 49806, '721', '420');

			// 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);
			
			adDisplayed=1;
			
			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/Logan/BannerAd1-125x125.jpg', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=49189&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=http%3A%2F%2Fwww%2Elogan%2Eedu%2Fpages%2Fprostudent%5Freqinfo%2Easp', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=49189&random=' + cacheBust() + '', 'stillimage', '', 49189, '709', '420');
			aAdsForPosition10[1] = new Array('http://media.collegepublisher.com/media/Images/ads/USAA/120x240usaa.gif ', 'http://admanager3.collegepublisher.com/runtime/nationalClickThrough.cfm?paperBannerAdId=50312&callingSite=' + cleanBaseHref(basehref) + '&timeStamp=' + makeTimeStamp() + '&redirectURL=http%3A%2F%2Fwww%2Estudentaidaction%2Ecom', 'http://admanager3.collegepublisher.com/runtime/nationalImp.cfm?pbaid=50312&random=' + cacheBust() + '', 'stillimage', '', 50312, '727', '420');

			// 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);
			
			adDisplayed=1;
			
			break;

		}
	return adDisplayed;
}
var admanagerIsAvailable = 1;
