//configure these two variables to set the rss link, and the timeout period. 


var listRssUrl = "http://vm-ws2003:9999/_layouts/listfeed.aspx?List=1700ba4b%2Da40d%2D491c%2Db7ae%2D6f7b3c75e9ff&View=e02a8916%2D7a96%2D42a0%2D8ffa%2D2f535d0a7b0b";
var configListRssUrl = "http://vm-ws2003:9999/_layouts/listfeed.aspx?List=5f57329f%2Dbe7d%2D416d%2D921c%2D35b9b9ac22a6&View=f5e6884d%2D97c1%2D4c2f%2D8d60%2D539b72960316";
var listUpdateUrl = "http://vm-ws2003:9999/Pages/AdRotator/SPCadcount.aspx";

var req;
var req2;
var index = 0;
var ads = new Array();
var levels = new Array();
var imgAd;
var mediaEl;
var downloader;
var dispAd;

if (!window.AdRotator)
	window.AdRotator = {};

AdRotator.Scene = function() 
{
}

AdRotator.Scene.prototype =
{
	handleLoad: function(control, userContext, rootElement) 
	{
           this.rootCanvas = rootElement;
           
           // Find UI elements
           imgAd = this.rootCanvas.findName("imgAd");
           mediaEl = this.rootCanvas.findName("mediaEl");
           
           imgAd.addEventListener("MouseLeftButtonDown", onImageClick);
           mediaEl.addEventListener("MouseLeftButtonDown", onImageClick);
           
           downloader = this.rootCanvas.getHost().createObject("downloader");
           downloader.addEventListener("completed", onCompleted);
           
           req = new XMLHttpRequest();
           req.onreadystatechange = this.processListRss;
	   req.open("POST", listRssUrl, true);
	   req.send("");
	   
	   //this.t = setTimeout(function() { tick(); }, timerTick);

 
	},
	processListRss: function()
	{
	
	      // only if req shows "loaded"
	      if (req.readyState == 4) {
	          // only if "OK"
	         if (req.status == 200) {
	              
		      ads = ProcessRss(req.responseXML);
		      
		      
		      req2 = new XMLHttpRequest();
		      req2.onreadystatechange = processLevelConfig;
		      req2.open("GET", configListRssUrl, true);
	   	      req2.send("");
		          
	          } else {
	              //eat it... 
	          }
    		}	
	
	
	}
}

function processLevelConfig()
{
	// only if req shows "loaded"
	if (req2.readyState == 4) {
	  // only if "OK"
	 if (req2.status == 200) {

	      levels = ProcessRss(req2.responseXML);
	      findDisplayAd();
	  } else {
	      //eat it... 
	  }
	}
}

function findDisplayAd()
{
	//at this point we need to process the ads, and levels...
	//todo this we are going to:
	
	//1. sort the ads by level, and calc the total number of impressions
	//2. loop through each of the groups of ads (grouped by level)
	//   a. if the number of impressions for an ad in a group is less
	//      then the percentage (stored in the level def), then we disply it, 
	//      and update the number of impressions. 
	//   b. if each ad in the group has a number of impressions > then the percentage
	//      goto the next group... 
	
	var i;
	var j;
	var k;
	var groups = new Array(levels.length);
	var totalImpressions = 0;
	var defaultLevel = 0;
	var currPercent = 0;
	levels.sort(sortAd);
	
	for (i=0;i<levels.length;i++)
	{
		k = 0;
		groups[i] = new Array();
		//for each level, find the ID, look at all the ads, and put them into the array
		var levelId = levels[i]['LevelId'];
		if(parseInt(levels[i]['Percentage']) > currPercent)
		{
			currPercent = parseInt(levels[i]['Percentage']);
			defaultLevel = i;
		}

		for(j=0;j<ads.length;j++)
		{
			var listLevelId = ads[j]['LevelId'];
			if(listLevelId == levelId)
			{
				totalImpressions += parseInt(ads[j]['Impressions']);
				groups[i][k] = ads[j];
				k++;
			}
		}
	}
	//ok so, now we have our ads grouped by level... now loop through each level... 
	//if the ads 'impressions' does not match the percentage for the level... 
	//then display the ad
	for (i=0;i<groups.length;i++)
	{
		var percentage = parseInt(levels[i]['Percentage']);
		percentage = percentage / 100;
		var target = totalImpressions * percentage;
			
		for (j=0;j<groups[i].length;j++)
		{ 	
			 var itemImpressions = parseInt(groups[i][j]['Impressions']);
			 //alert('level ' +levels[i]['Title'] +' percentage ' +levels[i]['Percentage'] +' target ' +target +' item ' +groups[i][j]['Title'] +' impressions ' +itemImpressions );
			 
			 if(itemImpressions <= Math.floor(target))
			 {
			 	dispAd = groups[i][j];
			 	downloader.open("GET", dispAd['ImageUri']);
				downloader.send();
				return;
			 }
		}
		
	}
	//if we hit this.. we did not find an ad... use the first one
	var randomAd = GetRandomNumber(ads.length);
	dispAd = ads[randomAd];
	downloader.open("GET", dispAd['ImageUri']);
	downloader.send();
	return;
}
	
function onCompleted(sender, eventArgs)
{
	var uri = sender.uri;
	if(uri.substring(uri.lastIndexOf(".")) == ".wmv")
	{
		mediaEl.setSource(sender, "");
		mediaEl.addEventListener("MediaEnded", onMediaEnded);
		mediaEl.Opacity=1;
	}
	else
	{
		imgAd.setSource(sender,"");
		imgAd.Opacity=1;
	}
	
	req = new XMLHttpRequest();
   	req.onreadystatechange = processUpdate;
  	req.open("POST", listUpdateUrl +"?adid=" +dispAd['Title'], true);
	req.send("");
}

function processUpdate()
{
	return;
}

function onImageClick(sender, eventArgs)
{
	if(index >= (ads.length ))
		index = 0;
	window.open(dispAd['AdLink'],"newWindow","");		
}

function onMediaEnded(sender, eventArgs)
{
	mediaEl.Position = "00:00:00";
	mediaEl.Play();
}

function trim(sString) 
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	while (sString.substring(0,1) == '\n')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == '\n')
		{
			sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function ProcessRss(rssXml)
{
	var retArray = new Array();
	var doc = rssXml;

	// get a reference to the root-element "rss"
	var root = doc.getElementsByTagName('rss')[0];
		// get reference to "channel" element
	var channels = root.getElementsByTagName("channel");
		// now get all "item" tags in the channel
	var items = channels[0].getElementsByTagName("item");

	for(i = 0; i < items.length;i++)
	{
		//create a new ad
		var objItem = new Array();

		//get the title
		var titles = items[i].getElementsByTagName("title");
		var title = titles[0].firstChild.nodeValue;
		objItem['Title'] = title;

		//grab the description field, which has all of the columns in it
		var descriptions = items[i].getElementsByTagName("description");
		var desc = trim(descriptions[0].firstChild.nodeValue);

		//while there are column... 
		while(desc.indexOf("</div>") >=0)
		{
			//get the name value pair
			var div = trim(desc.substring(5,desc.indexOf("</div>")));

			//need to break out the name value pair... 
			var name = trim(div.substring(3,div.indexOf("</b>")));
			name = name.substring(0,name.length-1);
			var value = trim(div.substring(div.indexOf("</b>") +4));

			//add the name/value to the current ad
			objItem[name] = value;
			//goto the next column...
			if(desc.indexOf("</div>") >=0)
				desc = trim(desc.substring(desc.indexOf("</div>") +6));
		}
		//add the ad to the array
		retArray[i] = objItem;
	}
	
	return retArray;
}

function sortAd(a,b)
{
  return parseInt(a['LevelId']) - parseInt(b['LevelId']);
}


function GetRandomNumber(limit)
{
	var ranNum= Math.floor(Math.random()*limit);
	return ranNum;
}