var username = "";
var password = "";
var queryInfoDate;
var dbName;
var number = 0;
// var db;
// var srateTy, oldValue;
// var playmodelst;
$(document).ready(function() {
    window.localStorage.setItem('Token', "default");
    if (window.deviceType == 'NVR' || window.deviceType == 'HVR') { //只针对ie
        var url = location.href;
        if (url.split('=')[1]) {
            $("#myModal").modal('show');
        }
    }
    initlanguage();
    $("#language_search").change(function() {
        sessionStorage.setItem("language", $("#language_search").select2("val"));
        loadProperties($("#language_search").select2("val"));
        // getcytext();
    });
    $("#confruomi").click(function() { //修改密码
        var rule = {
            ruopasswd: {
                required: true,
                ruopasswd: true
            },
            surepasswd: {
                required: true,
                equalTo: "#ruopasswd"
            },
        };
        var messages = {
            ruopasswd: {
                required: $.i18n.prop("i18n-default-msg6"),
            },
            surepasswd: {
                required: $.i18n.prop("i18n-default-msg7"),
                equalTo: $.i18n.prop("i18n-default-msg8")
            },
        };

        function ruomisubmit() {
            var ulevel = "";
            var cyURL = config.baseUrl + "/System/Users/1";
            if ($("#username").val() == "admin") {
                ulevel = "Administrator"
            } else {
                ulevel = "Normal"
            }
            var cyXml = "<?xml version='1.0' encoding='UTF-8' ?><User Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><ID></ID><UserName>" +
                $("#username").val() + "</UserName><Password>" + $("#surepasswd").val() +
                "</Password><IPAddress></IPAddress><MACAddress/><UserLevel>" + ulevel + "</UserLevel></User>";
            $.ajax({
                type: "PUT",
                url: cyURL,
                processData: false,
                async: false,
                data: cyXml,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("If-Modified-Since", "0");
                },
                complete: function(xhr, textStatus) {
                    var xmlDoc = xhr.responseXML;
                    var state = $(xmlDoc).find('statusCode').eq(0).text();
                    if ("-13" == state) {
                        $.optionBootoast($.i18n.prop("i18n-default-msg9"), 'danger');
                    } else if ("-31" == state) {
                        $.optionBootoast($.i18n.prop("i18n-default-msg10"), 'danger');
                    } else if ("0" == state) {
                        $.optionBootoast($.i18n.prop("i18n-default-msg11"), 'success');
                        setTimeout(function() {
                            $('#ruomibox').hide();
                            $('#userbox').show();
                        }, 2000)
                    }
                }
            });

        }
        validatetype("#ruomi-form", rule, messages, ruomisubmit);
    });
    // 为了让回车不更新坐标，并且火狐在有坐标的前提进去系统，在没有坐标时，为了暂时解决，坐标不更新的问题，先禁用表单提交操作，阻止登录
    var koinf = document.querySelector("#userform")
    koinf.addEventListener("keydown", function(event) {
        if (event.keyCode == 13 && navigator.userAgent.toLocaleLowerCase().match(/firefox/) != null) {
            event.preventDefault()
        }
    })

});

function initlanguage() {
    if (window.deviceType == 'NVR' || window.deviceType == 'HVR') {
        var languages = ['en', 'it', 'es', 'ja', 'ko', 'po', 'ru', 'tw', 'zh'];
    } else {
        var languages = ['en', 'it', 'es', 'ja', 'ko', 'po', 'ru', 'tw', 'zh', 'ar', 'uk', 'vn', 'fa'];
    }
    getlanguage();
    $("#language_search").select2({
        width: 135,
        height: 40,
        minimumResultsForSearch: -1 // 隐藏搜索
    });
    if (sessionStorage.getItem("language")) {
        $("#language_search").select2("val", sessionStorage.getItem("language"));
    } else {
        //1.如果系统语言我们设备网页内也支持：打开网页时显示对应的语言；
        //2.如果系统语言我们设备网页内不支持，打开网页时默认显示英语；
        var lang = '';
        if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0)) {
            lang = navigator.systemLanguage.toLowerCase();
        } else {
            lang = navigator.language.toLowerCase();
        }
        if (lang && lang.indexOf("tw") == -1) {
            lang = lang.substring(0, 2);
            if (lang == 'pt') {
                lang = 'po';
            }
        } else if (lang.indexOf("tw") != -1) {
            lang = 'tw';
        }
        if (languages.indexOf(lang) == -1) {
            lang = 'en';
        }
        sessionStorage.setItem("language", lang);
        $("#language_search").select2("val", lang);
        // getcytext();

    }
    loadProperties(sessionStorage.getItem("language"));
}

function validatetype(id, rule, messages, callback) {
    jQuery.validator.addMethod("ruopasswd", function(value, element) {
        var testpwd = '';
        if (config.deviceCap[number].PWDSpecialChars == "true") {
            testpwd = /^(?=.*[a-zA-Z])(?=.*\d)[\s\S]{8,16}$/;
        } else {
            testpwd = /^(?=.*?[A-Z])(?=.*?[0-9])[0-9a-zA-Z]{8,16}$/
        }
        return this.optional(element) || testpwd.test(value);
    }, $.i18n.prop("i18n-default-msg5"));
    $(id).validate({
        ignore: "",
        errorElement: 'span',
        errorClass: 'help-block',
        focusInvalid: true,
        ignore: "",
        errorElement: 'span',
        errorClass: 'help-block',
        focusInvalid: true,
        rules: rule,
        messages: messages,
        errorPlacement: function(error, element) {
            element.parent('div').append(error);
        },
        highlight: function(element) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        },
        success: function(label) {
            label.closest('.form-group').removeClass('has-error').addClass('has-success');
            label.remove();
        },
        submitHandler: callback
    })
}

function getlanguage() {
    $.ajax({
        type: 'get',
        async: false,
        url: "custom/language.json",
        dataType: 'json',
        success: function(result) {
            $("#language_search").empty();
            if (result.loginList && result.loginList.length > 0) {
                if (window.deviceType == 'NVR' || window.deviceType == 'HVR') {
                    for (var i = 0; i < result.loginList.length - 3; i++) { //nvr设备和hvr暂时不支持新加的语言
                        $("<option value='" + result.loginList[i].sysLangue + "'>" + result.loginList[i].showLangue + "</option>").appendTo("#language_search");
                    }
                } else {
                    for (var i = 0; i < result.loginList.length; i++) {
                        $("<option value='" + result.loginList[i].sysLangue + "'>" + result.loginList[i].showLangue + "</option>").appendTo("#language_search");
                    }
                }
            } else { //默认语言
                $("<option value='zh'>简体中文</option>").appendTo("#language_search");
            }

        },
        error: function(data) {

        }
    });
}
//暂时不需要
function getcytext() {
    $.ajax({
        type: 'get',
        async: false,
        url: "custom/copyright.json",
        dataType: 'json',
        success: function(res) {
            var lan = $("#language_search").select2("val");
            if (res.copyright && res.copyright.length > 0) {
                for (var i = 0; i < res.copyright.length; i++) {
                    if (res.copyright[i].sysLangue == lan) {
                        $(".cycontainer").text(res.copyright[i].showLangue);
                        break;
                    }
                }
            }
        }
    })
}
/**********************************
功能: 登陆
***********************************/
function Login(event) {//为了保证在刷新之后还能获取原始坐标值用于预览位置的计算所以这里需要保存一次
    var event = event || window.event;
    if (!event && window.event) {
        event = window.event;
    }
    var mousePos = {};
    mousePos.clientX = event.clientX;
    mousePos.clientY = event.clientY;
    mousePos.screenX = event.screenX;
    mousePos.screenY = event.screenY;
    localStorage.setItem('mousePos', JSON.stringify(mousePos));
    var rule = {
        username: {
            required: true,
            maxlength: 30
        },
        passwd: {
            maxlength: 17
        }
    };
    var messages = {
        username: {
            required: $.i18n.prop("i18n-default-msg4"),
            maxlength: $.i18n.prop("i18n-default-msg17"),
        },
        passwd: {
            maxlength: $.i18n.prop("i18n-default-msg18"),
        }
    };
    validatetype("#userform", rule, messages, debouncedSubmit);

    
}
function usersubmit() {
    var username = $('#username').val();
    var password = $('#passwd').val();
    config.isSupportUserAuthV2 = false;
    var nonce = generateNonce();
    var created = generateTimestamp();
    // 计算密码摘要
    var passwordDigest = calculatePasswordDigest(nonce, created, password);
    if (!passwordDigest) {
        console.log('生成密码摘要失败');
        return false;
    }
    
    var cyDate = '<Security>' +
                 '<Username>' + username + '</Username>' +
                 '<Password>' + passwordDigest + '</Password>' +
                 '<Nonce>' + nonce + '</Nonce>' +
                 '<Created>' + created + '</Created>' +
                 '</Security>';
    console.log('发送的XML:', cyDate);
    $.ajax({
        url: config.baseUrl + "/Security/UserAuthV2",
        type: "PUT",
        timeout: 15000,
        async: false,
        data: cyDate,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            config.isSupportUserAuthV2 = true;
            var statusflg = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
            if (0 == statusflg) { //成功登陆
                var responedtoken = xhr.getResponseHeader('Token');
                if ((responedtoken != "") && (responedtoken != null) && (responedtoken != "null") && (typeof(responedtoken) != "undefined")) {
                    window.localStorage.setItem('Token', responedtoken);
                }
                loginLoad();
            } else if (statusflg == "-25") {
                $.optionBootoast($.i18n.prop("i18n-default-msg12"), 'danger')
                return false;
            } else if (-17 == statusflg) { //密码出错
                $.optionBootoast($.i18n.prop("i18n-default-msg13"), 'danger')
                return false;
            } else if (-45 == statusflg) { //nvr会返回-45
                $.optionBootoast($.i18n.prop("i18n-link-statu10"), 'danger')
                config.deviceCap = getDeviceCap(); //设备能力
                if (window.deviceType == "NVR") {
                    config.deviceCapV2 = getDeviceCapV2(); //设备能力
                }
                // 此时判断密码是否为弱密 弱密码阻止表单提交
                if (config.deviceCap[number].isSupportComplexd == "true") { //支持强密码
                    var testpwd = /^(?=.*?[A-Z])(?=.*?[0-9])[0-9a-zA-Z]{8,16}$/g;
                    var pwds = testpwd.test($('#passwd').val());
                    if (!pwds) {
                        $("#usernamed").val($("#username").val());
                        if (config.deviceCap[number].PWDSpecialChars == "true") {
                            $("#ruomiTip").text($.i18n.prop('i18n-default-msg33'));
                        }
                        $('#ruomibox').show();
                        $('#userbox').hide();
                        if (config.deviceCap[number].isSupportEmptyPassword == 'true') { //拒绝空密码
                            $("#cancelruomi").hide();
                            $("#confruomi").css('width', '264px');
                        }
                    }
                }
                return false;
            } else if ("401" != xhr.status) { //其它异常
                if ("timeout" == textStatus) { //连接超时
                    $.optionBootoast($.i18n.prop("i18n-default-msg14"), 'danger')
                } else { //网络异常
                    $.optionBootoast($.i18n.prop("i18n-default-msg15"), 'danger')
                }
                return false;
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            config.isSupportUserAuthV2 = false;
            userAuth();
            return false;
        }
    });
}

function userAuth(){
    var cyDate = 'Username=' + $('#username').val() + '&Password=' + $('#passwd').val();
    username = $('#username').val();
    password = $('#passwd').val();
    $.ajax({
        url: config.baseUrl + "/Security/UserAuth",
        type: "PUT",
        timeout: 15000,
        data: cyDate,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function (xmlDoc, textStatus, xhr) {
            var statusflg = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
            if (0 == statusflg) { //成功登陆
                var responedtoken = xhr.getResponseHeader('Token');
                if ((responedtoken != "") && (responedtoken != null) && (responedtoken != "null") && (typeof(responedtoken) != "undefined")) {
                    window.localStorage.setItem('Token', responedtoken);
                }
                loginLoad();
            } else if (statusflg == "-25") {
                $.optionBootoast($.i18n.prop("i18n-default-msg12"), 'danger')
                return false;
            } else if (-17 == statusflg) { //密码出错
                $.optionBootoast($.i18n.prop("i18n-default-msg13"), 'danger')
                return false;
            } else if (-45 == statusflg) { //nvr会返回-45
                $.optionBootoast($.i18n.prop("i18n-link-statu10"), 'danger')
                config.deviceCap = getDeviceCap(); //设备能力
                if (window.deviceType == "NVR") {
                    config.deviceCapV2 = getDeviceCapV2(); //设备能力
                }
                // 此时判断密码是否为弱密 弱密码阻止表单提交
                if (config.deviceCap[number].isSupportComplexd == "true") { //支持强密码
                    var testpwd = /^(?=.*?[A-Z])(?=.*?[0-9])[0-9a-zA-Z]{8,16}$/g;
                    var pwds = testpwd.test($('#passwd').val());
                    if (!pwds) {
                        $("#usernamed").val($("#username").val());
                        if (config.deviceCap[number].PWDSpecialChars == "true") {
                            $("#ruomiTip").text($.i18n.prop('i18n-default-msg33'));
                        }
                        $('#ruomibox').show();
                        $('#userbox').hide();
                        if (config.deviceCap[number].isSupportEmptyPassword == 'true') { //拒绝空密码
                            $("#cancelruomi").hide();
                            $("#confruomi").css('width', '264px');
                        }
                    }
                }
                return false;
            } else if ("401" != xhr.status) { //其它异常
                if ("timeout" == textStatus) { //连接超时
                    $.optionBootoast($.i18n.prop("i18n-default-msg14"), 'danger')
                } else { //网络异常
                    $.optionBootoast($.i18n.prop("i18n-default-msg15"), 'danger')
                }
                return false;
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            $.optionBootoast($.i18n.prop("i18n-default-msg16"), 'danger')
            return false;
        }
    });
}
// 防抖函数
function debounce(func, wait) {
    var timeout;
    return function() {
        var context = this;
        var args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            func.apply(context, args);
        }, wait);
    };
}

// 只在验证成功后使用防抖
var debouncedSubmit = debounce(function() {
    usersubmit();
}, 300);


function loginLoad() {
    $.ajax({
        url: config.baseUrl + "/Network/Port",
        type: "GET",
        async: false,
        username: $('#username').val(),
        password: $('#passwd').val(),
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
            // xhr.setRequestHeader("Cache-Control:no-cache", "must-revalidate");
            // xhr.setRequestHeader("keep-alive", "timeout=0, max=1000");
        },
        success: function (xmlDoc, textStatus, xhr) {
            // 存储时转义密码中的 `:`
            var escapedPassword = $('#passwd').val().replace(/:/g, '\\:');
            var m_cyUserPwdValue = Base64.encode($('#username').val() + ":" + escapedPassword);
            $.cookie('userInfo', m_cyUserPwdValue);
            // 读取时恢复
            var decoded = Base64.decode($.cookie('userInfo'));
            var firstColonIndex = decoded.indexOf(':');
            var user = decoded.substring(0, firstColonIndex);
            var pwd = decoded.substring(firstColonIndex + 1).replace(/\\:/g, ':');
            config.user = user;
            config.password = pwd;
            config.MacAddress = getMacAddress(); //mac地址
            config.Network = getHTTPprot(); //网络端口号
            config.deviceCap = getDeviceCap(); //设备能力
            if (window.deviceType == "NVR") {
                config.deviceCapV2 = getDeviceCapV2(); //设备能力
            }
            localStorage.setItem("UID", "loginsuccess");
            // 此时判断密码是否为弱密 弱密码阻止表单提交
            if (config.deviceCap[number].isSupportComplexd == "true" || config.deviceCap[number].PWDSpecialChars == "true") { //支持强密码
                var testpwd = '';
                if (config.deviceCap[number].isSupportComplexd == "true") {
                    testpwd = /^(?=.*?[A-Z])(?=.*?[0-9])[0-9a-zA-Z]{8,16}$/g;
                }
                if (config.deviceCap[number].PWDSpecialChars == "true") {
                    testpwd = /^(?=.*[a-zA-Z])(?=.*\d)[\s\S]{8,16}$/;
                    $("#ruomiTip").text($.i18n.prop('i18n-default-msg33'));
                }
                var pwds = testpwd.test($('#passwd').val());
                if (!pwds) {
                    $("#usernamed").val($("#username").val());
                    $('#ruomibox').show();
                    $('#userbox').hide();
                    if (config.deviceCap[number].isSupportEmptyPassword == 'true') { //拒绝空密码
                        $("#cancelruomi").hide();
                        $("#confruomi").css('width', '264px');
                    }
                    return false
                }
            }
           
                isSupportEasyVideo();
           

        },
        error: function(xhr, textStatus, errorThrown) {
            if ("401" != xhr.status) {
                if ("timeout" == textStatus) { //连接超时
                    $.optionBootoast($.i18n.prop("i18n-default-msg14"), 'danger')
                } else { //网络异常
                    $.optionBootoast($.i18n.prop("i18n-default-msg15"), 'danger')
                }
            } else {
                $.optionBootoast($.i18n.prop("i18n-default-msg13"), 'danger')
            }
            return false; //阻止表单提交
        }
    });
}

function isSupportEasyVideo() {
    //判断定制播放模式是否存在EasyVideo,存在引入easyvoide文件，判断是否是ie浏览器，是ie直接通过，不是ie浏览器尝试链接webstcoke
    var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
    if (getBrowserType() && !g_bIsIE) { //目标浏览器且不是ie
        var res = getplayMode();
        if (res && res.length > 0) {
            if (res.indexOf("WebPlayer") !== -1) { //是否支持webplayer
                $.optionBootoast($.i18n.prop("i18n-chatip"), 'success');
                // 为了避免重复下载这个文件导致带宽占用升高
                if(sessionStorage.getItem('dnowe')=='undefined'||sessionStorage.getItem('dnowe')==undefined){
                sessionStorage.setItem('dnowe',"1");  
                downloadwasm("login");
            }else{
                $.optionBootoast($.i18n.prop("i18n-chatip"), 'success');
            }
            } else {
                if (res.indexOf("EasyVideo") !== -1) {
                    $.getScript("js/EasyVideo/playervideo.js", function() { //请求成功后的回调函数
                        self.playervideo = new Playervideo(); //尝试通话及创建设备连接，创建成功则是代表应用被注册，否则没有
                        self.playervideo.createdev();
                    });
                } else {
                window.location.href = "index.html";
                }
            }
        }
    } else { //ie直接登录
        window.location.href = "index.html";
    }
}