//nChannel 表示通道号，通道从1开始
//nStreamType的范围如下
//typedef enum eStreamMediaType
//{
//    eStreamMediaTypeBegin			=	0,				/*!< 起始值									*/
//    eMainVideoAndSound            =   1,				/*!< 主码流音视频							*/
//    eMainVideo,                   =   2，				/*!< 主码流视频								*/
//    eMainSound,					=	3，			    /*!< 主码流音频								*/
//    eAssistVideo,					=	4，				/*!< 子码流视频								*/
//    eAssistHDVideo,				=	5，				/*!< 高清子码流视频							*/
//    eStreamMediaTypeEnd,			=	6，				/*!< 结束值									*/
//}eStreamMediaType;
//通常我们使用枚举eMainVideoAndSound打开主码流，使用eAssistVideo打开子码流。rtsp流的URL
//下面的函数可以反复调用来加载不同码流的视频,但是最后退出时要调用UnLoadVideo()函数
function LoadVideoV1(nChannel, nStreamType) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    var urla = document.URL.split('/');
    var dev = urla.length > 3 ? urla[2] : '192.168.1.168';
    var strIP = dev.split(':')[0];
    var nPort = config.Network.commandPort;
    var strUserName = config.user;
    var strUserPassword = config.password;
    var nRet = ncx.LoadVideoV1(strIP, nPort, strUserName, strUserPassword, nChannel, nStreamType);
    if (nRet == 35) {
        bootoast({
            message: $.i18n.prop('i18n-maxline'),
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
}

function InitPreviewParameters(a, b, c) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    ncx.InitPreviewParameters(a, b, c);
}

function setAdaptiveResolution(n) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    ncx.AdaptiveResolution(n); //调节适配分辨率的接口
}

function setLanguageResource(xml) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }

    var urla = document.URL.split('/');
    var dev = urla.length > 3 ? urla[2] : '192.168.1.168';
    var nRet = ncx.SetLanaguageResource(xml);

}

//点阵
function setlattice(xml) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        return null
    } else {
        var nRet = ncx.StringToLattice(xml);
        return nRet
    }

}

// 查询回放当前回放进度
function PlaybackGetPos(params) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    // 当前进度转换
    var nowPos = ncx.RemotePlaybackGetPos(params - 1);
    if (nowPos) { //兼容ie
        config.SaveCavans.MovePosinVideo(new Date(nowPos.replace(/-/g, '/')).getTime(), config.RemoteplayPosin);
    }
}

//卸载视频流
function UnLoadVideo() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }

    var nRet = ncx.UnLoadVideo();

}

//全屏显示流
function FullScreen() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    ncx.FullScreen();
}

//开启语音对讲
function Playtalkback() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    ncx.StartVoiceStream(0);
}
//关闭语音对讲
function Stoptalkback() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    ncx.StopVoiceStream(0);
}

//PlayAudio是在保证LoadVideo之后并且要确保nStreamType 是eMainVideoAndSound的情况下，才能打开音频
//参数nChannel,表示打开的通道号,从1开始
function PlayAudio(nChannel) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    var nRet = ncx.PlayAudio(nChannel);

}

//StopAudio是在保证LoadVideo之后并且要确保nStreamType 是eMainVideoAndSound的情况下，才能打开音频
//参数nChannel,表示打开的通道号,从1开始
function StopAudio(nChannel) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    var nRet = ncx.StopAudio(nChannel);

}

//StartDrawRegion是在保证LoadVideo之后，调用该函数之后，可以在预览界面画选中区域，供移动侦测或者马赛克画区域使用
function StartDrawRegion() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    var nRet = ncx.StartDrawRegion();

}

//StopDrawRegion是在保证LoadVideo之后，调用该函数之后，不可以在预览界面画区域。
function StopDrawRegion() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    var nRet = ncx.StopDrawRegion();

}


//SetBrushColor的nR,nG,nB的范围都是【0-255】用来设置画刷的颜色，供移动侦测或者马赛克画区域使用
function SetBrushColor() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    var nRet = ncx.SetBrushColor(0x10000, 255, 0);

}


//AddDrawRegion(nLeft,nTop,nRight,nBottom),是在插件内部画一个区域
//其中nLeft,nRight的范围【0-704】，nTop,nBottom的范围是【0-576】
//nLeft的坐标要小于nRight
//nTop的坐标要小于nBottom
function AddDrawRegion(TopLeftX, TopLeftY, BottomRightX, BottomRightY) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    var nLeft = TopLeftX;
    var nTop = TopLeftY;
    var nRight = BottomRightX;
    var nBottom = BottomRightY;
    var nRet = ncx.AddDrawRegion(nLeft, nTop, nRight, nBottom);
    if (nRet != 0) {
        //alert("AddDrawRegion failed,nRet=" + nRet);
    } else {
        //alert("AddDrawRegion success");
    }
}

//GetDrawRegions()函数，返回的是当前选中的区域
//其中支持的最大区域是4，
//区域的大小是在704*576
//返回的是一个xml格式的字符串，里面保存了当前选中的区域，供移动侦测或者隐私遮蔽
function GetDrawRegions() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    try {
        var RegionList = ncx.GetDrawRegions();
        return RegionList;
    } catch (e) {
        // alert(e.description);
    }
}
//ClearDrawRegions，清除选中的区域
function ClearDrawRegions() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    try {
        var nRet = ncx.ClearDrawRegions();
    } catch (e) {
        // alert(e.description);
    }
}

//显示选中的区域，供移动侦测或隐私遮蔽使用
function SetDisplayRegionsEnable() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    try {
        var nRet = ncx.SetDisplayRegionsEnable(true);

    } catch (e) {
        // alert(e.description);
    }
}


//设置控件模式0，表示普通的预览模式（带右键菜单和码率显示），1表示马赛克，移动侦测，ISP预览模式（不带右键菜单）
//保证登录之后调用才效果
function SetActiveXMode(nmode) {
    var ncx = document.getElementById("previewocx");
    try {
        ncx.SetActiveXType(nmode);
    } catch (e) {

    }
}

function SetActiveChannel(chl) {
    var ncx = document.getElementById("previewocx");
    try {
        ncx.SetActiveChannel(chl);
    } catch (e) {

    }
}
// 布防多边形
function PolygonProtectionControl(a, b, c) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    try {
        return ncx.PolygonProtectionControl(a, b, c);
    } catch (e) {
        // alert(e.description);
    }
}
//绊线设置
function AssisstantLineControl(a) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    try {
        return ncx.AssisstantLineControl(a);
    } catch (e) {
        // alert(e.description);
    }
}

/**
 * axtive定时刷新码率
 * @param a
 * @param b
 * @param c
 * @constructor
 */

function UpdateStreamBitrate(a, b, c) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    try {
        ncx.UpdateStreamBitrate(a, b, c);
    } catch (e) {
        // alert(e.description);
    }
}


// 抓图（返回0表示执行正确，返回非0表示执行失败）
// 抓图的路径是【X:\\webclient2\\Image\\】，其中X是SetLocalSettings()函数设置“SelectDiskDriver”字段的值
function CaptureImage() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    try {
        ncx.CaptureImage(1);
    } catch (e) {
        // alert(e.description);
    }
}

// 开始录像（返回0表示执行正确，返回非0表示执行失败）
// 录像的路径是【X:\\webclient2\\video\\】，其中X是SetLocalSettings()函数设置“SelectDiskDriver”字段的值
function StartRecord() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    try {
        ncx.StartRecord(1);
    } catch (e) {
        // alert(e.description);
    }
}
// 改变预览比例
function AspectRatioControl(ratio) {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    ncx.AdaptiveResolution(ratio);
}
// 停止录像（返回0表示执行正确，返回非0表示执行失败）
function StopRecord() {
    var ncx = document.getElementById("previewocx");
    if (ncx == null) {
        bootoast({
            message: 'ActiveX plugin not attached!',
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
    try {
        ncx.StopRecord(0);
    } catch (e) {
        // alert(e.description);
    }
}

// 获取路径
function GetLocalSettings() {
    var ncx = document.getElementById("previewocx");
    try {
        var nRet = ncx.GetLocalSettings();
        var xmlDoc = parseXmlFromStr(nRet);
        console.log(xmlDoc.getElementsByTagName("LocalSettings")[0], "11111");
        return xmlDoc.getElementsByTagName("LocalSettings")[0].getAttribute("SelectDiskDriver");
    } catch (e) {}
}



/*******************************************************************************
 * Function ldvideos 功能: 载入视频流
 ******************************************************************************/
function ldvideos(num) {
    var ncx = document.getElementById("previewocx");
    if (!ncx.object) {
        window.location.href = "plugdow.html";
        return;
    }
    var ocxVersion = ncx.GetOCXVersion();
    var versionFlag = true;

    if (compareversion(ocxVersion, config.iePlugVersion) == -1) {
        versionFlag = false;
    }
    if (!versionFlag) { //如果当前版本小于最新版本提示跟新插件
        window.location.href = "plugdow.html";
        return;
    }
    SetActiveXMode(0); //先设置插件模式
    InitPreviewParameters(config.MacAddress, config.Network.HTTPprot, config.deviceCap[0].StreamCount);
    SetActiveChannel(num);
    LoadVideoV1(1, 1); // 主码流

    var xml = "<LanaguageResource ShowBitrate=" + "\"" + $.i18n.prop('i18n-showbitrate') + "\" " + "MainStream=" + "\"" + $.i18n.prop('i18n-miancodestream') + "\" " + "SubStream=" + "\"" + $.i18n.prop('i18n-codestream1') + "\" " + "MobileStream=" + "\"" + $.i18n.prop('i18n-codestream2') + "\"" + "</LanaguageResource>";
    try {
        if (setLanguageResource && typeof(setLanguageResource) == "function") {
            setLanguageResource(xml);
        }
    } catch (e) {
        //TODO handle the exception
    }
    setAdaptiveResolution(0);
    ncx.SetActiveXType(2);
}


/*******************************************************************************
 * Function ldvideos 功能: 载入视频流
 ******************************************************************************/
function ldspecialvideos(id) {
    SetActiveXMode(0);
    setAdaptiveResolution(0);
    var ncx = document.getElementById("previewocx");
    ncx.SetActiveXType(2);
    switch (id) {
        case "1":
            InitPreviewParameters(config.MacAddress, config.Network.HTTPprot, config.deviceCap[0].StreamCount);
            LoadVideoV1(1, 1); // 主码流
            break;
        case "4":
            InitPreviewParameters(config.MacAddress, config.Network.HTTPprot, config.deviceCap[0].StreamCount);
            LoadVideoV1(1, 4); // 子码流
            break;
        case "5":
            InitPreviewParameters(config.MacAddress, config.Network.HTTPprot, config.deviceCap[0].StreamCount);
            LoadVideoV1(1, 5); // 手机码流
            break;
        default:
            InitPreviewParameters(config.MacAddress, config.Network.HTTPprot, config.deviceCap[0].StreamCount);
            LoadVideoV1(1, 1);
            break;
    }
}

function compareversion(versionBegin, versionEnd) {
    var temp1;
    var temp2;
    temp1 = versionBegin.split(".");
    temp2 = versionEnd.split(".");
    for (var i = 0; i < 4; i++) {
        if (Number(temp1[i]) > Number(temp2[i])) {
            return 1;
        } else if (Number(temp1[i]) < Number(temp2[i])) {
            return -1;
        }
    }
    return 0;
}


function update() {
    var imgObj = document.getElementById('rimg12');
    var containerObj = document.getElementById('axdiv');
    imgObj.src = config.ipcsrc + (new Date()).getTime();
    if (config.original) {
        containerObj.style.height = 'auto';
        containerObj.style.width = 'auto';
        imgObj.style.width = 'auto';
        imgObj.style.height = 'auto';
        var widthFirst = imgObj.offsetWidth > imgObj.offsetHeight;
        var orgobj = useAdaptImage(imgObj.offsetWidth, imgObj.offsetHeight, containerObj.offsetWidth, containerObj.offsetHeight, widthFirst, true);
        imgObj.style.width = orgobj.width;
        imgObj.style.height = orgobj.height;
    } else {
        containerObj.style.height = '100%';
        imgObj.style.width = '100%';
        imgObj.style.height = '100%';
    }
}

function onloadMy() {
    var data = "<img src='" + config.ipcsrc + "' id='rimg12' style='width:100%;height: 100%'>";
    $("#axdiv").html(data);
    config.gs_interval = setInterval("update()", 500);

}


function InitPrivatePreviewEvent(num) {
    // SetActiveChannel(num);
    ldvideos(num); // 载入视频流
    // setAdaptiveResolution(0);
}
