var tcast_AdNum;
var tcast_adUrl = new Array();
var tcast_adFilePath = new Array();
var tcast_adtime; 
var tcast_adkeeptime = 12;
                           
var tcast_ver_4ie = '3.8';
var tcast_ver_4ff = '';
var tcast_f_v = '1';
var tcast_cab_v = '3.0.0.8';
var buffertimer;
var buffertimes=0;
var _starttm=new Date().getTime();
var tcast_playednum = 0;	
var tcast_isplay = false;
var tcast_version;  //1老版本 2新版本
 
                           
function  getAdvertiseConfig(xmlPath)
{
	var xmldoc;
		 
	if(window.ActiveXObject)
	{ 
		xmldoc = new ActiveXObject("Microsoft.XMLDOM");
		xmldoc.async = false; 		
        xmldoc.load(xmlPath); 
 	} else if(document.implementation && document.implementation.createDocument)
	{	    
		//xmldoc = document.implementation.createDocument("","",null);
		//xmldoc.async = false; 
		//xmldoc.load(xmlPath);		
		
		//09.4.1 Modify For Chrome 
		var xmlhttp = new window.XMLHttpRequest(); 
		xmlhttp.open("GET",xmlPath,false); 
		xmlhttp.send(null); 
		xmldoc = xmlhttp.responseXML.documentElement; 
		
	}
   try{
    if(window.ActiveXObject){
      var node = xmldoc.getElementsByTagName("Advertise_number")[0];
	    tcast_AdNum = node.text; 
	    node = xmldoc.getElementsByTagName("Advertise_Time")[0]; 
	    tcast_adtime = node.text; 
	     node = xmldoc.getElementsByTagName("Advertise_KeepTime")[0]; 
	    tcast_adkeeptime = node.text;
        var nodes = xmldoc.getElementsByTagName("Item");
        for( i=0; i<nodes.length ; i++)
        {
            tcast_adFilePath[i] = nodes[i].childNodes.item(0).text;
            tcast_adUrl[i] = nodes[i].childNodes.item(1).text;
        }
    }//ie
    else{
        var node = xmldoc.getElementsByTagName("Advertise_number")[0];
	    	tcast_AdNum = node.childNodes[0].textContent;
	   	 	node = xmldoc.getElementsByTagName("Advertise_Time")[0]; 
	   		tcast_adtime = node.childNodes[0].textContent; 
				node = xmldoc.getElementsByTagName("Advertise_KeepTime")[0]; 
	   		tcast_adkeeptime = node.childNodes[0].textContent; 
        var nodes = xmldoc.getElementsByTagName("Item");
        for( i=0; i<nodes.length ; i++)
        {
            tcast_adFilePath[i] = nodes[i].getElementsByTagName("Path")[0].textContent;
            tcast_adUrl[i] = nodes[i].getElementsByTagName("Link")[0].textContent;
        }
    }//ff
   }//try
   catch(e){}
}

 


var slist=
[
'zBMAAOtcu1thFlJxdd7oAcVAOiEy3OZ7o/VUaNYU8z6l',
'qmEAAM3HH0lIob2I3q01JQQg/rNT/bV+ZVlJgjRyHAsK',
'DEMAABtoRO4LIiV2hkdRvpLUydCAPCNT5qif864OUEOX',
'ZGcAAMFjMsRTJOMCXyVwZ7gT6rrDpqK9vIg7KNjIDCQt',
'lWQAACspW69C9XlgYThkt1oDKWx7w3p0ls9PcHfsxda8',
'SSMAAOgQ7OvafU6KyqVJYfNaLQVs55pHD9MmU3DEMQP2',
'iSUAADS3VYMbuh/Bql5TVJ9q3mGCjpi0GftEEcTZrlhP',
'IgAAACC6OqBFFPyEnIBnq5N93OxkmBhYHZOmVWCRtzuN', 
'+DYAAOSqQ0EJPyspGW7++1TZ0iH5V1feQhlPnR/ORN3h'
];



var llist=
[
1,
1,
1,
1,
1,
1,
1,
1,
1
];

function reportCount()
{
	var img=document.getElementById('countimg');
	img.src='http://xtrack.tomonline-inc.com/?ID=-.-TCASTAD-.-&ver=1&type=01';
}

function tcast_getList()
{
  var sl=new Array();
	var ll=0;
	sl[0]=0;
	for(i=0;i<llist.length;++i)
	{
		ll+=llist[i];
		sl[i+1]=ll;
	}
	var rd=Math.random()*ll;
	for(i=sl.length-1;i>=0;--i)
	{
		if(rd>=sl[i]) break;
	}    
	return i;
}

function outputTcast(ie, download)
{
	if(slist.length==0) return;
	function $(i){return document.getElementById(i);}
	tcast_html = $('tcast_Player');
	i = tcast_getList();
	
	var w=440;
	var h=395;
	var _ds='';
	var _os='';
	var tcast_obj ="";
	if(download)
	{
		_os='style="display:none" ';
		_ds='<div class="tallpic"><div class="upload"><p>如果您无法正常安装，请下载控件手动安装！</p>'+
			'<br/><br/><a href="http://nba.tom.com/video/tomliveV'+tcast_f_v+'.msi" target="_blank">'+
			'<img border="0" src="images/uploadbtn.jpg" /></a></div></div>';
	}
	else
	{
		_os='style="margin-top:22px" ';
	}

	if(ie)
	{
		
		tcast_obj = '<div style="width:440px;height:22px;background-color:#1f2a47">'+
		'<div style="margin-top:3px;margin-left:10px;float:left">'+
		'<IMG src="images/Fullscreen01.gif" onmouseout="this.src=\'images/Fullscreen01.gif\'" '+
			'onmouseenter="this.src=\'images/Fullscreen02.gif\'" '+
			'onmousedown="if(event.button==1)this.src=\'images/Fullscreen03.gif\'" '+
			'onmouseup="if(event.button==1){this.onmouseenter();tc.FullScreen=true;}"></div>'+
		'<div style="margin-top:3px;margin-left:10px;float:left;">'+
		'<IMG src="images/View03.gif" '+
			'onmousedown="if(event.button==1){tc.StretchToFit=!tc.StretchToFit;'+
			'if(tc.StretchToFit)this.src=\'images/View03.gif\';else this.src=\'images/View01.gif\';}" >'+
		'</div></div>'+
		'<object id="tc" style="margin-top:1px" classid="clsid:9CA74596-B5BB-4634-971C-F0224115A15F" '+
		'codebase="http://nba.tom.com/video/tcastV'+tcast_f_v+'.cab#version='+tcast_cab_v+'" width="'+w+'" height="'+h+'">'+
		'<param name="url" value="' + slist[i] + '">'+
		'<img id="countimg" src="about:blank" style="display:none"/>';
		tcast_html.innerHTML = "";
		tcast_html.innerHTML = tcast_obj;
		tc.attachEvent("StateChanged", OnStateChanged);
	}
	else
	{
		tcast_obj = '<embed type="application/x-tcast-v1"'+_os+
		'pluginspage="http://nba.tom.com/video/tcastV'+tcast_f_v+'.xpi" width="'+w+'" height="'+h+'" '+
		'url="' + slist[i] + '" directurl="'+hlist[i] + '">'+_ds;
		tcast_obj += '<img src="http://analytics.tom.com/live.png" style="display:none"/>';
		tcast_html.innerHTML = "";
		tcast_html.innerHTML = tcast_obj;
	}
}

function createTcast()
{
	
	function $(i){return document.getElementById(i);}
	var isie = false;

	if (tcast_isplay) {
	return;
  } 
  
  tcast_isplay = true;
  tcast_html = $('tcast_Player');
	if (navigator.userAgent.indexOf('MSIE') == -1) //not ie
	{
		if(navigator.userAgent.indexOf('Firefox/3') == -1 ) // not firefox 3
		{
			if(navigator.userAgent.indexOf('Firefox') == -1) //not firefox, browser not support
			{
				//show message to user
				tcast_html.innerHTML ='<div class="tallpic"><div class="upload bg01">TOMLive控件不支持您的WEB浏览器</div>'+
					'<p style="color:#fff;text-align:center;margin:5px; padding:5px;font-size:14px;">'+
            				'请使用<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9ae91ebe-3385-447c-8a30-081805b2f90b&DisplayLang=zh-cn"'+
            				'target="_blank">Internet Explorer 6.0</a>以上版本或<a href="http://download.mozilla.org/?product=firefox-3.0.3&os=win&lang=zh-CN"'+
            				'target="_blank">Firefox3.0</a>及以上版本浏览器</p></div>';
				return false;
			}
			else //prompt user to update firfox
			{
				//show message to user
				tcast_html.innerHTML ='<div class="tallpic"><div class="upload bg02">请升级浏览器到Firefox 3.0</div>'+
					'<p style="color:#fff;text-align:center;margin:5px; padding:5px;font-size:14px;">'+
					'点击下载<a href="http://download.mozilla.org/?product=firefox-3.0.3&os=win&lang=zh-CN" target="_blank">Firefox 3.0</a></p></div>';
				return false;
			}
		}
		else //firefox 3
		{
			if (navigator.mimeTypes && navigator.mimeTypes.length > 0)
			{
				for (var i=0; i < navigator.mimeTypes.length; i++ )
				{
					if(navigator.mimeTypes[i].type == 'application/x-tcast-v1' && navigator.mimeTypes[i].description == ('TCAST NP' + tcast_ver_4ff) )
					{
						outputTcast(false);
						return true;
					}
				}
			}
		}
	}
	else //ie
	{
		try
		{
			var x = new ActiveXObject('TCAST.Player.' + tcast_ver_4ie);
			
			outputTcast(true);
			return true;
		}
		catch(e){}
		isie = true;
	}
	outputTcast(isie, true);
	
	return false;
}
function checkBufferTimeout(){
	function $(i){return document.getElementById(i);}
	buffertimer=0;
	var ht=$("helptext");var hl=$("helplink");
	if(!ht || !hl)return;
	ht.innerHTML="出现长时间缓冲状态？尝试停止后再点击播放键";hl.href="http://nba.tom.com/help06/index.html";ht.parentNode.style.display="";
	}

function OnStateChanged(s){
	function $(i){return document.getElementById(i);}
	if(s==2)reportCount();
	var ht=$("helptext");var hl=$("helplink");
	if(!ht || !hl)return;
	if(s==4){ht.innerHTML="可能是您的UDP端口受限";hl.href="http://nba.tom.com/help04/index.html";ht.parentNode.style.display="";}
	else if(s==7){ht.innerHTML="为什么“频道已关闭”？请再次点击播放键";hl.href="http://nba.tom.com/help05/index.html";ht.parentNode.style.display="";}
	else if(s==101){if(tc&&tc.BufferingProgress&&buffertimer){window.clearTimeout(buffertimer);buffertimer=0;}}
	else if(s==102){++buffertimes;if(buffertimes>5&&buffertimes*60000/(new Date().getTime()-_starttm)>1)
	{ht.innerHTML="为什么播放断断续续的，不流畅？";hl.href="http://nba.tom.com/help07/index.html";ht.parentNode.style.display="";}
	if(!buffertimer){buffertimer=window.setTimeout("checkBufferTimeout()",20000);}}
}

function vcastrEvent(type,state,playHeadTime,loadPersent) {
	if (state == "paused") {
	    tcast_playednum++; 
	    if( state == "paused" && tcast_playednum == tcast_AdNum)       
	    {  
            //Set cookie to skip the ad
            
             var ua = navigator.userAgent;
						if( ua.indexOf('Opera/9') == -1 )
						{ //not Opera9 
							var  tcast_exp  =new Date();
            	tcast_exp.setTime(tcast_exp.getTime()+tcast_adkeeptime*60*60*1000); 
             	document.cookie ="NBA_ADVERTISE=has_seen;expire="+tcast_exp.toGMTString(); 

            }
            Tcast_Select($('tcast_Player'));
       }
        else {
            //ad switch
        }
   }//paused
}

function tcast_adClick()
{
    var url = tcast_adUrl[tcast_playednum];
    if(url != "#") 
    {
    	var img=document.getElementById('tcast_buffer_click');
			img.src='http://client.skype.tom.com/nba/tcast_buffer_click.gif?'+Math.ceil(Math.random()*100000);
    	window.open(url);
    }
}

  
function tcast_Advertise()
{		function $(i){return document.getElementById(i);}
	    var isie = false;
        var tcast_adFileList = "";
         for(i=0;i<tcast_adFilePath.length;i++)
	    {
	         tcast_adFileList +='<item>'+
							'<source>'+tcast_adFilePath[i]+'</source>'+
							'<duration></duration>'+
							'<link></link>'+
							'<isRepeat>false</isRepeat>'+
						'</item>';
	    }
  
       document.write( '<img id="tcast_buffer_click" src="" style="display:none">'+ 
       '<div id="tcast_Player" style="" > '+ 
       '<button style="z-index:2;width:440px;height:395px;background:transparent;border:0;padding:0;cursor:pointer" onfocus="this.blur();" onclick="tcast_adClick();">'+ '<object  type="application/x-shockwave-flash" data="vcastr3.swf" width="440" height="395" id="vcastr3">'+
			'<param name="movie" value="vcastr3.swf"/> '+
			'<param name="wmode" value="transparent"/>'+         
			'<param name="allowFullScreen" value="false" />'+
			'<param name="FlashVars" value="xml='+
				'<vcastr>'+
					'<channel>'+tcast_adFileList+
						/*'<item>'+
							'<source>NBALive/NBA_BMW.flv</source>'+
							'<duration></duration>'+
							'<link></link>'+
							'<isRepeat>false</isRepeat>'+
						'</item>'*/
	        	'</channel>'+				
					'<config>'+
						   '<controlPanelMode>none</controlPanelMode > '+					  
						   '<isAutoPlay>true</isAutoPlay> '+
						   '<scaleMode>exactFil</scaleMode> '+
						    '<isShowAbout>false</isShowAbout>'+
					'</config>'+
					'<plugIns>'+
						'<javaScriptPlugIn>'+
							'<url>javaScriptPlugIn.swf</url>'+
						'</javaScriptPlugIn>'+					
					'</plugIns>	'+
				'</vcastr>"/>'+
		'</object>'+ 
		' </button>' +	
		'</div>'
	);
    
    tcast_html = $('tcast_Player');
	
	if (document.cookie.indexOf("NBA_ADVERTISE") != -1 || tcast_AdNum == 0) {
        Tcast_Select($('tcast_Player'));
    }
}

//Update from here

function TcastReportCount()
{
	var img=document.getElementById('countimg');
	img.src='http://analytics.tom.com/live.png?'+Math.ceil(Math.random()*100000);
}

function TcastGetUrl()
{
	if(slist.length==0) return false;
	var sl=new Array();
	var ll=0;
	sl[0]=0;
	for(i=0;i<llist.length;++i)
	{
		ll+=llist[i];
		sl[i+1]=ll;
	}
	var rd=Math.random()*ll;
	for(i=sl.length-1;i>=0;--i)
	{
		if(rd>=sl[i]) break;
	}
	return slist[i];
}

function GetTcast() { return document.getElementById('tomcast'); }

function TcastCheckBufferTimeout()
{
	function $(i){return document.getElementById(i);}
	
	buffertimer=0;
	var ht=$("helptext");
	var hl=$("helplink");
	
	if(!ht || !hl)return;
	
	ht.innerHTML="出现长时间缓冲状态？尝试停止后再点击播放键";
	hl.href="http://nba.tom.com/help06/index.html";
	ht.parentNode.style.display="";
}

function Tcast_OnStateChanged(s)
{
	function $(i){return document.getElementById(i);}
	if(s==2)reportCount();
	var ht=$("helptext");
	var hl=$("helplink");
	
	if(!ht || !hl)return;
	
	if(s==4)
	{
		ht.innerHTML="可能是您的UDP端口受限";
		hl.href="http://nba.tom.com/help04/index.html";
		ht.parentNode.style.display="";
	}
	else if(s==7)
	{
		ht.innerHTML="为什么“频道已关闭”？请再次点击播放键";
		hl.href="http://nba.tom.com/help05/index.html";
		ht.parentNode.style.display="";
	}
	else if(s==101)
	{
		var tc = GetTcast();
		if(tc&&tc.BufferingProgress&&buffertimer)
		{
			window.clearTimeout(buffertimer);buffertimer=0;
		}
	}
	else if(s==102)
	{
		++buffertimes;
		if(buffertimes>10&&buffertimes*60000/(new Date().getTime()-_starttm)>1)
		{
			ht.innerHTML="为什么播放断断续续的，不流畅？";
			hl.href="http://nba.tom.com/help07/index.html";
			ht.parentNode.style.display="";
		}
		if(!buffertimer)
		{
			buffertimer=window.setTimeout("TcastCheckBufferTimeout()",20000);
		}
	}
}

function Tcast_Active() //控件已经加载
{
	GetTcast().Events.Attach('StateChanged', Tcast_OnStateChanged);
	document.getElementById('tcastheader').style.display = 'block';
}

function Tcast_CreateTcast(elem)
{
	
	function $(i){return document.getElementById(i);} 
	if (tcast_isplay) {
      return;
  } 
  tcast_isplay = true; 

		do
	{
		var videosrc = TcastGetUrl();
		var result = 0;
		var targ="5gkAAAECFdLHB9CZsM/opQnbI3vRn67xoKZRtUk+cCdzbVyr7Cb+8j+3woj3RgbhfFVmnI7YOJ2sawc4IkbAdrwoCtPiw+kQRGB2Cm2NO3REJ9OA44S7SLyKbFgssLEX0Vswowoq95mkLiR7AdXQ8Elk2HfOK7oxxNPbQiDDpnUBpcxB3dknZw1sEp9U8NpR46VzNrcXtg9gIJX5ALFNgmVqRGtj48VLna9be1ZT3g+PWHAt6tcLT/pi3mqmPAYDr+0JUanbxJY2WUSov1S7cn7b3J7kmHe43IuLVdJl8e3vV29IZ8t0kKwnTgjS8SndUQ==";
	
		var ua = navigator.userAgent;
		var ss = new Array();
		_ds='<center><div style="width:520px;height:405px;background:#000;overflow:hidden"><div class="upload"><p>如果您无法正常安装，请下载控件手动安装！</p>'+
			'<br/><br/><a href="http://nba.tom.com/video/TOM_NBA_Setup.zip" target="_blank">'+
			'<img border="0" src="images/uploadbtn.jpg" /></a></div></div></center>';
		ss.push('<img id="countimg" src="about:blank" style="display:none"/>');
		ss.push('<center><div id="tcastheader" style="display:none;width:440px;height:22px;background-color:#1f2a47">');
			ss.push('<div style="margin-top:3px;margin-left:10px;float:left">');
				ss.push('<IMG src="images/Fullscreen01.gif" ');
				ss.push('onmouseout="this.src=\'images/Fullscreen01.gif\'" ');
				ss.push('onmouseover="this.src=\'images/Fullscreen02.gif\'" ');
				ss.push('onmousedown="this.src=\'images/Fullscreen03.gif\'" ');
				ss.push('onmouseup="this.onmouseout();GetTcast().FullScreen=true;">');
			ss.push('</div>');
			ss.push('<div style="margin-top:3px;margin-left:10px;float:left;">');
				ss.push('<IMG src="images/View03.gif" ');
				ss.push('onmousedown="var tc=GetTcast();tc.StretchToFit=!tc.StretchToFit;');
				ss.push('if(tc.StretchToFit)this.src=\'images/View03.gif\';else this.src=\'images/View01.gif\';" >');
			ss.push('</div>');
		ss.push('</div></center>');
		
		if( ua.indexOf('MSIE') != -1 )
		{
			try
			{
				var x = new ActiveXObject("XPPIE.XPPIECtrl");
				result = 1;
			}catch(e){}
			
			ss.push('<object id="tomcast" classid="clsid:5AB1EF72-6CC6-4090-9030-8E0ACF7E6D3E" codebase="http://nba.tom.com/video/xppie.cab#version=1.0.0.1" width="440" height="395">');
			ss.push('<param name="Target" value="');
			ss.push(targ);
			ss.push('">');
			ss.push('<param name="url" value="');
			ss.push(videosrc);
			ss.push('">');
			ss.push('<param name="PluginLoaded" value="Tcast_Active()">');
			if(!result)	ss.push(_ds); //插件没有安装
			ss.push('</object>');
		}
		else if( (ua.indexOf('Firefox/3') != -1 || ua.indexOf('Opera/9') != -1) || ua.indexOf('Chrome') != -1 )
		{
			if(navigator.mimeTypes)
			{
				for (var i=0; i < navigator.mimeTypes.length; i++)
				{
					if(navigator.mimeTypes[i].type == 'application/x-tom-xpp')
					{
						result = 1;
						break;
					}
				}
			}
			
			if(!result) ss.push('<div style="display:none">');
			ss.push('<embed id="tomcast" ');
			ss.push('type="application/x-tom-xpp" pluginspage="http://nba.tom.com/video/xppff.xpi" width="440" height="395" ');
			ss.push('Target="');
			ss.push(targ);
			ss.push('" url="');
			ss.push(videosrc);
			ss.push('" PluginLoaded="Tcast_Active()">');
			if(!result) ss.push('</div>');
			if(!result) ss.push(_ds);
		}
		else
		{
			break;
		} 
		//if(elem)
			//$('tcast_Player').innerHTML = ss.join('');
		//else
		if(tcast_version == 0)
		{
			document.write(ss.join(''));
		}
		else $('tcast_Player').innerHTML = ss.join('');
		return result;
		
	} while(false);
	
	var d = document;
	d.write('<div class="tallpic">');
		d.write('<div class="upload bg01">您的WEB浏览器不支持TOM直接软件</div>');
		d.write('<p style="color:#fff;text-align:center;margin:5px; padding:5px;font-size:14px;">');
			d.write('请使用Internet Explorer 6.0、Firefox 3.0、Opera 9.0、Google Chome。(或以上版本)');
	d.write('</p></div>');

	return 2;
}

function CheckXPPInstalled() //判断插件是否安装,0没安装,1已经安装,2浏览器不支持
{
	var ua = navigator.userAgent;
	if( ua.indexOf('MSIE') != -1 )
	{
		try
		{
			var x = new ActiveXObject("XPPIE.XPPIECtrl");
			return 1;
		}catch(e){}
	}
	else if( (ua.indexOf('Firefox/3') != -1 || ua.indexOf('Opera/9') != -1) || ua.indexOf('Chrome') != -1 )
	{
		if(navigator.mimeTypes)
		{
			for (var i=0; i < navigator.mimeTypes.length; i++)
			{
				if(navigator.mimeTypes[i].type == 'application/x-tom-xpp')
					return 1;
			}
		}
	}
	else
		return 2; //浏览器不支持

	return 0; //插件没有安装
}

function CheckTcastInstalled()
{
	try
	{
		var x = new ActiveXObject('TCAST.Player.' + tcast_ver_4ie);
	}
		catch(e){
	return false;
	}
	return true;
} 

function Tcast_CheckTcast()
{ 
	var nCheck = CheckXPPInstalled();
  	if( nCheck == 0 && CheckTcastInstalled () )
  	{
  			if(Math.random()*10 > 5)
  			{
				tcast_version = 1;
				return true;
  			}
  	}
  	else if( nCheck  == 1 )
 		{
  		tcast_version  = 2;
   		return true;
  	}
  	tcast_version = 0;
  	Tcast_CreateTcast ();
	return false;
}         
  
function Tcast_Select()
{
	if(tcast_version == 1)
	{
		createTcast();
	}
	else {
		Tcast_CreateTcast();
	}
}
      
//Start from here 
if(Tcast_CheckTcast() == true){    
	getAdvertiseConfig("adconfig.xml");
	tcast_Advertise();
	if(document.cookie.indexOf("NBA_ADVERTISE") == -1){
		window.setTimeout('Tcast_Select()',tcast_adtime);
	}	
}




