var nowPlayingIndex = 0;
var queuedTids, nowShowingTids;
var adPlaying = false;
var agt=navigator.userAgent.toLowerCase(); 
var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));

function onTemplateLoaded(message) {	
       // callFlash("addEventListener", "lineupLoad", "onLineupLoad");	
	//callFlash("addEventListener", "titleLoad", "onTitleLoad");
	//callFlash("addEventListener", "contentLoad", "onContentLoad");
	//callFlash("addEventListener", "mediaComplete", "onMediaComplete");
        //callFlash("fetchLineupById",categories[tab]);			
        callFlash("addEventListener", "adStart", "onAdStart");		
        callFlash("addEventListener", "adComplete", "onAdComplete");	
	//chgVideoLineup(tab);				
}

function onAdStart(){
  adPlaying = true;	
  //alert("ad plays with no interruption!");	
}

function onAdComplete(){
  adPlaying = false;	
  //alert("ad completed .. ");	
}

function getCurrentTitle_Result(titleDTO){   
  //alert("getCurrentTitle");
  //alert(titleDTO.startDate.year);
//  var rectangleAdDiv = document.getElementById("rectangleAd");
  //rectangleAdDiv.innerHTML ="<table bgcolor='#ebebeb' id='rectangle' cellpadding='0' cellspacing='0' border='0' ><tr><td align='center' valign='middle'><IFRAME bgcolor='#ebebeb' WIDTH='336' HEIGHT='280' MARGINWIDTH=0 MARGINHEIGHT=0  FRAMEBORDER=0 SCROLLING=no BORDERCOLOR='#000000' allowTransparency='true'  SRC='http://ads.morningstar.com/RealMedia/ads/adstream_sx.ads/www.morningstar.com/@Middle'></iframe></td></tr></table>";
  var QAdRectangleDiv = document.getElementById("QAdRectangle");
QAdRectangleDiv.innerHTML ="<IFRAME WIDTH='336' HEIGHT='280' bgcolor='#ebebeb' ALIGN='MIDDLE' MARGINWIDTH=0 MARGINHEIGHT=0  FRAMEBORDER=0 SCROLLING=no BORDERCOLOR='#000000' allowTransparency='true'  SRC='"+adURL+"'></iframe>";
 /* 		
  document.getElementById("bcvidtitle").innerHTML = titleDTO.displayName;  
 
  var addedDate = new Date();
  addedDate.setTime(Date.parse(titleDTO.publishedDate));  
 alert(addedDate.getMonth()+1+"/"+addedDate.getDate()+"/"+addedDate.getFullYear());
  document.getElementById("addeddate").innerHTML = "Added on "+ (addedDate.getMonth()+1)+"/"+addedDate.getDate()+"/"+addedDate.getFullYear();
  document.getElementById("rreport").innerHTML = "";
  document.getElementById("vidopt").innerHTML = "";
  document.getElementById("relatedLink").innerText ="";
   
  chgTickerList(titleDTO.linkText);    
  if (titleDTO.longDescription!=null){  	
    var upsell = titleDTO.longDescription;
    upsell = upsell.substring(0, 3) + "class='premiumad' target='_blank' " + upsell.substring(3);	
    //alert(upsell);  	    
   document.getElementById("relatedLink").innerHTML = upsell;
  */
  
}

function onContentLoad(){
  //alert("content loaded..");
  callFlash("getCurrentTitle");	
}

function onMediaComplete(){
  //alert("media completed..");	
  //alert((queuedTids==nowShowingTids)?true:false);
  if(nowPlayingIndex < queuedTids.length-1){ //makes sure the counter doesn't just keep going forever  	        
    var t=setTimeout("playNext()",20);
  } 
}

function onLineupLoad(lineupDTO) {	    
	nowShowingTids = lineupDTO.parameters.lineup.videoIds;	
	//alert("nowShowingTids:"+nowShowingTids);	 
	if (firstLoad){
	  queuedTids = nowShowingTids;	
	  firstLoad = false;
	  if (tid == -1){       
	    tid = queuedTids[0];
	    callFlash("selectTitle", queuedTids[0], lineupDTO.parameters.lineup.id, "full");	    	
	    nowPlayingIndex = 0;
	  }else{	    
	    for (var count=0; count<queuedTids.length; count++){	      		    	
	      if (queuedTids[count]==tid){
	        nowPlayingIndex = count;
	        break;	
	      }	
	    }
	  } 	  
	}else{  	  		
	  for (var i=0; i<nowShowingTids.length; i++){	  
              callFlash("fetchTitleById", nowShowingTids[i]);
	  }	 
        }    
}			


function onTitleLoad(titleDTO){ 
    numOfVideos++;            	            
    var index = numOfVideos-1;        
                  
    var imgURL = titleDTO.parameters.title.thumbnailURL; 
    var name = titleDTO.parameters.title.displayName;
    var description = titleDTO.parameters.title.shortDescription;            
    description = textToASCII(description);
        
    var videoInfo = "<div class='vlink2'><a href='javascript:playTitle("+index+");' class='thumbnail'><img border='0' width='82' height='62' src='"+imgURL+"'/></a>";
    videoInfo +="<div class='vlink3'><a href='javascript:playTitle("+index+");' class='vlinktitle' title='"+description+"'>"+ name + "</a>";        
    videoInfo += "<a class='play' href='javascript:playTitle("+index+");'><img src='http://im.morningstar.com/im/videocenter/parrow.gif' border='0'>&nbsp;PLAY</a></div></div>";    

    var videoGrid = document.createElement("div");    
    if (!is_ie)  
      videoGrid.setAttribute("class", "vlink1");
    else{  
      var z = document.createAttribute('class');
      z.value = 'vlink1';
      videoGrid.setAttributeNode(z);
    }      
    videoGrid.innerHTML = videoInfo;    
    document.getElementById("vidlinks").appendChild(videoGrid);     
    
    if (numOfVideos == nowShowingTids.length){      
      var space = document.createElement("div");
      if (is_ie){
        var x = document.createAttribute('id');
        x.value = 'spacer';
        space.setAttributeNode(x);	      
      }else
      	space.setAttribute("id", "spacer");
      document.getElementById("vidlinks").appendChild(space);
           
      for (var i = 0; i <= 3; i ++)
        document.getElementById("TabVideo"+i).href = "javascript:chgVideoLineup("+i+")";					
    }       	             
}	


function chgVideoLineup(catNum){	
	numOfVideos = 0;
	for (var i = 0; i <= 3; i ++){            								
            document.getElementById("TabVideo"+i).removeAttribute("href");
            document.getElementById("TabVideo"+i).className = "tab";
	}	
	document.getElementById("TabVideo"+catNum).className = "tabon";	
	nowShowingCat = catName[catNum];	
	cleanVideoTable();					
        callFlash("fetchLineupById",categories[catNum]);
}

function cleanVideoTable(){     	      
    var t = document.getElementById("vidlinks");        
    t.innerHTML = "";   
}

function playTitle(i){    	
  if (!adPlaying){	
    callFlash("loadTitleById", nowShowingTids[i]);	  
    callFlash("getCurrentTitle");	    
    nowPlayingIndex = i;  
    queuedTids = nowShowingTids;  
    lineup = nowShowingCat;
  }else{
    alert("wait till ad finishes playing!");
  }
} 

function playNext(){
  nowPlayingIndex++;	
  callFlash("loadTitleById", queuedTids[nowPlayingIndex]);	  
  callFlash("getCurrentTitle");	  
}

function chgTickerList(tl){  
  //alert(tl);  
  var addTo = "";
  if ((tl!=null)&&(tl.length>0)){    
    var list = tl.split('|');
    var listTxt = "Read our report on:";
    for (var x=0; x<list.length-1; x++){
      if (list[x].indexOf("=")==-1)	
          listTxt += " <a href='http://quicktake.morningstar.com/stocknet/MorningstarAnalysis.aspx?Country=USA&Symbol="+list[x]+"' target='_blank'>"+list[x]+"</a> |";
      else
      	  listTxt += " <a href='http://quicktake.morningstar.com/fundnet/MorningstarAnalysis.aspx?Country=USA&Symbol="+list[x].substring(2)+"' target='_blank'>"+list[x].substring(2)+"</a> |";  
    }
    if (list[list.length-1].indexOf("=")==-1)
        listTxt += " <a href='http://quicktake.morningstar.com/stocknet/MorningstarAnalysis.aspx?Country=USA&Symbol="+list[list.length-1]+"' target='_blank'>"+list[list.length-1]+"</a>";    
    else
        listTxt += " <a href='http://quicktake.morningstar.com/fundnet/MorningstarAnalysis.aspx?Country=USA&Symbol="+list[list.length-1].substring(2)+"' target='_blank'>"+list[list.length-1].substring(2)+"</a>"; 	  
        
    document.getElementById("rreport").innerHTML = listTxt;	  
    addTo = "<a href='http://portfolio.morningstar.com/NewPort/Reg/AddToPortfolio.aspx?ticker="+tl+"' target='_blank'>Add to Portfolio</a> | ";  	
    
    if (list.length == 1)
      addTo += "<a href='http://portfolio.morningstar.com/PortAsp/EditAlerts.asp?ptype=T&action=A&x=#StockFundAlerts&symbol="+list[0]+"' target='_blank'>Add to Alerts</a> | ";            
  }
  addTo += "<a href='http://link.brightcove.com/services/link/bcpid1137732997?action=rss' target='_blank'>RSS</a> | <a href='http://members.morningstar.com/reprints/reprints_home.html' target='_blank'>License this video</a>";
  document.getElementById("vidopt").innerHTML = addTo;
}

function GetXmlHttpObject(){
  var xmlHttp=null;
  try{
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
  }catch (e){    
    // Internet Explorer
    try{
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }catch (e){
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return xmlHttp;
}


function playAd(adString, callback){		
	var oRequest=GetXmlHttpObject();  
        if (oRequest==null){
            alert ("Your browser does not support AJAX!");
            return;
        }             
        var dest = "/videoAdsLibrary/getVideoAdXML.aspx?sxtag=www.morningstar.com/video@x51&area=QE&topic=214728";
        var randomnumber=Math.floor(Math.random()*100);
        dest += "&s="+randomnumber;
       // alert(dest);
        oRequest.open("GET",dest,true);                  
        oRequest.onreadystatechange = function(){ 
          if (oRequest.readyState == 4){                      
            var txt = oRequest.responseText;    
           // alert(txt);                                                   
            var start = txt.indexOf("<videoAd");
            txt = txt.substring(start);
            var end = txt.indexOf("</span>");
            txt = txt.substring(0, end);
             if (txt.indexOf("empty.gif")>=0)
              callFlash("endExternalAd");
            else{     
              if (window.ActiveXObject){
                var adXML = new ActiveXObject("Microsoft.XMLDOM");     
                //alert(txt);             	
                adXML.loadXML(txt);
                parseAndPlay(adXML);
              }  
              else { 
                var adXML = (new DOMParser()).parseFromString(txt, "text/xml");	      
                //(adXML.documentElement);
                parseAndPlay(adXML);	        
              }	        
            }
	  }  
        }
        oRequest.send(null); 
}
        

function parseAndPlay(adXML)
{	
	//alert("parse the good XML and then play the ad");
	var ad = new Object(); //sets up our ad object for passing to the player later
	//alert(adXML.firstChild.childNodes.length);
	var nodeItems = adXML.firstChild.childNodes.length; //the number of items in the XML
	var currentNode = adXML.firstChild.firstChild; //sets the first node in the XML as the current node
        var adURL, adClickURL;	
	
	switch(adXML.firstChild.nodeName)
	{
		case "videoAd":
		  	ad.type = "videoAd";
		  	//alert(ad.type);
		  	break;  
		case "SynchedBanner728x90":
			ad.type = "synchedBanner";
			break;
		case "SynchedBanner468x60":
			ad.type = "synchedBanner";
			break;
		default:
		  	callFlash("endExternalAd"); //if it's not a recognized XML template, end the ad and start the content
			ad.type = null;
	}

	if(ad.type) //if it is recognized XML
	{
		//checks to see the duration was set and sets the variable
		if(adXML.firstChild.getAttribute("duration") !== "") ad.duration = adXML.firstChild.getAttribute("duration");
		if(adXML.firstChild.getAttribute("trackStartURLs") !== "") ad.trackStartURLs = adXML.firstChild.getAttribute("trackStartURLs").split(" ,");


		for(var i = 0; i < nodeItems; i++)
		{//alert(currentNode.firstChild.nodeName + ":" +currentNode.firstChild.nodeValue);
			//checks to see if the current nodes are in our Rich Media Templates and assigns them if they exist
			if(currentNode.nodeName == "videoURL") ad.videoURL = currentNode.firstChild.nodeValue; 			
			if(currentNode.nodeName == "videoClickURL") ad.videoClickURL = currentNode.firstChild.nodeValue;
			
			if(currentNode.nodeName == "RectangleAdURL"){
				adURL = currentNode.firstChild.nodeValue;
			}
			if(currentNode.nodeName == "RectangleAdClickURL"){
				adClickURL = currentNode.firstChild.nodeValue;
			}		

			currentNode = currentNode.nextSibling; //move to the next node for the next pass of the loop
		}

		ad.type = "videoAd"; //force it to be of type "video ad"
		callFlash("playAd", ad); //send the ad object to the player: in this case, it's just the video related pieces
		
		var QAdRectangleDiv = document.getElementById("QAdRectangle");
		QAdRectangleDiv.innerHTML ="<IFRAME WIDTH='336' HEIGHT='280' bgcolor='#ebebeb' ALIGN='MIDDLE' MARGINWIDTH=0 MARGINHEIGHT=0  FRAMEBORDER=0 SCROLLING=no BORDERCOLOR='#000000' allowTransparency='true'  SRC='"+adURL+"'></iframe>";
		
	}
}

function textToASCII(text){
  text = text.split("$").join("&#36;");
  text = text.split("%").join("&#37;");
  text = text.split("'").join("&#39;");	
  text = text.split("(").join("&#40;");
  text = text.split(")").join("&#41;");
  text = text.split("*").join("&#42;");
  text = text.split("+").join("&#43;");
  text = text.split("@").join("&#64;");
  text = text.split("^").join("&#94;");
   
  return text;
}
 