// JavaScript Document
var point_mac = "";
var wifiFlag = false;
var wifiModeUrl = '/Network/WhichNetworkCard';
var wifiUrl = '/Network/Interfaces/2';
var wifiTestUrl = "/Network/WifiParamTest";
var wifiListUrl = "/Network/Interfaces/2/WIFIAccessPointList";
var wifiTestStatusUrl = "/Network/WifiParamTestStatus";
var wapmac = {};
var wifi = [{
    able: "connected",
    result: $.i18n.prop("i18n-wifi-connected")
}, {
    able: "disconnected",
    result: $.i18n.prop("i18n-wifi-disconnected")
}];
var timing = null;
/*************************************************
 Function:
 Description:  初始化程序
 **************************************************/
$(document).ready(function() {
    $("#wifiType,#wifiAlgorithm,#ipType").select2({
        minimumResultsForSearch: -1,
        width: 220
    });
    $("#wifiType").change(function() {
        switch ($(this).val()) {
            case "NONE":
                $(".wpaid,.wepid,.wfinfo").hide();
                break;
            case "OPEN":
                $(".wepid,.wfinfo").show();
                $(".wpaid").hide();
                break;
            case "WPAPSK":
            case "WPA2PSK":
                $(".wpaid,.wfinfo").show();
                $(".wepid").hide();
                break;
            default:
                $(".wpaid,.wepid,.wfinfo").hide();
                break;
        }
    });
    $("#ipType").change(function() {
        if ($(this).val() === "true") {
            $("#ipAddres").prop('disabled', true);
            $("#subnetMask").prop('disabled', true);
            $("#gateway").prop('disabled', true);
        } else {
            $("#ipAddres").prop('disabled', false);
            $("#subnetMask").prop('disabled', false);
            $("#gateway").prop('disabled', false);
        }
    });

    getParameter(getWifiMode, wifiModeUrl, 0);

    $("#wifiSave").click(function() {
        if ($("#wifiType").val() !== "OPEN") {
            chkKey()
        }
        setWifiInfo();
    });

    $("#wifiSearch").click(function() {
        $.optionBootoast($.i18n.prop("i18n-wifi-chaxun"), "success")
        $("#MaskLayouts").show()
        getParameter(inWifiAPL, wifiListUrl, 0);
        $("#wifiserch").css({
            display: "block",
            left: "650px",
            top: "300px"
        });
    });
    $("#refresh").click(function() {
        $("#waplist").empty();
        getParameter(inWifiAPL, wifiListUrl, 0);
    });
    $("#closebtn").click(function() {
        $("#MaskLayouts").hide();
        $("#wifiserch").hide();
        $("#waplist").empty();
    });
    $("#wifiCheck").click(function() {
        if (chkKey()) {
            screenDisplay();
            chkWifiInfo();
        }
    });
});
// get请求
function getParameter(callback, url, flag) {

    $.ajax({
        url: config.baseUrl + url,
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xml, xhr) {
            callback(xml, xhr);
        },
        error: function(xhr) {

        }
    })
}
// set请求
function setParameter(callback, url, type, xml, flag, nFlag) {
    $.ajax({
        url: config.baseUrl + url,
        type: type,
        async: true,
        data: xml,
        processData: false,
        timeout: 15000,
        complete: function(xhr) {
            if (flag === 1) {
                callback(xhr, nFlag)
                if (url == '/Network/Interfaces/2') {
                    clearInterval(timing);
                    $("#popDiv,#cwin,#MaskLayouts").hide();
                    clearInterval(timing);
                    getParameter(updateStatus, wifiUrl, 0);
                }
                
            }
        },
        success: function(xhr) {
            if (flag === 0) {
                callback(xhr, nFlag);
                if (url == '/Network/Interfaces/2') {
                    clearInterval(timing);
                    $("#popDiv,#cwin,#MaskLayouts").hide();
                    clearInterval(timing);
                    getParameter(updateStatus, wifiUrl, 0);
                }
            }
        },
        error: function(xhr) {}
    })
}
// 获取当前wifi
function inWifiAPL(xmlDoc) {
    var ssid = "";
    var encrypt = "";
    var auth = "";
    var mac = "";

    var WAPList = $(xmlDoc).find('WIFIAccessPointList').eq(0).find('WIFIAccessPoint').length;

    for (var i = 0; i < WAPList; i++) {
        ssid = $(xmlDoc).find('WIFIAccessPointList').eq(0).find('WIFIAccessPoint').eq(i).find("SSID").text();
        mac = $(xmlDoc).find('WIFIAccessPointList').eq(0).find('WIFIAccessPoint').eq(i).find("MACAddress").text();
        encrypt = $(xmlDoc).find('WIFIAccessPointList').eq(0).find('WIFIAccessPoint').eq(i).find("EncryptType").text();
        auth = $(xmlDoc).find('WIFIAccessPointList').eq(0).find('WIFIAccessPoint').eq(i).find("Authentication").text();
        $("<tr class='wlist' id='wlist" + i + "'>" +
            "<td width='38' height='28' class='tdbgimg' bgcolor='#bfc7db'>" + $(xmlDoc).find('WIFIAccessPointList').eq(0).find('WIFIAccessPoint').eq(i).find("ID").text() + "</td>" +
            "<td width='56' height='28' class='tdbgimg' bgcolor='#bfc7db'>" + $(xmlDoc).find('WIFIAccessPointList').eq(0).find('WIFIAccessPoint').eq(i).find("SignalValue").text() + "</td>" +
            "<td width='227' class='tdbgimg' bgcolor='#bfc7db'>" + ssid + "</td>" +
            "<td width='91' class='tdbgimg' bgcolor='#bfc7db'>" + encrypt + "</td>" +
            "<td width='172' class='tdbgimg' bgcolor='#bfc7db'>" + auth + "</td></tr>").appendTo("#waplist");
        wapmac["wlist" + i] = {
            "ssid": ssid,
            "encrypt": encrypt,
            "auth": auth,
            "mac": mac
        };
    }

    $(".wlist").css("cursor", "pointer").click(function() {
        recallWifiScan(wapmac[this.id].ssid, wapmac[this.id].encrypt, wapmac[this.id].auth, wapmac[this.id].mac);
        $("#MaskLayouts").hide();
        $("#wifiserch").hide();
        $("#waplist").empty();
        return false;
    });
}
/*************************************************
 Function:     chkKey
 Description:  WIFI密码字符个数大于等于8
 **************************************************/
function chkKey() {
    if ($("#wifiName").val() === "") {
        $.optionBootoast($.i18n.prop("i18n-ssid-null"), "danger")
        return false
    } else {
        if ($("#wifiType").val() === "WPAPSK" || $("#wifiType").val() === "WPA2PSK") {
            if ($("#wifiKey").val().length < 8 && $("#wifiKey").val().length > 64) {
                $.optionBootoast($.i18n.prop("i18n-wifi-password-tip"), "danger");
                $("#wifiKey").focus();
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
}

/*************************************************
 Function:     getWifiInfo
 Description:  获取WIFI信息
 **************************************************/
function getWifiInfo(xmlDoc) {

    $("#wifiName").val($(xmlDoc).find('SSID').text());
    $("#wifiType").val($(xmlDoc).find('AuthMode').text());
    $("#wifiType").change();

    $("#wifiAlgorithm").val($(xmlDoc).find('EncryptType').text());
    $("#wifiKey").val($(xmlDoc).find("WPA").find('KeyValue').text());
    $("#ipType").val($(xmlDoc).find('DHCP').find('Enable').text());

    $("#ipType").change();
    $("#ipAddres").val($(xmlDoc).find('ipAddress').text())
    $("#subnetMask").val($(xmlDoc).find('SubnetMask').text());
    $("#gateway").val($(xmlDoc).find('Gateway').text());
    $("#primaryDNS").val($(xmlDoc).find('PrimaryDNS').text());
    $("#secondDNS").val($(xmlDoc).find('SecondaryDNS').text());
    $("#macAddress").val($(xmlDoc).find('MacAddress').text());
    var wifiStatus = $(xmlDoc).find('ConnectionConfig').find('Enable').text();
    for (var i = 0; i < wifi.length; i++) {
        if (wifiStatus === wifi[i].able) {
            $("#wifiStatus").val(wifi[i].result);
        }
    }
    //获取当前是STA/AP模式
    var wifiMode = $(xmlDoc).find('NetworkCardMode').text();
    if (wifiMode === 'None') {
        $(".wifimode").hide();
    } else if (wifiMode === 'STA') {
        if (wifiFlag) {
            $("#wifiCheck").attr("disabled", false);
        } else {
            $("#wifiCheck").attr("disabled", true);
        }
        $(".wifimode").show();
        $("#curMode").val($.i18n.prop("i18n-wifi-mode-1"));
    } else {
        $(".wifimode").show();
        $("#wifiCheck").attr("disabled", true);
        $("#curMode").val($.i18n.prop("i18n-wifi-mode-2"));
    }
}

/*************************************************
 Function:     getWifiMode
 Description:  获取wifi模式
 **************************************************/
function getWifiMode(xmlDoc) {
    var wifiMode = $(xmlDoc).find('NetcardType').text();
    if (wifiMode === "wired1" || wifiMode === "wired2") {
        wifiFlag = true;
    }

    getParameter(getWifiInfo, wifiUrl, 0);
}

/*************************************************
 Function:     setWifiInfo
 Description:  保存WIFI信息
 **************************************************/
function setWifiInfo() {

    var cyXml = "<?xml version='1.0' encoding='UTF-8' ?>" +
        "<Interface Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<ID>2</ID>" +
        "<NetworkCardMode></NetworkCardMode>" +
        "<IPAddress Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<ipVersion>V4</ipVersion>" +
        "<ipAddress>" + $("#ipAddres").val() + "</ipAddress>" +
        "<SubnetMask>" + $("#subnetMask").val() + "</SubnetMask>" +
        "<Gateway>" + $("#gateway").val() + "</Gateway>" +
        "<MacAddress></MacAddress>" +
        "<IPAdaptive></IPAdaptive>" +
        "<DHCP Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<Enable>" + $("#ipType").val() + "</Enable>" +
        "<Status></Status>" +
        "</DHCP>" +
        "<DNS Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<Enable></Enable>" +
        "<PrimaryDNS>" + $("#primaryDNS").val() + "</PrimaryDNS>" +
        "<SecondaryDNS>" + $("#secondDNS").val() + "</SecondaryDNS>" +
        "</DNS>" +
        "</IPAddress>" +
        "<ConnectionConfig Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<Enable></Enable>" +
        "<SSID>" + $("#wifiName").val() + "</SSID>" +
        "<MACAddress></MACAddress>" +
        "<NetworkType>Managed</NetworkType>" +
        "<AuthMode>" + $("#wifiType").val() + "</AuthMode>" +
        "<WEP Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<KeyID></KeyID>" +
        "</WEP>" +
        "<WPA Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<EncryptType>" + $("#wifiAlgorithm").val() + "</EncryptType>" +
        "<Key Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<ID>1</ID>" +
        "<KeyType>ASCII</KeyType>" +
        "<KeyValue>" + $("#wifiKey").val() + "</KeyValue>" +
        "<KeyValueBase64>" + Base64.encode($("#wifiKey").val()) + "</KeyValueBase64>" +
        "</Key>" +
        "</WPA>" +
        "</ConnectionConfig>" +
        "<WIFIStatus Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<State></State>" +
        "</WIFIStatus>" +
        "</Interface>";

    setParameter(SaveState, wifiUrl, "PUT", cyXml, 1, 0);
}


/*************************************************
 Function:     screenDisplay
 Description:  显示全屏
 **************************************************/
function screenDisplay() {
    $("#popDiv").html("");
    var str = "<label id='wifi_tip'>" + $.i18n.prop("i18n-wifi-check-tip") + "</label></br>" +
        "<button id='csave' style='cursor:pointer;margin: 0 20px;display: none;height: 25px;line-height: 20px;padding: 2px 10px;' type='button'>" + $.i18n.prop("i18n-save") + "</button>" +
        "<button id='cwin' style='cursor:pointer;display: none;height: 25px;line-height: 20px;padding: 2px 10px;' type='button'>" + $.i18n.prop("i18n-lock") + "</button>";
    $("#MaskLayouts").show();
    $("#popDiv").show();
    $("#popDiv").append(str);
    $("#csave").click(function () {
        setWifiInfo();
        $("#csave").attr("disabled", true);
        $("#cwin").attr("disabled", true);
        var i = 15;
        timing = setInterval(function() {
            if (i === 0) {
                $("#popDiv,#cwin,#MaskLayouts").hide();
                clearInterval(timing);
                getParameter(updateStatus, wifiUrl, 0);
            } else {
                --i;
                $("#wifi_tip").text($.i18n.prop("i18n-wifi-save-tip") + i + $.i18n.prop("i18n-second"));
            }
        }, 1000);
        
    });

    $("#cwin").click(function() {
        $("#popDiv,#cwin,#MaskLayouts").hide();
    });
}

/*************************************************
 Function:     chkWifiInfo
 Description:  检测WIFI信息
 **************************************************/
function chkWifiInfo() {
    var cyXml = "<ConnectionConfig Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<Enable></Enable>" +
        "<SSID>" + $("#wifiName").val() + "</SSID>" +
        "<MACAddress></MACAddress>" +
        "<NetworkType>Managed</NetworkType>" +
        "<AuthMode>" + $("#wifiType").val() + "</AuthMode>" +
        "<WEP Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<KeyID></KeyID>" +
        "<keyList Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'></keyList>" +
        "</WEP>" +
        "<WPA Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<EncryptType>" + $("#wifiAlgorithm").val() + "</EncryptType>" +
        "<Key Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'>" +
        "<ID>1</ID>" +
        "<KeyType>ASCII</KeyType>" +
        "<KeyValue>" + $("#wifiKey").val() + "</KeyValue>" +
        "<KeyValueBase64>" + Base64.encode($("#wifiKey").val()) + "</KeyValueBase64>" +
        "</Key></WPA>" +
        "</ConnectionConfig>";

    setParameter(getWifiTest, wifiTestUrl, "PUT", cyXml, 1, 0);
}


function getWifiTest(xhr) {
    var xmlDoc = xhr.responseXML;
    var statusCode = $(xmlDoc).find('statusCode').text();
    if (statusCode === '0') {
        getParameter(getConnStatus, wifiTestStatusUrl, 0);
    } else {
        $("#wifi_tip").text($.i18n.prop("i18n-wifi-link-failed"));
        $("#cwin").show();
    }
}

/*************************************************
 Function:        getConnStatus
 Description:    获取WIFI连接状态
 *************************************************/
function getConnStatus(xmlDoc) {

    var status = $(xmlDoc).find('Status').text();
    if (status === "disconnect") {
        $("#wifi_tip").text($.i18n.prop("i18n-wifi-link-timeout"));
        $("#cwin").show();
    } else if (status === "connected") {
        $("#wifi_tip").text($.i18n.prop("i18n-wifi-link-success") + $.i18n.prop("i18n-wifi-save-tip-2"));
        $("#csave").show();
        $("#cwin").show();
    } else {
        $("#wifi_tip").text($.i18n.prop("i18n-wifi-password-error"));
        $("#cwin").show();
    }
}

/*************************************************
 Function:     recallWifiScan
 Description:  回调选择WIFI热点
 **************************************************/
function recallWifiScan(ssid, encrypt, auth, mac) {
    var t_encrypt = encrypt.toUpperCase();
    var t_auth = auth.toUpperCase();
    $("#wifiName").val(ssid);
    $("#wifiType").val(t_auth).trigger('change');
    $("#wifiAlgorithm").val(t_encrypt).trigger('change');
    point_mac = mac;
    $("#wifiKey").val("");
}


function updateStatus(xmlDoc) {
    var wifiStatus = $(xmlDoc).find('ConnectionConfig').find('Enable').text();
    for (var i = 0; i < wifi.length; i++) {
        if (wifiStatus === wifi[i].able) {
            $("#wifiStatus").val(wifi[i].result);
        }
    }
}