var user = config.user,
    pwd = config.password;
var AlarmInputChannels = parseInt(config.deviceInfo.AlarmInputChannels); //语音
var VideoInputChannels = parseInt(config.deviceInfo.VideoInputChannels); //视频
var AudioChannels = parseInt(config.deviceInfo.AudioChannels); //音频
var rule = null,
    RegisterState = '';
$(document).ready(function() {

    initPageSet();
    initCodeBox();
    $('#codeId input[type="radio"]').click(function() {
        $(".videoBox,.audioBox,.alarmBox").hide();
        var id = $(this).attr("id");
        $("." + id).show();
    });
    $("#codeId .radio-inline input[name='codeId']").click(function() {
        if ($(this).attr('id') == 'video') {
            $('.videoBox').show();
            $('.audioBox,.alarmBox').hide();
        } else if ($(this).attr('id') == 'audio') {
            $('.audioBox').show();
            $('.alarmBox,.videoBox').hide();
        } else if ($(this).attr('id') == 'alarm') {
            $('.alarmBox').show();
            $('.videoBox,.audioBox').hide();
        }
    });
    $('#myTab a').click(function(e) {
        e.preventDefault();
        $(this).tab('show');
        if ($(this).attr("aria-controls") == "FTP") {
            initFTp();
        } else if ($(this).attr("aria-controls") == "Email") {
            initEmail();
        } else {
            getplatform();
        }
    });
    $("#platfrom").change(function() {
        if ($(this).is(":checked")) {
            $(".platBox").show();
        } else {
            $(".platBox").hide();
        }
    });
    $("#pla_save").click(function() {
        if ("admin" == user || "super_admin" == user) {
            setplatform();
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }
    });
    // 加密方式改变
    $("#sslOn").change(function() {
        if ($(this).val() == "on") {
            $("#emailPort").val("465")
        } else if ($(this).val() == "STARTTLS") {
            $("#emailPort").val("587")
        } else {
            $("#emailPort").val("25")
        }
    })
});

function initPageSet() {
    if (config.deviceCap.IsSupportGB28181 == "false" || !config.deviceCap.IsSupportGB28181) {
        $("#myTab").find("li").eq(0).hide();
        $(".tab-content").find('div[role="tabpanel"]').eq(0).hide();
    }
    if (config.deviceCap.IsSupportFTP == "false" || !config.deviceCap.IsSupportFTP) {
        $("#myTab").find("li").eq(1).hide();
        $(".tab-content").find('div[role="tabpanel"]').eq(1).hide();
    }
    if (config.deviceCap.IsSupportEmail == "false" || !config.deviceCap.IsSupportEmail) {
        $("#myTab").find("li").eq(2).hide();
        $(".tab-content").find('div[role="tabpanel"]').eq(2).hide();
    }
    if (config.deviceCap.IsSupportGB28181 == "true") {
        getplatform();
    }
    //选中ftp那肯定gb是false
    if (config.deviceCap.IsSupportGB28181 == "false" && config.deviceCap.IsSupportFTP == "true") {
        $("#myTab li").removeClass("active");
        $("#myTab").find("li").eq(0).hide();
        $("#Plat28181").hide();
        $('.tab-content div[role="tabpanel"]').removeClass("active");
        $(".tab-content").find('div[role="tabpanel"]').eq(1).addClass("active");
        $("#myTab").find("li").eq(1).addClass("active");
        initFTp();
    }
    //邮箱选中 那肯定只有邮箱为true
    if (!(config.deviceCap.IsSupportGB28181) && !(config.deviceCap.IsSupportFTP) && config.deviceCap.IsSupportEmail == "TRUE") { //这里应该要兼容写法 暂时写死大写适配老的设备
        $("#myTab").find("li").hide();
        $("#Plat28181,#FTP").hide();
        $(".tab-content").find('div[role="tabpanel"]').eq(2).show();
        $("#myTab").find("li").eq(2).addClass("active").show();
        initEmail();
    }
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width: 360
        });
    }
}
jQuery.validator.addMethod("isChinese", function(value, element) {
    var reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
    return this.optional(element) || (!reg.test(value));
}, $.i18n.prop("i18n-pla-msg2"));
jQuery.validator.addMethod("isemailSender", function(value, element) {
    var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    return this.optional(element) || (reg.test(value));
}, $.i18n.prop("i18n-pla-msg3"));
jQuery.validator.addMethod("isServerIpAddress", function(value, element) {
    var reg = /^(1(02[4-9]|0[3-9][0-9]|[1-9][0-9]{2})|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/;
    return this.optional(element) || (reg.test(value));
}, $.i18n.prop("i18n-pla-msg4"));
jQuery.validator.addMethod("isPort", function(value, element) {
    var reg = /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
    return this.optional(element) || (reg.test(value));
}, $.i18n.prop('i18n-ftp-porterr'));
jQuery.validator.addMethod("isVideo", function(value, element) {
    var reg = /^[0-9]{20}$/;
    //this.optional(element)  用于表单控件的值不为空时才触发验证
    return (reg.test(value)) || value.length == 0;
}, $.i18n.prop("i18n-pla-msg5"));

function validatetype(id, rule, messages, callback) {
    $(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').after(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 initEmail() {
    getEmailInfo();
    $("#emailEnable").change(function() {
        $(this).is(':checked') ? $('.isShowEmail').show() : $('.isShowEmail').hide();
    });
    $("#emailSave").click(function() {
        if ("admin" == user || "super_admin" == user) {
            setEmailInfo();
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }
    });
    $("#emailTest").click(function(e) {
        e.preventDefault();
        if ("admin" == user || "super_admin" == user) {
            testEmail();
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }
    });

}

function initFTp() {
    getFtpInfo();
    $("#ftpEnable").change(function() {
        $(this).is(':checked') ? $('.isShowFtp').show() : $('.isShowFtp').hide();
    });
    $("#ftpSave").click(function(event) {
        event.preventDefault();
        if ("admin" == user || "super_admin" == user) {
            setFtpInfo();
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }
    });
    $("#tftp").click(function(e) {
        e.preventDefault();
        if ("admin" == user || "super_admin" == user) {
            testFTP();
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }
    });
}

function initCodeBox() {
    AlarmInputChannels == 0 && $("#codeId").find("label").eq(2).hide();
    VideoInputChannels == 0 && $("#codeId").find("label").eq(0).hide();
    AudioChannels == 0 && $("#codeId").find("label").eq(1).hide();
    if (AlarmInputChannels == 0 && VideoInputChannels == 0 && AudioChannels == 0) { //全为0 则不存在
        $("#codeBox").remove();
        return;
    }
    $(".alarmBox,.audioBox,.videoBox").remove();
    for (var i = 0; i < AlarmInputChannels; i++) {
        $('<div class="encoded-itme alarmBox form-group" style="width: 400px">\
            <label class= "col-md-1 control-label" style="padding:0px"> ' + (i + 1) + '</label>\
            <div><div>\
            <input type="text" name="alarm_' + (i + 1) + '" class="form-control ip-itme" id="alarmBox_' + (i + 1) + '">\
            </div></div></div>').appendTo('.encoded-box');
    };
    for (var i = 0; i < AudioChannels; i++) {
        $('<div class="encoded-itme audioBox form-group" style="width: 400px">\
        <label class= "col-md-1 control-label" style="padding:0px"> ' + (i + 1) + '</label>\
        <div><div>\
        <input type="text" name="audio_' + (i + 1) + '" class="form-control ip-itme" id="audioBox_' + (i + 1) + '">\
        </div></div></div>').appendTo('.encoded-box');
    };
    for (var i = 0; i < VideoInputChannels; i++) {
        $('<div class="encoded-itme videoBox form-group" style="width: 400px">\
            <label class= "col-md-1 control-label" style="padding:0px"> ' + (i + 1) + '</label>\
            <div>\
                <div>\
                    <input type="text" name="video_' + (i + 1) + '" class="form-control ip-itme" id="videoBox_' + (i + 1) + '">\
                </div>\
            </div>\
        </div>').appendTo('.encoded-box');
    };
    if (VideoInputChannels > 0) {
        $(".alarmBox,.audioBox").hide();
        $("#videoBox").prop("checked", true);
    }
    if (VideoInputChannels == 0 && AudioChannels > 0) {
        $(".alarmBox").hide();
        $("#audioBox").prop("checked", true);
    }
    if (VideoInputChannels == 0 && AudioChannels == 0 && AlarmInputChannels > 0) {
        $("#alarmBox").prop("checked", true);
    }
    rule = {
        serverId: {
            required: true,
            maxlength: 20
        },
        serverRegion: {
            required: true,
            maxlength: 10
        },
        serverIpAddress: {
            required: true,
        },
        serverPort: {
            required: true,
            range: [1024, 65535],
            digits: true //必须输入整数
        },
        userName: {
            required: true
        },
        userAuthID: {
            required: true
        },
        password: {
            required: true
        },
        heartBeatInterval: {
            range: [5, 255],
            digits: true //必须输入整数
        },
        maxHeartbeatTimeoutCount: {
            range: [3, 255],
            digits: true //必须输入整数
        },
        registerExpire: {
            range: [3600, 100000],
            digits: true //必须输入整数
        },
        registerInterval: {
            range: [60, 3600],
            digits: true //必须输入整数
        },
        // video: {
        //     isVideo: true,
        // },
        // alarm: {
        //     isVideo: true,
        // },
        // audio: {
        //     isVideo: true,
        // }

    };
    for (var i = 0; i < VideoInputChannels; i++) {
        rule['video_' + (i + 1)] = {
            isVideo: true,
        }
    }
    for (var i = 0; i < AudioChannels; i++) {
        rule['audio_' + (i + 1)] = {
            isVideo: true,
        }
    };
    for (var i = 0; i < AlarmInputChannels; i++) {
        rule['alarm_' + (i + 1)] = {
            isVideo: true,
        }
    }

}

function getEmailInfo() {
    $.ajax({
        url: config.baseUrl + "/Network/EMail",
        type: "get",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            $("#emailEnable").prop('checked', JSON.parse($(xmlDoc).find('EMail').eq(0).find('Enable').eq(0).text()));
            $("#emailEnable").change();
            $("#sslOn").select2('val', $(xmlDoc).find('EMail').eq(0).find('SMTPTLSConfig').eq(0).find('SMTPTLS').eq(0).text());
            var SmtpPort = $(xmlDoc).find('EMail').eq(0).find('SMTPPort').eq(0).text();
            if (SmtpPort == "0") {
                $("#emailPort").val("25");
            } else {
                $("#emailPort").val(SmtpPort);
            }
            $("#emailServer").val($(xmlDoc).find('EMail').eq(0).find('SMTPServer').eq(0).text());
            $("#emailSender").val($(xmlDoc).find('EMail').eq(0).find('SenderEmailAddress').eq(0).text());
            $("#emailAttachsnapshot").prop("checked", JSON.parse($(xmlDoc).find('EMail').eq(0).find('AttachedSnapshot').eq(0).text()));
            // $("#authen").val($(xmlDoc).find('EMail').eq(0).find('SMTPAuthMethod').eq(0).text());
            // $("#emailSenderPwd").val($(xmlDoc).find('EMail').eq(0).find('SenderEmailAddress').eq(0).text(), $('#emailSenderPwd'));
            $("#emailR1").val($(xmlDoc).find('EMail').eq(0).find('ReceiverList').eq(0).find('EmailAddress').eq(0).text());
            $("#emailR2").val($(xmlDoc).find('EMail').eq(0).find('ReceiverList').eq(0).find('EmailAddress').eq(1).text());
            $("#emailR3").val($(xmlDoc).find('EMail').eq(0).find('ReceiverList').eq(0).find('EmailAddress').eq(2).text());
            $("#emTheme").val($(xmlDoc).find('EMail').eq(0).find('Topic').eq(0).text());
            $("#emContent").val($(xmlDoc).find('EMail').eq(0).find('Message').eq(0).text());
            $("#snapinterval").select("val", $(xmlDoc).find('EMail').eq(0).find('RefreshIntervals').eq(0).text());
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}

function setplatform() {
    var messages = {
        serverId: {
            required: $.i18n.prop("i18n-pla-msg"),
            maxlength: $.i18n.prop("i18n-pla-msg6")
        },
        serverRegion: {
            required: $.i18n.prop("i18n-pla-msg"),
            maxlength: $.i18n.prop("i18n-pla-msg7")
        },
        serverIpAddress: {
            required: $.i18n.prop("i18n-pla-msg"),
        },
        serverPort: {
            required: $.i18n.prop("i18n-pla-msg"),
            range: $.i18n.prop("i18n-pla-msg8"),
            digits: $.i18n.prop("i18n-pla-msg9")

        },
        userName: {
            required: $.i18n.prop("i18n-pla-msg"),
        },
        userAuthID: {
            required: $.i18n.prop("i18n-pla-msg"),
        },
        password: {
            required: $.i18n.prop("i18n-pla-msg"),
        },
        heartBeatInterval: {
            range: $.i18n.prop("i18n-pla-msg10"),
            digits: $.i18n.prop("i18n-pla-msg9")
        },
        maxHeartbeatTimeoutCount: {
            range: $.i18n.prop("i18n-pla-msg15"),
            digits: $.i18n.prop("i18n-pla-msg9")
        },
        registerExpire: {
            range: $.i18n.prop("i18n-pla-msg11"),
            digits: $.i18n.prop("i18n-pla-msg9")
        },
        registerInterval: {
            range: $.i18n.prop("i18n-pla-msg12"),
            digits: $.i18n.prop("i18n-pla-msg9")
        },

    };
    validatetype("#plat_from", rule, messages, setGB28181);
}

function setGB28181() {
    var AlarmInInfoxml = "<AlarmInInfoList Version='1.0'>";
    for (var i = 0; i < AlarmInputChannels; i++) {
        var id = i + 1;
        AlarmInInfoxml += "<AlarmInInfo><ID>" + id + "</ID><AlarmInID>" + $("#alarmBox_" + id).val() + "</AlarmInID></AlarmInInfo>";
    };
    AlarmInInfoxml += "</AlarmInInfoList>";
    var VideoOutInfoxml = "<VideoOutInfoList Version='1.0'>";
    for (var i = 0; i < VideoInputChannels; i++) {
        var id1 = i + 1;
        VideoOutInfoxml += "<VideoOutInfo><ID>" + id1 + "</ID><VideoOutID>" + $("#videoBox_" + id1).val() + "</VideoOutID></VideoOutInfo>";
    };
    VideoOutInfoxml += "</VideoOutInfoList>";
    var AudioOutInfoxml = "<AudioOutInfoList Version='1.0'>";
    for (var i = 0; i < AudioChannels; i++) {
        var id2 = i + 1;
        AudioOutInfoxml += "<AudioOutInfo><ID>" + id2 + "</ID><AudioOutID>" + $("#audioBox_" + id2).val() + "</AudioOutID></AudioOutInfo>";
    };
    AudioOutInfoxml += "</AudioOutInfoList>";
    var cyXml = '<?xml version="1.0" encoding="UTF-8" ?><GB28181Cfg Version="1.0"><ServerCfg Version="1.0"><ServerID>' + $("#serverId").val() + '</ServerID>' +
        '<ServerRegion>' + $("#serverRegion").val() + '</ServerRegion>' +
        '<ServerIpAddress>' + $("#serverIpAddress").val() + '</ServerIpAddress>' +
        '<ServerPort>' + $("#serverPort").val() + '</ServerPort>' +
        '<UserName>' + $("#userName").val() + '</UserName>' +
        '<UserAuthID>' + $("#userAuthID").val() + '</UserAuthID>' +
        '<Password>' + $("#password").val() + '</Password>' +
        '<TransportLayType>' + $("#transportLayType").select2('val') + '</TransportLayType>' +
        '</ServerCfg>' + AlarmInInfoxml + VideoOutInfoxml + AudioOutInfoxml +
        '<Enable>' + $("#platfrom").is(":checked") + '</Enable>' +
        '<ProtocolVersion>' + $("#protocolVersion").select2('val') + '</ProtocolVersion>' +
        '<HeartbeatInterval>' + $("#heartBeatInterval").val() + '</HeartbeatInterval>' +
        '<MaxHeartbeatTimeoutCount>' + $("#maxHeartbeatTimeoutCount").val() + '</MaxHeartbeatTimeoutCount>' +
        '<RegisterExpire>' + $("#registerExpire").val() + '</RegisterExpire>' +
        '<RegisterInterval>' + $("#registerInterval").val() + '</RegisterInterval>' +
        '<RegisterState>' + RegisterState + '</RegisterState>' +
        '<StreamType>' + $("#streamType").select2('val') + '</StreamType>' +
        '</GB28181Cfg>';
    $.ajax({
        type: "PUT",
        url: config.baseUrl + "/System/1/GB28181Config",
        async: false,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            $(".form-group").removeClass("has-success");
            SaveState(xhr);
        }
    });
}

function setEmailInfo() {
    var rule = {
        emTheme: {
            maxlength: 31,
            isChinese: true
        },
        emContent: {
            maxlength: 127,
            isChinese: true
        },
        emailSender: {
            maxlength: 127,
            isemailSender: true,
        },
        emailR1: {
            isemailSender: true,
            maxlength: 127,

        },
        emailR2: {
            isemailSender: true,
            maxlength: 127,
        },
        emailR3: {
            isemailSender: true,
            maxlength: 127,
        }

    };
    var messages = {
        emTheme: {
            maxlength: $.i18n.prop("i18n-pla-msg13")
        },
        emContent: {
            maxlength: $.i18n.prop("i18n-pla-msg14")
        },
        emailSender: {
            maxlength: $.i18n.prop("i18n-pla-msg14")
        },
        emailR1: {
            maxlength: $.i18n.prop("i18n-pla-msg14")

        },
        emailR2: {
            maxlength: $.i18n.prop("i18n-pla-msg14")
        },
        emailR3: {
            maxlength: $.i18n.prop("i18n-pla-msg14")
        }
    };
    validatetype("#Emailform", rule, messages, emailSubmit);


}

function emailSubmit() {
    var cyXml = "<?xml version='1.0' encoding='UTF-8'?>" +
        "<EMail Version = '1.0' xmlns = 'http://www.zwcloud.wang/ver10/XMLSchema' ><Enable>" + $("#emailEnable").is(":checked") + "</Enable>" +
        "<SMTPServer>" + $("#emailServer").val() + "</SMTPServer><SMTPPort>" + $("#emailPort").val() + "</SMTPPort>" +
        "<SMTPAuthMethod></SMTPAuthMethod><SenderEmailAddress>" + $("#emailSender").val() + "</SenderEmailAddress>" +
        "<SenderEmailPassword>" + $("#emailSenderPwd").val() + "</SenderEmailPassword><AttachedSnapshot>" + $("#emailAttachsnapshot").is(":checked") + "</AttachedSnapshot>" +
        "<RefreshIntervals>" + $("#snapinterval").select2("val") + "</RefreshIntervals><Topic>" + $("#emTheme").val() + "</Topic>" +
        "<Message>" + $("#emContent").val() + "</Message><SMTPTLSConfig Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<SMTPTLS>" + $("#sslOn").select2('val') + "</SMTPTLS></SMTPTLSConfig><ReceiverList Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<Receiver Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><ID>1</ID><EmailAddress>" + $("#emailR1").val() + "</EmailAddress>" +
        "</Receiver><Receiver Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><ID>2</ID><EmailAddress>" + $("#emailR2").val() + "</EmailAddress>" +
        "</Receiver><Receiver Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><ID>3</ID><EmailAddress>" + $("#emailR3").val() + "</EmailAddress>" +
        "</Receiver></ReceiverList > <Schedule Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><AllDay></AllDay>" +
        "<TimeBlockList Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><TimeBlock_0></TimeBlock_0><TimeBlock_1></TimeBlock_1><TimeBlock_2></TimeBlock_2><TimeBlock_3></TimeBlock_3><TimeBlock_4></TimeBlock_4><TimeBlock_5></TimeBlock_5><TimeBlock_6></TimeBlock_6></TimeBlockList></Schedule></EMail>";
    var cyURL = config.baseUrl + "/Network/EMail";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: cyXml,
        // contentType: "application/xml;charset=utf-8",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
            $(".form-group.isShowEmail").removeClass("has-success");
        }
    });
}

function testEmail() {
    var cyXml = "";
    var cyURL = config.baseUrl + "/System/SendTestEmail";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: true,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var state = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
            if ("0" == state) {
                $.optionBootoast($.i18n.prop("i18n-testsuccess"), "success");
            } else {
                $.optionBootoast($.i18n.prop("i18n-testfail"), "danger");
            }
        }
    });
}

function testFTP() {
    var cyURL = config.baseUrl + "/System/SendTestFTP";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: "",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var xmlDoc = xhr.responseXML;
            var state = $(xmlDoc).find("statusCode").eq(0).text();
            if ("0" == state) {
                $.optionBootoast($.i18n.prop("i18n-testsuccess"), "success");
            } else {
                $.optionBootoast($.i18n.prop("i18n-testfail"), "danger");
            }
        }
    });
}

function setFtpInfo() {
    if ($("#savePath").val().length > 40) {
        $.optionBootoast($.i18n.prop("i18n-ftp-path-tip"), "danger");
    } else {
        ftpSubmit();
    }

}

function ftpSubmit() {
    var cyXml = "";
    if ($("#ftppw").val() != 'YWRtaW5hZG1pbg=#' && $("#ftppw").val() != '******') {
        cyXml = "<?xml version='1.0' encoding='UTF-8' ?><FTP Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><Enable>" + $("#ftpEnable").is(':checked') + "</Enable><UserName>" + $("#ftpuser").val() + "</UserName><Password>" + $("#ftppw").val() + "</Password><IPAddress>" + $("#ftpserver").val() + "</IPAddress><Port>" + $("#ftpport").val() + "</Port><TransferContentTypeMask>" + $("#ftpup").select2('val') + "</TransferContentTypeMask><FTPMode>" + $("#passive-mode").is(':checked') + "</FTPMode><StorageDirectory>" + $("#savePath").val() + "</StorageDirectory><Status></Status></FTP>";
    } else {
        cyXml = "<?xml version='1.0' encoding='UTF-8' ?><FTP Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><Enable>" + $("#ftpEnable").is(':checked') + "</Enable><UserName>" + $("#ftpuser").val() + "</UserName><IPAddress>" + $("#ftpserver").val() + "</IPAddress><Port>" + $("#ftpport").val() + "</Port><TransferContentTypeMask>" + $("#ftpup").select2('val') + "</TransferContentTypeMask><FTPMode>" + $("#passive-mode").is(':checked') + "</FTPMode><StorageDirectory>" + $("#savePath").val() + "</StorageDirectory><Status></Status></FTP>";
    }
    var cyURL = config.baseUrl + "/Network/ftp";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: true,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            if (xhr.status == 200) {
                $.optionBootoast($.i18n.prop('i18n-savesuccess'), "success");
            } else {
                $.optionBootoast($.i18n.prop('i18n-savefail'), "danger");
            }
            $(".form-group.isShowFtp").removeClass("has-success");
        }
    });
}

function getFtpInfo() {
    $.ajax({
        url: config.baseUrl + "/Network/ftp",
        type: "get",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            $("#ftpEnable").prop('checked', JSON.parse($(xmlDoc).find('FTP').eq(0).find('Enable').eq(0).text()));
            $("#ftpEnable").change();
            $("#ftpserver").val($(xmlDoc).find('FTP').eq(0).find('IPAddress').eq(0).text());
            $("#ftpport").val($(xmlDoc).find('FTP').eq(0).find('Port').eq(0).text());
            $("#ftpuser").val($(xmlDoc).find('FTP').eq(0).find('UserName').eq(0).text());
            $("#ftppw").val($(xmlDoc).find('FTP').eq(0).find('UserName').eq(0).text(), $('#ftppw'));
            var FTPMode = $(xmlDoc).find('FTP').eq(0).find('FTPMode').eq(0).text();
            FTPMode = FTPMode == 'Active' ? false : true;
            $("#passive-mode").prop('checked', FTPMode);
            $("#savePath").val($(xmlDoc).find('FTP').eq(0).find('StorageDirectory').eq(0).text());
            $("#ftpup").select2('val', $(xmlDoc).find('FTP').eq(0).find('TransferContentTypeMask').eq(0).text());
            var ftpstatus = $(xmlDoc).find('FTP').eq(0).find('Status').eq(0).text();
            if (ftpstatus == "connected") {
                $("#ftpstaus").val($.i18n.prop('i18n-ftp-status-connected'));
            } else {
                $("#ftpstaus").val($.i18n.prop('i18n-ftp-status-disconnect'));
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}

function getplatform() {
    $.ajax({
        url: config.baseUrl + "/System/1/GB28181Config",
        type: "GET",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            if ($(xmlDoc).find('GB28181Cfg').eq(0).find('Enable').text()) {
                $("#platfrom").prop('checked', JSON.parse($(xmlDoc).find('GB28181Cfg').eq(0).find('Enable').text()));
            }
            $("#platfrom").change();
            $("#protocolVersion").select2('val', $(xmlDoc).find('GB28181Cfg').eq(0).find('ProtocolVersion').eq(0).text());
            $("#serverId").val($(xmlDoc).find('GB28181Cfg').eq(0).find('ServerID').eq(0).text());
            $("#serverRegion").val($(xmlDoc).find('GB28181Cfg').eq(0).find('ServerRegion').eq(0).text());
            $("#serverIpAddress").val($(xmlDoc).find('GB28181Cfg').eq(0).find('ServerIpAddress').eq(0).text());
            $("#serverPort").val($(xmlDoc).find('GB28181Cfg').eq(0).find('ServerPort').eq(0).text());
            $("#userName").val($(xmlDoc).find('GB28181Cfg').eq(0).find('UserName').eq(0).text());
            $("#userAuthID").val($(xmlDoc).find('GB28181Cfg').eq(0).find('UserAuthID').eq(0).text());
            $("#password").val($(xmlDoc).find('GB28181Cfg').eq(0).find('Password').eq(0).text());
            $("#transportLayType").select2('val', $(xmlDoc).find('GB28181Cfg').eq(0).find('TransportLayType').eq(0).text());
            $("#heartBeatInterval").val($(xmlDoc).find('GB28181Cfg').eq(0).find('HeartbeatInterval').eq(0).text());
            $("#maxHeartbeatTimeoutCount").val($(xmlDoc).find('GB28181Cfg').eq(0).find('MaxHeartbeatTimeoutCount').eq(0).text());
            $("#registerExpire").val($(xmlDoc).find('GB28181Cfg').eq(0).find('RegisterExpire').eq(0).text());
            $("#registerInterval").val($(xmlDoc).find('GB28181Cfg').eq(0).find('RegisterInterval').eq(0).text());
            var msg = {
                offline: $.i18n.prop('i18n-p2p-offline'),
                online: $.i18n.prop('i18n-p2p-online'),
            }
            RegisterState = $(xmlDoc).find('GB28181Cfg').eq(0).find('RegisterState').eq(0).text();
            $("#registerState").val(msg[RegisterState]);
            $("#streamType").select2('val', $(xmlDoc).find('GB28181Cfg').eq(0).find('StreamType').eq(0).text());
            // //填充数据
            var AlarmInInfoSize = $(xmlDoc).find('AlarmInInfoList').eq(0).find('AlarmInInfo').length;
            for (var i = 0; i < AlarmInInfoSize; i++) {
                var id1 = parseInt($(xmlDoc).find('AlarmInInfoList').eq(0).find('AlarmInInfo').eq(i).find('ID').text());
                $("#audioBox_" + id1).val($(xmlDoc).find('AlarmInInfoList').eq(0).find('AlarmInInfo').eq(i).find('AlarmInID').text());
            };
            var VideoOutInfoSize = $(xmlDoc).find('VideoOutInfoList').eq(0).find('VideoOutInfo').length;
            for (var i = 0; i < VideoOutInfoSize; i++) {
                var id2 = parseInt($(xmlDoc).find('VideoOutInfoList').eq(0).find('VideoOutInfo').eq(i).find('ID').text());
                $("#videoBox_" + id2).val($(xmlDoc).find('VideoOutInfoList').eq(0).find('VideoOutInfo').eq(i).find('VideoOutID').text());
            };
            var AudioOutInfoSize = $(xmlDoc).find('AudioOutInfoList').eq(0).find('AudioOutInfo').length;
            for (var i = 0; i < AudioOutInfoSize; i++) {
                var id3 = parseInt($(xmlDoc).find('AudioOutInfoList').eq(0).find('AudioOutInfo').eq(i).find('ID').text());
                $("#audioBox_" + id3).val($(xmlDoc).find('AudioOutInfoList').eq(0).find('AudioOutInfo').eq(i).find('AudioOutID').text());
            };
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
};
