﻿document.domain="xunlei.com";
var G_BUILD_VERSION=0;
var G_FLA_VERSION=0;
var G_TV5_BUILD=0;
var G_TV6_BUILD=0;
var G_WTV_BUILD=0;
var G_DAPCTRL_VER=0;
var G_VERSION=0;
var G_OCX_XPLAYER=null;
var G_CLICK_STAT=new Image(1,1);
var G_IS_HOMEPAGE = false;
//window.onerror=function(){return true;}
var isIE=(navigator.appName).indexOf("Microsoft")!=-1;if(window.Event&&!isIE){function SearchEvent(){var func=SearchEvent.caller;while(func!=null){var arg=func.arguments[0];if(arg){if(String(arg.constructor).indexOf('Event')>-1){return arg}}func=func.caller}return null};window.constructor.prototype.__defineGetter__("event",function(){return SearchEvent()});Event.prototype.__defineSetter__("returnValue",function(bool){if(!bool){this.preventDefault()}return bool});Event.prototype.__defineSetter__("cancelBubble",function(bool){if(bool){this.stopPropagation()}return bool});Event.prototype.__defineGetter__("clientX",function(){return this.pageX});Event.prototype.__defineGetter__("clientY",function(){return this.pageY});Event.prototype.__defineGetter__("keyCode",function(){return this.which});Event.prototype.__defineGetter__("button",function(){return this.which});Event.prototype.__defineGetter__("srcElement",function(){var n=this.target;while(n.nodeType!=1){n=n.parentNode}return n});Event.prototype.__defineGetter__("offsetX",function(){return this.layerX});Event.prototype.__defineGetter__("offsetY",function(){return this.layerY});Event.prototype.attachEvent=function(type,handler){this.addEventListener(type.substring(2),handler,true)};Event.prototype.detachEvent=function(type,handler){this.removeEventListener(type.substring(2),handler,true)};window.constructor.prototype.attachEvent=function(type,handler){this.addEventListener(type.substring(2),handler,true)};window.constructor.prototype.detachEvent=function(type,handler){this.removeEventListener(type.substring(2),handler,true)};document.constructor.prototype.attachEvent=function(type,handler){this.addEventListener(type.substring(2),handler,true)};document.constructor.prototype.detachEvent=function(type,handler){this.removeEventListener(type.substring(2),handler,true)};Element.prototype.attachEvent=function(type,handler){this.addEventListener(type.substring(2),handler,true)};Element.prototype.detachEvent=function(type,handler){this.removeEventListener(type.substring(2),handler,true)};HTMLElement.prototype.attachEvent=function(type,handler){this.addEventListener(type.substring(2),handler,true)};HTMLElement.prototype.detachEvent=function(type,handler){this.removeEventListener(type.substring(2),handler,true)}}
function $(s){return document.getElementById(s);}function $P(child,parent){return parent?parent.appendChild(child):document.body.appendChild(child);}function $C(s){return document.createElement(s);};function $R(child,parent){return parent?parent.removeChild(child):document.body.removeChild(child);};var E=new Object;E.add=function(o,t,f){if(o.addEventListener){o.addEventListener(t,f,false)}else if(o.attachEvent){o.attachEvent("on"+t,f)}else{o["on"+t]=f}};E.remove=function(o,t,f){if(o.removeEventListener){o.removeEventListener(t,f,false)}else if(o.detachEvent){o.detachEvent("on"+t,f)}else{o["on"+t]=null}};E.formatEvent=function(e){if(isIE&&isWin){e.charCode=(e.type=="keypress")?e.keyCode:0;e.eventPhase=2;e.isChar=(e.charCode>0);e.pageX=e.clientX+document.body.scrollLeft;e.pageY=e.clientY+document.body.scrollTop;e.preventDefault=function(){this.returnValue=false};if(e.type=="mouseout"){e.relatedTarget=e.toElement}else if(e.type=="mouseover"){e.relatedTarget=e.fromElement}e.stopPropagation=function(){this.cancelBubble=true};e.target=e.srcElement;e.time=(new Date).getTime()}return e};E.get=function(){if(window.event){return this.formatEvent(window.event)}else{return E.get.caller.arguments[0]}};function GetDataByIframe(url,cbf,err,para){if((cbf[0]&&typeof(cbf[0])!='function')||typeof(cbf)!='function'){return alert('cbf function is in error!')}if(url instanceof Array){for(var i=0;i<arr_url.length;i++){doWork(url[i],cbf[i],para[i])}}else if(typeof(url)=='string'){doWork(url,cbf,para)}function doWork(u,cb,p){var idp=$C('iframe');idp.style.display='none';idp.src=u;E.add(idp,'load',icb);function icb(){E.remove(idp,'load',icb);var json=idp.contentWindow.jsonObj;if(!json){if(typeof(err)=='function'){$R(idp);return err();}else{$R(idp);return;}}$R(idp);cb(json,p)}$P(idp)}};
function checkOldComponent(){
    var dapCtrl = null;
    var _iThunderVersion = 0;
    var _result = 0;
    try{
        dapCtrl = new ActiveXObject("DapCtrl.DapCtrl");
        _iThunderVersion = dapCtrl.Get("iThunderVersion");
        if(330 == _iThunderVersion){
            _result = 3;
        }else{
            if(_iThunderVersion >= 463){
                _result = 1;
            }else if(_iThunderVersion < 0){
                _result = 2;
            }else if(_iThunderVersion > 0 && _iThunderVersion < 463){
                _result = -1;
            }
        }
    }catch(e){_result=-1;_iThunderVersion=0;}finally{dapCtrl = null;}
    return {result:_result, iThunderVersion:_iThunderVersion};
}
function $init(){
    var xplayer = null;
    var com = checkOldComponent();
    try{
        xplayer = new ActiveXObject("PPlayer.XPPlayer");
        var ver = xplayer.PlayerVersion;
        var build = parseInt(ver.split(".")[3],10);
        G_BUILD_VERSION = build;
        G_OCX_XPLAYER=xplayer;
        G_VERSION=ver;
        G_DAPCTRL_VER=xplayer.Get("iVersion");
        if(com.result > 0 && undefined == G_DAPCTRL_VER){
            switch(com.result){
                case 1: G_TV5_BUILD = com.iThunderVersion;break;
                case 2: G_WTV_BUILD = Math.abs(com.iThunderVersion);break;
            }
        }else if(-1 == com.result){
            G_OCX_XPLAYER = null;
            G_VERSION = 0;
            G_BUILD_VERSION = 0;
            G_DAPCTRL_VER = 0;
        }else{
            G_TV5_BUILD=xplayer.Get("iTVBuild");
            G_TV6_BUILD=xplayer.Get("iTV6Build");
            G_WTV_BUILD=xplayer.Get("iWTVBuild");
        }
    }catch(e){}finally{xplayer = null;}
    com = null;
    var pattern = /(\d+\,?)+/;
    var swf = null;
    var sVersion = 0;
    try{
        swf = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
        sVersion = pattern.exec(swf.GetVariable("$version"));
        G_FLA_VERSION = parseInt(sVersion, 10);
    }catch(e){}finally{swf=null;pattern=null;}
}$init();
String.prototype.trim = function(){
	return this.replace(/\s+/gm,"");
}
String.prototype.lTrim = function(){
    return this.replace(/^\s+/gm,"");
}
String.prototype.rTrim = function(){
    return this.replace(/\s+$/gm,"");
}
String.prototype.size = function(){
    return this.replace(/[^\u0000-\u00FF]/gmi, "**").length;
}
function $(s){
	return document.getElementById(s);
}
function $C(tagName){
	return document.createElement(tagName);
}
function $P(child,parent){
	return parent?parent.appendChild(child):document.body.appendChild(child);
}
function $R(child,parent){
	return parent?parent.removeChild(child):document.body.removeChild(child);
}
var ioCtrl = {
    ioWriter:function(name,value,hours){
        if(G_DAPCTRL_VER>200000){
            this.ioCtrlWriter(name,value,hours||null);
        }else{
            if(hours){
                setCookie(name,value,hours);
            }else{
                setCookie(name,value);
            }
        }
    },
    ioReader:function(name){
        if(G_DAPCTRL_VER>200000){
            return this.ioCtrlReader(name) || "";
        }else{
            return getCookie(name);
        }
    },
    ioCtrlWriter:function(key, value, expires){
        var player = G_OCX_XPLAYER;
        var iExpire = expires || 720;
        player.Put("sCookieFileName", key+".dat");
        player.Put("sCookie", value+"～"+((new Date().getTime()) + iExpire * 3600000));
        player = null;
    },
    ioCtrlReader:function(key){
        var player = G_OCX_XPLAYER;
        var sCookie = null;
        var value = null;
        player.Put("sCookieFileName", key+".dat");
        sCookie = player.Get("sCookie")||null;
        if(null != sCookie){
            value = ioCtrlCheck(sCookie);
        }
        player = null;
        return value;
        function ioCtrlCheck(sCookie){
            var items = sCookie.split("～");
            var curDate = expires = 0;
            var value = null;
            if(items.length != 2){return null;}
            value = ""==items[0]?null:items[0];
            expires = parseInt(items[1], 10);
            curDate = new Date().getTime();
            if(curDate > expires){
                return null;
            }else{
                return value;
            }
        }
    }
};
function slice(a,l){
    if("undefined" == typeof(a)){return "";}
    var as=a.split("");
    var n=0;
    var s="",u="";
    for(var i=0;i<as.length;i++){
        u=as[i];
        if(n+u.size()<=l){
            s+=u;
        }else{ break;}
        n+=u.size();
    }
    return s.substr(0,s.length);
}
var Other={};

Other.build=function(){
	function cbf(json){
		var tag=['movie','tv','fun','cartoon'];
		var logs=['B0016;','B0023;','B0031;','B0038;'];
		for(var i=0;i<4;i++){
			var data=json[tag[i]];
			var html=[];
			for(var j=0;j<3;j++){
				html.push('<li><a onclick="L(\''+logs[i]+'\')" href="'+KK.playUrl(data[j].id)+'" target="kankanWindow"><img  title="点击播放&#13;&#10;'+data[j].name+'" src="'+data[j].pic+'" /></a><p><a onclick="L(\''+logs[i]+'\')" href="'+KK.playUrl(data[j].id)+'" target="kankanWindow" title="点击播放&#13;&#10;'+data[j].name+'">'+data[j].name+'</a></p></li>');
			}
			$('ul_'+tag[i]+'_other').innerHTML=html.join('');
			html=null;
		}
	}
	GetDataByIframe(KK.baseUrl+'list/vodlist_timer.html ',cbf);
}
Other.related=function(){
	var id=(getInfo())[0].movie_id;
	var url='';
	if(id){
		url=KK.baseUrl+'movie/'+id%100+'/'+id+'_timer.html';
	}else{
		url=KK.baseUrl+'movie/0/0_timer.html';
	}
	GetDataByIframe(url,cbf,onerror);
	function cbf(json){
		var html='';
		var obj=json.relative;
		//for(var i=0;i<obj.length-1;i++){
		for(var i=0;i<2;i++){
			html+='<li><a onclick="L(\'B0004;\')" href="'+KK.playUrl(obj[i].id)+'" target="kankanWindow"><img src="'+obj[i].pic+'" alt="" title="点击播放&#13;&#10;'+obj[i].name+'"/></a><div class="mov-title"><a onclick="L(\'B0004;\')" href="'+KK.playUrl(obj[i].id)+'" target="kankanWindow" title="点击播放&#13;&#10;'+obj[i].name+'">'+obj[i].name+'</a><a href="'+KK.playUrl(obj[i].id)+'" title="播放" target="kankanWindow" class="playMov"><img src="http://misc.web.xunlei.com/movie/img/playMov.png"  /></a></div></li>';
		}
		$('ul_related').innerHTML=html;
	}
	function onerror(){
		GetDataByIframe(KK.baseUrl+'movie/0/0_timer.html',cbf);
	}
}
var KK={};
KK.baseUrl='http://kankan.xunlei.com/5.1/';
KK.position=function(o){
	var p={Top:0,Left:0};
	while(!!o){
		p.Top+=o.offsetTop;
		p.Left+=o.offsetLeft;
		o=o.offsetParent;
	}
	return p;
}

KK.scrollCross={interval:0,count:0,duration:0,step:0,srcObj:null,callback:null};
KK.scrollCross.doit=function(obj,b,c,d){
	var s=KK.scrollCross;
	obj.style.marginLeft=cpu(s.count,b,c,d)+'px';
	s.count++;
	if(s.count==d){
		clearInterval(s.interval);
		s.count=0;
		obj.style.marginLeft=b+c+'px';
		s.callback();
	}
	function cpu(t,b,c,d) {return c*((t=t/d-1)*t*t+1)+b;};
}
KK.scrollCross.scroll=function(obj,step,span,beign,callback,duration){
	var s=KK.scrollCross;
	s.duration=duration;
	s.callback=callback;
	s.interval=setInterval(function(){s.doit(obj,beign,step*span,duration)},10);
}
KK.playUrl=function (id){
	return KK.baseUrl+'movie/'+id%100+'/'+id+'.html';
}
function logForClick(s){
    return;
    var url = "http://statis.kankan.xunlei.com/fcg-bin/cgi_click_statis_4.0.fcg?Log4Click="+encodeURIComponent(s)+"&cachetime="+getCacheTime();
    try{$("Stat").send(url);}catch(e){G_CLICK_STAT.src=url;}
}

//----------------------//
var G_ITEMS_CHAR="@@";
var G_GROUP_CHAR="|";
function string2Array(str,splitChar){
	return str.split(splitChar);
}
function array2String(arr,joinChar){
	return arr.join(joinChar);
}
function latest2normal(latest){
    var item=string2Array(latest,G_ITEMS_CHAR);
    return array2String(item.slice(0,6),G_ITEMS_CHAR);
}
function writeInfo(str){
	ioCtrl.ioWriter('view_histroy',str,720);
}
function readInfo(){
    return ioCtrl.ioReader("view_histroy");
}
function rewriteInfo(newInfo){
    var oldInfo = readInfo();
    var group = string2Array(oldInfo,G_GROUP_CHAR);
    var size = group.length;
    group.unshift(newInfo);
    ""==group[1]?group.pop():group[1]=latest2normal(group[1]);
    writeInfo(array2String(group.slice(0,6),G_GROUP_CHAR));
}
function checkInfoFormat(){
    var info = readInfo();
    var group = string2Array(info,G_GROUP_CHAR);
    var items = [];
    if(group.length > 0){
        items = string2Array(group[0],G_ITEMS_CHAR);
        if(items.length != 10){
            writeInfo("");
        }
    }
}
function removeExistInfo(movieName){
    var info = readInfo();
    var group = string2Array(info,G_GROUP_CHAR);
    for(var i=group.length-1;i>=0;i--){
        if(decodeURI(group[i]).indexOf(movieName) != -1){
            group.splice(i,1);
        }
    }
    writeInfo(array2String(group,G_GROUP_CHAR));
}
function formatInfo(info){
    var items=string2Array(info,G_ITEMS_CHAR);
    var size=items.length;
    if(size>6){
        return {isLatest:true,movie_id:items[0],time:items[1],movie_name:decodeURI(items[2]),cp:items[3],ext:items[4],type:items[5],subid:items[6],subname:decodeURI(items[7]),nextid:items[8],nextname:decodeURI(items[9])};
    }else{
        return {isLatest:false,movie_id:items[0],time:items[1],movie_name:decodeURI(items[2]),cp:items[3],ext:items[4],type:items[5]};
    }
}
function getInfo(){
    checkInfoFormat();
    var info = readInfo();
    var group = string2Array(info,G_GROUP_CHAR);
    var size = group.length;
    var tmp = [];
    for(var i=0;i<size;i++){
        tmp.push(formatInfo(group[i]));
    }
    return tmp;
}
function getLatestInfo(){
    var group = getInfo();
    if(group.length>0){
        return group[0];
    }else{
        return null;
    }
}
function setEmpty(bool){
    if(bool){
        writeInfo("");
    }
    $('view_history').innerHTML = '<center>您的观看历史为空。</div>';
}
function parseLinkScript(script){
    var userAgent = navigator.userAgent.toLowerCase();
    var env = null;
    var ver = 0;
    var link = ' href="javascript:'+script+';" ';
    env = userAgent.match(/msie ([\d.]+)/);
    ver = env ? parseInt(env[1], 10) : 0;
    if(ver < 7){
        link=' onclick="'+script+';" href="#" ';
    }
    return link;
}
function _GL(id,s,type,cp){
    var url="about:blank";
    var pattern=/^(http\:\/\/play\.)/gi;
    try{
        url=G_CP_MAP[cp].url;
        if(!url || pattern.test(url)){
            if(type==2){
                url = "http://live.kankan.xunlei.com/lunbo.html?id="+id;
            }else{
                url = "http://live.kankan.xunlei.com/live.html?id="+id;
            }
        }else{
            url=url+'?platform=2&ch_type='+type+'&id='+id;
        }
    }catch(e){
        if(type==2){
            url = "http://live.kankan.xunlei.com/lunbo.html?id="+id;
        }else{
            url = "http://live.kankan.xunlei.com/live.html?id="+id;
        }
    }
    win = window.open(url, "kankanWindow");
    win.focus();
    return null;
}
function getPlayUrl(cpIds, movieid, subid, ext, stat){
    var items = cpIds.split("|");
    var size= items.length;
    var filters = [];
    var rnd = 0;
    var url = "";
    for(var i = 0; i < size; i++){
        if(items[i]){
            filters.push(i);
        }
    }
    if(filters.length > 0){
        rnd = filters[Math.floor(Math.random() * filters.length)];
    }
    if("undefined" != typeof(G_CP_MAP) && typeof(G_CP_MAP[rnd]) != "undefined" && G_CP_MAP[rnd].url != "http://play.kankan.xunlei.com/"){
        url = G_CP_MAP[rnd].url || "http://kankan.xunlei.com/";
    }else{
        url = "http://kankan.xunlei.com/";
    }
    subid = subid || null;
    if(url != "http://kankan.xunlei.com/"){
        return ' onclick="logForClick(\''+stat+'\')" href="'+url+'?platform=6&hallid='+movieid+(null!=subid?'&subid='+subid:'')+'" target="kankanWindow"';
    }else{
        return ' onclick="logForClick(\''+stat+'\')" href="'+url+'5.1/movie/'+(parseInt(movieid, 10)%100)+'/'+movieid+'.html'+(null!=subid?'?subid='+subid:'')+'" target="kankanWindow"';
    }
}
function buildViewHistory(s1,s2,l1,l2,limit,wb){
	if(!limit){limit=5};
	if(!wb){wb=12;}
	var latest=getLatestInfo();
	var items=getInfo();
	var item=null;
	var sHtml="",tmp="";
	if(!latest){
		setEmpty(false);
    return false;
	}else{
		
		if(!latest.movie_id){
			setEmpty(true);
      return false;
		}else{
      sHtml='<p><span style="color:#939393" >'+calcTime(latest.time)+'看过</span> ';
      if("0"==latest.type+"" || "3"==latest.type+""){
          sHtml+='<a'+getPlayUrl(latest.cp,latest.movie_id,latest.subid,latest.ext,s1)+' title="点击播放&#13;&#10;'+latest.movie_name+'-'+latest.subname+'" class="a_blue">'+slice(latest.movie_name+'-'+latest.subname,wb)+'</a></p>'+(latest.nextid!='NO'?'<p><em style="font-style:normal;color:#FF5B01;" >您是否需要观看</em> <a'+getPlayUrl(latest.cp,latest.movie_id,latest.nextid,latest.ext,s1)+' title="点击播放&#13;&#10;'+latest.movie_name+'-'+latest.nextname+'" class="a_blue">'+slice(latest.nextname,13)+'</a></p>':'');
      
      }else if("1"==latest.type+"" || "2"==latest.type+""){
          sHtml+='<a'+parseLinkScript('_GL('+latest.movie_id+',\''+s1+'\',\''+latest.type+'\',\''+latest.cp+'\')')+'title="点击播放&#13;&#10;'+latest.movie_name+'" class="a_blue">'+slice(latest.movie_name,wb)+'</a></p>';
      }else{
          setEmpty(true);
          return false;
      }
     
			sHtml+='<div style="border-bottom:1px dotted #CFCFCF; height:6px; overflow:hidden" ></div>';
			var tmp_html='';
            for(var i=1;i<items.length && i<limit;i++){
                item=items[i];
                if("0"==item.type+""||"3"==item.type+""){
                    tmp_html+='<li><a'+getPlayUrl(item.cp,item.movie_id,null,item.ext,s2)+' title="点击播放&#13;&#10;'+item.movie_name+'">'+slice(item.movie_name, l1||10)+'</a>&nbsp;&nbsp;&nbsp;'+slice(calcTime(item.time)+'看过', l2||10)+'<span>&nbsp;&nbsp;&nbsp;'+formatDate(item.time)+'</span></li>';
                }else if("1"==item.type+"" || "2"==item.type+""){
                    tmp_html+='<li><a'+parseLinkScript('_GL('+item.movie_id+',\''+s2+'\', \''+item.type+'\', \''+item.cp+'\')')+'title="点击播放&#13;&#10;'+item.movie_name+'">'+slice(item.movie_name, l1||10)+'</a> &nbsp;&nbsp;&nbsp;'+slice(calcTime(item.time)+'看过', l2||10)+'<span>&nbsp;&nbsp;&nbsp;'+formatDate(item.time)+'</span></li>';
                }else{
                    setEmpty(true);
                    return false;
                }
            }
			if(tmp_html!=''){
				sHtml+='<ul class="looked">'+tmp_html+'</ul>';
			}
			
		}
	}
	
	
	$('view_history').innerHTML=sHtml;
    function formatDate(str){
        var d = new Date(parseInt(str));
        return ((d.getMonth()+1)<10?"0"+(d.getMonth()+1):(d.getMonth()+1))+"-"+(d.getDate()<10?"0"+d.getDate():d.getDate());
    }
	function calcTime(t){
		var str;
		var m=Math.round((new Date().getTime()-t)/(1000*60));
		if(m<60){
			str=(m?m:1)+'分钟前';
		}else if(m<(60*24)){
			str=Math.round(m/60)+'小时前';
		}else{
			str=Math.round(m/(60*24))+'天前';
		}
		return str;
	}
}
function _GC(){
	cleanViewHistory();
	function cleanViewHistory(){
		setEmpty(true);
	}
}
