
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 site has no national ads deployed.
function showNetworkBanner (iposition) {
	switch (iposition) {
	}
}
var admanagerIsAvailable = 1;