
secondsBeforeBannerFlip_local = 45; // How many seconds should we wait before flipping the ads?
var mspause_local = 1000 * secondsBeforeBannerFlip_local; // This converts the seconds to milliseconds.
var ads_local = new Array(); //  // Build up the arrays that contain the rotating ad information.
var aAdLinkLocations_local; // 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_local() {
	// 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_local in ads_local) {
		// Ever since we integrated the web 2.0 libraries, the generic handling on js objects has changed.
		// At this stage in the code, we need to see if the associative array is numeric.
		if (isNumeric(position_local)) {
			attemptFlip_local(position_local);
		}		
	}
	timerID_local = setTimeout("flipAds_local()", mspause_local);
}

function isNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }

// 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_local(topRange_local) {
	return Math.round(Math.random()*topRange_local);
}
// This will tell you if a given ad is allowed to display on the page.
// Pass in an array containing sections where this ad can run.
// This function will check the js enviornment for a section name
// variable and inform you as to whether or not this ad can appear
// on this page.
// Returns true or false.
function adCanAppearInThisSection_local(asectionrestrictions_local) {
	canappear_local = false;
	
	if (asectionrestrictions_local.length == 0) {
		canappear_local = true;
	} else if (asectionrestrictions_local.length > 0 && typeof isectioncategoryid != 'undefined') {
		thissectionname_local = isectioncategoryid;
		// Loop over each section name passed.
		for(i_local=0;i_local<asectionrestrictions_local.length;i_local++) {
			thistestsection_local = asectionrestrictions_local[i_local];
			if (thissectionname_local.indexOf(thistestsection_local + ',')>-1) {
				canappear_local = true;
			}
		}
	
	} else {
		canappear_local = false;
	}
	return canappear_local;
}

function frontpagerequirementspass_local(bfrontpageonly_local) {
	if (bfrontpageonly_local == 0) {
		return true;
	} else {
		theloc_local = document.URL;
		// If this is the front page, return true; 
		 if(theloc_local.match(/^http(?:s|)\:\/\/(?:media\.|)(?:www|[a-zA-Z_0-9\-]+?)\.[a-zA-Z_0-9\-]+?\.\w{2,3}\/??(?:home)*?\/??(?:index\.cfm)*?$/)){
		    return true;
		} else {
		    return false;
		}
	}
}

// This will instruct all compatible banner positions on the page to show
// the next banner in the rotation without refreshing the page.
function attemptFlip_local(position_local) {
	
	// Reset this variable just in case something else changed this variable.
	var aAdLinkLocations_local = lookUpAdLinks_local();
	
	// 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_local = 0;
	
	// Loop over each ad in this position.
	for (i_local=0; i_local < ads_local[position_local][0].length;i_local++) {
		adTypeInThisPosition_local = ads_local[position_local][0][i_local][3];
		if(adTypeInThisPosition_local == 'stillimage') {
			numberOfStillImagesForThisPosition_local++;
		}
	}
	
	
	if (ads_local[position_local][2] < 1 && eval("typeof document.cpstillad" + position_local + "local != 'undefined'") && numberOfStillImagesForThisPosition_local > 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_local[position_local][1] < ads_local[position_local][0].length-1) {
			ads_local[position_local][1]++;
		} else {
			ads_local[position_local][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_local[position_local][0][ads_local[position_local][1]][3] != 'stillimage') {
			if (ads_local[position_local][1] < ads_local[position_local][0].length-1) {
				ads_local[position_local][1]++;
			} else {
				ads_local[position_local][1] = 0;
			}
		}
		
		// Remember the fact we have iterated through this set another time.
		ads_local[position_local][2]++;
		
		// The next 3 lines will call back to the banner ad server and cache bust and allow you to count this view.
		tmpImg_local = new Image();
		tmpImg_local.src = ads_local[position_local][0][ads_local[position_local][1]][2] + cacheBust_local();
		eval("document.cpstillad" + position_local + "local.src = ads_local[position_local][0][ads_local[position_local][1]][0];");
		
		// This will set the click through URL for the ad we just flipped to the appropriate click through URL.
		document.links[aAdLinkLocations_local[position_local]].href = ads_local[position_local][0][ads_local[position_local][1]][1];
	}
}

// This function will return a new number every time you call it. Good for cache busting.
function cacheBust_local() {
	x_local = new Date();
	return x_local.getTime() + '' + randomIndex_local(1000);
}
// This will start the image flipping process.
function Start_local() {
	Reset_local();
	aAdLinkLocations_local = lookUpAdLinks_local(); // This defines the ads.
	tStart_local   = new Date();
	timerID_local  = setTimeout("flipAds_local()", mspause_local);
}
// The page first needs to build before we can analyize the links so we'll start this after a few 
// seconds.
function DelayedStart_local() {
	Reset_local();// Initialize the timer.
	tStart_local   = new Date();
	timerID_local  = setTimeout("Start_local()", 2000);
}
function Reset_local() {
	// This kills the timer object.
	var timerID_local = 0;
	var tStart_local = 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_local() {
	aLinkLocationsX_local = new Array();
	// Loop over each of the links on this page 
	// searching for the rotating ad positions.
	for (i_local=1;i_local<=document.links.length;i_local++) {
		// If this image object appears to be one of the banner positions, try to figure out which it is.
		if (typeof(document.links[i_local-1]) != 'undefined' && document.links[i_local-1].name.indexOf('cpstilladclicklocal') > -1) {
			aLinkLocationsX_local['' + document.links[i_local-1].name.substring(19,document.links[i_local-1].name.length+1)] = i_local-1;
		}
	}
	return aLinkLocationsX_local;
}
// This stops the banner rotations.
function Stop_local() {
   if (typeof timerID != 'undefined' && timerID_local) {
      clearTimeout_local(timerID_local);
      timerID_local  = 0;
   }
   tStart_local = null;
}
// Takes a url like "http://www.example.com:81/" and returns "www.example.com:81"
function cleanBaseHref_local(baseHrefIn_local){ 
	baseHrefOut_local = baseHrefIn_local;
	baseHrefOut_local =  replaceSubstring_local(baseHrefOut_local, "http://", "");
	baseHrefOut_local =  replaceSubstring_local(baseHrefOut_local, "/", "");	
	return escape(baseHrefOut_local);
}	
function replaceSubstring_local(inputString_local, fromString_local, toString_local) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp_local = inputString_local;
   if (fromString_local == "") {
      return inputString_local;
   }
   if (toString_local.indexOf(fromString_local) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp_local.indexOf(fromString_local) != -1) {
         var toTheLeft_local = temp_local.substring(0, temp_local.indexOf(fromString_local));
         var toTheRight_local = temp_local.substring(temp_local.indexOf(fromString_local)+fromString_local.length, temp_local.length);
         temp_local = toTheLeft_local + toString_local + toTheRight_local;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings_local = new Array("~", "`", "_", "^", "#");
      var midStringLen_local = 1;
      var midString_local = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString_local == "") {
         for (var i_local=0; i_local < midStrings_local.length; i_local++) {
            var tempMidString_local = "";
            for (var j_local=0; j_local < midStringLen_local; j_local++) { tempMidString += midStrings[i_local]; }
            if (fromString_local.indexOf(tempMidString_local) == -1) {
               midString_local = tempMidString_local;
               i_local = midStrings_local.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_local.indexOf(fromString) != -1) {
         var toTheLeft_local = temp_local.substring(0, temp_local.indexOf(fromString_local));
         var toTheRight_local = temp_local.substring(temp_local.indexOf(fromString_local)+fromString_local.length, temp_local.length);
         temp_local = toTheLeft_local + midString_local + toTheRight_local;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp_local.indexOf(midString_local) != -1) {
         var toTheLeft_local = temp_local.substring(0, temp_local.indexOf(midString_local));
         var toTheRight_local = temp_local.substring(temp_local.indexOf(midString_local)+midString_local.length, temp_local.length);
         temp_local = toTheLeft_local + toString_local + toTheRight_local;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp_local; // 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_local(aAds_local, position_local) {
	if (aAds_local.length == 0 || aAds_local.length == 1 || eval("typeof document.cpstillad" + position_local + "local == 'undefined'")) {
		return 0;
	} else {
		chosenIndex_local = null;
		// Find the index of the currently displayed ad.
		for (i_local=0;i_local<aAds_local.length;i_local++) {
			if (aAds_local[i_local][0] == eval("document.cpstillad" + position_local + "local.src")) {
				chosenIndex_local = i_local;
				break;
			}
		}
		return chosenIndex_local;
	}
}
// This will start the rotations after a small amount of time passes.
DelayedStart_local();

// Resolves timestamp variable in addition to resolving values for all of the other optional values that you pass after richmedia.
function resolveSimpleVars_local(richmedia_local, redirectURL_local, ibanner_ad_id_local, ipaper_id_local) {
	argv_local = resolveSimpleVars_local.arguments;
	argc_local = resolveSimpleVars_local.arguments.length;
	redirectURL_local = (argc_local > 1) ? argv_local[1] : '';
	ibanner_ad_id_local = (argc_local >2) ? argv_local[2] : '';
	ipaper_id_local = (argc_local >3) ? argv_local[3] : '';
	stringout_local = richmedia_local; // This input param is the only required input. If you don't pass the other optional values, they won't get resolved.
	
	basicClickThrough_local = redirectURL_local;
	
	stringout_local = replaceSubstring_local(stringout_local, "[BAS-CLICKTHROUGH]", escape(basicClickThrough_local));
	stringout_local = replaceSubstring_local(stringout_local, "[BAS-CLICKTHROUGH-PLAIN]", basicClickThrough_local);
	stringout_local = replaceSubstring_local(stringout_local, "[BAS-FLASHCLICKTHROUGH]", replaceSubstring_local(basicClickThrough_local, "&", "!"));
	stringout_local = replaceSubstring_local(stringout_local, "[ID]", ibanner_ad_id_local);
	stringout_local = replaceSubstring_local(stringout_local, "[paperid]", ipaper_id_local);
	stringout_local = replaceSubstring_local(stringout_local, "[timestamp]", makeTimeStamp_local());
	trimmedbasehref_local = basehref.substring(7,basehref.length-1);
	stringout_local = replaceSubstring_local(stringout_local, "[callingSite]", trimmedbasehref_local);
	return stringout_local;
}

function makeTimeStamp_local() {
	pcdateobject_local=new Date();
	timestamp_local=pcdateobject_local.getTime();
	return timestamp_local.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_local(aAdsForPosition_local, position_local) {
	 if (aAdsForPosition_local.length>0) {
		 indexOfBannerToStartWith_local = randomIndex_local(aAdsForPosition_local.length-1);
		 chosenBanner_local = aAdsForPosition_local[indexOfBannerToStartWith_local];
		 stillCreative_local = chosenBanner_local[0];
		 clickThrough_local = chosenBanner_local[1];
		 impressionLink_local = chosenBanner_local[2];
		 type_local = chosenBanner_local[3];
		 richmediacode_local = chosenBanner_local[4];
		 pbaid_local = chosenBanner_local[5];
		 ibanner_ad_id_local = chosenBanner_local[6];
		 ipaper_id_local = chosenBanner_local[7];
		 ubanner_ad_id_local = chosenBanner_local[8];
		 
		if (type_local == 'stillimage') {
		 	document.write('<img src="http://media.collegepublisher.com/media/images/blank.gif" border="0" height="2"><br>');
			document.write('<a href="' + resolveSimpleVars_local(clickThrough_local, clickThrough_local, ibanner_ad_id_local, ipaper_id_local) + '" target="_blank" name="cpstilladclicklocal' + position_local + '"><img src="' + resolveSimpleVars_local(stillCreative_local, clickThrough_local, ibanner_ad_id_local, ipaper_id_local) + '" border="0" name="cpstillad' + position_local + 'local"></a>');
			document.write('<br><img src="http://media.collegepublisher.com/media/images/blank.gif" border="0" height="2"><br>');
		} else {
			document.write(resolveSimpleVars_local(richmediacode_local, clickThrough_local, ibanner_ad_id_local, ipaper_id_local));
		}
		
		// Increment the impressions counter for this ad. 
		newimageobject_local = new Image();
		eval('impressionIMG' + position_local + '= newimageobject_local');
		eval('impressionIMG' + position_local + '.src = "http://localads.collegepublisher.com/localImp.cfm?ubanner_ad_id=' + ubanner_ad_id_local + '&random=" + cacheBust_local()');
	}
}
		
// This function is used to count the number of ads that are registered in a given position.
function getAdsInTag_local (iposition_local) {
	switch(iposition_local) {
		case 2:
			return 1;
			break;
			case 3:
			return 1;
			break;
			case 5:
			return 1;
			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 local ad position the front end needs an advertisement for.
function showClientBanner(iposition_local) {
	adDisplayed_local = 0;
	
	switch (iposition_local) {
	
		case 2:
// This array will take up a collection of each still ad for this position. 
			aAdsForPosition2_local = new Array();
//				The given ad may only appear in the following global section categories.
			asectionrestrictions_local = 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.

			// If there is no sectionname or section_name variable, any ad may be displayed.
				if (adCanAppearInThisSection_local(asectionrestrictions_local) && frontpagerequirementspass_local(0)) {
				aAdsForPosition2_local.push(new Array('http://www.utahstatesman.com/media/paper243/ads/ABFD6438.jpg', 'http://localads.collegepublisher.com/localClickThrough.cfm?uBanner_Ad_id=2b2bfac7-9789-4266-860f-53e67bd38523&callingSite=' + cleanBaseHref_local(basehref) + '&timeStamp=' + makeTimeStamp_local() + '&redirectURL=http%3A%2F%2Fwww%2Eutahstatesman%2Ecom%2Fad2ad%2Findex%2Ehtml', 'http://localads.collegepublisher.com/localImp.cfm?ubanner_ad_id=2b2bfac7-9789-4266-860f-53e67bd38523&random=' + cacheBust_local() + '', 'stillimage', '', 0, '10571', '243', '2b2bfac7-9789-4266-860f-53e67bd38523')); 
			}
			// Call the command that will select an ad in this position and draw it to the screen.
			pickAnAdForThisPositionAndDisplayIt_local(aAdsForPosition2_local, 2);

			// 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_local['2'] = new Array(aAdsForPosition2_local, findRotationIndex_local(aAdsForPosition2_local, 2), 0);
			
			adDisplayed_local=1;
			
			break;

		case 3:
// This array will take up a collection of each still ad for this position. 
			aAdsForPosition3_local = new Array();
//				The given ad may only appear in the following global section categories.
			asectionrestrictions_local = new Array();
			asectionrestrictions_local[0] = '5';
			asectionrestrictions_local[1] = '2';
			asectionrestrictions_local[2] = '3';
			asectionrestrictions_local[3] = '1';
			//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.

			// If there is no sectionname or section_name variable, any ad may be displayed.
				if (adCanAppearInThisSection_local(asectionrestrictions_local) && frontpagerequirementspass_local(1)) {
				aAdsForPosition3_local.push(new Array('http://www.utahstatesman.com/media/paper243/ads/E1EC2448.jpg', 'http://localads.collegepublisher.com/localClickThrough.cfm?uBanner_Ad_id=d7432982-01fc-4bdf-81ef-12ca5efad16a&callingSite=' + cleanBaseHref_local(basehref) + '&timeStamp=' + makeTimeStamp_local() + '&redirectURL=http%3A%2F%2Fwww%2Eutahstatesman%2Ecom%2Fmedia%2Fstorage%2Fpaper243%2Fnews%2F2006%2F08%2F04%2FWeddingNews%2FBrett%2EHamilton%2EAnd%2EEmily%2EAshton%2D2143412%2Eshtml%3Fnorewrite200608041155%26sourcedomain%3Dwww%2Eutahstatesman%2Ecom', 'http://localads.collegepublisher.com/localImp.cfm?ubanner_ad_id=d7432982-01fc-4bdf-81ef-12ca5efad16a&random=' + cacheBust_local() + '', 'stillimage', '', 0, '10782', '243', 'd7432982-01fc-4bdf-81ef-12ca5efad16a')); 
			}
			// Call the command that will select an ad in this position and draw it to the screen.
			pickAnAdForThisPositionAndDisplayIt_local(aAdsForPosition3_local, 3);

			// 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_local['3'] = new Array(aAdsForPosition3_local, findRotationIndex_local(aAdsForPosition3_local, 3), 0);
			
			adDisplayed_local=1;
			
			break;

		case 5:
// This array will take up a collection of each still ad for this position. 
			aAdsForPosition5_local = new Array();
//				The given ad may only appear in the following global section categories.
			asectionrestrictions_local = 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.

			// If there is no sectionname or section_name variable, any ad may be displayed.
				if (adCanAppearInThisSection_local(asectionrestrictions_local) && frontpagerequirementspass_local(0)) {
				aAdsForPosition5_local.push(new Array('http://www.utahstatesman.com/media/paper243/ads/E9E95571.gif', 'http://localads.collegepublisher.com/localClickThrough.cfm?uBanner_Ad_id=c3c1f48e-99c8-49ae-8b1d-fe7e9bca9ba4&callingSite=' + cleanBaseHref_local(basehref) + '&timeStamp=' + makeTimeStamp_local() + '&redirectURL=https%3A%2F%2Fwww%2Eeconomistsubscriptions%2Ecom%2Fstudy%2Fus', 'http://localads.collegepublisher.com/localImp.cfm?ubanner_ad_id=c3c1f48e-99c8-49ae-8b1d-fe7e9bca9ba4&random=' + cacheBust_local() + '', 'stillimage', '', 0, '11087', '243', 'c3c1f48e-99c8-49ae-8b1d-fe7e9bca9ba4')); 
			}
			// Call the command that will select an ad in this position and draw it to the screen.
			pickAnAdForThisPositionAndDisplayIt_local(aAdsForPosition5_local, 5);

			// 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_local['5'] = new Array(aAdsForPosition5_local, findRotationIndex_local(aAdsForPosition5_local, 5), 0);
			
			adDisplayed_local=1;
			
			break;

		}
	return adDisplayed_local;
}
var clientBannersAvailable = 1;
