/// <reference path="Extjs_Intellisense.js" />
/// <reference path="src/data/XmlStore.js" />
/// <reference path="addjs/Base.js" />
/// <reference path="addjs/XmlTreeLoader.js" />

connectwhileclick=false;


function InvitePTZControl(devid)
{
    try
    {
        var obj=$("loginobj");
        obj.InvitePTZControl(devId);
        obj.SendPTZCmd(devid,1,"<xml>\n<cmd>GetPresetList</cmd>\n</xml>");
    }catch(eevv){}
}

 

//unload body will call this function
function ExitIE()
{
    if(__userFCom)
    {     
        WriteWebLog("IE退出，调用audioobj FCom_Free开始...");
        try
        { 
            var audioobj=$("audioobj");
            if(LastTackCameraId!="")
            {
                WriteWebLog("停止对讲"+LastTackCameraId);
                var stopret=obj.FCom_StopTalk(LastTackCameraId);
                LastTackCameraId="";
            }
            try
            {
                audioobj.FCom_Free();
            }catch(eev2)
            {
                
            }
            try
            {
                audioobj.FCom_ClientLogOut();        
            }catch(eevv){}
        }catch(eee){}
        WriteWebLog("IE退出，调用audioobj FCom_Free结束...");
    }
    
      
    var playlist="player1,player2,player3,player4,replay1,replay2";
    var plls=playlist.split(",");
    WriteWebLog("IE退出player开始调用start StopWithOutWait...");  
    try
    {
        for(var idx=0;idx<plls.length;idx++)
        {
            try
            {
                var plobj=GetPlayerById(plls[idx]); 
                if(plobj && plobj.width!=undefined)
                {
                    if(plobj.IsRecording)
                    {
                        plobj.StopRecord();
                    }
                    plobj.StopWithOutWait();
                }
            }catch(eee){}
        }
        WriteWebLog("IE退出调用,end StopWithOutWait,start Stop and Release...");  
        for(var idx=0;idx<plls.length;idx++)
        {
            try
            {
                var plobj=GetPlayerById(plls[idx]);
                try
                {
                    if(plobj  && plobj.width!=undefined  )
                    {
                        plobj.Stop();
                        plobj.ReleaseByIE();
                    }
                }catch(eeevv){}
                plobj=null;
            }catch(eeee){}
        }
    }catch(ee){}
    WriteWebLog("IE退出player结束调用...");
    
     
    
        
    WriteWebLog("IE退出，调用LogoutPlat开始...");
    var obj=$("loginobj");
    try
    {
        obj.detachEvent("OnInterfaceXMLResp",OnLoginObj);
        if(LastTackCameraId!="")
        {
            obj.StopTalk(LastTackCameraId);//stop 
            LastTackCameraId="";
        }
        try
        {
            obj.LogoutPlat();
        }catch(ee){}
    }catch(ee){}
    try
    {
        var releaseValue=obj.ReleaseCtrl();
    WriteWebLog("ReleaseCtrl return "+releaseValue);
    }catch(eeee){}
    WriteWebLog("IE退出，调用LogoutPlat结束...");
}


function PlayFile(ip,port,user,DevId,item,typev)
{
    var obj;    
    lastRealPlayIdx=GetReplayPlayerIdx();
    obj=$("replay"+lastRealPlayIdx);
    var ipvalue=obj.IpStr2Value(ip);
    try
    {
        obj.SetVideoParameter(ipvalue,port,ipvalue,port,0);
        var ret=obj.PlayVSSFile(ipvalue,port,user,DevId,item,typev);
        return ret;
    }catch(ee){}
    return -1000;
}


function OnLoadBody()
{
    if(IsAutoLoginMode)
    {//自动登录模式时,一定是自动填写帐号,不允许用户更改
        var player=GetPlayerById("player1");
        var autoLoginUser=player.GetMacAddr();
        $("username").value=autoLoginUser;
        $("password").value=autoLoginUser;
        $("ipAddr").value=AutoLoginServer;
        $("port").value="" + AutoLoginServerPort;
    }
    
    if(AutoReadIpFromIeURL)
    {
        try
        {
            var urlstr="" + top.location;
            urlstr=urlstr.replace("http://","");
            urlstr=urlstr.replace("http:\\","");
            urlstr=urlstr.replace(/[/]+/g,"\\");
            var ls=urlstr.split("\\");
            var ipport=ls[0].split(":");
            if($("ipAddr").value=="")
            {
                $("ipAddr").value=ipport;
            }
        }catch(eeee){}
    }
}


function ShowSelectPlayer()
{
    WriteWebLog("Change Select Player "+selectPlayerId);
    for(var idx=1;idx<=Max_play_Count;idx++)
    {
        var nowplayer="player"+idx;
        if(nowplayer==selectPlayerId)
        {
            var obj=$("loginobj");
            var devId=playobjDevIdList[nowplayer];
            try
            {
                //GetPlayerById(nowplayer+"div").className="SelectPlayer";
                var tempdiv=GetPlayerById(nowplayer+"div");
                if(tempdiv.className!="SelectPlayer")
                {
                    tempdiv.className="SelectPlayer";
                }
            }catch(eeee){}
            if(devId!==undefined && devId!=="" && devId.length>2)
            {
                var videoType=main_but_d1;//Ext.get("ChangeVideoType");
                
//              var main_but_stop=null;
//              var main_but_d1=null;
//              var main_but_stopsound=null;
                
                //PlayVideoTypeList[selectPlayerId]=""+streamId;//流0表cif,1表示d1
                if(videoType)
                {
                    if(PlayVideoTypeList[selectPlayerId]=="1" || PlayVideoTypeList[selectPlayerId]==1)
                    {//如果当前正在播放D1
                        videoType.setText(GetDefaultLang("lang_swidthcif","切换子码流"));
                    }else
                    {
                        videoType.setText(GetDefaultLang("lang_switchd1","切换主码流"));
                    }
                }
                
                var playsound=main_but_stopsound;//Ext.get("PlaySound");
                var playobj=GetPlayerById(selectPlayerId);
                if(playsound)
                {
                    if(playobj.AudioIsOn && ""!=devId)
                    {
                        playsound.setText(GetDefaultLang("lang_stopsound","停止声音"));
                    }else
                    {
                        playsound.setText(GetDefaultLang("lang_startsound","播放声音"));
                    }
                }
                if(main_but_record)
                {
                    if(playobj.IsRecording)
                    {
                        main_but_record.setText(GetDefaultLang("lang_stoprecord","停止录像"));
                    }else
                    {
                        main_but_record.setText(GetDefaultLang("lang_startrecord","开始录像")); 
                    }
                }
                if(LastTackCameraId==devId)
                {
                    main_but_startaudio.setText(GetDefaultLang("lang_stopaudio","停止对讲"));
                }else
                {
                    main_but_startaudio.setText(GetDefaultLang("lang_startaudio","启动对讲"));
                }                
                main_but_stop.enable();
                main_but_stopsound.enable();
                main_but_d1.enable(); 
                main_but_startaudio.enable(); 
                main_but_record.enable(); 
                main_but_capture.enable(); 
            }else
            {
                main_but_stopsound.setText(GetDefaultLang("lang_startsound","播放声音"));
                main_but_stop.disable();
                main_but_stopsound.disable();
                main_but_d1.disable(); 
                main_but_startaudio.disable(); 
                main_but_record.disable(); 
                main_but_capture.disable(); 
                LastCmdOkDevId="";
                continue;// 选择到没有在播放的播放窗口，则不进行播放 ,不能改成break
            }
            var player=GetPlayerById(nowplayer);            
            if(!player.isOnFocus)
            {
                player.SetFocus(1);
            }
            WriteWebLog("选择播放器:"+selectPlayerId);
                        
            var realtree=GetRelaTimeTree();
            var node=realtree.root.findChild("id","rc"+devId,true);
            if(node)
            {
                if(LastSelectGroupNode && LastSelectGroupNode!=node.parentNode)
                {
                    LastSelectGroupNode.collapse();
                }                
                LastSelectGroupNode=node.parentNode;
                if(!LastSelectGroupNode.isExpanded())
                {
                    LastSelectGroupNode.expand();
                }                
                node.select();
                
                if(node && node.parentNode && node.parentNode.parentNode && node.parentNode.parentNode.attributes.tagName=="DevGroup")
                {
                    if(__LastGroupNode!=node.parentNode.parentNode)
                    {
                        if(__LastGroupNode)
                        {
                            __LastGroupNode.collapse();
                        }
                        __LastGroupNode=node.parentNode.parentNode;
                        __LastGroupNode.expand();
                    }
                }                
                if(node.ui)
                {
                    node.ui.focus();
                }            
                if(GetRightByDevId(devId,"ptz")=="")
                {
                    if(connectwhileclick)
                    {
                        LastCmdStatusMsg="";
                        LastCmdOkDevId="";//    去掉上一次申请的云台控制      
                        var ret=InvitePTZControl(devId);                        
                    }else
                    {//不请求，直接控制
                        LastCmdStatusMsg="";
                        LastCmdOkDevId=devId;//    去掉上一次申请的云台控制                           
                        // LastRecvPtzString[devid]=PresetList;
                        if(LastRecvPtzString[devId]===undefined)
                        {
                            UpdatePresetListByStr("0^",devId);
                            LastRecvPtzString[devId]="";
                            InvitePTZControl(devId);
                        }else
                        {
                            UpdatePresetListByStr(LastRecvPtzString[devId],devId);
                        }
                    }
                }else
                {
                    LastCmdOkDevId="";//    去掉上一次申请的云台控制      
                    LastCmdStatusMsg=GetRightByDevId(devId,"ptz");
                    UpdatePresetListByStr("0^",devId);
                    //"没有控制权限";
                }
            }
        }else
        {
            try
            {//
                var tempplayer=GetPlayerById(nowplayer);
                try
                {
                    if(tempplayer.isOnFocus)
                    {
                        tempplayer.SetFocus(0);
                    }
                }catch(eevv){}
                var tempdiv=GetPlayerById(nowplayer+"div");
                if(tempdiv.className!="NoSelectPlayer")
                {
                    tempdiv.className="NoSelectPlayer";
                }
            }catch(eeee){}
        }
    }
}




//EVENT_LBUTTONDOWN  1
//EVENT_LBUTTONUP 2
//EVENT_MOUSEMOVE  7
//EVENT_MOUSEWHEEL 8		

WM_MOUSEFIRST=0x0200;
WM_MOUSEMOVE=0x0200;
WM_LBUTTONDOWN=0x0201;
WM_LBUTTONUP=0x0202;
WM_LBUTTONDBLCLK=0x0203;
WM_RBUTTONDOWN=0x0204;
WM_RBUTTONUP=0x0205;
WM_RBUTTONDBLCLK=0x0206;
WM_MBUTTONDOWN=0x0207;
WM_MBUTTONUP=0x0208;
WM_MBUTTONDBLCLK=0x0209;
WM_MOUSEWHEEL=0x020A;
function OnPlayerMouseEvent(playid,uMsg,wParam,lParam)
{
    selectPlayerId=playid;//"player4";
    var obj=GetPlayerById(selectPlayerId);
    if(obj.GetFullScreen())
    {
        var playDevId=playobjDevIdList[selectPlayerId];//正在控制的设备ID
        if(playDevId=="" || GetRightByDevId(playDevId,"ptz")!="")
        {
            return false;
        } 
        if(!have_PTZRight || have_PTZRight===0 || have_PTZRight==="0" )
        {//没有云台控制权限，不要求控制。
            return ;
        }
        var eventcode=1;
        switch(uMsg)
        {
            case WM_LBUTTONDOWN:
            {
                eventcode=1;
            }
            break;
            case WM_LBUTTONUP:
            {
                eventcode=2;
            }
            break;
            case WM_LBUTTONDBLCLK:
            {
                eventcode=3;
            }
            break;
            case WM_MOUSEMOVE:
            {
                eventcode=7;
            }
            break;
            case WM_MOUSEWHEEL:
            {
                eventcode=8;
            }
            break;
            
        }
        //WriteWebLog("全屏事件ID："+eventcode+","+uMsg);
        doMouseEvent(eventcode,wParam,lParam);
    }else
    {
        //WriteWebLog("非全屏事件ID："+uMsg);
        switch(uMsg)
        {
            case 0x0202:
            {//mouseup 
                ShowSelectPlayer(); 
            }
            break;
        }
        //doMouseEvent(eventcode,wParam,lParam);
    }
}



function getTreeNodeStatusFile(statustype,ismasternode)
{
    statustype=parseInt(statustype);
    var imgurl="resources/images/camera/offline.gif";
    if(ismasternode)
    {
        imgurl="resources/images/camera/mastnodeoff.gif";
        switch(statustype)
        {
            case 0:
            {
                imgurl="resources/images/camera/mastnodeoff.gif";
            }
            break;
            case 1:
            {
                imgurl="resources/images/camera/mastnodeoff.gif";
            }
            break;
            case 2:
            {
                imgurl="resources/images/camera/mastnodeon.gif";
            }
            break;
            default:
            {
                imgurl="resources/images/camera/mastnodeon.gif";
            }
            break;
        }
    }else
    {
        switch(statustype)
        {
            case 0:
            {
                imgurl="resources/images/camera/notconnect.gif";
            }
            break;
            case 1:
            {
                imgurl="resources/images/camera/offline.gif";
            }
            break;
            case 2:
            {
                imgurl="resources/images/camera/online.gif";
            }
            break;
            default:
            {
                imgurl="resources/images/camera/offline.gif";
            }
            break;
        }
    }
    return imgurl;
}


var update_treenode_status_time=1000*600;

function StartUpdateDevStatusTimer()
{
    if(TimerHandleForUpdateStaus!=null)
    {
        try
        {
            window.clearTimeout(TimerHandleForUpdateStaus);
        }catch(eevv){}
        TimerHandleForUpdateStaus=null;
    }
    try
    {
        TimerHandleForUpdateStaus=window.setTimeout("UpdateDevStatus()",update_treenode_status_time);//10分钟更新一次状态
    }catch(eeeevv){}
}


//<Response Code="86" CameraRegInfo="{devid1:reginfo1,devid2:reginfo2,...}" Result ="0" />
//retginfo = bDoubleStream + (bWithPTZ*10) + (bWithAudioIn*100) + (bWithAudioOut*1000)   
//是否有云台音频输入，输出等信息更改了
function OnDeviceInfoChange(info)
{
    var evdata=info;
    evdata=evdata.replace("}","\"}");
    evdata=evdata.replace("{","{name#");
    evdata=evdata.replace(/,/g,"\"},{name#");
    evdata=evdata.replace(/:/g,"\",value:\"");
    evdata="["+evdata.replace(/#/g,":\"")+"]";
    var objlist=[];//{};
    var realtree=GetRelaTimeTree();
    try
    {
        realtree.root.firstChild.beginUpdate();
    }catch(eeeev){}
    try
    {
        __lasdevptzinfo=objlist=eval("objlist="+evdata+";");
        for(var idx=0;idx<objlist.length;idx++)
        {
            var camid=objlist[idx].name;
            var value=objlist[idx].value;
            //if( (LastDevStatus==undefined) ||  (LastDevStatus[camid]===undefined) ||  (LastDevStatus[camid]!==value) )
            {//状态更改了
                var cameranode=realtree.root.findChild("id","rc"+camid,true);
                if(cameranode!=undefined && cameranode!=null)
                {
                    var statusvalue=parseInt(value);
                    //cameranode.attributes["DoubleStream"]=statusvalue%10;//是否支持双码流
                    statusvalue=statusvalue/10;
                    cameranode.attributes["WithPTZ"]=statusvalue%10;
                    statusvalue=statusvalue/10;
                    cameranode.attributes["WithAudioIn"]=statusvalue%10;
                    statusvalue=statusvalue/10;
                }
            }
        }
    }catch(eeee){}    
}



function ShowDevStatusByString(xml)
{ 
//"<Response Code="83" DeviceState="{755000001:2,755000011:2,755000021:2,755000031:0,755000041:0,755000051:2,755000061:0,755010001:1,755010011:1,0:0}"  Result ="0"/>"   
    var doc=CreateXml(xml);
    var data="{}";
    if(doc)
    {
        var rescode=doc.getAttribute("Result");
        if(rescode===0 || rescode==="0")
        {//合法数据
            data=doc.getAttribute("DeviceState");
        }else
        {
            TimerHandleForUpdateStaus=window.setTimeout("UpdateDevStatus()",update_treenode_status_time);//10分钟更新一次状态
            return false;
        }
    }
    var evdata=data;
    evdata=evdata.replace("}","\"}");
    evdata=evdata.replace("{","{name#");
    evdata=evdata.replace(/,/g,"\"},{name#");
    evdata=evdata.replace(/:/g,"\",value:\"");
    evdata="["+evdata.replace(/#/g,":\"")+"]";
    var objlist=[];//{};
    var realtree=GetRelaTimeTree();
    try
    {
        realtree.root.firstChild.beginUpdate();
    }catch(eeeev){}
    try
    {
        __lastRecvDevListStatus=objlist=eval("objlist="+evdata+";");
        for(var idx=0;idx<objlist.length;idx++)
        {
            var camid=objlist[idx].name;
            var value=objlist[idx].value;
            //if( (LastDevStatus==undefined) ||  (LastDevStatus[camid]===undefined) ||  (LastDevStatus[camid]!==value) )
            {//状态更改了
                var groupnode=realtree.root.findChild("id","rg"+camid,true);
                if(groupnode && groupnode.childNodes && groupnode.childNodes.length>0)
                {
                    var imgurl=getTreeNodeStatusFile(value,true);//"";
                    try
                    {
                        groupnode.attributes.icon=imgurl;
                    }catch(eevvv){}
                    var nodeui=groupnode.getUI();
                    var img=nodeui.getIconEl();//img对象
                    if(img && img.src)
                    {//"resources/images/camera/mastnodeon.gif";
                        var srcurl=img.src;
                        if(srcurl.replace(imgurl,"")==srcurl)
                        {                        
                            img.src=imgurl;
                        }
                    }
                    imgurl=getTreeNodeStatusFile(value,false);//"";
                    for(var camidx=0;camidx<groupnode.childNodes.length;camidx++)
                    {
                        var node=groupnode.childNodes[camidx];
                        try
                        {
                            node.attributes.icon=imgurl;
                        }catch(eevvv){}
                        var nodeui=node.getUI();
                        var img=nodeui.getIconEl();//img对象
                        if(img && img.src)
                        {
                            var srcurl=img.src;
                            if(srcurl.replace(imgurl,"")==srcurl)
                            {                        
                                img.src=imgurl;
                            }
                        }
                    }
                }
            }
        }
    }catch(eeee){}    
    try
    {
        realtree.root.firstChild.endUpdate();
    }catch(eeeev){}
    try
    {
        LastDevStatus=eval("LastDevStatus="+data+";");
    }catch(eeee){}    
}



//会启动一个定时器不停的读
function UpdateDevStatus()
{       
    if(TimerHandleForUpdateStaus!=null)
    {
        window.clearTimeout(TimerHandleForUpdateStaus);
        TimerHandleForUpdateStaus=null;
    }
    var obj=$("loginobj");
    var xml=obj.GetDeviceState("");
    //"<Response Code="83" DeviceState="{755000001:2,755000011:2,755000021:2,755000031:0,755000041:0,755000051:2,755000061:0,755010001:1,755010011:1,0:0}"  Result ="0"/>"
    ShowDevStatusByString(xml);
    TimerHandleForUpdateStaus=window.setTimeout("UpdateDevStatus()",update_treenode_status_time);//10分钟更新一次状态
}


////消息（LIB）/事件(COM) 代码
//enum EventCode
//{
//	RECVDATATIMEOUT=1			//收取流时，如果10秒内都没有数据，则会发送此消息
//	,FOCUSCHANGE				//播放器焦点改变时发生
//	,STARTPLAY					//开始播放
//	,ENTERWAITFORBUFFER			//进入缓冲
//	,SETUP_VIDEO_PARAM_OK		//SetupDecoder返回成功
//	,SETUP_AUDIO_PARAM_OK		//SetupDecoder返回成功
//	,SNAPSHORT_FINISH			//抓图结束
//	,BINDPORTERROR				//邦定端口失败
//	,VSS_STOPPLAY				//播放VSS文件结束
//	,VSS_STARTPLAY				//开始播放
//	,VSS_PLAYNEXT				//播放下一个文件
//	,VSS_SETUPERROR				//调用setup返回失败
//	,CREATE_THREAD_ERROR		//创建线程失败
//	,LOC_STOPPLAY				//停止本地文件播放
//	,LOC_OPENFILEERROR			//本地文件播放时打开文件失败
//	,LOC_PLAYERROR				//播放失败退出
//	,LOC_PAUSEPLAY				//暂停播放
//	,LOC_OPENFILE_ERROR			//打开本地文件失败
//	,RECV_RETUN_ERROR			//RTPRECV读取数据返回少于16个字节
//};

function OnPlayerEvent(playid,code,msg)
{
    if(typeof(code)=="string")
    {
        code=parseInt(code);
    }
    WriteWebLog("收到事件:"+playid+",id="+code+",msg="+msg);
    switch(code)
    {
        case 1:
        {
            var devid=playobjDevIdList[playid];
            if(devid=="" || devid==null)
            {
                return false;
            }
            var stremtype=PlayVideoTypeList[playid];
            if(stremtype==="0" || stremtype===0)
            {
                stremtype=0;
            }else
            {
                stremtype=1;
            }
            var realtree=GetRelaTimeTree();
            var node=realtree.root.findChild("id","rc"+devid,true);
            if(node)
            {
                PlayVideoByNode(node,playid,stremtype,false);
            }
            break;
        }
        case 21:
        {//录像停止
            if(playid==selectPlayerId)
            {//正在播放的和当前ID一样的话，就要改变状态
                main_but_record.setText(GetDefaultLang("lang_startrecord","开始录像"));
            }            
        }
    }   
}




function CheckPlayerIsPlaying(playobj)
{
    for(var idx=0;idx<=100;idx++)
    {
        var playstatus=parseInt(playobj.GetUserData("gethaveplayed"));
        if(playstatus==1)
        {
            return true;
        }
    }
    return false;
}