var flv_urls = [];
var hls_urls = [];
var hls_fmp4_urls = [];
var venc_widths = [];
var venc_heights = [];
var webrtc_http_enables = [];

function getFlvUrl(input, output) {
    return (flv_urls[input] && flv_urls[input][output]) ? flv_urls[input][output] : '';
}

function getHlsUrl(input, output) {
    return (hls_urls[input] && hls_urls[input][output]) ? hls_urls[input][output] : '';
}

function getHlsFmp4Url(input, output) {
    return (hls_fmp4_urls[input] && hls_fmp4_urls[input][output]) ? hls_fmp4_urls[input][output] : '';
}

function getVencWidth(input, output) {
    return (venc_widths[input] && venc_widths[input][output]) ? venc_widths[input][output] : 0;
}

function getVencHeight(input, output) {
    return (venc_heights[input] && venc_heights[input][output]) ? venc_heights[input][output] : 0;
}

function isWebrtcPreviewEnabled(input, output) {
    return webrtc_http_enables[input] &&
        typeof webrtc_http_enables[input][output] !== 'undefined' &&
        webrtc_http_enables[input][output] == 1;
}

function refreshWebrtcPreviewStatus() {
    var deferred = $.Deferred();
    webrtc_http_enables = [];
    var pending = 0;

    for (var input = 0; input < max_input; input++) {
        webrtc_http_enables[input] = [];
        for (var output = 0; output < max_output; output++) {
            (function (i, o) {
                pending++;
                $.ajax({
                    type: "GET",
                    url: "/get_output?input=" + i + "&output=" + o,
                    dataType: "xml",
                    cache: false,
                    success: function (data) {
                        webrtc_http_enables[i][o] = $(data).find("webrtc_p2p_http_enable").text();
                    },
                    error: function () {
                        webrtc_http_enables[i][o] = "";
                    },
                    complete: function () {
                        pending--;
                        if (pending === 0) deferred.resolve();
                    }
                });
            })(input, output);
        }
    }

    if (pending === 0) {
        deferred.resolve();
    }

    return deferred.promise();
}

function buildPortStatusCards() {
    var container = $("#port_status_container");
    if (!container.length) return;

    container.empty();

    for (var portid = 0; portid < max_input; portid++) {
        var portTitle = getPortName(portid);
        var html = '';

        html += '<h4 class="section-title">' + portTitle + '</h4>';

        html += '    <div class="status-item"><span id="whframerate_' + portid + '" data-i18n="status.inputVideo">' + i18n.t('status.inputVideo') + '</span>';
        if (portid === 0) {
            html += '<span id="vga_auto_adjust" class="span_href" onclick="SetVgaParam()" data-i18n="status.vgaAutoAdjust">' + i18n.t('status.vgaAutoAdjust') + '</span>';
        }
        html += '</div>';
        html += '    <div class="status-item"><span id="int_cnt_' + portid + '" data-i18n="status.capturedFrames">' + i18n.t('status.capturedFrames') + '</span></div>';
        html += '    <div class="status-item"><span id="lost_int_' + portid + '" data-i18n="status.lostFrames">' + i18n.t('status.lostFrames') + '</span></div>';
        html += '    <div class="status-item"><span id="aisamplerate_' + portid + '" data-i18n="status.audioSampleRate">' + i18n.t('status.audioSampleRate') + '</span></div>';
        html += '    <div class="status-item" id="gb28181_status' + portid + '"><span id="gb28181_publish_status' + portid + '" data-i18n="status.gb28181">' + i18n.t('status.gb28181') + '</span></div>';

        for (var output = 0; output < max_output; output++) {
            var streamKey = 'status.subStream1';
            if (output === 0) streamKey = 'status.mainStream';
            else if (output === 1) streamKey = 'status.subStream1';
            else if (output === 2) streamKey = 'status.subStream2';
            else if (output === 3) streamKey = 'status.subStream3';

            if (output > 0) {
                html += '    <div id="no_use' + portid + '_' + output + '">';
            }

            html += '    <h4 class="section-title" data-i18n="' + streamKey + '">' + i18n.t(streamKey) + '</h4>';

            if (output > 0) {
                html += '    <div id="fileld_disable' + portid + '_' + output + '"><div class="status-item text-muted"><span data-i18n="status.streamDisabled">' + i18n.t('status.streamDisabled') + '</span></div></div>';
                html += '    <div id="second' + portid + '_' + output + '">';
            }

            html += '      <div class="status-item"><span id="codec' + portid + '_' + output + '" data-i18n="status.codecType">' + i18n.t('status.codecType') + '</span></div>';
            html += '      <div class="status-item"><span id="whframerate' + portid + '_' + output + '" data-i18n="status.encodeResolution">' + i18n.t('status.encodeResolution') + '</span></div>';
            html += '      <div class="status-item"><span id="bitrate' + portid + '_' + output + '" data-i18n="status.videoBitrate">' + i18n.t('status.videoBitrate') + '</span></div>';
            html += '      <div class="status-item"><span id="push_speed' + portid + '_' + output + '" data-i18n="status.realTimeBitrate">' + i18n.t('status.realTimeBitrate') + '</span></div>';
            html += '      <div class="status-item"><span id="stream_fps' + portid + '_' + output + '" data-i18n="status.realTimeFps">' + i18n.t('status.realTimeFps') + '</span></div>';
            html += '      <div class="status-item"><span id="total_sizem' + portid + '_' + output + '" data-i18n="status.videoEncoded">' + i18n.t('status.videoEncoded') + '</span></div>';
            html += '      <div id="div_mjpgandjpg' + portid + '_' + output + '">';
            html += '          <div class="status-item"><span id="mjpg0_url' + portid + '_' + output + '" data-i18n="status.mjpgUrl">' + i18n.t('status.mjpgUrl') + '</span></div>';
            html += '          <div class="status-item"><span id="jpg0_url' + portid + '_' + output + '" data-i18n="status.jpgUrl">' + i18n.t('status.jpgUrl') + '</span></div>';
            html += '      </div>';
            html += '      <div class="status-item"><span id="ts0_url' + portid + '_' + output + '" data-i18n="status.tsUrl">' + i18n.t('status.tsUrl') + '</span></div>';
            html += '      <div class="status-item"><span id="flv0_url' + portid + '_' + output + '" data-i18n="status.flvUrl">' + i18n.t('status.flvUrl') + '</span></div>';
            html += '      <div class="status-item"><span id="hls0_url' + portid + '_' + output + '" data-i18n="status.hlsTsUrl">' + i18n.t('status.hlsTsUrl') + '</span></div>';
            html += '      <div class="status-item"><span id="hls_fmp40_url' + portid + '_' + output + '" data-i18n="status.hlsMp4Url">' + i18n.t('status.hlsMp4Url') + '</span></div>';
            html += '      <div class="status-item"><span id="fmp40_url' + portid + '_' + output + '" data-i18n="status.mp4Url">' + i18n.t('status.mp4Url') + '</span></div>';
            html += '      <div class="status-item"><span id="rtsp0_url' + portid + '_' + output + '" data-i18n="status.rtspUrl">' + i18n.t('status.rtspUrl') + '</span></div>';
            html += '      <div class="status-item"><span id="rtmp_url' + portid + '_' + output + '" data-i18n="status.rtmpUrl">' + i18n.t('status.rtmpUrl') + '</span></div>';
            html += '      <div class="status-item"><span id="rtmp_push_url' + portid + '_' + output + '_0" data-i18n="status.rtmpPushUrlAny0">' + i18n.t('status.rtmpPushUrlAny0') + '</span><span id="rtmp_rc' + (portid * max_output * 3 + output * 3 + 1) + '" class="span_href" onclick="RestartRTMP(\'' + portid + '\',\'' + output + '\',\'rtmp_0\')" data-i18n="status.reconnect">' + i18n.t('status.reconnect') + '</span></div>';
            html += '      <div class="status-item"><span id="rtmp_push_url' + portid + '_' + output + '_1" data-i18n="status.rtmpPushUrlAny1">' + i18n.t('status.rtmpPushUrlAny1') + '</span><span id="rtmp_rc' + (portid * max_output * 3 + output * 3 + 2) + '" class="span_href" onclick="RestartRTMP(\'' + portid + '\',\'' + output + '\',\'rtmp_1\')" data-i18n="status.reconnect">' + i18n.t('status.reconnect') + '</span></div>';
            html += '      <div class="status-item"><span id="rtmp_push_url' + portid + '_' + output + '_2" data-i18n="status.rtmpPushUrlAny2">' + i18n.t('status.rtmpPushUrlAny2') + '</span><span id="rtmp_rc' + (portid * max_output * 3 + output * 3 + 3) + '" class="span_href" onclick="RestartRTMP(\'' + portid + '\',\'' + output + '\',\'rtmp_2\')" data-i18n="status.reconnect">' + i18n.t('status.reconnect') + '</span></div>';
            html += '      <div class="status-item"><span id="multicast_url' + portid + '_' + output + '" data-i18n="status.multicastUrl">' + i18n.t('status.multicastUrl') + '</span></div>';
            html += '      <div class="status-item"><span id="srt_url' + portid + '_' + output + '" data-i18n="status.srtListenerUrl">' + i18n.t('status.srtListenerUrl') + '</span></div>';
            html += '      <div class="status-item"><span id="srt_push_url' + portid + '_' + output + '" data-i18n="status.srtCallerUrl">' + i18n.t('status.srtCallerUrl') + '</span></div>';
            html += '      <div class="status-item"><span id="hls_push_url' + portid + '_' + output + '" data-i18n="status.hlsPushUrl">' + i18n.t('status.hlsPushUrl') + '</span></div>';
            if (output === 0 || output === 1) {
                html += '      <div class="status-item"><span id="icecast_publish_uri' + portid + '_' + output + '" data-i18n="status.icecastPushUrl">' + i18n.t('status.icecastPushUrl') + '</span></div>';
            }
            if (output === 0) {
                html += '      <div class="status-item"><span id="shoutcast_publish_uri' + portid + '_' + output + '" data-i18n="status.shoutcastPushUrl">' + i18n.t('status.shoutcastPushUrl') + '</span></div>';
            }
            html += '      <div class="status-item"><span id="webrtc_p2p_url' + portid + '_' + output + '" data-i18n="status.webrtcP2pUrl">' + i18n.t('status.webrtcP2pUrl') + '</span></div>';
            html += '      <div class="status-item"><span id="whip_publish_token' + portid + '_' + output + '" data-i18n="status.whipLabel">' + i18n.t('status.whipLabel') + '</span></div>';
            html += '      <div class="status-item"><span id="room_id' + portid + '_' + output + '" data-i18n="status.trtcRoomId">' + i18n.t('status.trtcRoomId') + '</span><span id="trtc_rc' + (portid * max_output + output + 1) + '" class="span_href" onclick="RestartRTMP(\'' + portid + '\',\'' + output + '\',\'trtc\')" data-i18n="status.reconnect">' + i18n.t('status.reconnect') + '</span></div>';
            html += '      <div class="status-item mt-2 text-start" id="play' + portid + '_' + output + '_h264">';
            html += '          <a id="webRTCPreviewH264_' + portid + '_' + output + '" class="span_href display_off" href="webrtc.html?group=' + portid + '&stream=' + output + '" target="_blank" data-i18n="status.previewWebRTC">' + i18n.t('status.previewWebRTC') + '</a>';
            html += '          <a class="span_href" href="" onclick="videoPlayerHTML5(getFlvUrl(' + portid + ',' + output + '), getHlsUrl(' + portid + ',' + output + '), getHlsFmp4Url(' + portid + ',' + output + '),\'\',\'640\',\'360\');return false" data-i18n="status.previewHTML5">' + i18n.t('status.previewHTML5') + '</a>';
            html += '      </div>';
            html += '      <div class="status-item mt-2 text-start" id="play' + portid + '_' + output + '_h265">';
            html += '          <a id="webRTCPreviewH265_' + portid + '_' + output + '" class="span_href display_off" href="webrtc.html?group=' + portid + '&stream=' + output + '" target="_blank" data-i18n="status.previewWebRTC">' + i18n.t('status.previewWebRTC') + '</a>';
            html += '          <a class="span_href" href="" onclick="videoPlayerH265(getFlvUrl(' + portid + ',' + output + '), getHlsUrl(' + portid + ',' + output + '),\'\',\'640\',\'360\', getVencWidth(' + portid + ',' + output + '), getVencHeight(' + portid + ',' + output + '));return false" data-i18n="status.previewHTML5">' + i18n.t('status.previewHTML5') + '</a>';
            html += '      </div>';

            if (output > 0) {
                html += '    </div>';
                html += '    </div>';
            }
        }

        container.append(html);
    }

    if (typeof i18n !== 'undefined') {
        if (typeof i18n.translate === 'function') {
            i18n.translate(container.length ? container[0] : document);
        } else if (typeof i18n.init === 'function') {
            i18n.init();
        }
    }
}

function refreshStatus() {
    refreshWebrtcPreviewStatus().always(function () {
        $.ajax({
            type: "GET",
            url: "/get_status",
            dataType: "xml",
            cache: false,
            success: function (data) {
                updateDeviceStatus(data);
                updatePortStatus(data);
                // 为所有 URL 添加复制按钮
                setTimeout(addAllCopyButtons, 100);
            }
        });
    });
}

function updateDeviceStatus(data) {
    $("#gps_time").hide();
    $("#gps_location").hide();
    $("#gps_height").hide();

    var runtime = $(data).find("runtime").text();
    $("#runtime").text(i18n.t('status.runningTime') + formatRuntimeDisplay(runtime));

    var systime = $(data).find("systime").text();
    $("#systime").text(i18n.t('status.deviceTime') + systime);

    var cpu_junction_temperature = $(data).find("cpu_junction_temperature").text();
    $("#cpu_junction_temperature").text(i18n.t('status.cpuTemp') + cpu_junction_temperature + "°C");

    var net_packet_sent = $(data).find("net_packet_sent").text();
    var net_packet_dropped = $(data).find("net_packet_dropped").text();
    $("#net_packet_sent").text(i18n.t('status.packetsSent') + net_packet_sent);
    $("#net_packet_dropped").text(i18n.t('status.packetsDropped') + net_packet_dropped);

    var memoryfree = $(data).find("memoryfree").text();
    var memorytotal = $(data).find("memorytotal").text();
    memoryfree = memoryfree / 1024;
    memorytotal = memorytotal / 1024;
    var memoryused = memorytotal - memoryfree;
    memorytotal = memorytotal.toFixed(1);
    memoryused = memoryused.toFixed(1);
    if (memoryfree < 15) {
        $("#memory").css("color", "red");
        $("#memory").text(i18n.t('status.memoryUsage') + memoryused + "M/" + memorytotal + "M" + i18n.t('status.memoryWarning'));
    } else {
        $("#memory").text(i18n.t('status.memoryUsage') + memoryused + "M/" + memorytotal + "M");
    }

    var cpuusage = $(data).find("cpuusage").text();
    if (cpuusage >= 85) {
        $("#cpuusage").css("color", "red");
        $("#cpuusage").text(i18n.t('status.cpuUsage') + cpuusage + "%" + i18n.t('status.cpuWarning'));
    } else {
        $("#cpuusage").text(i18n.t('status.cpuUsage') + cpuusage + "%");
    }

    $("#net_status").text(i18n.t('status.networkStatus'));
    GetNetStatus(data);

    Getsd_card(data);

    var dev_exist = $(data).find("wifi").find("dev_exist").text();
    var wifi_enable = $(data).find("wifi").find("enable").text();
    var state = $(data).find("wifi").find("state").text();
    var wifi_ap_mode = $(data).find("wifi").find("ap_mode").text();
    var ssid = $(data).find("wifi").find("ssid").text();
    var ip = $(data).find("wifi").find("ip").text();
    var level = $(data).find("wifi").find("level").text();
    var freq = $(data).find("wifi").find("freq").text();
    var mac = $(data).find("wifi").find("mac").text();
    if (wifi_ap_mode == "0") {
        get_wifi_sta(dev_exist, wifi_enable, state, ssid, ip, level, freq, mac);
    } else {
        get_wifi_ap(dev_exist, wifi_enable, ssid, ip, mac);
    }

    var g4_dev_exist = $(data).find("g4").find("dev_exist").text();
    var g4_enable = $(data).find("g4").find("enable").text();
    var g4_mode = $(data).find("g4").find("mode").text();
    var g4_status = $(data).find("g4").find("status").text();
    var g4_strength = $(data).find("g4").find("strength").text();
    var g4_gps = $(data).find("g4").find("gps").text();

    var g4_online_time = $(data).find("g4").find("online_time").text();
    var g4_in_kbyte = $(data).find("g4").find("in_kbyte").text() + "kbyte";
    var g4_out_kbyte = $(data).find("g4").find("out_kbyte").text() + "kbyte";
    var g4_gateway = $(data).find("g4").find("gateway").text();
    var g4_ip = $(data).find("g4").find("ip").text();
    var g4_imei = $(data).find("g4").find("imei").text();
    var g4_cme_err = $(data).find("g4").find("cme_err").text();
    Getg4(g4_dev_exist, g4_enable, g4_mode, g4_status, g4_strength, g4_gps, g4_online_time, g4_in_kbyte, g4_out_kbyte, g4_gateway, g4_ip, g4_imei, g4_cme_err);

    var enable = $(data).find("lan_dhcp").find("enable").text();
    var lan_ip = $(data).find("lan_dhcp").find("ip").text();
    var mask = $(data).find("lan_dhcp").find("mask").text();
    var route = $(data).find("lan_dhcp").find("route").text();
    $("#ip").empty();
    $("#mask").empty();
    $("#route").empty();
    get_dhcp(enable, lan_ip, mask, route);
}

function updatePortStatus(data) {
    flv_urls = [];
    hls_urls = [];
    hls_fmp4_urls = [];
    venc_widths = [];
    venc_heights = [];

    var vga_input = $(data).find("vga_input").text();
    if (vga_input === "" || vga_input === "0") {
        $("#vga_auto_adjust").hide();
    } else {
        $("#vga_auto_adjust").show();
    }

    var aisamplerate = $(data).find("aisamplerate").text();
    if (aisamplerate !== "") {
        aisamplerate = (parseFloat(aisamplerate) / 1000).toFixed(1) + "kHz";
    }

    for (var portid = 0; portid < max_input; portid++) {
        var vi = $(data).find("vi[id=" + portid + "]");
        if (!vi.length) continue;

        var framerate_0 = vi.children("framerate").text();
        var int_cnt_0 = vi.children("int_cnt").text();
        var lost_int_0 = vi.children("lost_int").text();
        var width_0 = vi.children("width").text();
        var height_0 = vi.children("height").text();
        var interlaced_0 = vi.children("interlaced").text();

        var whframerate_0 = width_0 + "x" + height_0;
        whframerate_0 = getI_P(interlaced_0, whframerate_0);
        whframerate_0 = whframerate_0 + "@" + framerate_0;

        $("#whframerate_" + portid).append(whframerate_0);
        $("#int_cnt_" + portid).append(int_cnt_0);
        $("#lost_int_" + portid).append(lost_int_0);
        $("#aisamplerate_" + portid).append(aisamplerate);

        var gb_state = vi.children("gb28181_publish_status").text();
        if (gb_state !== "") {
            $("#gb28181_publish_status" + portid).append(GetGB28181state(gb_state));
            $("#gb28181_status" + portid).show();
        } else {
            $("#gb28181_status" + portid).hide();
        }

        for (var output = 0; output < max_output; output++) {
            if (output != 0) {
                var no_use = vi.find("venc[id=" + output + "]").children("no_use").text();
                if (no_use !== "" && no_use != 0) {
                    $("#no_use" + portid + "_" + output).hide();
                } else {
                    $("#no_use" + portid + "_" + output).show();
                }
                var venc_enable = vi.find("venc[id=" + output + "]").children("enable").text();
                if (venc_enable == 0) {
                    $("#fileld_disable" + portid + "_" + output).show();
                    $("#second" + portid + "_" + output).hide();
                } else {
                    $("#fileld_disable" + portid + "_" + output).hide();
                    $("#second" + portid + "_" + output).show();
                }
            }

            var streamId = portid * max_output + output;
            var codec = vi.find("venc[id=" + output + "]").children("codec").text();

            if (codec == "96") {
                $("#codec" + portid + "_" + output).append("H.264");
                $("#play" + portid + "_" + output + "_h264").show();
                $("#play" + portid + "_" + output + "_h265").hide();
                $("#div_mjpgandjpg" + portid + "_" + output).hide();
            } else if (codec == "265") {
                $("#codec" + portid + "_" + output).append("H.265");
                $("#play" + portid + "_" + output + "_h264").hide();
                $("#play" + portid + "_" + output + "_h265").show();
                $("#div_mjpgandjpg" + portid + "_" + output).hide();
            } else if (codec == "1002") {
                $("#codec" + portid + "_" + output).append("MJPEG");
                $("#play" + portid + "_" + output + "_h264").hide();
                $("#play" + portid + "_" + output + "_h265").hide();
                $("#div_mjpgandjpg" + portid + "_" + output).show();
            }

            var rtmp_url = vi.find("venc[id=" + output + "]").children("rtmp_url0").text();
            if (rtmp_url == "") {
                $("#rtmp_url" + portid + "_" + output).append(i18n.t('status.disabled'));
            } else {
                rtmp_url = RmovePortIP(rtmp_url, 'rtmp://', hostip, '/');
                $("#rtmp_url" + portid + "_" + output).append(rtmp_url);
            }

            var rtmp_status_0 = vi.find("venc[id=" + output + "]").children("rtmp_status_0").text();
            var rtmp_status_1 = vi.find("venc[id=" + output + "]").children("rtmp_status_1").text();
            var rtmp_status_2 = vi.find("venc[id=" + output + "]").children("rtmp_status_2").text();
            var rtmp_push_url0 = vi.find("venc[id=" + output + "]").children("rtmp_publish_url_0").text();
            var rtmp_push_url1 = vi.find("venc[id=" + output + "]").children("rtmp_publish_url_1").text();
            var rtmp_push_url2 = vi.find("venc[id=" + output + "]").children("rtmp_publish_url_2").text();
            var rtmp_rc_base = portid * max_output * 3 + output * 3;
            var rtmp_rc0 = "#rtmp_rc" + (rtmp_rc_base + 1);
            var rtmp_rc1 = "#rtmp_rc" + (rtmp_rc_base + 2);
            var rtmp_rc2 = "#rtmp_rc" + (rtmp_rc_base + 3);

            var push_speed_rtmp = new Array(3);
            var total_size_rtmp = new Array(3);
            $(data).find("rtmp_push_speeds").find("stream[id=" + streamId + "]").each(function () {
                var rtmp_index = $(this).attr("rtmp_index");
                push_speed_rtmp[rtmp_index] = $(this).children("push_speed").text();
                total_size_rtmp[rtmp_index] = $(this).children("total_size").text();

                total_size_rtmp[rtmp_index] = (total_size_rtmp[rtmp_index] / 1024 / 1024).toFixed(2);
                if (total_size_rtmp[rtmp_index] >= 1024) {
                    total_size_rtmp[rtmp_index] = (total_size_rtmp[rtmp_index] / 1024).toFixed(2);
                    total_size_rtmp[rtmp_index] += "GByte";
                } else {
                    total_size_rtmp[rtmp_index] += "MByte";
                }
            });

            if (rtmp_push_url0 == "") {
                $("#rtmp_push_url" + portid + "_" + output + "_0").html(i18n.t('status.rtmpPushUrlAny', [0]) + i18n.t('status.disabled'));
                $(rtmp_rc0).hide();
            } else {
                var rtmpPushLabel0 = rtmp_push_url0.indexOf("rtsp://") !== -1
                    ? i18n.t('status.rtspPushUrl', [0])
                    : i18n.t('status.rtmpPushUrl', [0]);
                var rtmpPushText0 = '<span id=push_url_wrap>' + rtmpPushLabel0 + rtmp_push_url0 + '</span>';
                if (rtmp_status_0 == 0) {
                    $("#rtmp_push_url" + portid + "_" + output + "_0").html(rtmpPushText0);
                    $("#rtmp_push_url" + portid + "_" + output + "_0").append(' (' + i18n.t('status.connected') + ', ' + i18n.t('status.pushSpeedLabel') + push_speed_rtmp[0] + 'Kbps, ' + i18n.t('status.pushedLabel') + total_size_rtmp[0] + ')');
                } else {
                    $("#rtmp_push_url" + portid + "_" + output + "_0").html(rtmpPushText0);
                    $("#rtmp_push_url" + portid + "_" + output + "_0").append(' (' + i18n.t('status.disconnected') + ')');
                }
                $(rtmp_rc0).show();
            }

            if (rtmp_push_url1 == "") {
                $("#rtmp_push_url" + portid + "_" + output + "_1").html(i18n.t('status.rtmpPushUrlAny', [1]) + i18n.t('status.disabled'));
                $(rtmp_rc1).hide();
            } else {
                var rtmpPushLabel1 = rtmp_push_url1.indexOf("rtsp://") !== -1
                    ? i18n.t('status.rtspPushUrl', [1])
                    : i18n.t('status.rtmpPushUrl', [1]);
                var rtmpPushText1 = '<span id=push_url_wrap>' + rtmpPushLabel1 + rtmp_push_url1 + '</span>';
                if (rtmp_status_1 == 0) {
                    $("#rtmp_push_url" + portid + "_" + output + "_1").html(rtmpPushText1);
                    $("#rtmp_push_url" + portid + "_" + output + "_1").append(' (' + i18n.t('status.connected') + ', ' + i18n.t('status.pushSpeedLabel') + push_speed_rtmp[1] + 'Kbps, ' + i18n.t('status.pushedLabel') + total_size_rtmp[1] + ')');
                } else {
                    $("#rtmp_push_url" + portid + "_" + output + "_1").html(rtmpPushText1);
                    $("#rtmp_push_url" + portid + "_" + output + "_1").append(' (' + i18n.t('status.disconnected') + ')');
                }
                $(rtmp_rc1).show();
            }

            if (rtmp_push_url2 == "") {
                $("#rtmp_push_url" + portid + "_" + output + "_2").html(i18n.t('status.rtmpPushUrlAny', [2]) + i18n.t('status.disabled'));
                $(rtmp_rc2).hide();
            } else {
                var rtmpPushLabel2 = rtmp_push_url2.indexOf("rtsp://") !== -1
                    ? i18n.t('status.rtspPushUrl', [2])
                    : i18n.t('status.rtmpPushUrl', [2]);
                var rtmpPushText2 = '<span id=push_url_wrap>' + rtmpPushLabel2 + rtmp_push_url2 + '</span>';
                if (rtmp_status_2 == 0) {
                    $("#rtmp_push_url" + portid + "_" + output + "_2").html(rtmpPushText2);
                    $("#rtmp_push_url" + portid + "_" + output + "_2").append(' (' + i18n.t('status.connected') + ', ' + i18n.t('status.pushSpeedLabel') + push_speed_rtmp[2] + 'Kbps, ' + i18n.t('status.pushedLabel') + total_size_rtmp[2] + ')');
                } else {
                    $("#rtmp_push_url" + portid + "_" + output + "_2").html(rtmpPushText2);
                    $("#rtmp_push_url" + portid + "_" + output + "_2").append(' (' + i18n.t('status.disconnected') + ')');
                }
                $(rtmp_rc2).show();
            }

            var framerate = vi.find("venc[id=" + output + "]").children("framerate").text();
            var width = vi.find("venc[id=" + output + "]").children("width").text();
            var height = vi.find("venc[id=" + output + "]").children("height").text();
            var interlaced = vi.find("venc[id=" + output + "]").children("interlaced").text();
            venc_widths[portid] = venc_widths[portid] || [];
            venc_heights[portid] = venc_heights[portid] || [];
            venc_widths[portid][output] = parseInt(width, 10) || 0;
            venc_heights[portid][output] = parseInt(height, 10) || 0;
            var whframerate = width + "x" + height + "@" + framerate;
            $("#whframerate" + portid + "_" + output).append(whframerate);

            var bitrate = vi.find("venc[id=" + output + "]").children("bitrate").text();
            $("#bitrate" + portid + "_" + output).append(bitrate + "Kbps");

            var push_speed = $(data).find("stream_speeds").find("stream[id=" + streamId + "]").children("push_speed").text();
            $("#push_speed" + portid + "_" + output).append(push_speed + "Kbps");

            var fps = $(data).find("stream_fps").find("stream[id=" + streamId + "]").children("fps").text();
            $("#stream_fps" + portid + "_" + output).append(fps);

            var total_size = $(data).find("stream_speeds").find("stream[id=" + streamId + "]").children("total_size").text();
            var total_sizem = (total_size / 1024 / 1024).toFixed(1);
            var unitPushspeed = (total_sizem < 1024) ? 'MByte' : 'GByte';
            $("#total_sizem" + portid + "_" + output).append(total_sizem + unitPushspeed);

            var mjpg_url0 = vi.find("venc[id=" + output + "]").children("mjpg_url0").text();
            if (mjpg_url0 == "") {
                $("#mjpg0_url" + portid + "_" + output).append(i18n.t('status.disabled'));
            } else {
                mjpg_url0 = changeIP(mjpg_url0, window.location.protocol + '//');
                $("#mjpg0_url" + portid + "_" + output).append('<a target="_blank" href="' + mjpg_url0 + '">' + mjpg_url0 + '</a>');
            }

            var jpg_url0 = vi.find("venc[id=" + output + "]").children("jpg_url0").text();
            if (jpg_url0 == "") {
                $("#jpg0_url" + portid + "_" + output).append(i18n.t('status.disabled'));
            } else {
                jpg_url0 = changeIP(jpg_url0, window.location.protocol + '//');
                $("#jpg0_url" + portid + "_" + output).append('<a target="_blank" href="' + jpg_url0 + '">' + jpg_url0 + '</a>');
            }

            var ts_url0 = vi.find("venc[id=" + output + "]").children("ts_url0").text();
            if (ts_url0 == "") {
                $("#ts0_url" + portid + "_" + output).append(i18n.t('status.disabled'));
            } else {
                ts_url0 = changeIP(ts_url0, window.location.protocol + '//');
                $("#ts0_url" + portid + "_" + output).append(ts_url0);
            }

            var hls_url0 = vi.find("venc[id=" + output + "]").children("hls_url0").text();
            var cached_size = $(data).find("hls_cache").find("stream[id=" + streamId + "]").children("cached_size").text();
            var list_size = $(data).find("hls_cache").find("stream[id=" + streamId + "]").children("list_size").text();
            var delay_list_size = $(data).find("hls_cache").find("stream[id=" + streamId + "]").children("delay_list_size").text();

            if (hls_url0 == "") {
                $("#hls0_url" + portid + "_" + output).append(i18n.t('status.disabled'));
            } else {
                hls_url0 = changeIP(hls_url0, window.location.protocol + '//');
                hls_urls[portid] = hls_urls[portid] || [];
                hls_urls[portid][output] = hls_url0;

                var unit = "MByte";
                var cached_size_f = (cached_size / 1024 / 1024).toFixed(1);
                if (cached_size_f >= 1024) {
                    cached_size_f = (cached_size_f / 1024).toFixed(1);
                    unit = "GByte";
                }

                if (!isAppleDevice()) {
                    $("#hls0_url" + portid + "_" + output).append(hls_url0);
                } else {
                    $("#hls0_url" + portid + "_" + output).append('<span class="span_href" onclick="window.open(\'' + hls_url0 + '\')">' + hls_url0 + '</span>');
                }

                if (cached_size_f < 10) {
                    $("#hls0_url" + portid + "_" + output).append(' (' + i18n.t('status.memoryUsedLabel') + cached_size_f + unit + ', ' + i18n.t('status.cacheFilesLabel') + list_size + ')');
                } else {
                    $("#hls0_url" + portid + "_" + output).append(' <span style="color:red;">(' + i18n.t('status.memoryUsedLabel') + cached_size_f + unit + ', ' + i18n.t('status.cacheFilesLabel') + list_size + ')</span>');
                }
            }

            var flv_url0 = vi.find("venc[id=" + output + "]").children("flv_url0").text();
            flv_urls[portid] = flv_urls[portid] || [];
            if (flv_url0 == "") {
                $("#flv0_url" + portid + "_" + output).append(i18n.t('status.disabled'));
                flv_urls[portid][output] = '';
            } else {
                flv_url0 = changeIP(flv_url0, window.location.protocol + '//');
                flv_urls[portid][output] = flv_url0;
                $("#flv0_url" + portid + "_" + output).append(flv_url0);
            }

            var rtsp_url0 = vi.find("venc[id=" + output + "]").children("rtsp_url0").text();
            if (rtsp_url0 == "") {
                $("#rtsp0_url" + portid + "_" + output).append(i18n.t('status.disabled'));
            } else {
                rtsp_url0 = RmovePortIP(rtsp_url0, 'rtsp://', hostip, '/');
                $("#rtsp0_url" + portid + "_" + output).append(rtsp_url0);
            }

            var multicast_url0 = vi.find("venc[id=" + output + "]").children("multicast_url0").text();
            if (multicast_url0 == "") {
                $("#multicast_url" + portid + "_" + output).append(i18n.t('status.disabled'));
            } else {
                $("#multicast_url" + portid + "_" + output).append(multicast_url0);
            }

            var srt_url0 = vi.find("venc[id=" + output + "]").children("srt_url0").text();
            if (srt_url0 == "") {
                $("#srt_url" + portid + "_" + output).append(i18n.t('status.disabled'));
            } else {
                srt_url0 = RmovePortIP(srt_url0, 'srt://', hostip, ':');
                $("#srt_url" + portid + "_" + output).append(srt_url0);
            }

            var srt_publish_url0 = vi.find("venc[id=" + output + "]").children("srt_publish_url0").text();
            var srt_publish_status = vi.find("venc[id=" + output + "]").children("srt_publish_status").text();
            var push_speed_srt = $(data).find("srt_push_speeds").find("stream[id=" + streamId + "]").children("push_speed").text();
            var total_size_srt = $(data).find("srt_push_speeds").find("stream[id=" + streamId + "]").children("total_size").text();

            var srtPushLabel = i18n.t('status.srtCallerUrl');

            if (srt_publish_url0 == "") {
                $("#srt_push_url" + portid + "_" + output).html(srtPushLabel + i18n.t('status.disabled'));
            } else {
                total_size_srt = (total_size_srt / 1024 / 1024).toFixed(2);
                var unit_srt = total_size_srt >= 1024 ? 'GByte' : 'MByte';
                if (total_size_srt >= 1024) total_size_srt = (total_size_srt / 1024).toFixed(2);

                var srtUrlText = srtPushLabel + '<span id=push_url_wrap>' + srt_publish_url0 + '</span>';
                if (srt_publish_status == 0) {
                    $("#srt_push_url" + portid + "_" + output).html(srtUrlText);
                    $("#srt_push_url" + portid + "_" + output).append(' (' + i18n.t('status.connected') + ', ' + i18n.t('status.pushSpeedLabel') + push_speed_srt + 'Kbps, ' + i18n.t('status.pushedLabel') + total_size_srt + unit_srt + ')');
                } else {
                    $("#srt_push_url" + portid + "_" + output).html(srtUrlText);
                    $("#srt_push_url" + portid + "_" + output).append(' (' + i18n.t('status.disconnected') + ')');
                }
            }

            var hls_publish_status = vi.find("venc[id=" + output + "]").children("hls_publish_status").text();
            var hls_publish_url0 = vi.find("venc[id=" + output + "]").children("hls_publish_url0").text();
            var push_speed_hls = $(data).find("hls_push_speeds").find("stream[id=" + streamId + "]").children("push_speed").text();
            var total_size_hls = $(data).find("hls_push_speeds").find("stream[id=" + streamId + "]").children("total_size").text();

            var hlsPushLabel = i18n.t('status.hlsPushUrl');
            if (hls_publish_url0 == "") {
                $("#hls_push_url" + portid + "_" + output).html(hlsPushLabel + i18n.t('status.disabled'));
            } else {
                hls_publish_url0 = hls_publish_url0.replace(/&copy/, "&amp;copy");
                var url = hlsPushLabel + '<span id=push_url_wrap>' + hls_publish_url0 + '</span>';
                if (hls_publish_status.indexOf("200") != -1 || hls_publish_status.indexOf("202") != -1) {
                    total_size_hls = (total_size_hls / 1024 / 1024).toFixed(2);
                    var unit_hls = total_size_hls >= 1024 ? 'GByte' : 'MByte';
                    if (total_size_hls >= 1024) total_size_hls = (total_size_hls / 1024).toFixed(2);
                    $("#hls_push_url" + portid + "_" + output).html(url);
                    $("#hls_push_url" + portid + "_" + output).append(' (' + i18n.t('status.connected') + ', ' + i18n.t('status.pushSpeedLabel') + push_speed_hls + 'Kbps, ' + i18n.t('status.pushedLabel') + total_size_hls + unit_hls + ')');
                } else {
                    $("#hls_push_url" + portid + "_" + output).html(url);
                    $("#hls_push_url" + portid + "_" + output).append(' (' + i18n.t('status.disconnected') + ')');
                }
            }

            var hls_fmp4_url0 = vi.find("venc[id=" + output + "]").children("hls_fmp4_url0").text();
            var cached_size_mp4 = $(data).find("hls_mp4_cache").find("stream[id=" + streamId + "]").children("cached_size").text();
            var list_size_mp4 = $(data).find("hls_mp4_cache").find("stream[id=" + streamId + "]").children("list_size").text();
            hls_fmp4_urls[portid] = hls_fmp4_urls[portid] || [];

            if (hls_fmp4_url0 == "") {
                $("#hls_fmp40_url" + portid + "_" + output).append(i18n.t('status.disabled'));
                hls_fmp4_urls[portid][output] = '';
            } else {
                hls_fmp4_url0 = changeIP(hls_fmp4_url0, window.location.protocol + '//');
                hls_fmp4_urls[portid][output] = hls_fmp4_url0;
                var unit_mp4 = "MByte";
                var cached_size_fmp4 = (cached_size_mp4 / 1024 / 1024).toFixed(1);
                if (cached_size_fmp4 >= 1024) {
                    cached_size_fmp4 = (cached_size_fmp4 / 1024).toFixed(1);
                    unit_mp4 = "GByte";
                }

                if (!isAppleDevice()) {
                    $("#hls_fmp40_url" + portid + "_" + output).append(hls_fmp4_url0);
                } else {
                    $("#hls_fmp40_url" + portid + "_" + output).append('<span class="span_href" onclick="window.open(\'' + hls_fmp4_url0 + '\')">' + hls_fmp4_url0 + '</span>');
                }

                if (cached_size_fmp4 < 10) {
                    $("#hls_fmp40_url" + portid + "_" + output).append(' (' + i18n.t('status.memoryUsedLabel') + cached_size_fmp4 + unit_mp4 + ', ' + i18n.t('status.cacheFilesLabel') + list_size_mp4 + ')');
                } else {
                    $("#hls_fmp40_url" + portid + "_" + output).append(' <span style="color:red;">(' + i18n.t('status.memoryUsedLabel') + cached_size_fmp4 + unit_mp4 + ', ' + i18n.t('status.cacheFilesLabel') + list_size_mp4 + ')</span>');
                }
            }

            var fmp4_url0 = vi.find("venc[id=" + output + "]").children("fmp4_url0").text();
            if (fmp4_url0 == "") {
                $("#fmp40_url" + portid + "_" + output).append(i18n.t('status.disabled'));
            } else {
                fmp4_url0 = changeIP(fmp4_url0, window.location.protocol + '//');
                $("#fmp40_url" + portid + "_" + output).append('<span class="span_href" onclick="window.open(\'' + fmp4_url0 + '\')">' + fmp4_url0 + '</span>');
            }

            var webrtc_p2p_url = vi.find("venc[id=" + output + "]").children("webrtc_p2p_url").text();
            var webrtc_p2p_ws_status = vi.find("venc[id=" + output + "]").children("webrtc_p2p_ws_status").text();
            var webrtc_p2p_ws_viewers = vi.find("venc[id=" + output + "]").children("webrtc_p2p_ws_viewers").text();
            var previewEnabled = isWebrtcPreviewEnabled(portid, output);
            var webrtcLabel = i18n.t('status.webrtcP2pUrl');
            if (webrtc_p2p_url == "") {
                $("#webrtc_p2p_url" + portid + "_" + output).empty().append(webrtcLabel + i18n.t('status.disabled'));
            } else {
                var webrtcTmp = "<span class=\"span_href\" onclick=\"window.open('" + webrtc_p2p_url + "')\">" + webrtc_p2p_url + "</span>";
                if (webrtc_p2p_ws_status == 0) {
                    webrtcTmp += " (" + i18n.t('status.connected') + ", " + i18n.t('status.viewersLabel') + webrtc_p2p_ws_viewers + ")";
                } else {
                    webrtcTmp += " (" + i18n.t('status.disconnected') + ")";
                }
                $("#webrtc_p2p_url" + portid + "_" + output).empty().append(webrtcLabel).append(webrtcTmp);
            }
            if (codec == "96" && (previewEnabled || webrtc_p2p_url != "")) {
                $("#webRTCPreviewH264_" + portid + "_" + output).removeClass("display_off");
            } else {
                $("#webRTCPreviewH264_" + portid + "_" + output).addClass("display_off");
            }
            if (codec == "265" && (previewEnabled || webrtc_p2p_url != "") && browserSupportsH265WebRTC()) {
                $("#webRTCPreviewH265_" + portid + "_" + output).removeClass("display_off");
            } else {
                $("#webRTCPreviewH265_" + portid + "_" + output).addClass("display_off");
            }

            var whip_publish_server = vi.find("venc[id=" + output + "]").children("whip_publish_server").text();
            var whip_publish_status = vi.find("venc[id=" + output + "]").children("whip_publish_status").text();
            var whipLabel = i18n.t('status.whipLabel');
            if (whip_publish_server == "") {
                $("#whip_publish_token" + portid + "_" + output).empty().append(whipLabel + i18n.t('status.disabled'));
            } else {
                var whip_status_text = whip_show(whip_publish_status);
                $("#whip_publish_token" + portid + "_" + output).empty().html(whipLabel + '<span id=push_url_wrap>' + whip_publish_server + '</span> (' + whip_status_text + ')');
            }

            var shoutcast_publish_uri = vi.find("venc[id=" + output + "]").children("shoutcast_publish_uri").text();
            var shoutcast_status = vi.find("venc[id=" + output + "]").children("shoutcast_status").text();
            if (output == 0) {
                if (shoutcast_publish_uri == "") {
                    $("#shoutcast_publish_uri" + portid + "_" + output).append(i18n.t('status.disabled'));
                } else {
                    $("#shoutcast_publish_uri" + portid + "_" + output).append(shoutcast_publish_uri);
                    if (shoutcast_status >= 0) {
                        $("#shoutcast_publish_uri" + portid + "_" + output).append(' (' + i18n.t('status.connected') + ')');
                    } else {
                        $("#shoutcast_publish_uri" + portid + "_" + output).append(' (' + i18n.t('status.disconnected') + ')');
                    }
                }
            }

            if (output == 0 || output == 1) {
                var icecast_publish_uri = vi.find("venc[id=" + output + "]").children("icecast_publish_uri").text();
                var icecast_status = vi.find("venc[id=" + output + "]").children("icecast_status").text();
                if (icecast_publish_uri == "") {
                    $("#icecast_publish_uri" + portid + "_" + output).append(i18n.t('status.disabled'));
                } else {
                    $("#icecast_publish_uri" + portid + "_" + output).append(icecast_publish_uri);
                    if (icecast_status >= 0) {
                        $("#icecast_publish_uri" + portid + "_" + output).append(' (' + i18n.t('status.connected') + ')');
                    } else {
                        $("#icecast_publish_uri" + portid + "_" + output).append(' (' + i18n.t('status.disconnected') + ')');
                    }
                }
            }

            var trtc = $(data).find("trtc_status").find("trtc[id=" + streamId + "]");
            var in_room = trtc.children("in_room").text();
            var room_id = trtc.children("room_id").text();
            var error = trtc.children("error").text();
            var connection_state = trtc.children("connection_state").text();
            var network_quality = trtc.children("network_quality").text();
            var trtc_rc = "#trtc_rc" + (portid * max_output + output + 1);

            if (room_id == "") {
                $("#room_id" + portid + "_" + output).append(i18n.t('status.disabled'));
                $(trtc_rc).hide();
            } else {
                $(trtc_rc).show();
                if (!room_id || room_id.trim() === "") {
                    $("#room_id" + portid + "_" + output).append(i18n.t('status.disconnected'));
                } else {
                    var in_room_value = in_room_show(in_room);
                    var connection_state_value = connection_state_show(connection_state);
                    var network_quality_value = network_quality_show(network_quality);
                    if (error == "0") {
                        $("#room_id" + portid + "_" + output).append(room_id + ' (' + in_room_value + ', ' + connection_state_value + ', ' + network_quality_value + ')');
                    } else {
                        var error_value = error_show(error);
                        $("#room_id" + portid + "_" + output).append(room_id + ' (' + in_room_value + ', ' + connection_state_value + ', ' + network_quality_value + ', ' + i18n.t('status.errorCodeLabel') + error_value + ')');
                    }
                }
            }
        }
    }
}

function GetajaxStatus() {
    ShowWifi();
    ensurePortContext().done(function () {
        buildPortStatusCards();
        refreshStatus();
    });
}
