var categories = new Array (1151559543, 1113465438, 1119130858, 1118125882);
var catName = new Array("", "stocks", "options", "funds");
var numOfVideos = 0;
var nowPlayingIndex = 0;
var queuedTids;
var queuedTitles = new Array();
var adPlaying = false;
var adPaused = false;
var agt=navigator.userAgent.toLowerCase(); 
var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));

var vOffset;
if (is_ie) vOffset = 1479;
else vOffset =1456;
var isOut = false;
var isTriggered = false;

function onTemplateLoaded(message) {	
      //  callFlash("addEventListener", "lineupLoad", "onLineupLoad");	
	callFlash("addEventListener", "titleLoad", "onTitleLoad");
	callFlash("addEventListener", "contentLoad", "onContentLoad");
	callFlash("addEventListener", "mediaComplete", "onMediaComplete");
    //    callFlash("fetchLineupById",1410385636);        		
        callFlash("addEventListener", "adStart", "onAdStart");
        callFlash("addEventListener", "adStop", "onAdStop");		
        callFlash("addEventListener", "adComplete", "onAdComplete");	
        callFlash("addEventListener", "mediaStart", "onMediaStart");						
}

function onAdStart(){
//alert("test");
  adPlaying = true; 
  isTriggered = true;   
  callFlash("getCurrentTitle");
  if (!isOut){          	
    var rollout = document.getElementById("rolloutOL");		//NEW ADDED  		
//    rollout.style.top = vOffset;                         //NEW ADDED
    Slide('rolloutOL').left();
    isOut = true;
  }
  //alert("ad plays with no interruption!");  
}



function onAdComplete(){
  adPlaying = false;	
  //alert("ad completed .. ");	
}

function onMediaStart(){
  //alert("onPlay .. ");
  if (!isTriggered){  	
    isTriggered = true;
    callFlash("getCurrentTitle");
    if (!isOut){
      var rollout = document.getElementById("rolloutOL");		  		
     // rollout.style.top = vOffset;
      Slide('rolloutOL').left();
      isOut = true;	
    } 
  }	
}

getPosition=function(elem)
{
	var offsetTrail = elem;
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	var res = {"left":offsetLeft,"top":offsetTop};
	return res;
	
};

closeOL=function(){
  document.getElementById("rolloutOL").style.display="none";
  isOut = false;
};

function getCurrentTitle_Result(titleDTO){   
  //alert("getCurrentTitle");   
  
  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>";    
  document.getElementById("bigTitle").innerHTML = titleDTO.displayName;    
  document.getElementById("tickerlist").innerHTML = "";    
//  document.getElementById("nextTitle").innerHTML = "";
 // document.getElementById("nextTitle2").innerHTML = "";
  chgTickerList(titleDTO.linkText);  
    
//  if (nowPlayingIndex+1 <= numOfVideos-1)
//    document.getElementById("nextTitle").innerHTML = "<a href='javascript:playTitle("+(nowPlayingIndex+1)+");'>"+queuedTitles[nowPlayingIndex+1]+"</a>";    
//  if (nowPlayingIndex+2 <= numOfVideos-1)  
//    document.getElementById("nextTitle2").innerHTML = "<a href='javascript:playTitle("+(nowPlayingIndex+2)+");'>"+queuedTitles[nowPlayingIndex+2]+"</a>";       
}

function onContentLoad(){
  //alert("content loaded..");
  //callFlash("getCurrentTitle");	
}

function onMediaComplete(){
  //alert("media completed..");	  
  if(nowPlayingIndex < queuedTids.length-1){ //makes sure the counter doesn't just keep going forever  	        
    var t=setTimeout("playNext()",20);
  } 
}

function onLineupLoad(lineupDTO) {	    
	queuedTids = lineupDTO.parameters.lineup.videoIds;	
	//callFlash("selectTitle", queuedTids[0], lineupDTO.parameters.lineup.id, "full");	    	
	nowPlayingIndex = 0;
	  	  		
	for (var i=0; i<queuedTids.length; i++){	  
          callFlash("fetchTitleById", queuedTids[i]);
	}		        
}			


function onTitleLoad(titleDTO){ 
    numOfVideos++;            	            
    var index = numOfVideos-1;        
                  
    var imgURL = titleDTO.parameters.title.thumbnailURL; 
    var name = titleDTO.parameters.title.displayName;
    queuedTitles.push(name);        
    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'><div class='vlinktitle'>"+ name + "</div>";            
    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 == queuedTids.length){      	
      var space = document.createElement("div");
      if (is_ie){
        var x = document.createAttribute('class');
        x.value = 'spacer';
        space.setAttributeNode(x);	      
      }else
      	space.setAttribute("class", "spacer");
      document.getElementById("vidlinks").appendChild(space);                 					
    }       	             
}	

function playTitle(i){    	
  if (!adPlaying){
    nowPlayingIndex = i; 
    isTriggered = false;    	
    callFlash("loadTitleById", queuedTids[i]);	  
    //callFlash("getCurrentTitle");	                
  }else{
    alert("wait till ad finishes playing!");
  }
} 

function playNext(){
  nowPlayingIndex++;	
  isTriggered = false;  
  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; x++){
      if (list[x].indexOf("F=")!=-1)
      	  listTxt += " <a href='http://quicktake.morningstar.com/fundnet/MorningstarAnalysis.aspx?Country=USA&Symbol="+list[x].substring(2)+"' target='_blank'>"+list[x].substring(2)+"</a> |";  
      else if (list[x].indexOf("E=")!=-1)
      	  listTxt += " <a href='http://quicktake.morningstar.com/etfnet/MorningstarAnalysis.aspx?Country=USA&Symbol="+list[x].substring(2)+"' target='_blank'>"+list[x].substring(2)+"</a> |";  
      else	
          listTxt += " <a href='http://quicktake.morningstar.com/stocknet/MorningstarAnalysis.aspx?Country=USA&Symbol="+list[x]+"' target='_blank'>"+list[x]+"</a> |";                   	  
    } //get all tickers    	              	  
    
    tl = tl.replace(/F=/g, "");
    tl = tl.replace(/E=/g, "");
    addTo = " <a href='http://portfolio.morningstar.com/NewPort/Reg/AddToPortfolio.aspx?ticker="+tl+"&name="+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>";            
   
    document.getElementById("tickerlist").innerHTML = listTxt;
  }
  
  addTo += "<br/><a href='http://link.brightcove.com/services/link/bcpid1407952663?action=rss' target='_blank'>RSS</a> | <a href='http://members.morningstar.com/reprints/reprints_home.html' target='_blank'>License this video</a>";
  
  document.getElementById("tickerlist").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 = "getUsppVideoAdXML.aspx";
        var randomnumber=Math.floor(Math.random()*100);
        dest += "?s="+randomnumber;
        //alert(dest);
        oRequest.open("GET",dest,true);                  
        oRequest.onreadystatechange = function(){   
          //alert(oRequest.readyState);
          if (oRequest.readyState == 4){                      
            var txt = oRequest.responseText;                                                                  
            var start = txt.indexOf("<videoAd");
            txt = txt.substring(start);
            var end = txt.indexOf("</span>");
            txt = txt.substring(0, end);
            //alert(txt);             
            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

	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;
			        //alert(adClickURL);
			}		

			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 rectangleAdDiv = document.getElementById("rectangleAd");
		rectangleAdDiv.innerHTML ="<table style='overflow:hidden' bgcolor='#ebebeb' id='rectangle' cellpadding='0' cellspacing='0' border='0'  align='center'><tr><td><IFRAME WIDTH='336' HEIGHT='280' bgcolor='#ebebeb' ALIGN='MIDDLE' MARGINWIDTH=0 MARGINHEIGHT=0  FRAMEBORDER=0 SCROLLING=no BORDERCOLOR='#000000' allowTransparency='true'  SRC='"+adURL+"'></iframe></td></tr></table>";
		
	}
}

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;
}
 
var slideInUse = new Array();

function Slide(objId, options) {

	this.obj = document.getElementById(objId);
	this.duration = 1;
	this.width = parseInt(this.obj.style.width);
	
	if(typeof options != 'undefined') { this.options = options; } else { this.options = {}; }
	if(this.options.duration) { this.duration = this.options.duration; }
		
	this.up = function() {
		this.curHeight = this.height;
		this.newHeight = '1';
		if(slideInUse[objId] != true) {
			var finishTime = this.slide();
			window.setTimeout("Slide('"+objId+"').finishup("+this.height+");",finishTime);
		}
	}
	
	this.down = function() {
		this.newHeight = this.height;
		this.curHeight = '1';
		if(slideInUse[objId] != true) {
			this.obj.style.height = '1px';
			this.obj.style.display = 'block';
			this.slide();
		}
	}
	this.left2 = function() {
		this.curWidth = this.width;
		this.newWidth = '1';
		if(slideInUse[objId] != true) {
			var finishTime = this.slide();
			window.setTimeout("Slide('"+objId+"').finishup("+this.width+");",finishTime);
		}
	}
	this.right = function() {
	//alert("right");
		this.newWidth = this.width;
		this.curWidth = '1';
//		this.curLeft='580';
		if(slideInUse[objId] != true) {
			this.obj.style.width = '1px';
//			this.obj.style.left = '580px';
			this.obj.style.display = 'block';
			this.slide();
		}
	}
	this.slide = function() {
		slideInUse[objId] = true;
		var frames = 30 * duration; // Running at 30 fps
		var tIncrement = (duration*1000) / frames;
		tIncrement = Math.round(tIncrement);
		var sIncrement = (this.curWidth-this.newWidth) / frames;
		var frameSizes = new Array();
		for(var i=0; i < frames; i++) {
			if(i < frames/2) {
				frameSizes[i] = (sIncrement * (i/frames))*4;
			} else {
				frameSizes[i] = (sIncrement * (1-(i/frames)))*4;
			}
		}
		
		for(var i=0; i < frames; i++) {
			this.curWidth = this.curWidth - frameSizes[i];
//this.curLeft=this.curLeft - this.curWidth;
		//	alert(i);
//window.setTimeout(this.showup(this.curWidth,this.curLeft),tIncrement * i);

			window.setTimeout("document.getElementById('"+objId+"').style.width='"+Math.round(this.curWidth)+"px';",tIncrement * i);
		}
		window.setTimeout("delete(slideInUse['"+objId+"']);",tIncrement * i);
		
		if(this.options.onComplete) {
			window.setTimeout(this.options.onComplete, tIncrement * (i-2));
		}
		return tIncrement * i;

	}
	
	this.finishup = function(width) {
		this.obj.style.display = 'none';
		this.obj.style.width = width + 'px';
	}

	 
	this.left = function() {

            this.newWidth = this.width;
            this.curWidth = '1';
            this.curLeft= document.getElementById("video_player").offsetLeft;

            if(slideInUse[objId] != true) {
                  this.obj.style.width = '1px';
                  this.obj.style.left = document.getElementById("video_player").offsetLeft + 'px';
                  this.obj.style.display = 'block';
                  this.slide2();

            }

      }

      this.slide2 = function() {
            slideInUse[objId] = true;
            var frames = 30 * duration; // Running at 30 fps
            var tIncrement = (duration*1000) / frames;
            tIncrement = Math.round(tIncrement);
            var sIncrement = (this.curWidth-this.newWidth) / frames;
            var frameSizes = new Array();

            for(var i=0; i < frames; i++) {
                  if(i < frames/2) {
                        frameSizes[i] = (sIncrement * (i/frames))*4;
                  } else {
                        frameSizes[i] = (sIncrement * (1-(i/frames)))*4;
                  }
            }
            for(var i=0; i < frames; i++) {
                  this.curWidth = this.curWidth - frameSizes[i];
                  this.curLeft = this.curLeft + frameSizes[i];
                  //window.setTimeout("document.getElementById('"+objId+"').style.width='"+Math.round(this.curWidth)+"px';",tIncrement * i);

                  //alert ("this.resetPos('" + objId + "'," + this.curWidth + "," + this.curLeft +");");
                  window.setTimeout("this.resetPos('" + objId + "'," + this.curWidth + "," + this.curLeft +");",tIncrement * i);

            }

            window.setTimeout("delete(slideInUse['"+objId+"']);",tIncrement * i);
           

            if(this.options.onComplete) {

                  window.setTimeout(this.options.onComplete, tIncrement * (i-2));

            }

            return tIncrement * i;

      }
      this.resetPos=function(objId, width, left){

          var obj = document.getElementById(objId);
          obj.style.width = Math.round(this.curWidth)+"px";
          obj.style.left = Math.round(this.curLeft)+"px";   

      }
 
	 
	return this;
} 