const TX_PRESENT_NONE       = 0;
const TX_PRESENT_D1550      = 1;
const TX_PRESENT_B170       = 2;
const TX_PRESENT_D1837      = 3;
const TX_PRESENT_B160_B170  = 4;
const TX_PRESENT_B170_D1550 = 5;

var timer = null;
var CustID;
var BoardType;
var TxPresent = TX_PRESENT_NONE;
var TxActive = -1;
var B180Present;
var RFDcBiasPresent;
var DTM3200Present;
var PresetNumber;
var B120Present;
var LicenseMask;
var LicDec;
var license_des;
var license_biss;
var license_enc;
var license_dec;
var license_iptx;
var license_rec;
var license_uhd;

var logo = 'logo.jpg';

var EncodeMode_Select = ["H.265 HEVC", "H.264 AVC", "MPEG-2"];
var VideoFormat_Select = ["480i59", "576i50", "480p59", "576p50", "720p50", "720p59", "720p60", "1080i50", "1080i59", "1080i60", "1080p23", "1080p24", "1080p25", "1080p29", "1080p30", "1080psf23", "1080psf24", "1080psf25", "1080psf29", "1080psf30", "1080p50", "1080p59", "1080p60", "2160p23", "2160p24", "2160p25", "2160p29", "2160p30", "2160p50", "2160p59", "2160p60", "4KDCIp23", "4KDCIp24", "4KDCIp25", "4KDCIp29", "4KDCIp30", "4KDCIp50", "4KDCIp59", "4KDCIp60"];
var VideoFormat_Select_HD = ["480i59", "576i50", "480p59", "576p50", "720p50", "720p59", "720p60", "1080i50", "1080i59", "1080i60", "1080p23", "1080p24", "1080p25", "1080p29", "1080p30", "1080psf23", "1080psf24", "1080psf25", "1080psf29", "1080psf30", "1080p50", "1080p59", "1080p60"];
var VideoSource_Select = ["Default", "QuadSync 1", "QuadSync 2", "QuadSync 3", "QuadSync 4", "Pattern + Tones", "Pattern"];
var VideoBitrate_Select = ["Auto", "Manual"];
var LowDelayMode_Select = ["Normal", "Low", "Ultra Low"];
var SampleFormat_Select = ["2SI", "SQD/HFR"];
var QuadSync_Select = ["Off", "On", "Freerun"];
var BitDepth_Select = ["8-bit", "10-bit"];
var ChromaFormat_Select = ["4:2:0", "4:2:2"];
var HDRWCGMode_Select = ["Auto", "SDR 709/601", "SDR 2020 CL", "SDR 2020 NCL", "HLG 2100 YCbCr", "HLG 2100 ICtCp", "PQ 2100 YCbCr", "PQ 2100 ICtCp"];
var Toggle_Select = ["Off", "On"];
var NoYes_Select = ["No", "Yes"];
var AudioRefLev_Select = ["+24dBu","+18dBu","+20dBu"];
var AudioSource0_Select = ["Analogue 1", "Analogue 2", "SDI 1 (G1P1)", "Test Tone"];
var AudioSource1_Select = ["Analogue 1", "Analogue 2", "SDI 1 (G1P2)", "SDI 2 (G1P1)", "Test Tone"];
var AudioSource2_Select = ["Analogue 1", "Analogue 2", "SDI 1 (G2P1)", "SDI 3 (G1P1)", "Test Tone"];
var AudioSource3_Select = ["Analogue 1", "Analogue 2", "SDI 1 (G2P2)", "SDI 4 (G1P1)", "Test Tone"];
var AudioSource4_Select = ["Analogue 1", "Analogue 2", "SDI 1 (G3P1)", "SDI 1 (G1P2)", "Test Tone"];
var AudioSource5_Select = ["Analogue 1", "Analogue 2", "SDI 1 (G3P2)", "SDI 2 (G1P2)", "Test Tone"];
var AudioSource6_Select = ["Analogue 1", "Analogue 2", "SDI 1 (G4P1)", "SDI 3 (G1P2)", "Test Tone"];
var AudioSource7_Select = ["Analogue 1", "Analogue 2", "SDI 1 (G4P2)", "SDI 4 (G1P2)", "Test Tone"];
var AudioEncoder0_Select = ["Off", "LPCM (16-bit)", "LPCM (20-bit)", "LPCM (24-bit)", "AAC-LC", "MPEG-1 L1", "MPEG-1 L2"];
var AudioEncoder4_Select = ["Off", "LPCM (16-bit)", "LPCM (20-bit)", "LPCM (24-bit)", "MPEG-1 L1", "MPEG-1 L2"];
var AncillaryMode_Select = ["Off", "All Type 2", "HANC Type 2", "User Type 1"];
var AudioBitrateLPCM16_Select = ["1920", "1920", "1920", "1920", "1920", "1920", "1920", "1920", "1920"];
var AudioBitrateLPCM20_Select = ["2304", "2304", "2304", "2304", "2304", "2304", "2304", "2304", "2304"];
var AudioBitrateLPCM24_Select = ["2688", "2688", "2688", "2688", "2688", "2688", "2688", "2688", "2688"];
var AudioBitrateAAC_Select = ["256", "192", "128", "96", "64", "-", "-", "-", "-"];
var AudioBitrateL2_Select = ["384", "256", "192", "128", "96", "320", "224", "160", "112"];
var AudioBitrateL1_Select = ["448", "384", "320", "256", "192", "416", "352", "288", "224"];
var AudioBitrateNone_Select = ["-", "-", "-", "-", "-", "-", "-", "-", "-"];
var DataMode_Select = ["Off", "RS-232", "External CFU", "Internal CC", "RS-232 Raw"];
var DataBaud_Select = ["1200", "2400", "4800", "9600", "19200", "38400", "57600", "115200", "230400"];
var RemuxMode_Select = ["Off", "Relay (ASI)", "Relay (SDI/HANC)"];
var stream_enable_select = ["Off", "Transmit"];
var stream_interface_select = ["Port 1", "Port 2", "IP Module"];
var stream_interface_set = [0, 1, 2];
var stream_interface_get = [0, 1, 2];
var IPStreamNumTP_Select = ["1", "2", "3", "4", "5", "6", "7"];
var IPStreamProtocol_Select = ["UDP", "RTP", "SRT"];
var SRTMode_Select = ["Caller", "Listener", "Rendezvous"];
var UnitMode_Select = ["Encoder", "Decoder"];
var TxPresent_Select = ["No", "D1550", "B170/B30X", "D1837", "B160+B170", "B170+D1550"];
var OLEDType_Select = ["SSD1307 (96x16)", "SSD1306 (96x16)", "SSD1309 (128x64)"];
var FanMode_Select = ["Record", "Idle", "Full"];
var FanSpeeds_Select = ["Off","Low","High"];
var RecordEnable_Select = ["Off", "On", "Triggered"];
var RFBandwidth_Select = ["Custom", "1980 - 2700 MHz", "5500 - 6000 MHz", "2000 - 2900 MHz", "3200 - 3700 MHz", "1000 - 1500 MHz", "2000 - 2500 MHz"];
var ModemBandwidth_Select = ["403 - 473 MHz", "410 - 475 MHz", "902 - 928 MHz"];
var CamCtrlPresent_Select = ["No", "B180", "CAMRX", "CAMRX-E"];

var supported_formats = ["480i59", "576i50", "480i59", "576i50", "720p50", "720p59", "720p60", "1080i50", "1080i59", "1080i60", "1080p23", "1080p24", "1080p25", "1080p29", "1080p30", "1080psf23", "1080psf24", "1080psf25", "1080psf29", "1080psf30", "1080p50", "1080p59", "1080p60", "2160p23", "2160p24", "2160p25", "2160p29", "2160p30", "2160p50", "2160p59", "2160p60", "4KDCIp23", "4KDCIp24", "4KDCIp25", "4KDCIp29", "4KDCIp30", "4KDCIp50", "4KDCIp59", "4KDCIp60"];
var quad_sync_3G_formats = ["480i59", "576i50", "480i59", "576i50", "720p25/p50", "720p29/p59", "720p30/p60", "1080i50/p50", "1080i59/p59", "1080i60/p60", "psf23/p23", "psf24/p24", "psf25/p25/p50", "psf29/p29/p59", "psf30/p30/p60", "psf23/p23", "psf24/p24", "psf25/p25/p50", "psf29/p29/p59", "psf30/p30/p60", "i50/p25/p50", "i59/p29/p59", "i60/p30/p60", "psf23/p23", "psf24/p24", "psf25/p25/p50", "psf29/p29/p59", "psf30/p30/p60", "i50/p25/p50", "i59/p29/p59", "i60/p30/p60", "psf23/p23", "psf24/p24", "psf25/p25/p50", "psf29/p29/p59", "psf30/p30/p60", "p25/p50", "p29/p59", "p30/p60"];
var quad_sync_HD_formats = ["480i59", "576i50", "480i59", "576i50", "720p25/p50", "720p29/p59", "720p30/p60", "1080i50", "1080i59", "1080i60", "psf23/p23", "psf24/p24", "psf25/p25", "psf29/p29", "psf30/p30", "psf23/p23", "psf24/p24", "psf25/p25", "psf29/p29", "psf30/p30", "i50/p25", "i59/p29", "i60/p30", "psf23/p23", "psf24/p24", "psf25/p25", "psf29/p29", "psf30/p30", "i50/p25", "i59/p29", "i60/p30", "psf23/p23", "psf24/p24", "psf25/p25", "psf29/p29", "psf30/p30", "p25", "p29", "p30"];
var genlock_mode = ["Off", "External", "Internal"];
var video_fail_mode = ["Freeze", "Blue"];
var service_select = ["Manual", "Auto"];

var dvbt_bw = ["6 MHz", "7 MHz", "8 MHz", "5 MHz"];
var dvbt_bw_d1550 = ["6 MHz", "7 MHz", "8 MHz"];
var constel_dvbt = ["QPSK", "16-QAM", "64-QAM"];
var fec_dvbt = ["1/2", "2/3", "3/4", "5/6" ,"7/8"];
var guard_dvbt = ["1/32", "1/16", "1/8", "1/4"];
var bandwidth_nb = ["6 MHz", "7 MHz", "8 MHz", "5 MHz", "2.5 MHz", "1.25 MHz", "0.625 MHz"];
var bandwidth_nb_d1550 = ["6 MHz", "7 MHz", "8 MHz", "2.5 MHz", "1.25 MHz", "0.625 MHz"];
var constel_nb = ["QPSK", "16-QAM", "BPSK", "8-PSK"];
var fec_nb = ["2/3", "1/3"];
var guard_nb = ["1/16", "1/8"];
var interleaver_nb = ["0ms", "100ms", "200ms", "400ms", "800ms"];
var spec_pol = ["Normal", "Inverted"];
var power = ["10 mW", "50 mW","100 mW"];
var power_dbm = [10.00, 17.00, 20.00];
var dvbt_4k_offset = ["None", "+4kHz","-4kHz"];
var rf_mode = ["NB/UMVL", "DVB-T", "ISDB-T"];
var rf_mode_d1550 = ["NB/UMVL", "DVB-T"];
var cam_types = ["Hitachi", "Sony","Panasonic RC10","Grass Valley LDK","Ikegami","Grass Valley LDX","Grass Val Bi-Dir","Nac Hi-Motion","Videosys","Tally Only","Pana Studio","Panasonic EC4"];
var sfp_rate = ["HD", "3G", "6G", "12G"];

var filt_5600k = ["Enabled (Filters)", "Disabled (ECC)"];
var tally_modes = ["Standard", "Force Record"];
var shutter_modes = ["Relative (HDW)", "Absolute"];
var hitachi_nds = ["5 Position (Cap)", "4 Position"];
var sony_filters = ["Disabled", "Enabled (ECC)"];
var sony_colours = ["Absolute", "Relative (AWB)"];
var dreamchip_maps = ["Linear (Full Range)", "Quadratic"];
var mzone_modes = ["Primary Frequency", "Multizone List"];
var connect_modes = ["Serial", "IP"];

var isdbt_bw = ["6 MHz", "7 MHz"];
var constel_isdbt = ["DQPSK", "QPSK", "16-QAM", "64-QAM"];
var fec_isdbt = ["1/2", "2/3", "3/4", "5/6" ,"7/8"];
var guard_isdbt = ["1/32", "1/16", "1/8", "1/4"];
var interleaver_isdbt = ["0ms", "110ms", "220ms", "440ms"];

var preset_sel = ["Unit", "Config"]
var preset_val = ["Unit", "Encoder"]

var srt_cnt = 0;

function getCPBDelayStep(EncodeMode, LowDelayMode)
{
	if ((EncodeMode == 0 || EncodeMode == 1) && LowDelayMode == 0)
		return 18000;
	else if (EncodeMode == 0 && LowDelayMode == 1)
		return 9000;
	else if (EncodeMode == 1 && LowDelayMode == 1)
		return 4500;
	else
		return 1800;
}

function ethDHCPChange(port)
{
	var dhcp = getValue("DHCPModeSelect"+port);
	if(dhcp != 0)
	{
		document.getElementById("IPAddr"+port).style.display = "none"
		document.getElementById("IPGateway"+port).style.display = "none"
		document.getElementById("IPMask"+port).style.display = "none"
		document.getElementById("eth"+port+"_ipaddr").style.display = "inline-block"
		document.getElementById("eth"+port+"_gwaddr").style.display = "inline-block"
		document.getElementById("eth"+port+"_mask").style.display = "inline-block"
	}
	else
	{
		document.getElementById("IPAddr"+port).style.display = "inline-block"
		document.getElementById("IPGateway"+port).style.display = "inline-block"
		document.getElementById("IPMask"+port).style.display = "inline-block"
		document.getElementById("eth"+port+"_ipaddr").style.display = "none"
		document.getElementById("eth"+port+"_gwaddr").style.display = "none"
		document.getElementById("eth"+port+"_mask").style.display = "none"
	}
}

function dtmDHCPChange()
{
	var dhcp = getValue("DtmDHCPModeSelect");
	if(dhcp != 0)
	{
		document.getElementById("DtmIPAddress").style.display = "none"
		document.getElementById("DtmIPGateway").style.display = "none"
		document.getElementById("DtmIPMask").style.display = "none"
		document.getElementById("dtm_ipaddr").style.display = "inline-block"
		document.getElementById("dtm_gwaddr").style.display = "inline-block"
		document.getElementById("dtm_mask").style.display = "inline-block"
	}
	else
	{
		document.getElementById("DtmIPAddress").style.display = "inline-block"
		document.getElementById("DtmIPGateway").style.display = "inline-block"
		document.getElementById("DtmIPMask").style.display = "inline-block"
		document.getElementById("dtm_ipaddr").style.display = "none"
		document.getElementById("dtm_gwaddr").style.display = "none"
		document.getElementById("dtm_mask").style.display = "none"
	}
}

function sdrDHCPChange() {
  var dhcp = getValue("SDRDHCPModeSelect");
  if (dhcp != 0) {
    document.getElementById("SDR_NetIPAddr").style.display = "none"
    document.getElementById("SDR_NetGWAddr").style.display = "none"
    document.getElementById("SDR_NetMaskAddr").style.display = "none"
    document.getElementById("sdr_active_ipaddr").style.display = "inline-block"
    document.getElementById("sdr_active_gwaddr").style.display = "none"
    document.getElementById("sdr_active_mask").style.display = "inline-block"
    document.getElementById("sdrGW").style.display = "none"
  }
  else {
    document.getElementById("SDR_NetIPAddr").style.display = "inline-block"
    document.getElementById("SDR_NetGWAddr").style.display = "inline-block"
    document.getElementById("SDR_NetMaskAddr").style.display = "inline-block"
    document.getElementById("sdr_active_ipaddr").style.display = "none"
    document.getElementById("sdr_active_gwaddr").style.display = "none"
    document.getElementById("sdr_active_mask").style.display = "none"
    document.getElementById("sdrGW").style.display = "inline-block"
  }
}

function videoSourceB160()
{
	var vid_src_sel = ["Default", "Pattern + Tones", "Pattern"];

	removeOptions("VideoSourceSelect");
	selectOptions("VideoSourceSelect",vid_src_sel);
}

function audioSourceB160()
{
	var aud_src0_sel = ["Analogue 1", "SDI 1 (G1P1)", "Test Tone"];
	var aud_src1_sel = ["Analogue 1", "SDI 1 (G1P2)", "Test Tone"];
	var aud_src2_sel = ["Analogue 1", "SDI 1 (G2P1)", "Test Tone"];
	var aud_src3_sel = ["Analogue 1", "SDI 1 (G2P2)", "Test Tone"];
	var aud_src4_sel = ["Analogue 1", "SDI 1 (G3P1)", "Test Tone"];
	var aud_src5_sel = ["Analogue 1", "SDI 1 (G3P2)", "Test Tone"];
	var aud_src6_sel = ["Analogue 1", "SDI 1 (G4P1)", "Test Tone"];
	var aud_src7_sel = ["Analogue 1", "SDI 1 (G4P2)", "Test Tone"];

	removeOptions("AudioSource0Select");
	selectOptions("AudioSource0Select",aud_src0_sel);

	removeOptions("AudioSource1Select");
	selectOptions("AudioSource1Select",aud_src1_sel);

	removeOptions("AudioSource2Select");
	selectOptions("AudioSource2Select",aud_src2_sel);

	removeOptions("AudioSource3Select");
	selectOptions("AudioSource3Select",aud_src3_sel);

	removeOptions("AudioSource4Select");
	selectOptions("AudioSource4Select",aud_src4_sel);

	removeOptions("AudioSource5Select");
	selectOptions("AudioSource5Select",aud_src5_sel);

	removeOptions("AudioSource6Select");
	selectOptions("AudioSource6Select",aud_src6_sel);

	removeOptions("AudioSource7Select");
	selectOptions("AudioSource7Select",aud_src7_sel);
}

function ipInterfaceChange()
{
	var port1 = getNumber("IPName0");
	var port2 = getNumber("IPName1");
	var port3 = (DTM3200Present == 0)?"":"IP Module";
	if(port1 != "" || port2 != "")
	{
		var tmpIPStreamInterface = stream_interface_get[getValue("IPStreamInterface")];
		stream_interface_select = [];
		stream_interface_get = [];
		if(port1 != "")
		{
			stream_interface_set[0] = stream_interface_get.length;
			stream_interface_get.push(0);
			stream_interface_select.push(port1);
		}
		if(port2 != "")
		{
			stream_interface_set[1] = stream_interface_get.length;
			stream_interface_get.push(1);
			stream_interface_select.push(port2);
		}
		if(port3 != "")
		{
			stream_interface_set[2] = stream_interface_get.length;
			stream_interface_get.push(2);
			stream_interface_select.push(port3);
		}
		removeOptions("IPStreamInterface");
		selectOptions("IPStreamInterface",stream_interface_select);
		setSelectValue("IPStreamInterface",stream_interface_set[tmpIPStreamInterface]);
	}

	if((DTM3200Present == 0) && (license_iptx == 0))
    {
		document.getElementById("ip_tx_sts_row").style.display = "none";
		document.getElementById("ipstream").style.display = "none";
    }
    else
    {
		document.getElementById("ip_tx_sts_row").style.display = "inline-block";
		document.getElementById("ipstream").style.display = "inline-block";
    }

    if(DTM3200Present == 0)
	{
		document.getElementById("EthernetStream").style.display = "none";
		document.getElementById("IP_Hardware").style.display = "none";
	}
	else
	{
		document.getElementById("EthernetStream").style.display = "inline-block";
		document.getElementById("IP_Hardware").style.display = "inline-block";
	}

	var IPStreamEnable = getValue("IPStreamEnable");
	var IPStreamInterface = stream_interface_get[getValue("IPStreamInterface")];
	var IPStreamProtocol = getValue("IPStreamProtocol");
	var SRTMode = getValue("SRTMode");

    if(IPStreamEnable == 1) // transmit
    {
        document.getElementById("IPStreamProtocolRow").style.display = "inline-block";
		document.getElementById("IPStreamAddressRow").style.display = (IPStreamProtocol != 2 || SRTMode != 1)?"inline-block":"none"; // not SRT or not listener
        document.getElementById("IPStreamPortRow").style.display = "inline-block";
        document.getElementById("IPStreamTTLRow").style.display = "inline-block";
        document.getElementById("IPStreamNumTPRow").style.display = "inline-block";

        if(IPStreamInterface != 2) // not DTM-3200
        {
            document.getElementById("DTM_Diagnostics").style.display = "none";
            document.getElementById("B110_Diagnostics").style.display = "inline-block";

            IPStreamProtocol_Select = ["UDP", "RTP", "SRT"];
            var tmpIPStreamProtocol = getValue("IPStreamProtocol");
            removeOptions("IPStreamProtocol");
            selectOptions("IPStreamProtocol",IPStreamProtocol_Select);
            setSelectValue("IPStreamProtocol",tmpIPStreamProtocol);
        }
        else
        {
            document.getElementById("DTM_Diagnostics").style.display = "inline-block";
            document.getElementById("B110_Diagnostics").style.display = "none";

            IPStreamProtocol_Select = ["UDP", "RTP"];
            var tmpIPStreamProtocol = getValue("IPStreamProtocol");
            if(tmpIPStreamProtocol > 1) tmpIPStreamProtocol = 0;
            removeOptions("IPStreamProtocol");
            selectOptions("IPStreamProtocol",IPStreamProtocol_Select);
            setSelectValue("IPStreamProtocol",tmpIPStreamProtocol);
        }
    }
    else // disabled
    {
        document.getElementById("IPStreamProtocolRow").style.display = "none";
        document.getElementById("IPStreamAddressRow").style.display = "none";
        document.getElementById("IPStreamPortRow").style.display = "none";
        document.getElementById("IPStreamTTLRow").style.display = "none";
        document.getElementById("IPStreamNumTPRow").style.display = "none";

        document.getElementById("DTM_Diagnostics").style.display = "none";
        document.getElementById("B110_Diagnostics").style.display = "none";
    }

	if(IPStreamEnable == 0 || IPStreamInterface != 2 || IPStreamProtocol != 1) // disabled or not DTM-3200 or not RTP
	{
		document.getElementById("IPFECEnableRow").style.display = "none";
		document.getElementById("IPFECColsRow").style.display = "none";
		document.getElementById("IPFECRowsRow").style.display = "none";
	}
	else
	{
		document.getElementById("IPFECEnableRow").style.display = "inline-block";
        document.getElementById("IPFECColsRow").style.display = "inline-block";
        document.getElementById("IPFECRowsRow").style.display = "inline-block";
	}

	if(IPStreamEnable == 0 || IPStreamProtocol != 2) // disabled or not SRT
	{
		document.getElementById("SRTModeRow").style.display = "none";
		document.getElementById("SRTDelayRow").style.display = "none";
		document.getElementById("SRT_Diagnostics").style.display = "none";
	}
	else
	{
		document.getElementById("SRTModeRow").style.display = "inline-block";
		document.getElementById("SRTDelayRow").style.display = "inline-block";
        document.getElementById("SRT_Diagnostics").style.display = "inline-block";
	}
}

function videoQuadSyncChange()
{
	if(getValue("QuadSyncSelect") == 0)
		document.getElementById("QuadSyncAlignment").style.display = "none";
	else
		document.getElementById("QuadSyncAlignment").style.display = "inline-block";
}

function audioModeChange(stream)
{
	var aud_enc_map = [0,1,5,6,2,3,4]
	var aud_enc_map4 = [0,1,5,6,3,4]
	var AudioEncoder = getValue("AudioEncoder"+stream+"Select");
	if(stream < 4) AudioEncoder = aud_enc_map[AudioEncoder];
	else           AudioEncoder = aud_enc_map4[AudioEncoder];

	var AudioBitrate = getValue("AudioBitrate"+stream+"Select");

	removeOptions("AudioBitrate"+stream+"Select");
	switch (AudioEncoder) {
		case 1:  selectOptions("AudioBitrate"+stream+"Select",AudioBitrateLPCM16_Select);
				 document.getElementById("AudioBitrate"+stream+"Select").disabled = true; break;
		case 5:  selectOptions("AudioBitrate"+stream+"Select",AudioBitrateLPCM20_Select);
				 document.getElementById("AudioBitrate"+stream+"Select").disabled = true; break;
		case 6:  selectOptions("AudioBitrate"+stream+"Select",AudioBitrateLPCM24_Select);
				 document.getElementById("AudioBitrate"+stream+"Select").disabled = true; break;;
		case 2:  selectOptions("AudioBitrate"+stream+"Select",AudioBitrateAAC_Select);
				 document.getElementById("AudioBitrate"+stream+"Select").disabled = false; break;
		case 4:  selectOptions("AudioBitrate"+stream+"Select",AudioBitrateL2_Select);
				 document.getElementById("AudioBitrate"+stream+"Select").disabled = false; break;
		case 3:  selectOptions("AudioBitrate"+stream+"Select",AudioBitrateL1_Select);
				 document.getElementById("AudioBitrate"+stream+"Select").disabled = false; break;
		default: selectOptions("AudioBitrate"+stream+"Select",AudioBitrateNone_Select);
				 document.getElementById("AudioBitrate"+stream+"Select").disabled = true; break;
	}

    setSelectValue("AudioBitrate"+stream+"Select",AudioBitrate);
}

function dataModeChange()
{
    if(getValue("DataModeSelect") == 2)
	{
		document.getElementById("DataBaudRow").style.display = "none";
	}
	else
	{
		document.getElementById("DataBaudRow").style.display = "inline-block";
	}
}

function videoHelper(buttonPress)
{
	var videoFormat = parseInt(getValue("VideoFormatSelect"));
	var currentRate = 0;
	switch (videoFormat) {
		case 10: case 15: case 23: case 31:
			currentRate = 23; break;
		case 11: case 16: case 24: case 32:
			currentRate = 24; break;
		case 12: case 17: case 25: case 33:
			currentRate = 25; break;
		case 13: case 18: case 26: case 34:
			currentRate = 29; break;
		case 14: case 19: case 27: case 35:
			currentRate = 30; break;
		case 7: case 20: case 28: case 36: case 4: case 1: case 3:
			currentRate = 50; break;
		case 8: case 21: case 29: case 37: case 5: case 0: case 2:
			currentRate = 59; break;
		case 9: case 22: case 30: case 38: case 6:
			currentRate = 60; break;
	}

	if(buttonPress == "720p")
	{
		switch (currentRate) {
			case 23: case 24:	setSelectValue("VideoFormatSelect",4);break;
			case 25: case 50:	setSelectValue("VideoFormatSelect",4);break;
			case 29: case 59:	setSelectValue("VideoFormatSelect",5);break;
			case 30: case 60:	setSelectValue("VideoFormatSelect",6);break;
		}
		setSelectValue("QuadSyncSelect",0);
	}
	else if(buttonPress == "1080i")
	{
		switch (currentRate) {
			case 23: case 24:	setSelectValue("VideoFormatSelect",7);break;
			case 25: case 50:	setSelectValue("VideoFormatSelect",7);break;
			case 29: case 59:	setSelectValue("VideoFormatSelect",8);break;
			case 30: case 60:	setSelectValue("VideoFormatSelect",9);break;
		}
		setSelectValue("QuadSyncSelect",0);
	}
	else if(buttonPress == "1080psf")
	{
		switch (currentRate) {
			case 23:			setSelectValue("VideoFormatSelect",15);break;
			case 24:			setSelectValue("VideoFormatSelect",16);break;
			case 25: case 50:	setSelectValue("VideoFormatSelect",17);break;
			case 29: case 59:	setSelectValue("VideoFormatSelect",18);break;
			case 30: case 60:	setSelectValue("VideoFormatSelect",19);break;
		}
		setSelectValue("QuadSyncSelect",0);
	}
	else if(buttonPress == "1080p" || buttonPress == "1xHD")
	{
		switch (currentRate) {
			case 23:	setSelectValue("VideoFormatSelect",10);break;
			case 24:	setSelectValue("VideoFormatSelect",11);break;
			case 25:	setSelectValue("VideoFormatSelect",12);break;
			case 29:	setSelectValue("VideoFormatSelect",13);break;
			case 30:	setSelectValue("VideoFormatSelect",14);break;
			case 50:	setSelectValue("VideoFormatSelect",20);break;
			case 59:	setSelectValue("VideoFormatSelect",21);break;
			case 60:	setSelectValue("VideoFormatSelect",22);break;
		}
		setSelectValue("QuadSyncSelect",(buttonPress == "1xHD")?1:0);
	}
	else if(buttonPress == "2SI" || buttonPress == "SQD" || buttonPress == "4xHD")
	{
		switch (currentRate) {
			case 23:	setSelectValue("VideoFormatSelect",23);break;
			case 24:	setSelectValue("VideoFormatSelect",24);break;
			case 25:	setSelectValue("VideoFormatSelect",25);break;
			case 29:	setSelectValue("VideoFormatSelect",26);break;
			case 30:	setSelectValue("VideoFormatSelect",27);break;
			case 50:	setSelectValue("VideoFormatSelect",28);break;
			case 59:	setSelectValue("VideoFormatSelect",29);break;
			case 60:	setSelectValue("VideoFormatSelect",30);break;
		}
		setSelectValue("QuadSyncSelect",(buttonPress == "4xHD")?1:0);
		setSelectValue("SampleFormatSelect",(buttonPress == "2SI")?0:1);
	}
	else if(buttonPress == "4K2SI" || buttonPress == "4KSQD" || buttonPress == "4x2K")
	{
		switch (currentRate) {
			case 23:	setSelectValue("VideoFormatSelect",31);break;
			case 24:	setSelectValue("VideoFormatSelect",32);break;
			case 25:	setSelectValue("VideoFormatSelect",33);break;
			case 29:	setSelectValue("VideoFormatSelect",34);break;
			case 30:	setSelectValue("VideoFormatSelect",35);break;
			case 50:	setSelectValue("VideoFormatSelect",36);break;
			case 59:	setSelectValue("VideoFormatSelect",37);break;
			case 60:	setSelectValue("VideoFormatSelect",38);break;
		}
		setSelectValue("QuadSyncSelect",(buttonPress == "4x2K")?1:0);
		setSelectValue("SampleFormatSelect",(buttonPress == "4K2SI")?0:1);
	}
	else
	{
		var newRateIndex = parseInt(buttonPress);

		if(videoFormat <= 1)
		{
			if(newRateIndex >= 5) newRateIndex -= 3;
			setSelectValue("VideoFormatSelect",(newRateIndex >= 3)?0:1);
		}
		else if(videoFormat <= 3)
		{
			if(newRateIndex >= 5) newRateIndex -= 3;
			setSelectValue("VideoFormatSelect",(newRateIndex >= 3)?2:3);
		}
		else if(videoFormat <= 6)
		{
			if(newRateIndex < 2) newRateIndex = 2;
			if(newRateIndex >= 5) newRateIndex -= 3;
			setSelectValue("VideoFormatSelect",4+(newRateIndex-2))
		}
		else if(videoFormat <= 9)
		{
			if(newRateIndex < 2) newRateIndex = 2;
			if(newRateIndex >= 5) newRateIndex -= 3;
			setSelectValue("VideoFormatSelect",7+(newRateIndex-2))
		}
		else if(videoFormat >= 15 && videoFormat <= 19)
		{
			if(newRateIndex >= 5) newRateIndex -= 3;
			setSelectValue("VideoFormatSelect",15+newRateIndex)
		}
		else if(videoFormat <= 22)
		{
			if(newRateIndex >= 5) newRateIndex += 5;
			setSelectValue("VideoFormatSelect",10+newRateIndex)
		}
		else if(videoFormat <= 30)
		{
			setSelectValue("VideoFormatSelect",23+newRateIndex)
		}
		else
		{
			setSelectValue("VideoFormatSelect",31+newRateIndex)
		}
	}

	videoQuadSyncChange();
}

function audioHelper(buttonPress)
{
	var ultraLowLatency = (getValue("LowDelayModeSelect")=="2")?true:false;
	var numChannels = 0;

	if(buttonPress == "4x0" || buttonPress == "4x2" || buttonPress == "4x4")
	{
		if(BoardType == "B160" || BoardType == "B300")
		{
			for(var i = 0; i < 8; i++)
				setSelectValue("AudioSource"+i+"Select",1);
		}
		else
		{
			setSelectValue("AudioSource0Select",2);

			for(var i = 1; i < 8; i++)
				setSelectValue("AudioSource"+i+"Select",3);
		}

		var numChannels = 0;
		switch (buttonPress) {
			case "4x0": numChannels = 0; break;
			case "4x2": numChannels = 4; break;
			case "4x4": numChannels = 8; break;
		}
	}
	else
	{
		if(BoardType == "B160" || BoardType == "B300")
		{
			for(var i = 0; i < 8; i++)
				setSelectValue("AudioSource"+i+"Select",1);
		}
		else
		{
			for(var i = 0; i < 8; i++)
				setSelectValue("AudioSource"+i+"Select",2);
		}

		switch (buttonPress) {
			case "1x0": numChannels = 0; break;
			case "1x2": numChannels = 1; break;
			case "1x4": numChannels = 2; break;
			case "1x6": numChannels = 3; break;
			case "1x8": numChannels = 4; break;
			case "1x10": numChannels = 5; break;
			case "1x12": numChannels = 6; break;
			case "1x14": numChannels = 7; break;
			case "1x16": numChannels = 8; break;
		}
	}

	for(var i = 0; i < 4 && i < numChannels; i++)
		setSelectValue("AudioEncoder"+i+"Select",ultraLowLatency?5:6);
	for(var i = numChannels; i < 4; i++)
		setSelectValue("AudioEncoder"+i+"Select",0);

	for(var i = 4; i < 8 && i < numChannels; i++)
		setSelectValue("AudioEncoder"+i+"Select",ultraLowLatency?4:5);
	for(var i = numChannels; i < 8; i++)
		setSelectValue("AudioEncoder"+i+"Select",0);

	for(var i = 0; i < 8; i++)
		audioModeChange(i);
}

function serviceHelper(buttonPress)
{
	var prog_num = getNumber("ProgramNumberVal");
    if (1 > prog_num || prog_num > 65535) prog_num = 1;

    var prog_div = Math.floor(parseInt(buttonPress) / 32);
    var pid = 32 * (((prog_num - 1) % prog_div) + 1)
	
	setNumber("VideoPidVal", pid++);
	setNumber("AudioPid0Val", pid++);
	setNumber("AudioPid1Val", pid++);
	setNumber("AudioPid2Val", pid++);
	setNumber("AudioPid3Val", pid++);
	setNumber("AudioPid4Val", pid++);
	setNumber("AudioPid5Val", pid++);
	setNumber("AudioPid6Val", pid++);
	setNumber("AudioPid7Val", pid++);
	setNumber("AncillaryPidVal", pid++);
	setNumber("DataPidVal", pid++);
	setNumber("MetadataPidVal", pid++);
	setNumber("PCRPidVal", pid++);
	setNumber("PMTPidVal", pid++);
}

function videoDelayModeChange()
{
	var encoder = getValue("EncodeModeSelect");
	var latency = getValue("LowDelayModeSelect");

	if((encoder == 0 || encoder == 1) && latency == 0)
	{
		document.getElementById('CPBDelayRow').style.display = "inline-block";
		document.getElementById('CPBDelayMin').innerHTML = "200";
		document.getElementById('CPBDelayMax').innerHTML = "1000";
	}
	else if(encoder == 0 && latency == 1)
	{
		document.getElementById('CPBDelayRow').style.display = "inline-block";
		document.getElementById('CPBDelayMin').innerHTML = "100";
		document.getElementById('CPBDelayMax').innerHTML = "500";
	}
	else if(encoder == 1 && latency == 1)
	{
		document.getElementById('CPBDelayRow').style.display = "inline-block";
		document.getElementById('CPBDelayMin').innerHTML = "50";
		document.getElementById('CPBDelayMax').innerHTML = "250";
	}
	else if(encoder == 0 && latency == 2)
	{
		document.getElementById('CPBDelayRow').style.display = "none";
		document.getElementById('CPBDelayMin').innerHTML = "Default";
		document.getElementById('CPBDelayMax').innerHTML = "9000";
	}
	else
		document.getElementById('CPBDelayRow').style.display = "none";
}

function ancillaryModeChange()
{
	var mode = getValue("AncillaryModeSelect");
	document.getElementById("AncillaryBitrateVal").disabled = (mode == 0)?true:false;
}

function videoBitrateModeChange(VideoBitrate)
{
	var mode = getValue("VideoBitrateSelect");

    if(TxPresent == TX_PRESENT_NONE)
		document.getElementById("VideoBitrateVal").disabled = (mode == 0)?true:false;

	videoBitrateAutoUpdate(VideoBitrate);
}

function videoBitrateAutoUpdate(VideoBitrate)
{
	var mode = getValue("VideoBitrateSelect");

    if(TxPresent > TX_PRESENT_NONE)
    {
		vid_rate_display = document.getElementById('VideoBitrateVal').value = document.getElementById('vid_sts_rate').innerHTML.replace(/[^\d-]/g, '');
    }
    else if(mode == 0)
	{
		vid_rate_display = document.getElementById('VideoBitrateVal').value = document.getElementById('vid_sts_rate').innerHTML.replace(/[^\d-]/g, '');
	}
	else if(VideoBitrate >= 0)
	{
		vid_rate_display = setNumber("VideoBitrateVal",VideoBitrate);
	}
}

function showEngineering()
{
	if(document.getElementById('Unit').style.display == "inline-block")
		document.getElementById('EngineeringOptions').style.display = "inline-block"
}

function startupEnc()
{
  openTabh(event, 'Status');
  selectOptions("EncodeModeSelect",EncodeMode_Select);
  selectOptions("VideoFormatSelect",VideoFormat_Select);
  selectOptions("VideoSourceSelect",VideoSource_Select);
  selectOptions("VideoBitrateSelect",VideoBitrate_Select);
  selectOptions("LowDelayModeSelect",LowDelayMode_Select);
  selectOptions("SampleFormatSelect",SampleFormat_Select);
  selectOptions("BitDepthSelect",BitDepth_Select);
  selectOptions("ChromaFormatSelect",ChromaFormat_Select);
  selectOptions("HDRWCGModeSelect",HDRWCGMode_Select);
  selectOptions("QuadSyncSelect",QuadSync_Select);
  selectOptions("AudioP48EnableL0Select",Toggle_Select);
  selectOptions("AudioP48EnableR0Select",Toggle_Select);
  selectOptions("AudioP48EnableL1Select",Toggle_Select);
  selectOptions("AudioP48EnableR1Select",Toggle_Select);
  selectOptions("AudioRefLevel0Select",AudioRefLev_Select);
  selectOptions("AudioRefLevel1Select",AudioRefLev_Select);
  selectOptions("AudioSource0Select",AudioSource0_Select);
  selectOptions("AudioEncoder0Select",AudioEncoder0_Select);
  selectOptions("AudioBitrate0Select",AudioBitrateNone_Select);
  selectOptions("AudioSource1Select",AudioSource1_Select);
  selectOptions("AudioEncoder1Select",AudioEncoder0_Select);
  selectOptions("AudioBitrate1Select",AudioBitrateNone_Select);
  selectOptions("AudioSource2Select",AudioSource2_Select);
  selectOptions("AudioEncoder2Select",AudioEncoder0_Select);
  selectOptions("AudioBitrate2Select",AudioBitrateNone_Select);
  selectOptions("AudioSource3Select",AudioSource3_Select);
  selectOptions("AudioEncoder3Select",AudioEncoder0_Select);
  selectOptions("AudioBitrate3Select",AudioBitrateNone_Select);
  selectOptions("AudioSource4Select",AudioSource4_Select);
  selectOptions("AudioEncoder4Select",AudioEncoder4_Select);
  selectOptions("AudioBitrate4Select",AudioBitrateNone_Select);
  selectOptions("AudioSource5Select",AudioSource5_Select);
  selectOptions("AudioEncoder5Select",AudioEncoder4_Select);
  selectOptions("AudioBitrate5Select",AudioBitrateNone_Select);
  selectOptions("AudioSource6Select",AudioSource6_Select);
  selectOptions("AudioEncoder6Select",AudioEncoder4_Select);
  selectOptions("AudioBitrate6Select",AudioBitrateNone_Select);
  selectOptions("AudioSource7Select",AudioSource7_Select);
  selectOptions("AudioEncoder7Select",AudioEncoder4_Select);
  selectOptions("AudioBitrate7Select",AudioBitrateNone_Select);
  selectOptions("RemuxModeSelect",RemuxMode_Select);
  selectOptions("DESModeSelect",Toggle_Select);
  selectOptions("BISSModeSelect",Toggle_Select);
  selectOptions("AncillaryModeSelect",AncillaryMode_Select);
  selectOptions("DataModeSelect",DataMode_Select);
  selectOptions("DataBaudSelect",DataBaud_Select);
  selectOptions("RecordEnable",RecordEnable_Select);
  selectOptions("IPStreamEnable",stream_enable_select);
  selectOptions("IPStreamInterface",stream_interface_select);
  selectOptions("IPStreamProtocol",IPStreamProtocol_Select);
  selectOptions("SRTMode",SRTMode_Select);
  selectOptions("IPStreamNumTP",IPStreamNumTP_Select);
  selectOptions("IPFECEnable",Toggle_Select);
  selectOptions("DHCPModeSelect0",Toggle_Select);
  selectOptions("DHCPModeSelect1",Toggle_Select);
  selectOptions("DtmDHCPModeSelect",Toggle_Select);
  selectOptions("IPBridgeSelect",Toggle_Select);
  selectOptions("FanModeSelect",FanMode_Select);
  selectOptions("FanSpeedIdleSelect",FanSpeeds_Select);
  selectOptions("FanSpeedRecSelect",FanSpeeds_Select);
  selectOptions("UnitModeSelect",UnitMode_Select);
  selectOptions("TxPresentSelect",TxPresent_Select);
  selectOptions("B120PresentSelect",NoYes_Select);
  selectOptions("DTM3200PresentSelect",NoYes_Select);
  selectOptions("B180PresentSelect",CamCtrlPresent_Select);
  selectOptions("RFDCBiasPresentSelect",NoYes_Select);
  selectOptions("OLEDTypeSelect",OLEDType_Select);
  selectOptions("RFBandwidthSelect",RFBandwidth_Select);
  selectOptions("ModemBandwidthSelect",ModemBandwidth_Select);
  getStatus(false);
  getUnit();
  getEncode();
  selectOptions("Mod_outputSelect",Toggle_Select);
  selectOptions("Mod_out_pwrSelect",power);
  selectOptions("Mod_schemeSelect",rf_mode);
  selectOptions("Dvbt_bwSelect",dvbt_bw);
  selectOptions("Dvbt_constSelect",constel_dvbt);
  selectOptions("Dvbt_fecSelect",fec_dvbt);
  selectOptions("Dvbt_giSelect",guard_dvbt);
  selectOptions("Dvbt_dual_pedSelect",Toggle_Select);
  selectOptions("Dvbt_polSelect",spec_pol);
  selectOptions("Dvbt_4k_offsetSelect",dvbt_4k_offset);
  selectOptions("Umvl_bwSelect",bandwidth_nb);
  selectOptions("Umvl_constSelect",constel_nb);
  selectOptions("Umvl_fecSelect",fec_nb);
  selectOptions("Umvl_giSelect",guard_nb);
  selectOptions("Umvl_dual_pedSelect",Toggle_Select);
  selectOptions("Umvl_polSelect",spec_pol);
  selectOptions("Umvl_interleaverSelect",interleaver_nb);
  selectOptions("CCtrl_TypeSelect",cam_types);
  selectOptions("Isdbt_bwSelect",isdbt_bw);
  selectOptions("Isdbt_constSelect",constel_isdbt);
  selectOptions("Isdbt_fecSelect",fec_isdbt);
  selectOptions("Isdbt_giSelect",guard_isdbt);
  selectOptions("Isdbt_interleaverSelect",interleaver_isdbt);
  selectOptions("Isdbt_polSelect",spec_pol);
  selectOptions("CCtrl_5600KSelect", filt_5600k);
  selectOptions("CCtrl_TallyModeSelect", tally_modes);
  selectOptions("CCtrl_ShutterModeSelect", shutter_modes);
  selectOptions("CCtrl_HitachiNDSelect", hitachi_nds);
  selectOptions("CCtrl_SonyFiltersSelect", sony_filters);
  selectOptions("CCtrl_SonyColoursSelect", sony_colours);
  selectOptions("CCtrl_DreamchipMapSelect", dreamchip_maps);
  selectOptions("CCtrl_MZModeSelect", mzone_modes);
  selectOptions("CCtrl_ModeSelect", connect_modes);
  getStatus();
  getPreset();

  if(license_uhd == 0)
  {
  	removeOptions("VideoFormatSelect");
  	selectOptions("VideoFormatSelect",VideoFormat_Select_HD);
  }

  if(TxPresent > TX_PRESENT_NONE)
  {
    removeOptions("Mod_schemeSelect");
    removeOptions("Umvl_bwSelect");
    removeOptions("Dvbt_bwSelect");
    if (TxActive == TX_PRESENT_D1837) {
      selectOptions("Mod_schemeSelect",rf_mode_d1550);
      selectOptions("Umvl_bwSelect",bandwidth_nb);
      selectOptions("Dvbt_bwSelect",dvbt_bw);
    } else if (TxActive == TX_PRESENT_D1550) {
      selectOptions("Mod_schemeSelect",rf_mode_d1550);
      selectOptions("Umvl_bwSelect",bandwidth_nb_d1550);
      selectOptions("Dvbt_bwSelect",dvbt_bw_d1550);
    } else if(TxActive == TX_PRESENT_B170 || TxActive == TX_PRESENT_B160_B170) {
      selectOptions("Mod_schemeSelect",rf_mode);
      selectOptions("Umvl_bwSelect",bandwidth_nb);
      selectOptions("Dvbt_bwSelect",dvbt_bw);
    }
    if (TxActive == TX_PRESENT_D1837)
    {
      document.getElementById('TxNetwork').style.display = "none"
      document.getElementById('Mod_out_pwr').style.display = "none"
    }
    else 
      document.getElementById('TxNetwork').style.display = "none"

    getTx();

    preset_sel = ["Unit", "Config", "Tx"]
    preset_val = ["Unit", "Encoder", "Tx"]
  }

  if ((CustID == "0000afb4") || (CustID == "00007c0c") || (CustID == "0000ba74"))
    getSDR();

  selectOptions("SDRDHCPModeSelect", Toggle_Select);
  selectOptions("SDR_rf_outputSelect", Toggle_Select);

  selectOptionsValue("filePre",preset_sel,preset_val);
  document.getElementById("status").click();
  var down = document.getElementById('PresetSelect')
  down.addEventListener("change",downloadPreset);
}

function removeOptions(selectbox) {
    let select = document.getElementById(selectbox)
    let i
    for (i = select.options.length - 1; i >= 0; i--) {
        select.remove(i)
    }
}

function selectOptions(param,variable)
{
  var e = document.getElementById(param);
  for(index in variable) {
    e.options[e.options.length] = new Option(variable[index], index);
  }
}

function selectOptionsValue(param,variable,value)
{
  var e = document.getElementById(param);
  for(index in variable) {
    e.options[e.options.length] = new Option(variable[index], value[index]);
  }
}

function updateLevelBar(e,a,d,b,c,m)
{
  var elem = document.getElementById("LevelBar" + b + c);
  if (e == 0)
  {
    elem.style.backgroundColor = 'white'
    elem.style.width = (0) + '%';
  }
  else if (d != 0)
  {
    elem.style.backgroundColor = '#1e1a37'
    elem.style.width = (100) + '%';
  }
  else if (a >=90)
  {
    elem.style.backgroundColor = 'red'
    elem.style.width = ((a/90)*100) + '%';
  }
  else if ((a >=78) && (a < 90))
  {
    elem.style.backgroundColor = 'orange'
    elem.style.width = ((a/90)*100) + '%';
  }
  else
  {
    elem.style.backgroundColor = 'green'
    elem.style.width = ((a/90)*100) + '%';
  }

  var label = (b+1)+": ";
  if(e == 0)
  {
	 label += "Disabled";
  }
  else if(m == 1 || m == 5 || m == 6)
  {
	  if(d == 0)
		 label += "LPCM";
	  else if(d & (1<<1))
		 label += "AC-3";
	  else if(d & (3<<4))
		 label += "MPEG-1";
	  else if(d & (13<<6))
		 label += "MPEG-2";
	  else if(d & (1<<27))
		 label += "SMPTE KLV";
	  else if(d & (1<<28))
		 label += "Dolby E";
	  else
		 label += "Non-PCM";
  }
  else if(m == 2)
  {
	 label += "AAC-LC";
  }
  else if(m == 3)
  {
	 label += "MPEG-1";
  }
  else if(m == 4)
  {
	 label += "MPEG-1";
  }
  else
  {
	 label += "Unknown";
  }
  document.getElementById("meter_"+(b+1)).innerHTML = label;
}

function refresh()
{
  getEncode()

  if(TxPresent > TX_PRESENT_NONE)
  {
    getTx();
  }

  if(B180Present > 0)
  {
    getCameraCtrl();
  }

  if ((CustID == "0000afb4") || (CustID == "00007c0c") || (CustID == "0000ba74"))
    getSDR();
}

function refresh_unit()
{
  getUnit()
}

function setSelectValue(param,new_select)
{
  var e = document.getElementById(param);
  e.selectedIndex = new_select;
}

function setNumber(param, new_num)
{
  var e = document.getElementById(param);
  e.value = new_num;
}

function getValue(param)
{
  var e = document.getElementById(param);
  var strUser = e.options[e.selectedIndex].value;
  return strUser;
}

function getNumber(param)
{
  var e = document.getElementById(param).value;
  return e;
}

function getText(param)
{
  var e = document.getElementById(param);
  var strUser = e.options[e.selectedIndex].text;
  return strUser;
}

function isHexKey(evt)
{
  var charCode = (evt.which) ? evt.which : event.keyCode
  if ((charCode < 65 || charCode > 70) && (charCode < 48 || charCode > 57) && (charCode < 97 || charCode > 102) && (charCode != 8))
  {
    return false;
  }
  else
  {
    return true;
  }
}

function isOKKey(evt)
{
  var charCode = (evt.which) ? evt.which : event.keyCode
  if ((charCode < 65 || charCode > 90) && (charCode < 48 || charCode > 57) && (charCode != 95) && (charCode < 97 || charCode > 122) && (charCode != 8))
  {
    return false;
  }
  else
  {
    return true;
  }
}

function processIPvalue()
{
	document.getElementById('apply_unit').innerText = "Applying . ."
	document.getElementById('apply_unit').disabled = true
  var check_ip = 1;

  check_ip &= ValidateIPaddress("IPAddr0");
  check_ip &= ValidateIPaddress("IPGateway0");
  check_ip &= ValidateIPaddress("IPMask0");

  check_ip &= ValidateIPaddress("IPAddr1");
  check_ip &= ValidateIPaddress("IPGateway1");
  check_ip &= ValidateIPaddress("IPMask1");

  if(DTM3200Present == 1)
  {
	  check_ip &= ValidateIPaddress("DtmIPAddress");
	  check_ip &= ValidateIPaddress("DtmIPGateway");
	  check_ip &= ValidateIPaddress("DtmIPMask");
  }

  if(check_ip == 1)
  {
    setUnit();
  }
}

function ValidateIPaddress(field)
{
  var ipaddr = document.getElementById(field).value;
  var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  if(ipaddr.match(ipformat))
  {
    return 1;
  }
  else
  {
    alert("Invalid IP address");
    document.getElementById(field).value = '';
    return 0;
  }
}

function addrFieldCheck(event)
{
  var char = event.which || event.keyCode;
  if (char != 8 && char != 46 && (char  < 0x30 || char  > 0x39) && char != 9 && char != 37 && char != 39)
  {
    event.returnValue = false;
    if(event.preventDefault)
    {
      event.preventDefault();
    }
  }
}

function timer_function()
{
  refreshPreview();
  getEncode();
  getUnit();
  getStatus();
  if(TxPresent > TX_PRESENT_NONE)
  {
    getTx();
  }

  if(B180Present > 0)
  {
    getCameraCtrl();
  }

  if ((CustID == "0000afb4") || (CustID == "00007c0c") || (CustID == "0000ba74"))
    getSDR();

  // some manual content requires refreshed data
  if(window.location.search.substr(1) == "manual")
	showUserManual();
}

function timer_status_only()
{
  getStatus();
  videoBitrateModeChange(-1);
}

function openTab(evt, tabName)
{
  var i, tabcontent, tablinks;

  if(tabName == 'Tx')
  {
    if(TxPresent > TX_PRESENT_NONE)
    {
      getTx();
    }
    document.getElementById("apply_tx_config").style.display = "inline-block";
    document.getElementById("apply_config").style.display = "none";
    document.getElementById("apply_cam_ctrl_config").style.display = "none";
    document.getElementById("apply_sdr_config").style.display = "none";
  }
  else if(tabName == 'Camera')
  {
    if(B180Present > 0)
    {
      getCameraCtrl();
      if (B180Present !=3 )
      {
        document.getElementById("Cam_Ctrl_Options").style.display = "none";
        document.getElementById("Cam_Ctrl_Multizone").style.display = "none";
        document.getElementById("Cam_Ctrl_Network").style.display = "none";
        document.getElementById("Cam_Ctrl_CamNetwork").style.display = "none";
        document.getElementById("Cam_Ctrl_Mode").style.display = "none";
      }
      else
      {
        document.getElementById("Cam_Ctrl_Options").style.display = "inline-block";
        document.getElementById("Cam_Ctrl_Multizone").style.display = "inline-block";
        document.getElementById("Cam_Ctrl_Network").style.display = "inline-block";
        document.getElementById("Cam_Ctrl_CamNetwork").style.display = "inline-block";
        document.getElementById("Cam_Ctrl_Mode").style.display = "inline-block";
      }
    }
    document.getElementById("apply_tx_config").style.display = "none";
    document.getElementById("apply_config").style.display = "none";
    document.getElementById("apply_cam_ctrl_config").style.display = "inline-block";
    document.getElementById("apply_sdr_config").style.display = "none";
  }
  else if (tabName == 'Mesh') 
  {
    if ((CustID == "0000afb4") || (CustID == "00007c0c") || (CustID == "0000ba74")) // B2TXR or BTXR or GVTXR
    {
      getSDR();
    }
    document.getElementById("apply_tx_config").style.display = "none";
    document.getElementById("apply_config").style.display = "none";
    document.getElementById("apply_cam_ctrl_config").style.display = "none";
    document.getElementById("apply_sdr_config").style.display = "inline-block";
  }
  else
  {
    getEncode();
    document.getElementById("apply_config").style.display = "inline-block";
    document.getElementById("apply_tx_config").style.display = "none";
    document.getElementById("apply_cam_ctrl_config").style.display = "none";
    document.getElementById("apply_sdr_config").style.display = "none";
  }
  // hide all tabs contents
  tabcontent = document.getElementsByClassName("cfg_tabcontent");
  for (i = 0; i < tabcontent.length; i++)
  {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++)
  {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(tabName).style.display = "inline-block";
  evt.currentTarget.className += " active";
  helpContent();
}

function openTabh(evt, tabName)
{
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontenth");
  for (i = 0; i < tabcontent.length; i++)
  {
    tabcontent[i].style.display = "none";
  }
  clearInterval(timer);

  if (tabName == 'Status') {
    getStatus();
    document.getElementById("cfg_buttons").style.display = "none";
    document.getElementById("apply_config").style.display = "none";
    document.getElementById("apply_unit").style.display = "none";
    document.getElementById("load").style.display = "none";
    document.getElementById("apply_tx_config").style.display = "none";
    document.getElementById("apply_cam_ctrl_config").style.display = "none";
    document.getElementById("apply_sdr_config").style.display = "none";
    document.getElementById("reload_preset").style.display = "none";
    document.getElementById("restore_def").style.display = "none";
    document.getElementById("load_unit").style.display = "none";
    document.getElementById("reboot_unit").style.display = "none";
    document.getElementById("reset_codec").style.display = "none";
    document.getElementById("diag_download").style.display = "none";
    document.getElementById("help_window").style.display = "none";
    timer = setInterval("timer_function();",1000);
  }
  else if (tabName == 'Config')
  {
    getEncode();
    document.getElementById("cfg_buttons").style.display = "inline-block";
    document.getElementById("apply_config").style.display = "inline-block";
    document.getElementById("apply_unit").style.display = "none";
    document.getElementById("load").style.display = "inline-block";
    document.getElementById("apply_tx_config").style.display = "none";
    document.getElementById("apply_cam_ctrl_config").style.display = "none";
    document.getElementById("apply_sdr_config").style.display = "none";
    document.getElementById("load_unit").style.display = "none";
    document.getElementById("reload_preset").style.display = "none";
    document.getElementById("restore_def").style.display = "none";
    document.getElementById("reboot_unit").style.display = "none";
    document.getElementById("reset_codec").style.display = "inline-block";
    document.getElementById("diag_download").style.display = "none";
    document.getElementById("help_window").style.display = document.getElementById("Support").style.display;
    document.getElementById("help_window").style.marginTop = "0px";
    document.getElementById("video").click();
    timer = setInterval("timer_status_only();",1000);
  }
  else if (tabName == 'Unit')
  {
    getUnit();
    document.getElementById("cfg_buttons").style.display = "none";
    document.getElementById("apply_config").style.display = "none";
    document.getElementById("apply_unit").style.display = "inline-block";
    document.getElementById("load").style.display = "none";
    document.getElementById("apply_tx_config").style.display = "none";
    document.getElementById("apply_cam_ctrl_config").style.display = "none";
    document.getElementById("apply_sdr_config").style.display = "none";
    document.getElementById("reload_preset").style.display = "none";
    document.getElementById("restore_def").style.display = "inline-block";
    document.getElementById("load_unit").style.display = "inline-block";
    document.getElementById("reboot_unit").style.display = "inline-block";
    document.getElementById("reset_codec").style.display = "none";
    document.getElementById("diag_download").style.display = "none";
    document.getElementById("help_window").style.display = document.getElementById("Support").style.display;
    document.getElementById("help_window").style.marginTop = "-5px";
    timer = setInterval("timer_status_only();",1000);
  }
  else if (tabName == 'Upgrade')
  {
    document.getElementById("cfg_buttons").style.display = "none";
    document.getElementById("apply_config").style.display = "none";
    document.getElementById("apply_unit").style.display = "none";
    document.getElementById("load").style.display = "none";
    document.getElementById("apply_tx_config").style.display = "none";
    document.getElementById("apply_cam_ctrl_config").style.display = "none";
    document.getElementById("apply_sdr_config").style.display = "none";
    document.getElementById("reload_preset").style.display = "none";
    document.getElementById("restore_def").style.display = "none";
    document.getElementById("load_unit").style.display = "none";
    document.getElementById("reboot_unit").style.display = "none";
    document.getElementById("reset_codec").style.display = "none";
    document.getElementById("diag_download").style.display = "none";
    document.getElementById("help_window").style.display = document.getElementById("Support").style.display;
    document.getElementById("help_window").style.marginTop = "-5px";
    timer = setInterval("timer_status_only();",1000);
  }
  else if (tabName == 'Preset')
  {
    document.getElementById("cfg_buttons").style.display = "none";
    document.getElementById("apply_config").style.display = "none";
    document.getElementById("apply_unit").style.display = "none";
    document.getElementById("load").style.display = "none";
    document.getElementById("apply_tx_config").style.display = "none";
    document.getElementById("apply_cam_ctrl_config").style.display = "none";
    document.getElementById("apply_sdr_config").style.display = "none";
    document.getElementById("reload_preset").style.display = "inline-block";
    document.getElementById("restore_def").style.display = "inline-block";
    document.getElementById("load_unit").style.display = "none";
    document.getElementById("reboot_unit").style.display = "none";
    document.getElementById("reset_codec").style.display = "none";
    document.getElementById("diag_download").style.display = "none";
    document.getElementById("help_window").style.display = "none";
    timer = setInterval("timer_status_only();",1000);
  }
  else if (tabName == 'Info')
  {
    document.getElementById("cfg_buttons").style.display = "none";
    document.getElementById("apply_config").style.display = "none";
    document.getElementById("apply_unit").style.display = "none";
    document.getElementById("load").style.display = "none";
    document.getElementById("apply_tx_config").style.display = "none";
    document.getElementById("apply_cam_ctrl_config").style.display = "none";
    document.getElementById("apply_sdr_config").style.display = "none";
    document.getElementById("reload_preset").style.display = "none";
    document.getElementById("restore_def").style.display = "none";
    document.getElementById("load_unit").style.display = "none";
    document.getElementById("reboot_unit").style.display = "none";
    document.getElementById("reset_codec").style.display = "none";
    document.getElementById("diag_download").style.display = "inline-block";
    document.getElementById("help_window").style.display = "none";
    timer = setInterval("timer_status_only();",1000);
  }
  // Disable all tabs "active" status (default colour)
  tablinks = document.getElementsByClassName("tablinksh");
  for (i = 0; i < tablinks.length; i++)
  {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(tabName).style.display = "inline-block";
  evt.currentTarget.className += " active";
  helpContent();
}

function headerChange(title, UnitName, TxPresent)
{
  var a = document.getElementById('title');
  var b = document.getElementById('logo');

  if(title == undefined || title == "")
  {
      title = "Sapphire HEVC 4K";
  }
  if ((CustID == "0000d959") || (CustID == "00007dbf") || (CustID == "0000afb4") || (CustID == "00007c0c") || (CustID == "0000ba74") || ((CustID == "00001234") && (TxPresent == TX_PRESENT_B170 || TxPresent == TX_PRESENT_B170_D1550)))
	  title += "";
  else if(TxPresent != TX_PRESENT_NONE)
	  title += " TX";
  else
	  title += " Encoder";

  if(a.innerHTML != "<h1>" + title + "</h1>")
  {
    a.innerHTML = "<h1>" + title + "</h1>";
  }

  document.getElementById('titleUp').value = title;
  document.getElementById('titleLic').value = title;
  document.getElementById('titleUpTx').value = title;
  document.getElementById('titleTx').value = title;
  document.getElementById('headUp').value = UnitName;
  document.getElementById('headLic').value = UnitName;
  document.getElementById('headUpTx').value = UnitName;
  document.getElementById('headTx').value = UnitName;
  document.getElementById('unit_name').innerText = UnitName;

  img_tag = '<img src="'+ logo + '">';
  if(b.innerHTML != img_tag)
  {
    b.innerHTML = img_tag;
  }
}

function removeOptions(selectbox)
{
    var select = document.getElementById(selectbox);
    var i;
    for(i = select.options.length - 1 ; i >= 0 ; i--)
    {
        select.remove(i);
    }
}

function save_json()
{
	document.getElementById('apply_config').innerText = "Applying . ."
	document.getElementById('apply_config').disabled = true
  var check_ip = 1;

  check_ip &= ValidateIPaddress("IPStreamAddress");

  if(check_ip == 1)
  {
    setEncoder();
  }
}

function handle_tx()
{
	document.getElementById('apply_tx_config').innerText = "Applying . ."
	document.getElementById('apply_tx_config').disabled = true
  setTx()
}

function handle_cam_ctrl()
{
	document.getElementById('apply_cam_ctrl_config').innerText = "Applying . ."
	document.getElementById('apply_cam_ctrl_config').disabled = true
  setCamCtrl()
}

function handle_sdr() 
{
  document.getElementById('apply_sdr_config').innerText = "Applying . ."
  document.getElementById('apply_sdr_config').disabled = true
  var check_ip = 1;

  check_ip &= ValidateIPaddress("SDR_NetIPAddr");
  check_ip &= ValidateIPaddress("SDR_NetGWAddr");
  check_ip &= ValidateIPaddress("SDR_NetMaskAddr");

  check_ip &= ValidateIPaddress("HubIPAddress");

  if (check_ip == 1)
  {
    setSDR()
  }
}

function refreshPreview()
{
  var img = document.getElementById('vid_bmp');
  img.src = img.src.split("?")[0] + "?" + new Date().getTime();
}

function getStatus(sync_flag=true)
{
  var get_json = new XMLHttpRequest();
  get_json.addEventListener("load", (e) =>
    {
      var json_load = JSON.parse(e.target.responseText);
      var UnitMode = json_load.UnitMode;
      var PrevTxActive = TxActive;
      document.getElementById('serial_num').innerHTML = json_load.SerialNumber;
      document.getElementById('software_ver').innerHTML = json_load.SoftwareVersion;
      document.getElementById('hardware_ver').innerHTML = json_load.HardwareVersion;
      document.getElementById('lic_msk').innerHTML = json_load.LicenseMask;
      document.getElementById('srt_ver').innerHTML = json_load.SRTVersion;
      CustID = json_load.CustID;
      BoardType = json_load.BoardType;
      TxPresent = json_load.TxPresent;
      TxActive = json_load.TxActive ?? TX_PRESENT_NONE;
      DTM3200Present = json_load.DTM3200Present;
      B120Present = json_load.B120Present;
      B180Present = json_load.B180Present;
      RFDcBiasPresent = json_load.RFDcBiasPresent;
      LicenseMask = json_load.LicenseMask;
      LicDec = parseInt(LicenseMask, 16)
      license_des = (LicDec&(1<<12))>>12
      license_biss = (LicDec&(1<<14))>>14
      license_enc = LicDec&(1<<0)
      license_dec = (LicDec&(1<<1))>>1
      license_iptx = (LicDec&(1<<15))>>15
      license_rec = (LicDec&(1<<19))>>19
      license_uhd = (LicDec&(1<<6))>>6

      // Refresh web page on active TX change
      if(TxActive != PrevTxActive && TxActive != TX_PRESENT_NONE && 
                                 PrevTxActive >= TX_PRESENT_NONE) location.reload();

      // Only show Support if not OEM customer
      if(CustID != "0000f55b" && CustID != "00006943" && CustID != "0000b866" && CustID != "0000cd90" && CustID != "00009c46" && CustID != "0000bb3a" && CustID != "0000d959")
      {
        document.getElementById("Support").style.display = "inline-block"
      }

      // Fan speed controls only for BTX/B2TX, Cineark FTX, RogueWaves HTX, DBS HTX, any B300
      if((CustID != "0000061e") && (CustID != "0000d959") && (CustID != "00007dbf") && (CustID != "000026de") && (CustID != "0000b3ae") && (TxPresent != TX_PRESENT_B170) && (TxPresent != TX_PRESENT_B170_D1550) && (BoardType != "B300"))
      {
        document.getElementById("FanModeRow").style.display = "none"
        document.getElementById("FanSpeedIdleRow").style.display = "none"
        document.getElementById("FanSpeedRecRow").style.display = "none"
      }

      // Hide all scrambling settings for DTC AEON
      if(CustID == "0000e5ad")
      {
        license_des = 0
        license_biss = 0
      }

      if((license_biss == 0) && (license_des == 0))
      {
        document.getElementById("Scrambling").style.display = "none"
      }
      if(license_des == 0)
      {
        document.getElementById("hide_des").style.display = "none"
      }
      if(license_biss == 0)
      {
        document.getElementById("hide_biss").style.display = "none"
      }
      if(license_rec == 0)
      {
        document.getElementById("rec_sts_row").style.display = "none";
        document.getElementById("usbtab").style.display = "none";
      }
	  ipInterfaceChange();

	  if(BoardType == "B160" || BoardType == "B300")
	  {
		document.getElementById("vid_sts_sdi_row").style.display = "none";
		document.getElementById("ST352_2").style.display = "none";
		document.getElementById("ST352_3").style.display = "none";
		document.getElementById("ST352_4").style.display = "none";

		document.getElementById("QuadSyncRow").style.display = "none";
		document.getElementById("VideoHelperUHDB110Row").style.display = "none";
		document.getElementById("VideoHelper4KB110Row").style.display = "none";
		document.getElementById("VideoHelperQuadSyncRow").style.display = "none";

		document.getElementById("AnalogueTwo").style.display = "none";
		document.getElementById("AudioHelperQuadSyncRow").style.display = "none";
		document.getElementById("AudioHelperQuadSyncDiv").style.display = "none";
		document.getElementById("P48right0").style.display = "none";
		document.getElementById("P48left0_name").innerHTML = "Phantom Power";

		document.getElementById("psu_temp").style.display = "none";
		document.getElementById("UnitModeRow").style.display = "none";

		document.getElementById("lic_decode").style.display = "none";
		document.getElementById("lic_quadsync").style.display = "none";
		document.getElementById("LicenceDecodeRow").style.display = "none";

		document.getElementById("DocQuadSyncHD").style.display = "none";
		document.getElementById("DocQuadSync4K").style.display = "none";
	  }
      else
      {
		document.getElementById("VideoHelperUHDB160Row").style.display = "none";

		document.getElementById("Remux").style.display = "none";
      }

      if(TxPresent == TX_PRESENT_NONE)
      {
        document.getElementById("Status_Tx").style.display = "none";
        document.getElementById("tx").style.display = "none";
        document.getElementById("Tx_Hardware").style.display = "none";
        document.getElementById("tx_div").style.display = "none";
        document.getElementById("TxFirmware").style.display = "none";
        document.getElementById("TxLicense").style.display = "none";
      }
      else
      {
        if(TxPresent == TX_PRESENT_D1550)
        {
          document.getElementById("Tx_Hardware_Band2").style.display = "none";
        }
        else if(TxPresent == TX_PRESENT_D1837)
        {
          document.getElementById("tx_rf_band_header").innerHTML = "RF Bands";
          document.getElementById("TxFirmware").style.display = "none";
          document.getElementById("TxLicense").style.display = "none";
        }
        else if(TxPresent == TX_PRESENT_B160_B170)
        {
          document.getElementById("Tx_Hardware_Band2").style.display = "none";
          document.getElementById("TxFirmware").style.display = "none";
          document.getElementById("TxLicense").style.display = "none";
        }
        else if(TxPresent == TX_PRESENT_B170_D1550)
        {
          document.getElementById("tx_rf_band_header").innerHTML = "RF Bands";
        }
        else if(TxPresent == TX_PRESENT_B170)
        {
          document.getElementById("Tx_Hardware_SW").style.display = "none";
          document.getElementById("Tx_Hardware_ESN").style.display = "none";
          document.getElementById("Tx_Hardware_Lic").style.display = "none";
          document.getElementById("Tx_Hardware_Band2").style.display = "none";
          document.getElementById("TxFirmware").style.display = "none";
          document.getElementById("TxLicense").style.display = "none";
        }
        document.getElementById("VideoBitrateSelect").disabled = true;
        document.getElementById("VideoBitrateVal").disabled = true;
        document.getElementById("SystemBitrateVal").disabled = true;
      }

      if(TxActive == TX_PRESENT_D1550 || TxActive == TX_PRESENT_D1837)
      {
        document.getElementById("Tx_ISDBT").style.display = "none";
        document.getElementById("nb_umvl_interleaver").style.display = "none";
        document.getElementById("umvl_dualped").style.display = "none";
        document.getElementById("dvbt_4koff").style.display = (TxPresent == TX_PRESENT_D1837)?"none":"inline-block";
      }
      else if(TxActive == TX_PRESENT_B170)
      {
        if(CustID == "0000d959") { // RogueWaves HTX
          document.getElementById("mod_scheme").style.display = "none";
          document.getElementById("Tx_ISDBT").style.display = "none";
          document.getElementById("Tx_NB_UMVL").style.display = "none";
          document.getElementById("dvbt_dualped").style.display = "none";
        }
        document.getElementById("dvbt_4koff").style.display = "none";
      }
      else if(TxActive == TX_PRESENT_B160_B170)
      {
        document.getElementById("dvbt_4koff").style.display = "none";
      }

      if (CustID != "0000afb4") // not B2TXR
      {
        if (CustID != "00007c0c" && CustID != "0000ba74")  // not BTXR or GVTXR
        {
            document.getElementById("Status_TSL_Tally").style.display = "none";
            document.getElementById("TSLTally").style.display = "none";
            document.getElementById("sdrtab").style.display = "none";
            document.getElementById("sdr_div").style.display = "none";
            document.getElementById("Status_SDR").style.display = "none";
            document.getElementById("SDR_Hardware").style.display = "none";
        }
        else
        {
            document.getElementById("Status_TSL_Tally").style.display = "none";
            document.getElementById("TSLTally").style.display = "none";
            getSDRStatus();
        }
      }
      else
      {
        document.getElementById("TxFirmware").style.display = "none";
        document.getElementById("TxLicense").style.display = "none";
        
        getTSLTallyStatus();
        getSDRStatus();
      }
    
      document.getElementById("Sda1Size").innerHTML = json_load.Sda1Size;
      document.getElementById("Sda1Type").innerHTML = json_load.Sda1Type;
      document.getElementById("USBStorage").style.display = (json_load.Sda1Size == "" && json_load.Sda1Type == "")?"none":"inline-block";

      var remuxMode = parseInt(getValue("RemuxModeSelect"));
      if(remuxMode == 1)
      {
		document.getElementById("vid_sts_rate_row").style.display = "none";
		document.getElementById("Video_Encoder").style.display = "none";
		document.getElementById("ASI_Stream").style.display = "none";
		document.getElementById("AV_Monitoring").style.display = "none";
		document.getElementById("ST352").style.display = "none";
      }
      else
      {
		document.getElementById("vid_sts_rate_row").style.display = "inline-block";
		document.getElementById("Video_Encoder").style.display = "inline-block";
		document.getElementById("ASI_Stream").style.display = "inline-block";
		document.getElementById("AV_Monitoring").style.display = "inline-block";
		document.getElementById("ST352").style.display = "inline-block";
      }
      document.getElementById("Input_Stream_sts").style.display = (remuxMode == 0)?"none":"inline-block";

      if(getValue("IPBridgeSelect") != 0)
      {
		document.getElementById("eth0_ipaddr").innerHTML = json_load.Br0IPaddrActive;
		document.getElementById("eth0_gwaddr").innerHTML = json_load.Br0GWaddrActive;
		document.getElementById("eth0_mask").innerHTML = json_load.Br0MaskActive;
      }
      else
      {
		document.getElementById("eth0_ipaddr").innerHTML = json_load.Eth0IPaddrActive;
		document.getElementById("eth0_gwaddr").innerHTML = json_load.Eth0GWaddrActive;
		document.getElementById("eth0_mask").innerHTML = json_load.Eth0MaskActive;
      }
      document.getElementById("eth0_macaddr").innerHTML = json_load.Eth0MACaddr;
      document.getElementById("eth0_state").innerHTML = "Link State " + json_load.Eth0LinkState;
      document.getElementById("eth0_rx_count").innerHTML = "RX: " + json_load.Eth0RxCount;
      document.getElementById("eth0_tx_count").innerHTML = "TX: " + json_load.Eth0TxCount;

      document.getElementById("eth1_ipaddr").innerHTML = json_load.Eth1IPaddrActive;
      document.getElementById("eth1_gwaddr").innerHTML = json_load.Eth1GWaddrActive;
      document.getElementById("eth1_mask").innerHTML = json_load.Eth1MaskActive;
      document.getElementById("eth1_macaddr").innerHTML = json_load.Eth1MACaddr;
      document.getElementById("eth1_state").innerHTML = "Link State " + json_load.Eth1LinkState;
      document.getElementById("eth1_rx_count").innerHTML = "RX: " + json_load.Eth1RxCount;
      document.getElementById("eth1_tx_count").innerHTML = "TX: " + json_load.Eth1TxCount;

      var bytesPerIP = (parseInt(getValue("IPStreamNumTP"))+1)*188;
      var packetSize = bytesPerIP;
	  switch(parseInt(getValue("IPStreamProtocol"))) {
        case 0: packetSize += 28; break; // UDP
        case 1: packetSize += 40; break; // RTP
        case 2: packetSize += 44; break; // SRT
	  }
      var estimatedBitrate = (json_load.SystemBitrate/1000)*(packetSize/bytesPerIP);
      document.getElementById("b110_bitrate").innerHTML = estimatedBitrate.toFixed(3) + " Mb/s";
      document.getElementById("b110_packetsize").innerHTML = packetSize + " bytes";

      if(DTM3200Present == 1)
      {
        document.getElementById("ip_hardware_ver").innerHTML = "v" + (json_load.DtmSWVersion/10).toFixed(1);

        document.getElementById("dtm_ipaddr").innerHTML = json_load.DtmIPaddrActive;
        document.getElementById("dtm_gwaddr").innerHTML = json_load.DtmGWaddrActive;
        document.getElementById("dtm_mask").innerHTML = json_load.DtmMaskActive;
        document.getElementById("dtm_macaddr").innerHTML = json_load.DtmMACaddr;
        document.getElementById("dtm_state").innerHTML = "Link State " + json_load.DtmLinkState;
        document.getElementById("dtm_rx_count").innerHTML = "RX: " + ((json_load.DtmLinkState=="")?"-":json_load.DtmRxCount);
        document.getElementById("dtm_tx_count").innerHTML = "TX: " + ((json_load.DtmLinkState=="")?"-":json_load.DtmTxCount);

		var fecEnabled = getValue("IPFECEnable");
		var fecCols = (fecEnabled==0)?0.0:(getNumber("IPFECCols")*1.0);
		var fecRows = (fecEnabled==0)?0.0:(getNumber("IPFECRows")*1.0);
		var fecOverheads = ((fecCols==0)||(fecRows==0))?0:((fecCols+fecRows)/(fecCols*fecRows));
		var bytesPerIP = (parseInt(getValue("IPStreamNumTP"))+1)*188;
		var packetSize = bytesPerIP+((getValue("IPStreamProtocol")==0)?28:40);
		var estimatedBitrate = (json_load.DtmTxBitrate/1000000)*(packetSize/bytesPerIP)*(fecOverheads+1.0);
        document.getElementById("dtm_bitrate").innerHTML = estimatedBitrate.toFixed(3) + " Mb/s";
        document.getElementById("dtm_packetsize").innerHTML = packetSize + " bytes";
        document.getElementById("dtm_overheads").innerHTML = (fecOverheads*100.0).toFixed(1) + "%";
        document.getElementById("dtm_resolved").innerHTML = (json_load.DtmTxResolved==0)?"Yes":"No";
	  }

	  if(getValue("IPStreamEnable") == 0 || getValue("IPStreamProtocol") != 2)
	  {
		//document.getElementById("b110_public_ip").innerHTML = PublicIPAddress;
		document.getElementById("srt_connect").innerHTML = "Not Connected";
		document.getElementById("srt_host").innerHTML = "-";
		document.getElementById("srt_delay").innerHTML = "-";
		document.getElementById("mbpsSendRate").innerHTML = "-";
		document.getElementById("pktSentTotal").innerHTML = "-";
		document.getElementById("pktSndDropTotal").innerHTML = "-";
		document.getElementById("pktSndLoss").innerHTML = "-";
		document.getElementById("pktRetrans").innerHTML = "-";
		document.getElementById("msSndBuf").innerHTML = "-";
		document.getElementById("msRTT").innerHTML = "-";
	  }
	  else
	  {
		getSRTStatus();
	  }

	  if(getValue("RecordEnable") == 0)
	  {
		  document.getElementById("file_remaining").innerHTML = '-';
		  document.getElementById("file_recorded").innerHTML = '-';
		  document.getElementById("recorder_state").innerHTML = "Disabled";
		  document.getElementById("playback_state").innerHTML = "Disabled";
	  }
	  else
	  {
		  var RecorderRemaining = json_load.RecorderRemaining;
		  var RecorderRecorded = json_load.RecorderRecorded;
		  var RecorderState = json_load.RecorderState;
		  var PlaybackState = json_load.PlaybackState;
		  switch(RecorderState) {
			  case 0:  document.getElementById("recorder_state").innerHTML = "No Disk"; break;
			  case 1:
			  case 2:  document.getElementById("recorder_state").innerHTML = "Ready"; break;
			  case 3:  document.getElementById("recorder_state").innerHTML = "Active"; break;
			  case 4:  document.getElementById("recorder_state").innerHTML = "Full Disk"; break;
			  default: document.getElementById("recorder_state").innerHTML = "Error"; break;
		  }
		  document.getElementById("playback_state").innerHTML = (PlaybackState == 0)?"Stopped":("-" + PlaybackState + ((PlaybackState == 1)?" minute":" minutes"));
		  document.getElementById("file_remaining").innerHTML = RecorderRemaining + ((RecorderRemaining == 1)?" minute":" minutes");
		  document.getElementById("file_recorded").innerHTML = RecorderRecorded + ((RecorderRecorded == 1)?" minute":" minutes");
	  }

	  if(json_load.WebPassword)
	  {
	    document.getElementById("WebPasswordSet").value = "Change";
	    document.getElementById("WebPasswordClear").style.display = "inline-block";
	  }
	  else
	  {
	    document.getElementById("WebPasswordSet").value = "Set";
	    document.getElementById("WebPasswordClear").style.display = "none";
	  }

	if(B180Present == 0)
	{
    if (CustID != "00007c0c")
    {
      document.getElementById("Status_Cam_Ctrl").style.display = "none";
      document.getElementById("cam_ctrl").style.display = "none";
      document.getElementById("CamrRxLicense").style.display = "none";
      document.getElementById("CamRx_Hardware").style.display = "none";
      document.getElementById("CamRxFirmware").style.display = "none";
    }
    else
    {
      document.getElementById("cam_ctrl").style.display = "none";
      document.getElementById("CamrRxLicense").style.display = "none";
      document.getElementById("CamRx_Hardware").style.display = "none";
      document.getElementById("CamRxFirmware").style.display = "none";
      document.getElementById("cctrl_freq_sts_row").style.display = "none";
      document.getElementById("cctrl_num_sts_row").style.display = "none";
      getCamCtrlStatus();
    }
	}
	else
	{
	  getCamCtrlStatus();
    if (B180Present > 1)
    {
      document.getElementById("CamrRxLicense").style.display = "inline-block";
      document.getElementById("CamRx_Hardware").style.display = "inline-block";
      if (B180Present == 2)
        document.getElementById("CamRxFirmware").style.display = "inline-block";
      else
        document.getElementById("CamRxFirmware").style.display = "none";
    }
    else
    {
      document.getElementById("CamrRxLicense").style.display = "none";
      document.getElementById("CamRx_Hardware").style.display = "inline-block";
      document.getElementById("camrx_software_ver_line").style.display = "inline-block";
      document.getElementById("camrx_serial_num_line").style.display = "none";
      document.getElementById("camrx_lic_msk_line").style.display = "none"; 
      document.getElementById("CamRxFirmware").style.display = "none";
    }
	}

	  var aud_enc_map = [0,1,5,6,2,3,4]
	  var aud_enc_map4 = [0,1,5,6,3,4]
      var enableLevelBar0 = getValue("AudioEncoder0Select");
      var enableLevelBar1 = getValue("AudioEncoder1Select");
      var enableLevelBar2 = getValue("AudioEncoder2Select");
      var enableLevelBar3 = getValue("AudioEncoder3Select");
      var enableLevelBar4 = getValue("AudioEncoder4Select");
      var enableLevelBar5 = getValue("AudioEncoder5Select");
      var enableLevelBar6 = getValue("AudioEncoder6Select");
      var enableLevelBar7 = getValue("AudioEncoder7Select");
      updateLevelBar(enableLevelBar0,json_load.AudLevL0,json_load.AudData0,0,0,aud_enc_map[enableLevelBar0]);
      updateLevelBar(enableLevelBar0,json_load.AudLevR0,json_load.AudData0,0,1,aud_enc_map[enableLevelBar0]);
      updateLevelBar(enableLevelBar1,json_load.AudLevL1,json_load.AudData1,1,0,aud_enc_map[enableLevelBar1]);
      updateLevelBar(enableLevelBar1,json_load.AudLevR1,json_load.AudData1,1,1,aud_enc_map[enableLevelBar1]);
      updateLevelBar(enableLevelBar2,json_load.AudLevL2,json_load.AudData2,2,0,aud_enc_map[enableLevelBar2]);
      updateLevelBar(enableLevelBar2,json_load.AudLevR2,json_load.AudData2,2,1,aud_enc_map[enableLevelBar2]);
      updateLevelBar(enableLevelBar3,json_load.AudLevL3,json_load.AudData3,3,0,aud_enc_map[enableLevelBar3]);
      updateLevelBar(enableLevelBar3,json_load.AudLevR3,json_load.AudData3,3,1,aud_enc_map[enableLevelBar3]);
      updateLevelBar(enableLevelBar4,json_load.AudLevL4,json_load.AudData4,4,0,aud_enc_map4[enableLevelBar4]);
      updateLevelBar(enableLevelBar4,json_load.AudLevR4,json_load.AudData4,4,1,aud_enc_map4[enableLevelBar4]);
      updateLevelBar(enableLevelBar5,json_load.AudLevL5,json_load.AudData5,5,0,aud_enc_map4[enableLevelBar5]);
      updateLevelBar(enableLevelBar5,json_load.AudLevR5,json_load.AudData5,5,1,aud_enc_map4[enableLevelBar5]);
      updateLevelBar(enableLevelBar6,json_load.AudLevL6,json_load.AudData6,6,0,aud_enc_map4[enableLevelBar6]);
      updateLevelBar(enableLevelBar6,json_load.AudLevR6,json_load.AudData6,6,1,aud_enc_map4[enableLevelBar6]);
      updateLevelBar(enableLevelBar7,json_load.AudLevL7,json_load.AudData7,7,0,aud_enc_map4[enableLevelBar7]);
      updateLevelBar(enableLevelBar7,json_load.AudLevR7,json_load.AudData7,7,1,aud_enc_map4[enableLevelBar7]);

      var s352_xx = ["s352_1a","s352_1b","s352_2a","s352_2b","s352_3a","s352_3b","s352_4a","s352_4b"];
      for (var i = 0; i < s352_xx.length; i++)
      {
        var s352 = "00000000";
        switch(i) {
          case 0: s352 = json_load.ST352SDI1A; break;
          case 1: s352 = json_load.ST352SDI1B; break;
          case 2: s352 = json_load.ST352SDI2A; break;
          case 3: s352 = json_load.ST352SDI2B; break;
          case 4: s352 = json_load.ST352SDI3A; break;
          case 5: s352 = json_load.ST352SDI3B; break;
          case 6: s352 = json_load.ST352SDI4A; break;
          case 7: s352 = json_load.ST352SDI4B; break;
        }
        var s352_byte1 = parseInt(s352[6]+s352[7], 16);
        var s352_byte2 = parseInt(s352[4]+s352[5], 16);
        var s352_byte3 = parseInt(s352[2]+s352[3], 16);
        var s352_byte4 = parseInt(s352[0]+s352[1], 16);
        var s352_text = s352[6]+s352[7] + " " + s352[4]+s352[5] + " " + s352[2]+s352[3] + " " + s352[0]+s352[1];
        var s352_samp = 0;
        var s352_trans = 0;
        var s352_color = 0;
        var s352_depth = 1;
        var s352_yicc = 0;

        switch(s352_byte1&0x7f) {
          case 0x01: // SD-SDI
          case 0x02: // SD-SDI Dual Link
          case 0x03: // ED-SDI
            s352_text += " : " + (((s352_byte1&0x7f)==0x03)?"E":"S") + "D-SDI " + (((s352_byte3&0x40)!=0)?"960":"720");
            switch(s352_byte2&0x4f) {
              case 0x05: s352_text += "x576i50"; break;
              case 0x06: s352_text += "x483i59"; break;
              case 0x49: s352_text += "x576p50"; break;
              case 0x4a: s352_text += "x483p59"; break;
              default:   s352_text += "x??????"; break; }
            s352_text += " " + (((s352_byte3&0x80)!=0)?"16:9":"4:3");
            if ((s352_byte1&0x7f)==0x03) {
              s352_text += " Link " + (((s352_byte4&0x40)!=0)?"2":"1"); }
            s352_depth = (((s352_byte4&0x03)==0)?4:1);
            break;

          case 0x04: // HD-SDI 720
          case 0x05: // HD-SDI 1080
          case 0x06: // HD-SDI 483/576
          case 0x07: // HD-SDI Dual Link 1080
          case 0x09: // 3G-SDI Level A 1080
          case 0x0a: // 3G-SDI Level B 1080
          case 0x0b: // 3G-SDI Level B Dual Stream 720
          case 0x0c: // 3G-SDI Level B Dual Stream 1080
          case 0x14: // 3G-SDI Level A Dual Link 1080
          case 0x15: // 3G-SDI Level B Dual Link 1080
          case 0x16: // 3G-SDI Level B Dual Link 2160
          case 0x17: // 3G-SDI Level A Quad Link 2160
          case 0x18: // 3G-SDI Level B Quad Link 2160
          case 0x19: // 3G-SDI Level A Dual Link 3D 1080
          case 0x1b: // 3G-SDI Level B Dual Link 3D 2160
          case 0x31: // HD-SDI Dual Link 3D 720/1080
          case 0x40: // 6G-SDI 2160
          case 0x41: // 6G-SDI 1080
          case 0x42: // 6G-SDI Dual Link 2160
          case 0x4e: // 12G-SDI 2160
            s352_samp = (s352_byte3&0x0f)>>0;
            s352_text += " : ";
            switch(s352_byte1&0x7f) {
              case 0x4e:
                         s352_text += "12G-SDI "; break;
              case 0x40: case 0x41: case 0x42:
                         s352_text += "6G-SDI "; break;
              case 0x0a: case 0x0b: case 0x0c: case 0x15: case 0x16: case 0x18: case 0x1b:
                         s352_text += "3GB-SDI "; break;
              case 0x09: case 0x14: case 0x17: case 0x19:
                         s352_text += "3GA-SDI "; break;
              default:   s352_text += "HD-SDI "; break; }
            switch(s352_byte1&0x7f) {
              case 0x06:
                s352_text += (((s352_byte3&0x0f)>6)?"2x":"") + (((s352_byte3&0x0f)==1||(s352_byte3&0x0f)==8)?"960":"720") + "x" + (((s352_byte2&0x10)!=0)?"576":"483");
                switch(s352_byte3&0x0f) {
                  case 0x00: s352_samp = 0; s352_text += "i"; s352_byte2 &= ~0x40; break;
                  case 0x01: s352_samp = 0; s352_text += "i"; s352_byte2 &= ~0x40; break;
                  case 0x02: s352_samp = 3; s352_text += "p"; s352_byte2 |= 0x40; break;
                  case 0x03: s352_samp = 5; s352_text += "i"; s352_byte2 &= ~0x40; break;
                  case 0x04: s352_samp = 6; s352_text += "i"; s352_byte2 &= ~0x40; break;
                  case 0x05: s352_samp = 0; s352_text += "p"; s352_byte2 |= 0x40; break;
                  case 0x06: s352_samp = 0; s352_text += "p"; s352_byte2 |= 0x40; break;
                  case 0x07: s352_samp = 0; s352_text += "i"; s352_byte2 &= ~0x40; break;
                  case 0x08: s352_samp = 0; s352_text += "i"; s352_byte2 &= ~0x40; break;
                  case 0x09: s352_samp = 3; s352_text += "p"; s352_byte2 |= 0x40; break;
                  default: s352_text += "?"; break; }
                s352_depth = (((s352_byte4&0x03)==0)?4:1);
                break;
              case 0x31:
                s352_text += ((s352_byte2&0x0f)>7) ? "1280x720" : ((((s352_byte3&0x40)!=0)?"2048":"1920") + "x1080");
                s352_text += (((s352_byte2&0xc0)!=0)?(((s352_byte2&0x80)!=0)?"p":"psf"):"i");
                s352_trans = ((s352_byte2&0x30)>>4);
                s352_color = ((s352_byte3&0x80)>>6)|((s352_byte3&0x10)>>4);
                s352_depth = (((s352_byte4&0x03)==0)?4:1);
                s352_yicc = (s352_byte4&0x10)>>4;
                break;
              case 0x04: case 0x0b:
                s352_text += "1280x720" + (((s352_byte2&0x40)!=0)?"p":"?");
                s352_trans = ((s352_byte2&0x30)>>4);
                s352_color = ((s352_byte3&0x30)>>4);
                s352_depth = (((s352_byte4&0x03)==0)?4:1);
                s352_yicc = (s352_byte4&0x10)>>4;
                break;
              case 0x17: case 0x40: case 0x41: case 0x42: case 0x4e:
                s352_text += (((s352_byte3&0x40)!=0)?"4096":"3840") + "x2160" + (((s352_byte2&0xc0)!=0)?(((s352_byte2&0x80)!=0)?"p":"psf"):"i");
                s352_trans = ((s352_byte2&0x30)>>4);
                s352_color = ((s352_byte3&0x30)>>4);
                s352_depth = ((s352_byte4&0x03)>>0);
                s352_yicc = (s352_byte4&0x10)>>4;
                break;
              case 0x16: case 0x18: case 0x1b:
                s352_text += (((s352_byte3&0x40)!=0)?"4096":"3840") + "x2160" + (((s352_byte2&0xc0)!=0)?"p":"i");
                s352_trans = ((s352_byte2&0x30)>>4);
                s352_color = (((s352_byte3&0x80)>>6)|((s352_byte3&0x10)>>4));
                s352_depth = ((s352_byte4&0x03)>>0);
                s352_yicc = (s352_byte4&0x10)>>4;
                break;
              case 0x09: case 0x14: case 0x19:
                s352_text += (((s352_byte3&0x40)!=0)?"2048":"1920") + "x1080" + (((s352_byte2&0xc0)!=0)?(((s352_byte2&0x80)!=0)?"p":"psf"):"i");
                s352_trans = ((s352_byte2&0x30)>>4);
                s352_color = ((s352_byte3&0x30)>>4);
                s352_depth = ((s352_byte4&0x03)>>0);
                s352_yicc = (s352_byte4&0x10)>>4;
                break;
              case 0x0a: case 0x15:
                s352_text += (((s352_byte3&0x40)!=0)?"2048":"1920") + "x1080" + (((s352_byte2&0xc0)!=0)?"p":"i");
                s352_trans = ((s352_byte2&0x30)>>4);
                s352_color = (((s352_byte3&0x80)>>6)|((s352_byte3&0x10)>>4));
                s352_depth = ((s352_byte4&0x03)>>0);
                s352_yicc = (s352_byte4&0x10)>>4;
                break
              case 0x05:
                s352_text += (((s352_byte3&0x40)!=0)?"2048":"1920") + "x1080" + (((s352_byte2&0xc0)!=0)?(((s352_byte2&0x80)!=0)?"p":"psf"):"i");
                s352_trans = ((s352_byte2&0x30)>>4);
                s352_color = (((s352_byte3&0x80)>>6)|((s352_byte3&0x10)>>4));
                s352_depth = (((s352_byte4&0x03)==0)?4:(((s352_byte4&0x03)==3)?0:1));
                s352_yicc = (s352_byte4&0x10)>>4;
                break;
              default:
                s352_text += (((s352_byte3&0x40)!=0)?"2048":"1920") + "x1080" + (((s352_byte2&0xc0)!=0)?(((s352_byte2&0x80)!=0)?"p":"psf"):"i");
                s352_trans = ((s352_byte2&0x30)>>4);
                s352_color = (((s352_byte3&0x80)>>6)|((s352_byte3&0x10)>>4));
                s352_depth = ((s352_byte4&0x03)>>0);
                s352_yicc = (s352_byte4&0x10)>>4;
                break; }
            switch(s352_byte2&0x4f) {
              case 0x02: s352_text += "47"; break;
              case 0x03: s352_text += "48"; break;
              case 0x05: s352_text += "50"; break;
              case 0x06: s352_text += "59"; break;
              case 0x07: s352_text += "60"; break;
              case 0x42: s352_text += "23"; break;
              case 0x43: s352_text += "24"; break;
              case 0x45: s352_text += "25"; break;
              case 0x46: s352_text += "29"; break;
              case 0x47: s352_text += "30"; break;
              case 0x44: s352_text += "47"; break;
              case 0x48: s352_text += "48"; break;
              case 0x49: s352_text += "50"; break;
              case 0x4a: s352_text += "59"; break;
              case 0x4b: s352_text += "60"; break;
              default:   s352_text += "??"; break; }
            switch(s352_byte1&0x7f) {
              case 0x06:
                s352_text += " " + (((s352_byte4&0x10)!=0)?"16:9":"4:3");
                break;
              case 0x07: case 0x14: case 0x19:
                s352_text += " Link " + (((s352_byte4&0x40)!=0)?"2":"1");
                break;
              case 0x0b: case 0x0c:
                s352_text += " Stream " + (((s352_byte4&0x40)!=0)?"2":"1");
                break;
              case 0x15:
                s352_text += " Link " + (((s352_byte4&0x80)!=0)?"2":"1");
                //s352_text += " Stream " + (((s352_byte4&0x40)!=0)?"2":"1");
                break;
              case 0x16: case 0x1b:
                s352_text += " 2SI Link " + (((s352_byte4&0x80)!=0)?"2":"1");
                //s352_text += " Stream " + (((s352_byte4&0x40)!=0)?"2":"1");
                break;
              case 0x17: case 0x18:
                s352_text += " 2SI Link ";
                switch(s352_byte4&0xc0) {
                  case 0x00: s352_text += "1"; break;
                  case 0x40: s352_text += "2"; break;
                  case 0x80: s352_text += "3"; break;
                  case 0xc0: s352_text += "4"; break; }
                break;
              case 0x42:
                s352_text += " 2SI Link ";
                switch(s352_byte4&0xe0) {
                  case 0x00: s352_text += "1"; break;
                  case 0x20: s352_text += "2"; break;
                  case 0x40: s352_text += "3"; break;
                  case 0x60: s352_text += "4"; break;
                  case 0x80: s352_text += "5"; break;
                  case 0xa0: s352_text += "6"; break;
                  case 0xc0: s352_text += "7"; break;
                  case 0xe0: s352_text += "8"; break; }
                break;
              case 0x31:
                s352_text += (((s352_byte4&0x40)!=0)?" Right":" Left") + " Eye";
                break;
              default: break }
            break;

          default: s352_byte1 = 0; break;
        }
        if (s352_byte1!=0)
        {
          switch (s352_trans) {
            case 0: s352_text += " SDR"; break;
            case 1: s352_text += " HLG"; break;
            case 2: s352_text += " PQ"; break;
          }
          switch (s352_color) {
            case 0: s352_text += " Rec.709"; break;
            case 2: s352_text += " Rec.2020"; break;
          }
          switch (s352_samp) {
            case 0x00: s352_text += (s352_yicc==0)?" 4:2:2 YCbCr":" 4:2:2 ICtCp"; break;
            case 0x01: s352_text += (s352_yicc==0)?" 4:4:4 YCbCr":" 4:4:4 ICtCp"; break;
            case 0x02: s352_text += " 4:4:4 GBR"; break;
            case 0x03: s352_text += (s352_yicc==0)?" 4:2:0 YCbCr":" 4:2:0 ICtCp"; break;
            case 0x04: s352_text += (s352_yicc==0)?" 4:2:2:4 YCbCrA":" 4:2:2:4 ICtCpA"; break;
            case 0x05: s352_text += (s352_yicc==0)?" 4:4:4:4 YCbCrA":" 4:4:4:4 ICtCpA"; break;
            case 0x06: s352_text += " 4:4:4:4 GBRA"; break;
            case 0x07: s352_text += " 2048-2 FS"; break;
            case 0x08: s352_text += (s352_yicc==0)?" 4:2:2:4 YCbCrD":" 4:2:2:4 ICtCpD"; break;
            case 0x09: s352_text += (s352_yicc==0)?" 4:4:4:4 YCbCrD":" 4:4:4:4 ICtCpD"; break;
            case 0x0a: s352_text += " 4:4:4:4 GBRD"; break;
          }
          switch (s352_depth) {
            case 0:  s352_text += " 10-bit Full"; break;
            case 1:  s352_text += " 10-bit"; break;
            case 2:  s352_text += " 12-bit"; break;
            case 3:  s352_text += " 12-bit Full"; break;
            default: s352_text += " 8-bit"; break;
          }
        }
        if(s352=="00000000")
        {
          document.getElementById(s352_xx[i]).style.color = "#ddd";
        }
        else
        {
          document.getElementById(s352_xx[i]).style.color = "#1e1a37";
        }
        document.getElementById(s352_xx[i]).innerHTML = s352_text;
      }

      var quad_sync = getValue("QuadSyncSelect");
      var video_format = getValue("VideoFormatSelect");
      var video_lock = json_load.VideoLock;
      var is_locked = 0;
      if(quad_sync == 0)
      {
        if(video_format > 22)
        {
          if((video_lock&15) == 15)
            is_locked = 1;
        }
        else
        {
          if((video_lock&8) == 8)
            is_locked = 1;
        }
      }
      if(is_locked == 1)
      {
        document.getElementById("vid_lock").innerHTML = "LOCKED";
        document.getElementById("vid_lock").classList.add("low");
        document.getElementById("vid_lock").classList.remove("med");
        document.getElementById("vid_lock").classList.remove("high");
      }
      else if((video_lock&15) != 0)
      {
        var vid_lock1 = (video_lock&8);
        var vid_lock2 = (video_lock&4);
        var vid_lock3 = (video_lock&2);
        var vid_lock4 = (video_lock&1);
        var vid_lock_str = '';

        if(vid_lock1 == 8)
          vid_lock_str += '1';
        else
          vid_lock_str += 'x ';
        if(vid_lock2 == 4)
          vid_lock_str += ' 2 ';
        else
          vid_lock_str += ' x ';
        if(vid_lock3 == 2)
          vid_lock_str += ' 3 ';
        else
          vid_lock_str += ' x ';
        if(vid_lock4 == 1)
          vid_lock_str += ' 4 ';
        else
          vid_lock_str += ' x ';

        document.getElementById("vid_lock").innerHTML = vid_lock_str;
        if(quad_sync == 0)
        {
          document.getElementById("vid_lock").classList.remove("low");
          document.getElementById("vid_lock").classList.add("med");
          document.getElementById("vid_lock").classList.remove("high");
        }
        else
        {
          document.getElementById("vid_lock").classList.add("low");
          document.getElementById("vid_lock").classList.remove("med");
          document.getElementById("vid_lock").classList.remove("high");
        }
      }
      else
      {
        document.getElementById("vid_lock").innerHTML = "NO LOCK";
        document.getElementById("vid_lock").classList.remove("low");
        document.getElementById("vid_lock").classList.remove("med");
        document.getElementById("vid_lock").classList.add("high");
      }

      if(json_load.B111Present)
      {
          switch(json_load.B111Mode) {
              case 15:
              case 0:  document.getElementById("sfp_mode_sts").innerHTML =        "Bypass"; break;
              case 1:  document.getElementById("sfp_mode_sts").innerHTML =  "1x3G to 2xHD"; break;
              case 2:  document.getElementById("sfp_mode_sts").innerHTML =  "1x6G to 2x3G"; break;
              case 3:  document.getElementById("sfp_mode_sts").innerHTML = "1x12G to 2x6G"; break;
              case 4:  document.getElementById("sfp_mode_sts").innerHTML =  "2x6G to 4x3G"; break;
              case 5:  document.getElementById("sfp_mode_sts").innerHTML = "2x12G to 4x6G"; break;
              case 6:  document.getElementById("sfp_mode_sts").innerHTML =  "1x6G to 4xHD"; break;
              case 7:  document.getElementById("sfp_mode_sts").innerHTML = "1x12G to 4x3G"; break;
              default: document.getElementById("sfp_mode_sts").innerHTML =             "-"; break;
          }
          var b110Lock = json_load.B111Lock;
          if(video_format <= 3) {
              document.getElementById("sfp_1_sts").innerHTML = ((video_lock&8)==0)?"-":"SD";
              document.getElementById("sfp_2_sts").innerHTML = ((video_lock&4)==0)?"-":"SD";
              document.getElementById("sfp_3_sts").innerHTML = ((video_lock&2)==0)?"-":"SD";
              document.getElementById("sfp_4_sts").innerHTML = ((video_lock&1)==0)?"-":"SD";
          }
          else {
              document.getElementById("sfp_1_sts").innerHTML = ((b110Lock&1)==0)?"-":sfp_rate[json_load.B111Rate1];
              document.getElementById("sfp_2_sts").innerHTML = ((b110Lock&2)==0)?"-":sfp_rate[json_load.B111Rate2];
              document.getElementById("sfp_3_sts").innerHTML = ((b110Lock&4)==0)?"-":sfp_rate[json_load.B111Rate3];
              document.getElementById("sfp_4_sts").innerHTML = ((b110Lock&8)==0)?"-":sfp_rate[json_load.B111Rate4];
          }
          switch(json_load.B111Mode) {
              case 1: case 2: case 3: case 6: case 7: // 1x mode
                  document.getElementById("sfp_1_sts").classList.toggle("high", ((b110Lock&1)==0));
                  document.getElementById("sfp_1_sts").classList.toggle("low", ((b110Lock&1)!=0));
                  document.getElementById("sfp_2_sts").classList.remove("high");
                  document.getElementById("sfp_2_sts").classList.remove("low");
                  document.getElementById("sfp_3_sts").classList.remove("high");
                  document.getElementById("sfp_3_sts").classList.remove("low");
                  document.getElementById("sfp_4_sts").classList.remove("high");
                  document.getElementById("sfp_4_sts").classList.remove("low");
                  break;
              case 4: case 5: // 2x mode
                  document.getElementById("sfp_1_sts").classList.toggle("high", ((b110Lock&1)==0));
                  document.getElementById("sfp_1_sts").classList.toggle("low", ((b110Lock&1)!=0));
                  document.getElementById("sfp_2_sts").classList.remove("high");
                  document.getElementById("sfp_2_sts").classList.remove("low");
                  document.getElementById("sfp_3_sts").classList.toggle("high", ((b110Lock&4)==0));
                  document.getElementById("sfp_3_sts").classList.toggle("low", ((b110Lock&4)!=0));
                  document.getElementById("sfp_4_sts").classList.remove("high");
                  document.getElementById("sfp_4_sts").classList.remove("low");
                  break;
              default: // bypass
                  if(video_format <= 3)
                  {
                      document.getElementById("sfp_1_sts").classList.toggle("high", ((video_lock&8)==0));
                      document.getElementById("sfp_1_sts").classList.toggle("low", ((video_lock&8)!=0));
                      document.getElementById("sfp_2_sts").classList.remove("high");
                      document.getElementById("sfp_2_sts").classList.remove("low");
                      document.getElementById("sfp_3_sts").classList.remove("high");
                      document.getElementById("sfp_3_sts").classList.remove("low");
                      document.getElementById("sfp_4_sts").classList.remove("high");
                      document.getElementById("sfp_4_sts").classList.remove("low");
                  }
                  else if((quad_sync != 0) || (video_format > 22))
                  {
                      document.getElementById("sfp_1_sts").classList.toggle("high", ((b110Lock&1)==0));
                      document.getElementById("sfp_1_sts").classList.toggle("low", ((b110Lock&1)!=0));
                      document.getElementById("sfp_2_sts").classList.toggle("high", ((b110Lock&2)==0));
                      document.getElementById("sfp_2_sts").classList.toggle("low", ((b110Lock&2)!=0));
                      document.getElementById("sfp_3_sts").classList.toggle("high", ((b110Lock&4)==0));
                      document.getElementById("sfp_3_sts").classList.toggle("low", ((b110Lock&4)!=0));
                      document.getElementById("sfp_4_sts").classList.toggle("high", ((b110Lock&8)==0));
                      document.getElementById("sfp_4_sts").classList.toggle("low", ((b110Lock&8)!=0));
                  }
                  else
                  {
                      document.getElementById("sfp_1_sts").classList.toggle("high", ((b110Lock&1)==0));
                      document.getElementById("sfp_1_sts").classList.toggle("low", ((b110Lock&1)!=0));
                      document.getElementById("sfp_2_sts").classList.remove("high");
                      document.getElementById("sfp_2_sts").classList.remove("low");
                      document.getElementById("sfp_3_sts").classList.remove("high");
                      document.getElementById("sfp_3_sts").classList.remove("low");
                      document.getElementById("sfp_4_sts").classList.remove("high");
                      document.getElementById("sfp_4_sts").classList.remove("low");
                  }
                  break;
          }
          document.getElementById("Status_SFP").style.display = "inline-block";
      }
      else
      {
          document.getElementById("Status_SFP").style.display = "none";
      }

      var video_fmt = getText("VideoFormatSelect");
      document.getElementById("vid_sts_fmt").innerHTML = video_fmt;

      if(quad_sync == 0)
      {
        document.getElementById("vid_sts_sdi").innerHTML = supported_formats[video_format];
      }
      else if(quad_sync == 1)
      {
        document.getElementById("vid_sts_sdi").innerHTML = quad_sync_3G_formats[video_format];
      }
      else
      {
        document.getElementById("vid_sts_sdi").innerHTML = quad_sync_HD_formats[video_format];
      }

      var sample_fmt = getText("SampleFormatSelect");
      document.getElementById("vid_sts_sample").innerHTML = sample_fmt;

      var delay_mode = getText("LowDelayModeSelect");
      document.getElementById("vid_sts_delay").innerHTML = delay_mode;

      var bit_depth = getText("BitDepthSelect");
      document.getElementById("vid_sts_depth").innerHTML = bit_depth;

      var chroma_fmt = getText("ChromaFormatSelect");
      document.getElementById("vid_sts_chroma").innerHTML = chroma_fmt;

      var FullRange = json_load.FullRange;
      var Colour = json_load.Colour;
      var Transfer = json_load.Transfer;
      var Matrix = json_load.Matrix;
      switch(FullRange) {
        case 1: document.getElementById("vid_sts_range").innerHTML = "Full"; break;
        default: document.getElementById("vid_sts_range").innerHTML = "Narrow"; break;
      }
      switch(Colour) {
        case 2: document.getElementById("vid_sts_colour").innerHTML = "Unspecified"; break;
        case 1: document.getElementById("vid_sts_colour").innerHTML = "Rec.709"; break;
        case 5: document.getElementById("vid_sts_colour").innerHTML = "Rec.601 625"; break;
        case 6: document.getElementById("vid_sts_colour").innerHTML = "Rec.601 525"; break;
        case 9: document.getElementById("vid_sts_colour").innerHTML = "Rec.2020"; break;
        default: document.getElementById("vid_sts_colour").innerHTML = Colour; break;
      }
      switch(Transfer) {
        case 2: document.getElementById("vid_sts_transfer").innerHTML = "Unspecified"; break;
        case 1: document.getElementById("vid_sts_transfer").innerHTML = "Rec.709 SDR"; break;
        case 6: document.getElementById("vid_sts_transfer").innerHTML = "Rec.601 SDR"; break;
        case 14: document.getElementById("vid_sts_transfer").innerHTML = "Rec.2020 SDR"; break;
        case 15: document.getElementById("vid_sts_transfer").innerHTML = "Rec.2020 SDR"; break;
        case 16: document.getElementById("vid_sts_transfer").innerHTML = "Rec.2100 PQ"; break;
        case 18: document.getElementById("vid_sts_transfer").innerHTML = "Rec.2100 HLG"; break;
        default: document.getElementById("vid_sts_transfer").innerHTML = Transfer; break;
      }
      switch(Matrix) {
        case 2: document.getElementById("vid_sts_matrix").innerHTML = "Unspecified"; break;
        case 1: document.getElementById("vid_sts_matrix").innerHTML = "Rec.709"; break;
        case 5: document.getElementById("vid_sts_matrix").innerHTML = "Rec.601 625"; break;
        case 6: document.getElementById("vid_sts_matrix").innerHTML = "Rec.601 525"; break;
        case 9: document.getElementById("vid_sts_matrix").innerHTML = ((Transfer==16)||(Transfer==18))?"Rec.2100 YCbCr":"Rec.2020 NCL"; break;
        case 10: document.getElementById("vid_sts_matrix").innerHTML = "Rec.2020 CL"; break;
        case 14: document.getElementById("vid_sts_matrix").innerHTML = "Rec.2100 ICtCp"; break;
        default: document.getElementById("vid_sts_matrix").innerHTML = Matrix; break;
      }

      var ser_name = getNumber("ServiceNameVal");
      document.getElementById("vid_sts_ser_name").innerHTML = ser_name;

      var prog_num = getNumber("ProgramNumberVal");
      document.getElementById("vid_sts_ser_id").innerHTML = prog_num;

      var vid_pid = getNumber("VideoPidVal");
      document.getElementById("vid_sts_pid").innerHTML = vid_pid;

      var ancillary_pid = getNumber("AncillaryPidVal");
      document.getElementById("ancillary_sts_pid").innerHTML = (getValue("AncillaryModeSelect")==0)?"-":ancillary_pid;

      var data_pid = getNumber("DataPidVal");
      document.getElementById("data_sts_pid").innerHTML = (getValue("DataModeSelect")==0)?"-":data_pid;

      var metadata_pid = getNumber("MetadataPidVal");
      document.getElementById("metadata_sts_pid").innerHTML = metadata_pid;

      var pcr_pid = getNumber("PCRPidVal");
      document.getElementById("pcr_sts_pid").innerHTML = pcr_pid;

      var pmt_pid = getNumber("PMTPidVal");
      document.getElementById("pmt_sts_pid").innerHTML = pmt_pid;

      var aud1_pid = getNumber("AudioPid0Val");
      document.getElementById("aud1_sts_pid").innerHTML = (getValue("AudioEncoder0Select")==0)?"-":aud1_pid;

      var aud2_pid = getNumber("AudioPid1Val");
      document.getElementById("aud2_sts_pid").innerHTML = (getValue("AudioEncoder1Select")==0)?"-":aud2_pid;

      var aud3_pid = getNumber("AudioPid2Val");
      document.getElementById("aud3_sts_pid").innerHTML = (getValue("AudioEncoder2Select")==0)?"-":aud3_pid;

      var aud4_pid = getNumber("AudioPid3Val");
      document.getElementById("aud4_sts_pid").innerHTML = (getValue("AudioEncoder3Select")==0)?"-":aud4_pid;

      var aud5_pid = getNumber("AudioPid4Val");
      document.getElementById("aud5_sts_pid").innerHTML = (getValue("AudioEncoder4Select")==0)?"-":aud5_pid;

      var aud6_pid = getNumber("AudioPid5Val");
      document.getElementById("aud6_sts_pid").innerHTML = (getValue("AudioEncoder5Select")==0)?"-":aud6_pid;

      var aud7_pid = getNumber("AudioPid6Val");
      document.getElementById("aud7_sts_pid").innerHTML = (getValue("AudioEncoder6Select")==0)?"-":aud7_pid;

      var aud8_pid = getNumber("AudioPid7Val");
      document.getElementById("aud8_sts_pid").innerHTML = (getValue("AudioEncoder7Select")==0)?"-":aud8_pid;

      if(getValue("RecordEnable") == 0)
      {
          document.getElementById("rec_sts").innerHTML = "DISABLED";
          document.getElementById("rec_sts").classList.remove("low");
          document.getElementById("rec_sts").classList.remove("med");
          document.getElementById("rec_sts").classList.remove("high");
      }
	  else
	  {
		  document.getElementById("rec_sts").innerHTML = document.getElementById("recorder_state").innerHTML.toUpperCase();
          var RecorderState = json_load.RecorderState;
		  var errorLevel = "high";
		  if((RecorderState==1)||(RecorderState==2))
              errorLevel = "med";
          else if((RecorderState==3))
              errorLevel = "low";

          document.getElementById("rec_sts").classList.remove("low");
          document.getElementById("rec_sts").classList.remove("med");
          document.getElementById("rec_sts").classList.remove("high");
          document.getElementById("rec_sts").classList.add(errorLevel);
	  }

      if(getValue("IPStreamEnable") != 1)
      {
          document.getElementById("ip_tx_sts").innerHTML = "DISABLED";
          document.getElementById("ip_tx_sts").classList.remove("low");
          document.getElementById("ip_tx_sts").classList.remove("med");
          document.getElementById("ip_tx_sts").classList.remove("high");
      }
      else if(stream_interface_get[getValue("IPStreamInterface")] == 2) // DTM-3200
      {
          document.getElementById("ip_tx_sts").innerHTML = ((getValue("IPStreamProtocol")==0)?"UDP":"RTP") + ((getValue("IPFECEnable")==0)?"":"+FEC");
          var errorLevel = "low";
		  if((json_load.DtmTxResolved!=0))
              errorLevel = "med";
          if((json_load.DtmTxBitrate==0))
              errorLevel = "high";

          document.getElementById("ip_tx_sts").classList.remove("low");
          document.getElementById("ip_tx_sts").classList.remove("med");
          document.getElementById("ip_tx_sts").classList.remove("high");
          document.getElementById("ip_tx_sts").classList.add(errorLevel);
      }
      else if(getValue("IPStreamProtocol") == 2) // SRT
	  {
		  document.getElementById("ip_tx_sts").innerHTML = "SRT";
		  var errorLevel = "low";
		  if(document.getElementById("srt_connect").innerHTML != "Connected")
              errorLevel = "high";

		  document.getElementById("ip_tx_sts").classList.remove("low");
		  document.getElementById("ip_tx_sts").classList.remove("med");
		  document.getElementById("ip_tx_sts").classList.remove("high");
		  document.getElementById("ip_tx_sts").classList.add(errorLevel);
	  }
	  else
	  {
		  document.getElementById("ip_tx_sts").innerHTML = ((getValue("IPStreamProtocol")==0)?"UDP":"RTP") + ((getValue("IPFECEnable")==0)?"":"+FEC");
          document.getElementById("ip_tx_sts").classList.add("low");
          document.getElementById("ip_tx_sts").classList.remove("med");
          document.getElementById("ip_tx_sts").classList.remove("high");
	  }

      var asi_output_rate = (json_load.SystemBitrate)/1000;
      document.getElementById("asi_sts_rate").innerHTML = asi_output_rate.toFixed(3)+" Mb/s";

      var vid_rate = (json_load.VideoBitrate)/1000;
      document.getElementById("vid_sts_rate").innerHTML = vid_rate.toFixed(3)+" Mb/s";

      var enc_mode = getText("EncodeModeSelect");
      document.getElementById("vid_sts_mode").innerHTML = enc_mode;
    
      var asi_input_rate = (json_load.ASIBitrate)/1000;
      if(json_load.ASILock == '1') // may be overwriten by IP lock status
      {
        document.getElementById("asi_lock").innerHTML = asi_input_rate.toFixed(3)+" Mb/s";
      if(asi_input_rate > asi_output_rate)
      {
          document.getElementById("asi_lock").classList.remove("low");
          document.getElementById("asi_lock").classList.add("med");
      }
      else
      {
          document.getElementById("asi_lock").classList.add("low");
          document.getElementById("asi_lock").classList.remove("med");
      }
        document.getElementById("asi_lock").classList.remove("high");
      }
      else
      {
        document.getElementById("asi_lock").innerHTML = "NO LOCK";
        document.getElementById("asi_lock").classList.remove("low");
        document.getElementById("asi_lock").classList.remove("med");
        document.getElementById("asi_lock").classList.add("high");
      }

      var fpga_temp =  json_load.FPGATemp;
      document.getElementById("unit_sts_temp1").innerHTML = fpga_temp+" &deg;C";
      if(fpga_temp > 85)
      {
        document.getElementById("unit_sts_temp1").classList.remove("low");
        document.getElementById("unit_sts_temp1").classList.remove("med");
        document.getElementById("unit_sts_temp1").classList.add("high");
      }
      else if(fpga_temp > 75)
      {
        document.getElementById("unit_sts_temp1").classList.remove("low");
        document.getElementById("unit_sts_temp1").classList.add("med");
        document.getElementById("unit_sts_temp1").classList.remove("high");
      }
      else
      {
        document.getElementById("unit_sts_temp1").classList.add("low");
        document.getElementById("unit_sts_temp1").classList.remove("med");
        document.getElementById("unit_sts_temp1").classList.remove("high");
      }

	  var psu_temp =  json_load.PSUTemp;
	  document.getElementById("unit_sts_temp2").innerHTML = psu_temp+" &deg;C";
	  if(psu_temp > 125)
	  {
		document.getElementById("unit_sts_temp2").classList.remove("low");
		document.getElementById("unit_sts_temp2").classList.remove("med");
		document.getElementById("unit_sts_temp2").classList.add("high");
	  }
	  else if(psu_temp > 85)
	  {
		document.getElementById("unit_sts_temp2").classList.remove("low");
		document.getElementById("unit_sts_temp2").classList.add("med");
		document.getElementById("unit_sts_temp2").classList.remove("high");
	  }
	  else
	  {
		document.getElementById("unit_sts_temp2").classList.add("low");
		document.getElementById("unit_sts_temp2").classList.remove("med");
		document.getElementById("unit_sts_temp2").classList.remove("high");
	  }

      var in_volt =  json_load.InVoltage;
      var hi_lev1 = 17.5;
      var hi_lev2 = 17.9;
      var hi_lev3 = 18;

      if(BoardType == "B160" || BoardType == "B300")
      {
		  hi_lev1 = hi_lev1+18;
		  hi_lev2 = hi_lev1+18;
		  hi_lev3 = hi_lev1+18;
	  }

      document.getElementById("unit_sts_volt_in").innerHTML = in_volt+" V";
      if(in_volt > hi_lev1 && in_volt < hi_lev3)
      {
        document.getElementById("unit_sts_volt_in").classList.remove("low");
        document.getElementById("unit_sts_volt_in").classList.add("med");
        document.getElementById("unit_sts_volt_in").classList.remove("high");
      }
      else if(in_volt < 9.5 && in_volt > 9)
      {
        document.getElementById("unit_sts_volt_in").classList.remove("low");
        document.getElementById("unit_sts_volt_in").classList.add("med");
        document.getElementById("unit_sts_volt_in").classList.remove("high");
      }
      else if(in_volt > hi_lev2 || in_volt < 9.1)
      {
        document.getElementById("unit_sts_volt_in").classList.remove("low");
        document.getElementById("unit_sts_volt_in").classList.remove("med");
        document.getElementById("unit_sts_volt_in").classList.add("high");
      }
      else
      {
        document.getElementById("unit_sts_volt_in").classList.add("low");
        document.getElementById("unit_sts_volt_in").classList.remove("med");
        document.getElementById("unit_sts_volt_in").classList.remove("high");
      }

      document.getElementById("quadsync_delay1").innerHTML = json_load.GenlockDelay1 + " us";
      document.getElementById("quadsync_delay2").innerHTML = json_load.GenlockDelay2 + " us";
      document.getElementById("quadsync_delay3").innerHTML = json_load.GenlockDelay3 + " us";
      document.getElementById("quadsync_delay4").innerHTML = json_load.GenlockDelay4 + " us";

      var controller_ver = json_load.ControllerVersion;
      document.getElementById("controller_ver").innerHTML = controller_ver;
      document.getElementById("controller_ver_row").style.display = (controller_ver == "")?"none":"inline-block";
      document.getElementById("ControllerUpgrade").style.display = (controller_ver == "")?"none":"inline-block";

      var FPGAHash = json_load.FPGAHash;
      document.getElementById("fpga_ver_row").style.display = (FPGAHash === undefined || FPGAHash == "ffffffff")?"none":"inline-block";
      document.getElementById('fpga_ver').innerHTML = json_load.FPGAHash;

      var lic_msk = json_load.LicenseMask;
      var lic_bits = parseInt(lic_msk,16);
      document.getElementById("lic_encode"      ).classList.toggle("rightLicDisable", ((lic_bits&0x00000001)==0));
      document.getElementById("lic_decode"      ).classList.toggle("rightLicDisable", ((lic_bits&0x00000002)==0));
      document.getElementById("lic_hevc"        ).classList.toggle("rightLicDisable", ((lic_bits&0x00000004)==0));
      document.getElementById("lic_h264"        ).classList.toggle("rightLicDisable", ((lic_bits&0x00000008)==0));
      document.getElementById("lic_mpeg2"       ).classList.toggle("rightLicDisable", ((lic_bits&0x00000010)==0));
      document.getElementById("lic_ull"         ).classList.toggle("rightLicDisable", ((lic_bits&0x00000020)==0));
      document.getElementById("lic_uhd"         ).classList.toggle("rightLicDisable", ((lic_bits&0x00000040)==0));
      document.getElementById("lic_422"         ).classList.toggle("rightLicDisable", ((lic_bits&0x00000080)==0));
      document.getElementById("lic_10bit"       ).classList.toggle("rightLicDisable", ((lic_bits&0x00000100)==0));
      document.getElementById("lic_quadsync"    ).classList.toggle("rightLicDisable", ((lic_bits&0x00000200)==0));
      document.getElementById("lic_psf"         ).classList.toggle("rightLicDisable", ((lic_bits&0x00000400)==0));
      document.getElementById("lic_dolby"       ).classList.toggle("rightLicDisable", ((lic_bits&0x00000800)==0));
      document.getElementById("lic_des"         ).classList.toggle("rightLicDisable", ((lic_bits&0x00001000)==0));
      document.getElementById("lic_biss"        ).classList.toggle("rightLicDisable", ((lic_bits&0x00004000)==0));
      document.getElementById("lic_ipstream"    ).classList.toggle("rightLicDisable", ((lic_bits&0x00008000)==0));
      document.getElementById("lic_ipdecode"    ).classList.toggle("rightLicDisable", ((lic_bits&0x00010000)==0));
      document.getElementById("lic_layer1"      ).classList.toggle("rightLicDisable", ((lic_bits&0x00020000)==0));
      document.getElementById("lic_4kdci"       ).classList.toggle("rightLicDisable", ((lic_bits&0x00040000)==0));
      document.getElementById("lic_record"      ).classList.toggle("rightLicDisable", ((lic_bits&0x00080000)==0));
      document.getElementById("lic_interleaver" ).classList.toggle("rightLicDisable", ((lic_bits&0x00100000)==0));

	  if(TxPresent == TX_PRESENT_D1550 || TxPresent == TX_PRESENT_D1837)
	  {
        document.getElementById("LicenceTransmitRow").style.display = "none";
        document.getElementById("LicenceD15xxRow").style.display = "inline-block";
        document.getElementById("lic_dualped").style.display = (TxPresent == TX_PRESENT_D1837)?"none":"inline-block";
	  }
	  else if(TxPresent == TX_PRESENT_B170 || TxPresent == TX_PRESENT_B160_B170)
	  {
        document.getElementById("LicenceTransmitRow").style.display = "inline-block";
        document.getElementById("LicenceD15xxRow").style.display = "none";
	  }
	  else if(TxPresent == TX_PRESENT_B170_D1550)
	  {
        document.getElementById("LicenceTransmitRow").style.display = "inline-block";
        document.getElementById("LicenceD15xxRow").style.display = "inline-block";
        document.getElementById("LicenceD15xxRowHeader").style.display = "none";
	  }
	  else
	  {
        document.getElementById("LicenceTransmitRow").style.display = "none";
        document.getElementById("LicenceD15xxRow").style.display = "none";
	  }

	  if(TxPresent == TX_PRESENT_D1550 || TxPresent == TX_PRESENT_D1837 || TxPresent == TX_PRESENT_B170_D1550)
	  {
		var tx_lic_msk = json_load.TxLicenseMask;
        document.getElementById("tx_software_ver").innerHTML = "v" + json_load.TxSwVersion;
        document.getElementById("tx_serial_num").innerHTML = json_load.TxSerialNum;
        document.getElementById("tx_lic_msk").innerHTML = tx_lic_msk;

        var tx_lic_bits = parseInt(tx_lic_msk,16);
        document.getElementById("lic_solo25" ).classList.toggle("rightLicDisable", ((tx_lic_bits&0x00000001)==0));
        document.getElementById("lic_solo125").classList.toggle("rightLicDisable", ((tx_lic_bits&0x00000002)==0));
        document.getElementById("lic_solo625").classList.toggle("rightLicDisable", ((tx_lic_bits&0x00000004)==0));
        document.getElementById("lic_umvl"   ).classList.toggle("rightLicDisable", ((tx_lic_bits&0x00000010)==0));
        document.getElementById("lic_dvbt"   ).classList.toggle("rightLicDisable", ((tx_lic_bits&0x00000020)==0));
        document.getElementById("lic_dualped").classList.toggle("rightLicDisable", ((tx_lic_bits&0x00020000)==0));
	  }
	  else if(TxPresent == TX_PRESENT_B160_B170)
      {
		var tx_lic_msk = json_load.TxLicenseMask;
        document.getElementById("tx_software_ver").innerHTML = json_load.TxSwVersion;
        document.getElementById("tx_serial_num").innerHTML = json_load.TxSerialNum;
        document.getElementById("tx_lic_msk").innerHTML = tx_lic_msk;

        var tx_lic_bits = parseInt(tx_lic_msk,16);
        document.getElementById("lic_interleaver").classList.toggle("rightLicDisable", ((tx_lic_bits&0x00100000)==0));
      }

	  if(TxPresent == TX_PRESENT_D1550 || TxPresent == TX_PRESENT_B160_B170)
      {
        document.getElementById("tx_rf_band1").innerHTML = json_load.TxMinFreq.split(".")[0] + " - " + json_load.TxMaxFreq.split(".")[0] + " MHz";
      }
      else if(TxPresent == TX_PRESENT_D1837)
      {
        document.getElementById("tx_rf_band1").innerHTML = "1980 - 2700 MHz";
        document.getElementById("tx_rf_band2").innerHTML = "6400 - 7500 MHz";
      }
      else if(TxPresent == TX_PRESENT_B170_D1550)
      {
        document.getElementById("tx_rf_band2").innerHTML = json_load.TxMinFreq.split(".")[0] + " - " + json_load.TxMaxFreq.split(".")[0] + " MHz";
      }

      if(TxPresent > TX_PRESENT_NONE)
      {
        var tx_temp = parseInt(json_load.TxTemp);
        document.getElementById("tx_temp").innerHTML = tx_temp.toFixed(1)+" &deg;C";
        if(tx_temp > 85)
        {
          document.getElementById("tx_temp").classList.remove("low");
          document.getElementById("tx_temp").classList.remove("med");
          document.getElementById("tx_temp").classList.add("high");
        }
        else if(tx_temp > 75)
        {
          document.getElementById("tx_temp").classList.remove("low");
          document.getElementById("tx_temp").classList.add("med");
          document.getElementById("tx_temp").classList.remove("high");
        }
        else
        {
          document.getElementById("tx_temp").classList.add("low");
          document.getElementById("tx_temp").classList.remove("med");
          document.getElementById("tx_temp").classList.remove("high");
        }
      }
    }
  );
  get_json.open("GET", "/sts/UnitStatus.json",sync_flag);
  get_json.setRequestHeader('Cache-Control', 'no-cache')
  get_json.setRequestHeader('Pragma', 'no-cache')
  get_json.setRequestHeader('Expires', '0')
  get_json.send();
}

function getSRTStatus()
{
  var get_json = new XMLHttpRequest();
  get_json.addEventListener("load", (e) =>
  {
    var json_load = JSON.parse(e.target.responseText);
    var SrtConnected = json_load.SrtConnected;
    var SrtRemoteAddress = json_load.SrtRemoteAddress;
    var PublicIPAddress = json_load.PublicIPAddress;

	if(SrtConnected != 1)
	{
		//document.getElementById("b110_public_ip").innerHTML = PublicIPAddress;
		document.getElementById("srt_connect").innerHTML = "Not Connected";
		document.getElementById("srt_host").innerHTML = "-";
		document.getElementById("srt_delay").innerHTML = "-";
		document.getElementById("mbpsSendRate").innerHTML = "-";
		document.getElementById("pktSentTotal").innerHTML = "-";
		document.getElementById("pktSndDropTotal").innerHTML = "-";
		document.getElementById("pktSndLoss").innerHTML = "-";
		document.getElementById("pktRetrans").innerHTML = "-";
		document.getElementById("msSndBuf").innerHTML = "-";
		document.getElementById("msRTT").innerHTML = "-";
	}
	else // transmit
	{
        var msSndTsbPdDelay =  json_load.msSndTsbPdDelay;
        var mbpsSendRate =  json_load.mbpsSendRate;
        var pktSentTotal =  json_load.pktSentTotal;
        var pktSndDropTotal =  json_load.pktSndDropTotal;
        var pktSndLoss =  json_load.pktSndLoss;
        var pktRetrans =  json_load.pktRetrans;
        var msSndBuf =  json_load.msSndBuf;
        var msRTT =  json_load.msRTT;

		//document.getElementById("b110_public_ip").innerHTML = PublicIPAddress;
		document.getElementById("srt_connect").innerHTML = "Connected";
		document.getElementById("srt_host").innerHTML = SrtRemoteAddress;
		document.getElementById("srt_delay").innerHTML = msSndTsbPdDelay + " ms";
		document.getElementById("mbpsSendRate").innerHTML = (mbpsSendRate).toFixed(3) + " Mb/s";
		document.getElementById("pktSentTotal").innerHTML = pktSentTotal;
		document.getElementById("pktSndDropTotal").innerHTML = pktSndDropTotal;
		document.getElementById("pktSndLoss").innerHTML = pktSndLoss + " (" + ((pktSndLoss/pktSentTotal)*100).toFixed(2) + "%)";
		document.getElementById("pktRetrans").innerHTML = pktRetrans + " (" + ((pktRetrans/pktSentTotal)*100).toFixed(2) + "%)";
		document.getElementById("msSndBuf").innerHTML = msSndBuf + " ms";
		document.getElementById("msRTT").innerHTML = msRTT + " ms";
	}

//	mySRTCanvas();
  }
);
get_json.open("GET", "/sts/SRTStatus.json", true);
get_json.setRequestHeader('Cache-Control', 'no-cache')
get_json.setRequestHeader('Pragma', 'no-cache')
get_json.setRequestHeader('Expires', '0')
get_json.send();
}

function getUnit()
{
  var get_json = new XMLHttpRequest();
  get_json.addEventListener ("load", (e) =>
  {
    var json_load = JSON.parse(e.target.responseText);
    PresetNumber = json_load.PresetNumber;
    B120Present = json_load.B120Present;
    B180Present = json_load.B180Present;
    RFDcBiasPresent = json_load.RFDcBiasPresent;
    DTM3200Present = json_load.DTM3200Present;
    var UnitMode = json_load.UnitMode;
    var UnitName = json_load.UnitName;
    var UnitAddress = json_load.UnitAddress;
    var DHCPMode0 = json_load.DHCPMode0;
    var IPAddress0 = json_load.IPAddress0;
    var IPGateway0 = json_load.IPGateway0;
    var IPMask0 = json_load.IPMask0;
    var IPName0 = json_load.IPName0;
    var DHCPMode1 = json_load.DHCPMode1;
    var IPAddress1 = json_load.IPAddress1;
    var IPGateway1 = json_load.IPGateway1;
    var IPMask1 = json_load.IPMask1;
    var IPName1 = json_load.IPName1;
    var IPBridgingMode = json_load.IPBridgingMode;
    var FanMode = json_load.FanMode;
    var FanSpeedIdle = json_load.FanSpeedIdle;
    var FanSpeedRec = json_load.FanSpeedRec;
    var DtmDHCPMode = json_load.DtmDHCPMode;
    var DtmIPAddress = json_load.DtmIPAddress;
    var DtmIPGateway = json_load.DtmIPGateway;
    var DtmIPMask = json_load.DtmIPMask;
    var ProductName = json_load.ProductName;
    var TxPresent = json_load.TxPresent;
    var B120Present = json_load.B120Present;
    var DTM3200Present = json_load.DTM3200Present;
    var OLEDType = json_load.OLEDType;
    var B180Present = json_load.B180Present;
    var RFDcBiasPresent = json_load.RFDcBiasPresent;
    var RFBand = json_load.RFBand;
    var ModemBand = json_load.ModemBand;
    var HubIPAddress = json_load.HubIPAddress;
    var TSLAddress = json_load.TSLAddress;

    headerChange(ProductName,UnitName,TxPresent);

    setSelectValue("UnitModeSelect",UnitMode);
    setNumber("UnitName",UnitName);
    setNumber("UnitAddress",UnitAddress);
	document.getElementById("UnitAddressRow").style.display = (CustID == "000076b6")?"inline-block":"none";

    document.getElementById("IPName0Head").innerHTML = "Ethernet " + IPName0;
	if(IPName0 == "")
		document.getElementById("EthernetOne").style.display = "none";
	else
		document.getElementById("EthernetOne").style.display = "inline-block";

    setSelectValue("DHCPModeSelect0",DHCPMode0);
    setNumber("IPAddr0",IPAddress0);
    setNumber("IPGateway0",IPGateway0);
    setNumber("IPMask0",IPMask0);
    setNumber("IPName0",IPName0);
	ethDHCPChange(0);

    document.getElementById("IPName1Head").innerHTML = "Ethernet " + IPName1;
	if(IPName1 == "")
		document.getElementById("EthernetTwo").style.display = "none";
	else
		document.getElementById("EthernetTwo").style.display = "inline-block";

    setSelectValue("DHCPModeSelect1",DHCPMode1);
    setNumber("IPAddr1",IPAddress1);
    setNumber("IPGateway1",IPGateway1);
    setNumber("IPMask1",IPMask1);
    setNumber("IPName1",IPName1);
	ethDHCPChange(1);

	if((IPName0 == "") || (IPName1 == ""))
		document.getElementById("IPBridgeSelectRow").style.display = "none";
	else
		document.getElementById("IPBridgeSelectRow").style.display = "inline-block";

    setSelectValue("IPBridgeSelect",IPBridgingMode);
    setSelectValue("FanModeSelect",FanMode);
    setSelectValue("FanSpeedIdleSelect",FanSpeedIdle);
    setSelectValue("FanSpeedRecSelect",FanSpeedRec);

    setSelectValue("DtmDHCPModeSelect",DtmDHCPMode);
    setNumber("DtmIPAddress",DtmIPAddress);
    setNumber("DtmIPGateway",DtmIPGateway);
    setNumber("DtmIPMask",DtmIPMask);
	dtmDHCPChange();

    setSelectValue("TxPresentSelect",TxPresent);
    setSelectValue("B120PresentSelect",B120Present);
    setSelectValue("B180PresentSelect",B180Present);
    setSelectValue("RFDCBiasPresentSelect",RFDcBiasPresent);
    setSelectValue("DTM3200PresentSelect",DTM3200Present);
    setSelectValue("OLEDTypeSelect",OLEDType);
    setSelectValue("RFBandwidthSelect",RFBand+1);
    setSelectValue("ModemBandwidthSelect",ModemBand);

    setNumber("CustIDVal",parseInt(CustID,16));

    setNumber("HubIPAddress", HubIPAddress);
    setNumber("TSLAddress", TSLAddress);

  }
  );
  get_json.open("GET", "/config/UnitParamsList.json");
  get_json.setRequestHeader('Cache-Control', 'no-cache')
  get_json.setRequestHeader('Pragma', 'no-cache')
  get_json.setRequestHeader('Expires', '0')
  get_json.send();
}

function getEncode()
{
  var get_json = new XMLHttpRequest();
  get_json.addEventListener ("load", (e) =>
  {
    var json_load = JSON.parse(e.target.responseText);
    var EncodeMode = json_load.EncodeMode;
    var VideoFormat = json_load.VideoFormat;
    var VideoSource = json_load.VideoSource;
    var HDRWCGMode = json_load.HDRWCGMode;
    var ChromaFormat = json_load.ChromaFormat;
    var BitDepth = json_load.BitDepth;
    var SampleFormat = json_load.SampleFormat;
    var LowDelayMode = json_load.LowDelayMode;
    var EncodeMode = json_load.EncodeMode;
    var SynergyMode = json_load.SynergyMode;
    var VideoBitrate = json_load.VideoBitrate;
    var AncillaryBitrate = json_load.AncillaryBitrate;
    var SystemBitrate = json_load.SystemBitrate;
    var AudioSource0 = json_load.AudioSource0;
    var AudioEncoder0 = json_load.AudioEncoder0;
    var AudioBitrate0 = json_load.AudioBitrate0;
    var AudioRefLevel0 = json_load.AudioRefLevel0;
    var AudioGainLeft0 = (json_load.AudioGainLeft0)/2;
    var AudioGainRight0 = (json_load.AudioGainRight0)/2;
    var AudioP48EnableL0 = json_load.AudioP48EnableL0;
    var AudioP48EnableR0 = json_load.AudioP48EnableR0;
    var AudioSource1 = json_load.AudioSource1;
    var AudioEncoder1 = json_load.AudioEncoder1;
    var AudioBitrate1 = json_load.AudioBitrate1;
    var AudioRefLevel1 = json_load.AudioRefLevel1;
    var AudioGainLeft1 = (json_load.AudioGainLeft1)/2;
    var AudioGainRight1 = (json_load.AudioGainRight1)/2;
    var AudioP48EnableL1 = json_load.AudioP48EnableL1;
    var AudioP48EnableR1 = json_load.AudioP48EnableR1;
    var AudioSource2 = json_load.AudioSource2;
    var AudioEncoder2 = json_load.AudioEncoder2;
    var AudioBitrate2 = json_load.AudioBitrate2;
    var AudioSource3 = json_load.AudioSource3;
    var AudioEncoder3 = json_load.AudioEncoder3;
    var AudioBitrate3 = json_load.AudioBitrate3;
    var AudioSource4 = json_load.AudioSource4;
    var AudioEncoder4 = json_load.AudioEncoder4;
    var AudioBitrate4 = json_load.AudioBitrate4;
    var AudioSource5 = json_load.AudioSource5;
    var AudioEncoder5 = json_load.AudioEncoder5;
    var AudioBitrate5 = json_load.AudioBitrate5;
    var AudioSource6 = json_load.AudioSource6;
    var AudioEncoder6 = json_load.AudioEncoder6;
    var AudioBitrate6 = json_load.AudioBitrate6;
    var AudioSource7 = json_load.AudioSource7;
    var AudioEncoder7 = json_load.AudioEncoder7;
    var AudioBitrate7 = json_load.AudioBitrate7;
    var ProgramNumber = json_load.ProgramNumber;
    var ServiceName = json_load.ServiceName;
    var VideoPid = json_load.VideoPid;
    var AudioPid0 = json_load.AudioPid0;
    var AudioPid1 = json_load.AudioPid1;
    var AudioPid2 = json_load.AudioPid2;
    var AudioPid3 = json_load.AudioPid3;
    var AudioPid4 = json_load.AudioPid4;
    var AudioPid5 = json_load.AudioPid5;
    var AudioPid6 = json_load.AudioPid6;
    var AudioPid7 = json_load.AudioPid7;
    var AncillaryPid = json_load.AncillaryPid;
    var MetadataPid = json_load.MetadataPid;
    var DataPid = json_load.DataPid;
    var PCRPid = json_load.PCRPid;
    var PMTPid = json_load.PMTPid;
    var DESMode = json_load.DESMode;
    var DESKey = json_load.DESKey;
    var AncillaryMode = json_load.AncillaryMode;
    var DataMode = json_load.DataMode;
    var DataBaudrate = json_load.DataBaudrate;
    var RemuxMode = json_load.RemuxMode;
    var BISSMode = json_load.BISSMode;
    var BISSKey = json_load.BISSKey;
    var RecordEnable = json_load.RecordEnable;
    var IPStreamEnable = json_load.IPStreamEnable;
    var IPStreamInterface = json_load.IPStreamInterface-1;
    var IPStreamAddress = json_load.IPStreamAddress;
    var IPStreamPort = json_load.IPStreamPort;
    var IPStreamTTL = json_load.IPStreamTTL;
    var IPStreamNumTP = json_load.IPStreamNumTP-1;
    var IPStreamProtocol = json_load.IPStreamProtocol;
    var SRTMode = json_load.SRTMode;
    var SRTDelay = json_load.SRTDelay;
    var IPFECEnable = json_load.IPFECEnable;
    var IPFECCols = json_load.IPFECCols;
    var IPFECRows = json_load.IPFECRows;
    var SpatialFilter = json_load.SpatialFilter;
    var CPBDelay = json_load.CPBDelay;

    var vid_src_map = [0,1,2,3,4,5,6]
    var aud_src_map0 = [0,2,3,1]
    var aud_src_map1 = [0,2,4,1,3]

	if(BoardType == "B160" || BoardType == "B300")
	{
      vid_src_map = [0,0,0,0,0,1,2]
	  aud_src_map0 = [0,1,2,0]
	  aud_src_map1 = [0,1,2,0,1]

	  videoSourceB160();
	  audioSourceB160();
	}

    var audio_enc_map = [0,1,4,5,6,2,3]
    var audio_enc_map4 = [0,1,0,4,5,2,3]

	var CPBDelayStep = getCPBDelayStep(EncodeMode, LowDelayMode);

    setSelectValue("VideoFormatSelect",VideoFormat);
    setSelectValue("VideoSourceSelect",vid_src_map[VideoSource]);
    setSelectValue("VideoBitrateSelect",(VideoBitrate==0)?0:1);
    setSelectValue("HDRWCGModeSelect",HDRWCGMode);
    setSelectValue("ChromaFormatSelect",ChromaFormat);
    setSelectValue("BitDepthSelect",BitDepth);
    setSelectValue("SampleFormatSelect",SampleFormat);
    setSelectValue("LowDelayModeSelect",LowDelayMode);
    setSelectValue("EncodeModeSelect",EncodeMode);
    setSelectValue("QuadSyncSelect",SynergyMode);
    setNumber("AncillaryBitrateVal",AncillaryBitrate);
    setNumber("SystemBitrateVal",SystemBitrate);
    setSelectValue("AudioSource0Select",aud_src_map0[AudioSource0]);
    setSelectValue("AudioEncoder0Select",audio_enc_map[AudioEncoder0]);
    setSelectValue("AudioBitrate0Select",AudioBitrate0);
    setSelectValue("AudioRefLevel0Select",AudioRefLevel0);
    setNumber("AudioGainL0Val",AudioGainLeft0.toFixed(1));
    setNumber("AudioGainR0Val",AudioGainRight0.toFixed(1));
    setSelectValue("AudioP48EnableL0Select",AudioP48EnableL0);
    setSelectValue("AudioP48EnableR0Select",AudioP48EnableR0);
    setSelectValue("AudioSource1Select",aud_src_map1[AudioSource1]);
    setSelectValue("AudioEncoder1Select",audio_enc_map[AudioEncoder1]);
    setSelectValue("AudioBitrate1Select",AudioBitrate1);
    setSelectValue("AudioRefLevel1Select",AudioRefLevel1);
    setNumber("AudioGainL1Val",AudioGainLeft1.toFixed(1));
    setNumber("AudioGainR1Val",AudioGainRight1.toFixed(1));
    setSelectValue("AudioP48EnableL1Select",AudioP48EnableL1);
    setSelectValue("AudioP48EnableR1Select",AudioP48EnableR1);
    setSelectValue("AudioSource2Select",aud_src_map1[AudioSource2]);
    setSelectValue("AudioEncoder2Select",audio_enc_map[AudioEncoder2]);
    setSelectValue("AudioBitrate2Select",AudioBitrate2);
    setSelectValue("AudioSource3Select",aud_src_map1[AudioSource3]);
    setSelectValue("AudioEncoder3Select",audio_enc_map[AudioEncoder3]);
    setSelectValue("AudioBitrate3Select",AudioBitrate3);
    setSelectValue("AudioSource4Select",aud_src_map1[AudioSource4]);
    setSelectValue("AudioEncoder4Select",audio_enc_map4[AudioEncoder4]);
    setSelectValue("AudioBitrate4Select",AudioBitrate4);
    setSelectValue("AudioSource5Select",aud_src_map1[AudioSource5]);
    setSelectValue("AudioEncoder5Select",audio_enc_map4[AudioEncoder5]);
    setSelectValue("AudioBitrate5Select",AudioBitrate5);
    setSelectValue("AudioSource6Select",aud_src_map1[AudioSource6]);
    setSelectValue("AudioEncoder6Select",audio_enc_map4[AudioEncoder6]);
    setSelectValue("AudioBitrate6Select",AudioBitrate6);
    setSelectValue("AudioSource7Select",aud_src_map1[AudioSource7]);
    setSelectValue("AudioEncoder7Select",audio_enc_map4[AudioEncoder7]);
    setSelectValue("AudioBitrate7Select",AudioBitrate7);
    setNumber("ProgramNumberVal",ProgramNumber);
    setNumber("ServiceNameVal",ServiceName);
    setNumber("VideoPidVal",VideoPid);
    setNumber("AudioPid0Val",AudioPid0);
    setNumber("AudioPid1Val",AudioPid1);
    setNumber("AudioPid2Val",AudioPid2);
    setNumber("AudioPid3Val",AudioPid3);
    setNumber("AudioPid4Val",AudioPid4);
    setNumber("AudioPid5Val",AudioPid5);
    setNumber("AudioPid6Val",AudioPid6);
    setNumber("AudioPid7Val",AudioPid7);
    setNumber("AncillaryPidVal",AncillaryPid);
    setNumber("MetadataPidVal",MetadataPid);
    setNumber("DataPidVal",DataPid);
    setNumber("PCRPidVal",PCRPid);
    setNumber("PMTPidVal",PMTPid);
    setSelectValue("RemuxModeSelect",RemuxMode);
    setSelectValue("DESModeSelect",DESMode);
    setNumber("DESKeyVal",DESKey);
    setSelectValue("AncillaryModeSelect",AncillaryMode);
    setSelectValue("DataModeSelect",DataMode);
    setSelectValue("DataBaudSelect",DataBaudrate);
    setSelectValue("BISSModeSelect",BISSMode);
    setNumber("BISSKeyVal",BISSKey);
    setSelectValue("RecordEnable",RecordEnable);
    setSelectValue("IPStreamEnable",IPStreamEnable);
    setSelectValue("IPStreamInterface",stream_interface_set[IPStreamInterface]);
    setNumber("IPStreamAddress",IPStreamAddress);
    setNumber("IPStreamPort",IPStreamPort);
    setNumber("IPStreamTTL",IPStreamTTL);
    setSelectValue("IPStreamNumTP",IPStreamNumTP);
    setSelectValue("IPStreamProtocol",IPStreamProtocol);
    setSelectValue("IPFECEnable",IPFECEnable);
    setNumber("IPFECCols",IPFECCols);
    setNumber("IPFECRows",IPFECRows)
    setSelectValue("SRTMode",SRTMode);
    setNumber("SRTDelay",SRTDelay);
    setNumber("SpatialFilter",SpatialFilter);
	setNumber("CPBDelay",CPBDelay/CPBDelayStep);
    videoDelayModeChange();
    videoBitrateModeChange(VideoBitrate);
    ancillaryModeChange();
	ipInterfaceChange();
	videoQuadSyncChange();
	audioModeChange(0);
	audioModeChange(1);
	audioModeChange(2);
	audioModeChange(3);
	audioModeChange(4);
	audioModeChange(5);
	audioModeChange(6);
	audioModeChange(7);
	dataModeChange();
  }
);
get_json.open("GET", "/config/EncoderParamsList.json");
get_json.setRequestHeader('Cache-Control', 'no-cache')
get_json.setRequestHeader('Pragma', 'no-cache')
get_json.setRequestHeader('Expires', '0')
get_json.send();
}

function setUnit()
{
  var json_send;
  var set_json = new XMLHttpRequest();
  var url = "/cgi-bin/set_unit_val.cgi";
  var str_val = {
    UnitMode: parseInt(getValue("UnitModeSelect")),
    UnitName: getNumber("UnitName"),
    UnitAddress: parseInt(getNumber("UnitAddress")),
    DHCPMode0: parseInt(getValue("DHCPModeSelect0")),
    IPAddress0: getNumber("IPAddr0"),
    IPGateway0: getNumber("IPGateway0"),
    IPMask0: getNumber("IPMask0"),
    IPName0: getNumber("IPName0"),
    DHCPMode1: parseInt(getValue("DHCPModeSelect1")),
    IPAddress1: getNumber("IPAddr1"),
    IPGateway1: getNumber("IPGateway1"),
    IPMask1: getNumber("IPMask1"),
    IPName1: getNumber("IPName1"),
    IPBridgingMode: parseInt(getValue("IPBridgeSelect")),
    FanMode: parseInt(getValue("FanModeSelect")),
    FanSpeedIdle: parseInt(getValue("FanSpeedIdleSelect")),
    FanSpeedRec: parseInt(getValue("FanSpeedRecSelect")),
    DtmDHCPMode: parseInt(getValue("DtmDHCPModeSelect")),
    DtmIPAddress: getNumber("DtmIPAddress"),
    DtmIPGateway: getNumber("DtmIPGateway"),
    DtmIPMask: getNumber("DtmIPMask"),
    TxPresent: parseInt(getValue("TxPresentSelect")),
    B120Present: parseInt(getValue("B120PresentSelect")),
    B180Present: parseInt(getValue("B180PresentSelect")),
    RFDcBiasPresent: parseInt(getValue("RFDCBiasPresentSelect")),
    DTM3200Present: parseInt(getValue("DTM3200PresentSelect")),
    OLEDType: parseInt(getValue("OLEDTypeSelect")),
    RFBand: parseInt(getValue("RFBandwidthSelect"))-1,
    ModemBand: parseInt(getValue("ModemBandwidthSelect")),
    HubIPAddress: getNumber("HubIPAddress"),
    TSLAddress: parseInt(getNumber("TSLAddress")),
  };
  json_send = JSON.stringify(str_val);
  set_json.addEventListener ("load", (e) =>
  {
    var reply = e.target.responseText;
    alert("Unit Changes Applied Successfully" + "\n" + reply.trim());
		document.getElementById('apply_unit').innerText = "Apply"
		document.getElementById('apply_unit').disabled = false
		getUnit()
  });
  set_json.open("POST", url, true);
  set_json.setRequestHeader("Content-type", "application/json");
  set_json.send(json_send);
}

function setEncoder()
{
  var json_send;
  var set_json = new XMLHttpRequest();
  var url = "/cgi-bin/set_enc_val.cgi";
  des_key_val = document.getElementById('DESKeyVal').value.toUpperCase();
  biss_key_val = document.getElementById('BISSKeyVal').value.toUpperCase();
  document.getElementById('DESKeyVal').value = des_key_val;
  document.getElementById('BISSKeyVal').value = biss_key_val;

  var vid_src_map = [0,1,2,3,4,5,6]
  var aud_src_map0 = [0,3,1,2]
  var aud_src_map1 = [0,3,1,4,2]

  if(BoardType == "B160" || BoardType == "B300")
  {
	  vid_src_map = [0,5,6]
	  aud_src_map0 = [0,1,2]
	  aud_src_map1 = [0,1,2]
  }

  var aud_enc_map = [0,1,5,6,2,3,4]
  var aud_enc_map4 = [0,1,5,6,3,4]

  VideoBitrateVal = parseInt(getNumber("VideoBitrateVal"));
  if(getValue("VideoBitrateSelect") == 0)
	VideoBitrateVal = 0;

  var CPBDelayStep = getCPBDelayStep(getValue("EncodeModeSelect"), getValue("LowDelayModeSelect"));

  var str_val = {
    VideoFormat: parseInt(getValue("VideoFormatSelect")),
    VideoSource: vid_src_map[getValue("VideoSourceSelect")],
    HDRWCGMode: parseInt(getValue("HDRWCGModeSelect")),
    ChromaFormat: parseInt(getValue("ChromaFormatSelect")),
    BitDepth: parseInt(getValue("BitDepthSelect")),
    SampleFormat: parseInt(getValue("SampleFormatSelect")),
    LowDelayMode: parseInt(getValue("LowDelayModeSelect")),
    EncodeMode: parseInt(getValue("EncodeModeSelect")),
    SynergyMode: parseInt(getValue("QuadSyncSelect")),
    VideoBitrate: VideoBitrateVal,
    AncillaryBitrate: parseInt(getNumber("AncillaryBitrateVal")),
    SystemBitrate: parseInt(getNumber("SystemBitrateVal")),
    AudioSource0: aud_src_map0[getValue("AudioSource0Select")],
    AudioEncoder0: aud_enc_map[getValue("AudioEncoder0Select")],
    AudioBitrate0: parseInt(getValue("AudioBitrate0Select")),
    AudioRefLevel0: parseInt(getValue("AudioRefLevel0Select")),
    AudioGainLeft0: parseInt(getNumber("AudioGainL0Val")*2),
    AudioGainRight0: parseInt(getNumber("AudioGainR0Val")*2),
    AudioP48EnableL0: parseInt(getValue("AudioP48EnableL0Select")),
    AudioP48EnableR0: parseInt(getValue("AudioP48EnableR0Select")),
    AudioSource1: aud_src_map1[getValue("AudioSource1Select")],
    AudioEncoder1: aud_enc_map[getValue("AudioEncoder1Select")],
    AudioBitrate1: parseInt(getValue("AudioBitrate1Select")),
    AudioRefLevel1: parseInt(getValue("AudioRefLevel1Select")),
    AudioGainLeft1: parseInt(getNumber("AudioGainL1Val")*2),
    AudioGainRight1: parseInt(getNumber("AudioGainR1Val")*2),
    AudioP48EnableL1: parseInt(getValue("AudioP48EnableL1Select")),
    AudioP48EnableR1: parseInt(getValue("AudioP48EnableR1Select")),
    AudioSource2: aud_src_map1[getValue("AudioSource2Select")],
    AudioEncoder2: aud_enc_map[getValue("AudioEncoder2Select")],
    AudioBitrate2: parseInt(getValue("AudioBitrate2Select")),
    AudioSource3: aud_src_map1[getValue("AudioSource3Select")],
    AudioEncoder3: aud_enc_map[getValue("AudioEncoder3Select")],
    AudioBitrate3: parseInt(getValue("AudioBitrate3Select")),
    AudioSource4: aud_src_map1[getValue("AudioSource4Select")],
    AudioEncoder4: aud_enc_map4[getValue("AudioEncoder4Select")],
    AudioBitrate4: parseInt(getValue("AudioBitrate4Select")),
    AudioSource5: aud_src_map1[getValue("AudioSource5Select")],
    AudioEncoder5: aud_enc_map4[getValue("AudioEncoder5Select")],
    AudioBitrate5: parseInt(getValue("AudioBitrate5Select")),
    AudioSource6: aud_src_map1[getValue("AudioSource6Select")],
    AudioEncoder6: aud_enc_map4[getValue("AudioEncoder6Select")],
    AudioBitrate6: parseInt(getValue("AudioBitrate6Select")),
    AudioSource7: aud_src_map1[getValue("AudioSource7Select")],
    AudioEncoder7: aud_enc_map4[getValue("AudioEncoder7Select")],
    AudioBitrate7: parseInt(getValue("AudioBitrate7Select")),
    ProgramNumber: parseInt(getNumber("ProgramNumberVal")),
    ServiceName: getNumber("ServiceNameVal"),
    VideoPid: parseInt(getNumber("VideoPidVal")),
    AudioPid0: parseInt(getNumber("AudioPid0Val")),
    AudioPid1: parseInt(getNumber("AudioPid1Val")),
    AudioPid2: parseInt(getNumber("AudioPid2Val")),
    AudioPid3: parseInt(getNumber("AudioPid3Val")),
    AudioPid4: parseInt(getNumber("AudioPid4Val")),
    AudioPid5: parseInt(getNumber("AudioPid5Val")),
    AudioPid6: parseInt(getNumber("AudioPid6Val")),
    AudioPid7: parseInt(getNumber("AudioPid7Val")),
    AncillaryPid: parseInt(getNumber("AncillaryPidVal")),
    MetadataPid: parseInt(getNumber("MetadataPidVal")),
    DataPid: parseInt(getNumber("DataPidVal")),
    PCRPid: parseInt(getNumber("PCRPidVal")),
    PMTPid: parseInt(getNumber("PMTPidVal")),
    RemuxMode: parseInt(getValue("RemuxModeSelect")),
    DESMode: parseInt(getValue("DESModeSelect")),
    DESKey: des_key_val,
    AncillaryMode: parseInt(getValue("AncillaryModeSelect")),
    DataMode: parseInt(getValue("DataModeSelect")),
    DataBaudrate: parseInt(getValue("DataBaudSelect")),
    BISSMode: parseInt(getValue("BISSModeSelect")),
    BISSKey: biss_key_val,
    RecordEnable: parseInt(getValue("RecordEnable")),
    IPStreamEnable: parseInt(getValue("IPStreamEnable")),
    IPStreamInterface: parseInt(stream_interface_get[getValue("IPStreamInterface")])+1,
    IPStreamAddress: getNumber("IPStreamAddress"),
    IPStreamPort: parseInt(getNumber("IPStreamPort")),
    IPStreamProtocol: parseInt(getValue("IPStreamProtocol")),
    IPStreamTTL: parseInt(getNumber("IPStreamTTL")),
    IPStreamNumTP: parseInt(getValue("IPStreamNumTP"))+1,
    IPFECEnable: parseInt(getValue("IPFECEnable")),
    IPFECCols: parseInt(getNumber("IPFECCols")),
    IPFECRows: parseInt(getNumber("IPFECRows")),
    SRTMode: parseInt(getValue("SRTMode")),
    SRTDelay: parseInt(getNumber("SRTDelay")),
    SpatialFilter: parseInt(getNumber("SpatialFilter")),
    CPBDelay: parseInt(getNumber("CPBDelay"))*CPBDelayStep,
  };
  json_send = JSON.stringify(str_val);
  set_json.addEventListener ("load", (e) =>
  {
    var reply = e.target.responseText;
    alert("Config Changes Applied Successfully" + "\n" + reply.trim());
		document.getElementById('apply_config').innerText = "Apply"
		document.getElementById('apply_config').disabled = false
		getEncode()
  });
  set_json.open("POST", url, true);
  set_json.setRequestHeader("Content-type", "application/json");
  set_json.send(json_send);
}

function restoreDef()
{
  if (confirm("Are You Sure You Want To Restore Default Settings?"))
  {
		document.getElementById('restore_def').innerText = "Restoring Defaults . ."
		document.getElementById('restore_def').disabled = true
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/wui_action.cgi";
    data.append("action", 1);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim());
			document.getElementById('restore_def').innerText = "Restore Defaults"
			document.getElementById('restore_def').disabled = false
			getUnit()
    });
    set_json.open("POST", url, true);
    set_json.send(data);
  }
}

function resetCodec()
{
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/wui_action.cgi";
    data.append("action", 2);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim());
    });
    set_json.open("POST", url, true);
    set_json.send(data);
}

function rebootUnit()
{
  if (confirm("Are You Sure You Want To Reboot?"))
  {
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/wui_action.cgi";
    data.append("action", 3);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim());
    });
    set_json.open("POST", url, true);
    set_json.send(data);
  }
}

function setCustomID()
{
  var cid = parseInt(getNumber("CustIDVal"));
  if (isNaN(cid) || cid == 0 || cid > 65535)
  {
	  alert("Invalid Custom ID");
  }
  else if (confirm("Are You Sure You Want To Change Custom ID?"))
  {
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/wui_action.cgi";
    data.append("action", 4);
    data.append("cid", cid);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim());
    });
    set_json.open("POST", url, true);
    set_json.send(data);
  }
}

function syncTime()
{
    const now = new Date()  
    const secondsSinceEpoch = Math.round(now.getTime() / 1000)
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/wui_action.cgi";
    data.append("action", 'c');
    data.append("time", secondsSinceEpoch);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim());
    });
    set_json.open("POST", url, true);
    set_json.send(data);
}

function enableUmvlOptions()
{
    var umvl_bw = parseInt(getValue("Umvl_bwSelect"));
    var interleave = document.getElementById('Umvl_interleaverSelect');
    var dual_ped = document.getElementById('Umvl_dual_pedSelect');
    if(umvl_bw > 3)
    {
        // Narrow-band case: dualped and interleaving not allowed.
        interleave.disabled = true;
        dual_ped.disabled = true;
    }
    else
    {
        interleave.disabled = false; 
        dual_ped.disabled = false;
    }
}

function getTx()
{
  var get_json = new XMLHttpRequest();
  get_json.addEventListener ("load", (e) =>
  {
    var json_load = JSON.parse(e.target.responseText);

    var mod_freq = json_load.mod_freq;
    var mod_att = json_load.mod_att;
    var mod_output = json_load.mod_output;
    var mod_out_pwr = json_load.mod_out_pwr;
    var mod_scheme = json_load.mod_scheme;

	try {
		setSelectValue("Dvbt_4k_offsetSelect",json_load.dvbt_4k_offset);
		setSelectValue("Dvbt_bwSelect",json_load.dvbt_bw);
		setSelectValue("Dvbt_constSelect",json_load.dvbt_const);
		setSelectValue("Dvbt_dual_pedSelect",json_load.dvbt_dual_ped);
		setSelectValue("Dvbt_fecSelect",json_load.dvbt_fec);
		setSelectValue("Dvbt_giSelect",json_load.dvbt_gi);
		setSelectValue("Dvbt_polSelect",json_load.dvbt_pol);
	} catch (error) {
		console.error(error);
	}

	try {
		setSelectValue("Isdbt_interleaverSelect",json_load.isdbt_interleaver);
		setSelectValue("Isdbt_bwSelect",json_load.isdbt_bw);
		setSelectValue("Isdbt_constSelect",json_load.isdbt_const);
		setSelectValue("Isdbt_fecSelect",json_load.isdbt_fec);
		setSelectValue("Isdbt_giSelect",json_load.isdbt_gi);
		setSelectValue("Isdbt_polSelect",json_load.isdbt_pol);
	} catch (error) {
		console.error(error);
	}
	
	try {
        setSelectValue("Umvl_interleaverSelect",json_load.umvl_interleaver);
		setSelectValue("Umvl_bwSelect",json_load.umvl_bw);
		setSelectValue("Umvl_constSelect",json_load.umvl_const);
        setSelectValue("Umvl_dual_pedSelect",json_load.umvl_dual_ped);
		setSelectValue("Umvl_fecSelect",json_load.umvl_fec);
		setSelectValue("Umvl_giSelect",json_load.umvl_gi);
		setSelectValue("Umvl_polSelect",json_load.umvl_pol);
        enableUmvlOptions();
	} catch (error) {
		console.error(error);
	}

    setNumber("Mod_freqVal",parseFloat(mod_freq).toFixed(4));
    setNumber("Mod_attVal",parseFloat(mod_att).toFixed(2));
    setSelectValue("Mod_outputSelect",mod_output);
    setSelectValue("Mod_out_pwrSelect",mod_out_pwr);
    setSelectValue("Mod_schemeSelect",mod_scheme);
	document.getElementById("Mod_out_pwrSelect").disabled = (CustID == "0000061e")?true:false;

    if(TxActive == TX_PRESENT_D1837) {
        // D1837 doesn't have preset power modes, mod_out_pwr isn't used
        // output power is either 100mW for S-band or 200mW for C-band (assuming high linearity mode)
        var power_dbm_ref = (parseFloat(mod_freq) > 6000.0) ? 23.0 : 20.0;
    } else {
        var power_dbm_ref = power_dbm[mod_out_pwr];
    }
	var power_mw_float = Math.pow(10,((power_dbm_ref-mod_att)/10));
	var power_mw = power_mw_float.toFixed(0);
	if(power_mw==0) power_mw = power_mw_float.toFixed(1);
	if(power_mw==0.0) power_mw = power_mw_float.toFixed(2);
	if(power_mw==0.00) power_mw = power_mw_float.toFixed(3);
    document.getElementById("freq_sts").innerHTML = parseFloat(mod_freq).toFixed(4)+" MHz";
    document.getElementById("pwr_sts").innerHTML = (power_mw+" mW");
    document.getElementById("rf_sts").innerHTML = Toggle_Select[mod_output];
    document.getElementById("mod_sts").innerHTML = rf_mode[mod_scheme];

    if(mod_output == '1')
    {
      document.getElementById("rf_sts").classList.add("low");
      document.getElementById("rf_sts").classList.remove("med");
      document.getElementById("rf_sts").classList.remove("high");
    }
    else if(mod_output == "0")
    {
      document.getElementById("rf_sts").classList.remove("low");
      document.getElementById("rf_sts").classList.remove("med");
      document.getElementById("rf_sts").classList.add("high");
    }
    else
    {
      document.getElementById("rf_sts").classList.remove("low");
      document.getElementById("rf_sts").classList.add("med");
      document.getElementById("rf_sts").classList.remove("high");
    }
    if(mod_scheme == 2)
    {
      var bw_val = getText("Isdbt_bwSelect");
      var const_val = getText("Isdbt_constSelect");
      var fec_val = getText("Isdbt_fecSelect");
      var guard_val = getText("Isdbt_giSelect");
      var dual_p_val = 0;
    }
    else if(mod_scheme == 1)
    {
      var bw_val = getText("Dvbt_bwSelect");
      var const_val = getText("Dvbt_constSelect");
      var fec_val = getText("Dvbt_fecSelect");
      var guard_val = getText("Dvbt_giSelect");
      var dual_p_val = getValue("Dvbt_dual_pedSelect");
    }
    else
    {
      var bw_val = getText("Umvl_bwSelect");
      var const_val = getText("Umvl_constSelect");
      var fec_val = getText("Umvl_fecSelect");
      var guard_val = getText("Umvl_giSelect");
      var dual_p_val = getValue("Umvl_dual_pedSelect");
    }
    document.getElementById("bw_st").innerHTML = ((dual_p_val == 1)?"2x":"")+bw_val;
    document.getElementById("cons_sts").innerHTML = const_val;
    document.getElementById("fec_sts").innerHTML = fec_val;
    document.getElementById("guard_sts").innerHTML = guard_val;

    if(TxPresent == TX_PRESENT_B170 || TxPresent == TX_PRESENT_B170_D1550)
    {
      document.getElementById("tx_rf_band1").innerHTML = json_load.min_freq + " - " + json_load.max_freq + " MHz";
    }
  }
);
get_json.open("GET", "/config/TxParamsList.json");
get_json.setRequestHeader('Cache-Control', 'no-cache')
get_json.setRequestHeader('Pragma', 'no-cache')
get_json.setRequestHeader('Expires', '0')
get_json.send();
}

function setTx()
{
  var json_send;
  var set_json = new XMLHttpRequest();
  var url = "/cgi-bin/set_tx_val.cgi";
  var str_val = {
    dvbt_4k_offset: parseInt(getValue("Dvbt_4k_offsetSelect")),
    dvbt_bw: parseInt(getValue("Dvbt_bwSelect")),
    dvbt_const: parseInt(getValue("Dvbt_constSelect")),
    dvbt_dual_ped: parseInt(getValue("Dvbt_dual_pedSelect")),
    dvbt_fec: parseInt(getValue("Dvbt_fecSelect")),
    dvbt_gi: parseInt(getValue("Dvbt_giSelect")),
    dvbt_pol: parseInt(getValue("Dvbt_polSelect")),

    isdbt_interleaver: parseInt(getValue("Isdbt_interleaverSelect")),
    isdbt_bw: parseInt(getValue("Isdbt_bwSelect")),
    isdbt_const: parseInt(getValue("Isdbt_constSelect")),
    isdbt_fec: parseInt(getValue("Isdbt_fecSelect")),
    isdbt_gi: parseInt(getValue("Isdbt_giSelect")),
    isdbt_pol: parseInt(getValue("Isdbt_polSelect")),

    umvl_interleaver: parseInt(getValue("Umvl_interleaverSelect")),
    umvl_bw: parseInt(getValue("Umvl_bwSelect")),
    umvl_const: parseInt(getValue("Umvl_constSelect")),
    umvl_dual_ped: parseInt(getValue("Umvl_dual_pedSelect")),
    umvl_fec: parseInt(getValue("Umvl_fecSelect")),
    umvl_gi: parseInt(getValue("Umvl_giSelect")),
    umvl_pol: parseInt(getValue("Umvl_polSelect")),

    mod_freq: parseFloat(getNumber("Mod_freqVal")).toFixed(4),
    mod_att: parseFloat(getNumber("Mod_attVal")).toFixed(4),
    mod_output: parseInt(getValue("Mod_outputSelect")),
    mod_out_pwr: parseInt(getValue("Mod_out_pwrSelect")),
    mod_scheme: parseInt(getValue("Mod_schemeSelect"))
  };
  json_send = JSON.stringify(str_val);
  set_json.addEventListener ("load", (e) =>
  {
    var reply = e.target.responseText;
    alert("Config Changes Applied Successfully"  + "\n" + reply.trim());
		document.getElementById('apply_tx_config').innerText = "Apply"
		document.getElementById('apply_tx_config').disabled = false
		getTx()
  });
  set_json.open("POST", url, true);
  set_json.setRequestHeader("Content-type", "application/json");
  set_json.send(json_send);
}

function getCameraCtrl()
{
  var get_json = new XMLHttpRequest();
  get_json.addEventListener ("load", (e) =>
  {
    var json_load = JSON.parse(e.target.responseText);
    var modem_freq = json_load.modem_freq;
    var cam_number = json_load.cam_number;
    var cam_type = json_load.cam_type;
    var filter_mode = json_load.filter_mode;
    var tally_mode = json_load.tally_mode;
    var shutter_mode = json_load.shutter_mode;
    var hitachi_nd = json_load.hitachi_nd;
    var sony_filter = json_load.sony_filter;
    var sony_colour = json_load.sony_colour;
    var dreamchip_map = json_load.dreamchip_map;
    var mzone_mode = json_load.mzone_mode;
    var modem_mz_freq1 = json_load.modem_mz_freq1;
    var modem_mz_freq2 = json_load.modem_mz_freq2;
    var modem_mz_freq3 = json_load.modem_mz_freq3;
    var modem_mz_freq4 = json_load.modem_mz_freq4;
    var modem_mz_freq5 = json_load.modem_mz_freq5;
    var modem_mz_freq6 = json_load.modem_mz_freq6;
    var modem_mz_freq7 = json_load.modem_mz_freq7;
    var modem_mz_freq8 = json_load.modem_mz_freq8;
    var pkt_err_rate = json_load.pkt_err_rate;
    var rx_timeout = json_load.rx_timeout;
    var rx_search_delay = json_load.rx_search_delay;
    var arri_port = json_load.arri_port;
    var idt_port = json_load.idt_port;
    var panasonic_port = json_load.panasonic_port;
    var panasonic_ip_addr = json_load.panasonic_ip_addr;
    var sony_ip_addr = json_load.sony_ip_addr;
    var idt_ip_addr = json_load.idt_ip_addr;
    var ip_address = json_load.ip_address;
    var ip_mask = json_load.ip_mask;
    var ip_gateway = json_load.ip_gateway;
    var panasonic_user = json_load.panasonic_user;
    var panasonic_psw = json_load.panasonic_psw;
    var connect_mode = json_load.connect_mode;
    
    setNumber("CCtrl_FreqVal",parseFloat(modem_freq/1000000).toFixed(6));
    setNumber("CCtrl_NumVal",cam_number);
    setSelectValue("CCtrl_TypeSelect",cam_type);
    setSelectValue("CCtrl_5600KSelect", filter_mode);
    setSelectValue("CCtrl_TallyModeSelect", tally_mode);
    setSelectValue("CCtrl_ShutterModeSelect", shutter_mode);
    setSelectValue("CCtrl_HitachiNDSelect", hitachi_nd);
    setSelectValue("CCtrl_SonyFiltersSelect", sony_filter);
    setSelectValue("CCtrl_SonyColoursSelect", sony_colour);
    setSelectValue("CCtrl_DreamchipMapSelect", dreamchip_map);
    setSelectValue("CCtrl_MZModeSelect", mzone_mode);
    setSelectValue("CCtrl_ModeSelect", connect_mode);
    setNumber("CCtrl_MZFreqVal1", parseFloat(modem_mz_freq1 / 1000000).toFixed(6));
    setNumber("CCtrl_MZFreqVal2", parseFloat(modem_mz_freq2 / 1000000).toFixed(6));
    setNumber("CCtrl_MZFreqVal3", parseFloat(modem_mz_freq3 / 1000000).toFixed(6));
    setNumber("CCtrl_MZFreqVal4", parseFloat(modem_mz_freq4 / 1000000).toFixed(6));
    setNumber("CCtrl_MZFreqVal5", parseFloat(modem_mz_freq5 / 1000000).toFixed(6));
    setNumber("CCtrl_MZFreqVal6", parseFloat(modem_mz_freq6 / 1000000).toFixed(6));
    setNumber("CCtrl_MZFreqVal7", parseFloat(modem_mz_freq7 / 1000000).toFixed(6));
    setNumber("CCtrl_MZFreqVal8", parseFloat(modem_mz_freq8 / 1000000).toFixed(6));
    setNumber("CCtrl_PktErrorRate", pkt_err_rate);
    setNumber("CCtrl_RxTimeout", rx_timeout);
    setNumber("CCtrl_RxSearchDelay", rx_search_delay);
    setNumber("CCtrl_CamNetArriPort", arri_port);
    setNumber("CCtrl_CamNetIDTPort", idt_port);
    setNumber("CCtrl_CamNetPanaPort", panasonic_port);
    setNumber("CCtrl_NetIPAddr", ip_address);
    setNumber("CCtrl_NetGWAddr", ip_gateway);
    setNumber("CCtrl_NetMaskAddr", ip_mask);
    setNumber("CCtrl_CamNetPanaIPAddr", panasonic_ip_addr);
    setNumber("CCtrl_CamNetSonyIPAddr", sony_ip_addr);
    setNumber("CCtrl_CamNetIDTIPAddr", idt_ip_addr);
    setNumber("CCtrl_CamNetPanaUser", panasonic_user);
    setNumber("CCtrl_CamNetPanaPsw", panasonic_psw);

    document.getElementById("cctrl_freq_sts").innerHTML = parseFloat(modem_freq/1000000).toFixed(4)+" MHz";
    document.getElementById("cctrl_num_sts").innerHTML = (cam_number);
  }
);
get_json.open("GET", "/config/CamCtrlParamsList.json");
get_json.setRequestHeader('Cache-Control', 'no-cache')
get_json.setRequestHeader('Pragma', 'no-cache')
get_json.setRequestHeader('Expires', '0')
get_json.send();
}

function setCamCtrl()
{
  var json_send;
  var set_json = new XMLHttpRequest();
  var url = "/cgi-bin/set_cam_ctrl_val.cgi";
  var str_val = {
    modem_freq: parseFloat(getNumber("CCtrl_FreqVal")*1000000),
    cam_number: parseInt(getNumber("CCtrl_NumVal")),
    cam_type: parseInt(getValue("CCtrl_TypeSelect")),
    filter_mode: parseInt(getValue("CCtrl_5600KSelect")),
    tally_mode: parseInt(getValue("CCtrl_TallyModeSelect")),
    shutter_mode: parseInt(getValue("CCtrl_ShutterModeSelect")),
    hitachi_nd: parseInt(getValue("CCtrl_HitachiNDSelect")),
    sony_filter: parseInt(getValue("CCtrl_SonyFiltersSelect")),
    sony_colour: parseInt(getValue("CCtrl_SonyColoursSelect")),
    dreamchip_map: parseInt(getValue("CCtrl_DreamchipMapSelect")),
    mzone_mode: parseInt(getValue("CCtrl_MZModeSelect")),
    modem_mz_freq1: parseFloat(getNumber("CCtrl_MZFreqVal1") * 1000000),
    modem_mz_freq2: parseFloat(getNumber("CCtrl_MZFreqVal2") * 1000000),
    modem_mz_freq3: parseFloat(getNumber("CCtrl_MZFreqVal3") * 1000000),
    modem_mz_freq4: parseFloat(getNumber("CCtrl_MZFreqVal4") * 1000000),
    modem_mz_freq5: parseFloat(getNumber("CCtrl_MZFreqVal5") * 1000000),
    modem_mz_freq6: parseFloat(getNumber("CCtrl_MZFreqVal6") * 1000000),
    modem_mz_freq7: parseFloat(getNumber("CCtrl_MZFreqVal7") * 1000000),
    modem_mz_freq8: parseFloat(getNumber("CCtrl_MZFreqVal8") * 1000000),
    pkt_err_rate: parseInt(getNumber("CCtrl_PktErrorRate")),
    rx_timeout: parseInt(getNumber("CCtrl_RxTimeout")),
    rx_search_delay: parseInt(getNumber("CCtrl_RxSearchDelay")),
    arri_port: parseInt(getNumber("CCtrl_CamNetArriPort")),
    idt_port: parseInt(getNumber("CCtrl_CamNetIDTPort")),
    panasonic_port: parseInt(getNumber("CCtrl_CamNetPanaPort")),
    ip_address: getNumber("CCtrl_NetIPAddr"),
    ip_gateway: getNumber("CCtrl_NetGWAddr"),
    ip_mask: getNumber("CCtrl_NetMaskAddr"),
    panasonic_ip_addr: getNumber("CCtrl_CamNetPanaIPAddr"),
    sony_ip_addr: getNumber("CCtrl_CamNetSonyIPAddr"),
    idt_ip_addr: getNumber("CCtrl_CamNetIDTIPAddr"),
    panasonic_user: getNumber("CCtrl_CamNetPanaUser"),
    panasonic_psw: getNumber("CCtrl_CamNetPanaPsw"),
    connect_mode: parseInt(getValue("CCtrl_ModeSelect")),
};
  json_send = JSON.stringify(str_val);
  set_json.addEventListener ("load", (e) =>
  {
    var reply = e.target.responseText;
    alert("Config Changes Applied Successfully"  + "\n" + reply.trim());
		document.getElementById('apply_cam_ctrl_config').innerText = "Apply"
		document.getElementById('apply_cam_ctrl_config').disabled = false
		getCameraCtrl()
  });
  set_json.open("POST", url, true);
  set_json.setRequestHeader("Content-type", "application/json");
  set_json.send(json_send);
}

function getCamCtrlStatus()
{
  var get_json = new XMLHttpRequest();
  get_json.addEventListener("load", (e) =>
  {
    var json_load = JSON.parse(e.target.responseText);

    var cam_rx_lic_msk = json_load.CamRxLicenseMask;
    document.getElementById("camrx_software_ver").innerHTML = "v" + json_load.CamRxSoftwareVersion;
    document.getElementById("camrx_serial_num").innerHTML = json_load.CamRxSerialNumber;
    document.getElementById("camrx_lic_msk").innerHTML = cam_rx_lic_msk;

    var CamConnected = json_load.CamConnected;

    if((CamConnected & 0x02) == 2)
    {
      document.getElementById("cctrl_cam_sts").innerHTML = "Connected";
    }
    else
    {
      document.getElementById("cctrl_cam_sts").innerHTML = "Not Connected";
    }

    if((CamConnected & 0x01) == 1)
    {
      document.getElementById("cctrl_con_sts").innerHTML = "Connected";
    }
    else
    {
      document.getElementById("cctrl_con_sts").innerHTML = "Not Connected";
    }

    if((CamConnected & 0x10) == 0x10)
    {
      document.getElementById("cctrl_tallyr_sts").innerHTML = "Active";
    }
    else
    {
      document.getElementById("cctrl_tallyr_sts").innerHTML = "Not Active";
    }

    if((CamConnected & 0x20) == 0x20)
    {
      document.getElementById("cctrl_tallyg_sts").innerHTML = "Active";
    }
    else
    {
      document.getElementById("cctrl_tallyg_sts").innerHTML = "Not Active";
    }
  }
);
get_json.open("GET", "/sts/CamCtrlStatus.json", true);
get_json.setRequestHeader('Cache-Control', 'no-cache')
get_json.setRequestHeader('Pragma', 'no-cache')
get_json.setRequestHeader('Expires', '0')
get_json.send();
}

function getTSLTallyStatus() {
  var get_json = new XMLHttpRequest();
  get_json.addEventListener("load", (e) => 
  {
    var json_load = JSON.parse(e.target.responseText);

    var serverConnected = json_load.ServerConnect;
    var AddressOk = json_load.AddressOk;
//    var GreenTally = json_load.GreenTally;
    var RedTally = json_load.RedTally;

    if (serverConnected == '1') {
      document.getElementById("tsl_srv_sts").innerHTML = "Connected";
    }
    else {
      document.getElementById("tsl_srv_sts").innerHTML = "Not Connected";
    }

    if (AddressOk == '1') {
      document.getElementById("tsl_addr_sts").innerHTML = "Ok";
    }
    else {
      if(serverConnected == '1')
        document.getElementById("tsl_addr_sts").innerHTML = "Error";
      else 
        document.getElementById("tsl_addr_sts").innerHTML = "---";
    }

    if (RedTally == '1') {
      document.getElementById("tsl_tallyr_sts").innerHTML = "Active";
    }
    else {
      document.getElementById("tsl_tallyr_sts").innerHTML = "Not Active";
    }
  }
  );
  get_json.open("GET", "/sts/TSLTallyStatus.json", true);
  get_json.setRequestHeader('Cache-Control', 'no-cache')
  get_json.setRequestHeader('Pragma', 'no-cache')
  get_json.setRequestHeader('Expires', '0')
  get_json.send();
}

function getSDRStatus() {
  var get_json = new XMLHttpRequest();
  get_json.addEventListener("load", (e) => {
    var json_load = JSON.parse(e.target.responseText);

    var meshConnected = json_load.mesh_connected;
    var activeIPAddress = json_load.active_ipaddress;
//    var activeGWAddress = json_load.active_gateway;
    var activeIPNetmask = json_load.active_netmask;
    var SWVersion = json_load.SDRSwVersion;
    var SerialNumber = json_load.SDRSerialNum;
    var LicenseMask = json_load.SDRLicenseMask;
    var sdr_temp = parseInt(json_load.SDRTemp);

    document.getElementById("sdr_temp").innerHTML = sdr_temp.toFixed(1) + " &deg;C";
    if (tx_temp > 85) 
    {
      document.getElementById("sdr_temp").classList.remove("low");
      document.getElementById("sdr_temp").classList.remove("med");
      document.getElementById("sdr_temp").classList.add("high");
    }
    else if (tx_temp > 75) 
    {
      document.getElementById("sdr_temp").classList.remove("low");
      document.getElementById("sdr_temp").classList.add("med");
      document.getElementById("sdr_temp").classList.remove("high");
    }
    else 
    {
      document.getElementById("sdr_temp").classList.add("low");
      document.getElementById("sdr_temp").classList.remove("med");
      document.getElementById("sdr_temp").classList.remove("high");
    }

    if (meshConnected == '1') {
      document.getElementById("mesh_connected").innerHTML = "Connected";
    }
    else {
      document.getElementById("mesh_connected").innerHTML = "Not Connected";
    }

    document.getElementById("sdr_active_ipaddr").innerHTML = activeIPAddress;
    document.getElementById("sdr_active_mask").innerHTML = activeIPNetmask;

    document.getElementById("sdr_software_ver").innerHTML = "v" + SWVersion;
    document.getElementById("sdr_serial_num").innerHTML = SerialNumber;
    document.getElementById("sdr_lic_msk").innerHTML = LicenseMask;
    //    document.getElementById("sdr_active_gwaddr").innerHTML = activeGWAddress;
  }
  );
  get_json.open("GET", "/sts/SDRStatus.json", true);
  get_json.setRequestHeader('Cache-Control', 'no-cache')
  get_json.setRequestHeader('Pragma', 'no-cache')
  get_json.setRequestHeader('Expires', '0')
  get_json.send();
}

function getSDR() {
  var get_json = new XMLHttpRequest();
  get_json.addEventListener("load", (e) => {
    var json_load = JSON.parse(e.target.responseText);
    var sdr_freq = json_load.frequency;
    var mesh_id = json_load.mesh_id;
    var node_id = json_load.node_id;
    var rf_out = json_load.rf_out;
    var dhcp_mode = json_load.dhcp_mode;
    var ip_address = json_load.ip_address;
    var ip_netmask = json_load.ip_netmask;
    var gw_address = json_load.gw_address;

    setNumber("SDR_FreqVal", parseFloat(sdr_freq).toFixed(4));
    setNumber("SDR_MeshID", mesh_id);
    setNumber("SDR_NodeID", node_id);
    setSelectValue("SDRDHCPModeSelect", dhcp_mode);
    setSelectValue("SDR_rf_outputSelect", rf_out);
    setNumber("SDR_NetIPAddr", ip_address);
    setNumber("SDR_NetMaskAddr", ip_netmask);
    setNumber("SDR_NetGWAddr", gw_address);

    sdrDHCPChange();

    document.getElementById("sdr_freq_sts").innerHTML = parseFloat(sdr_freq).toFixed(4) + " MHz";
    document.getElementById("sdr_rf_sts").innerHTML = Toggle_Select[rf_out];

    if (rf_out == '1') {
      document.getElementById("sdr_rf_sts").classList.add("low");
      document.getElementById("sdr_rf_sts").classList.remove("med");
      document.getElementById("sdr_rf_sts").classList.remove("high");
    }
    else if (rf_out == "0") {
      document.getElementById("sdr_rf_sts").classList.remove("low");
      document.getElementById("sdr_rf_sts").classList.remove("med");
      document.getElementById("sdr_rf_sts").classList.add("high");
    }
    else {
      document.getElementById("sdr_rf_sts").classList.remove("low");
      document.getElementById("sdr_rf_sts").classList.add("med");
      document.getElementById("sdr_rf_sts").classList.remove("high");
    }
  }
  );
  get_json.open("GET", "/config/SDRParamsList.json");
  get_json.setRequestHeader('Cache-Control', 'no-cache')
  get_json.setRequestHeader('Pragma', 'no-cache')
  get_json.setRequestHeader('Expires', '0')
  get_json.send();
}

function setSDR() {
  var json_send;
  var set_json = new XMLHttpRequest();
  var url = "/cgi-bin/set_sdr_val.cgi";
  var str_val = {
    dhcp_mode: parseInt(getValue("SDRDHCPModeSelect")),
    ip_address: getNumber("SDR_NetIPAddr"),
    gw_address: getNumber("SDR_NetGWAddr"),
    ip_netmask: getNumber("SDR_NetMaskAddr"),
    frequency: parseFloat(getNumber("SDR_FreqVal")).toFixed(4),
    rf_out: parseInt(getValue("SDR_rf_outputSelect")),
    mesh_id: parseInt(getNumber("SDR_MeshID")),
    node_id: parseInt(getNumber("SDR_NodeID")),
  };
  json_send = JSON.stringify(str_val);
  set_json.addEventListener("load", (e) => {
    var reply = e.target.responseText;
    alert("Config Changes Applied Successfully" + "\n" + reply.trim());
    document.getElementById('apply_sdr_config').innerText = "Apply"
    document.getElementById('apply_sdr_config').disabled = false
    getSDR()
  });
  set_json.open("POST", url, true);
  set_json.setRequestHeader("Content-type", "application/json");
  set_json.send(json_send);
}

function upgradeController()
{
  if (confirm("Are You Sure You Want To Start Controller Upgrade?"))
  {
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/wui_action.cgi";
    data.append("action", 5);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim());
    });
    set_json.open("POST", url, true);
    set_json.send(data);
  }
}

function diagDownload()
{
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/wui_action.cgi";
    data.append("action", 8);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim() + ", download should start after pressing OK\nIf not browse to " + window.location.origin + "/sts/support.tar.gz");

	  let a = document.createElement('a');
	  a.href = window.location.origin + "/sts/support.tar.gz";
	  a.download = "support.tar.gz";
	  document.body.appendChild(a);
	  a.click();
	  document.body.removeChild(a);
    });
    set_json.open("POST", url, true);
    set_json.send(data);
}

function formatSdaX(fs)
{
  if (confirm("Are You Sure You Want To Format Device?"))
  {
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/wui_action.cgi";
    data.append("action", 6);
    data.append("fs", fs);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim());
    });
    set_json.open("POST", url, true);
    set_json.send(data);
  }
}

function setWebPassword(set)
{
  var pw = "";
  if(set)
  {
    pw = prompt("Please Set New admin Password...\n(alphanumeric characters only, max length 16)")
    if(pw != null && pw != "")
    {
	  if(!pw.match(/^[0-9a-zA-Z]+$/)) {
        alert("Password contains non-alphanumeric characters");
        pw = null;
	  }
	  else if(pw.length > 16) {
        alert("Length exceeds 16 characters");
        pw = null;
      }
      else if(!confirm("Are You Sure You Want To Set admin Password to " + pw + "?"))
        pw = null;
    }
  }

  if(pw == "")
    if (!confirm("Are You Sure You Want To Clear admin Password?"))
	  pw = null;

  if(pw != null)
  {
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/wui_action.cgi";
    data.append("action", 7);
    data.append("pw", pw);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim());
    });
    set_json.open("POST", url, true);
    set_json.send(data);
  }
}

function setRecordControl(type)
{
  var set_json = new XMLHttpRequest();
  var data = new FormData();
  var url = "/cgi-bin/wui_action.cgi";
  if(type == "toggle")
    data.append("action", 'b');
  else
    return
  set_json.addEventListener ("load", (e) =>
  {
    var reply = e.target.responseText;
    alert(reply.trim());
  });
  set_json.open("POST", url, true);
  set_json.send(data);
}

function setPlaybackControl(type)
{
  var offset = -1;
  if(type == "start")
  {
    offset = getNumber("PlaybackOffset");
	if(offset == "")
		offset = -1;
	else if(offset < 0)
		offset = 0 - offset;
  }
  else if(type == "stop")
    offset = 0;

  if(offset != -1)
  {
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/wui_action.cgi";
    data.append("action", 'a');
    data.append("offset", offset);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim());
    });
    set_json.open("POST", url, true);
    set_json.send(data);
  }
}

function rfCalibration(type)
{
  var set_json = new XMLHttpRequest();
  var data = new FormData();
  var url = "/cgi-bin/wui_action.cgi";
  data.append("action", 'd');
  if (type == "start")
  {
    data.append("start", 0);
  }
  set_json.addEventListener ("load", (e) =>
  {
    var reply = e.target.responseText;
    alert(reply.trim());
  });
  set_json.open("POST", url, true);
  set_json.send(data);
}

function uploadPreset()
{
  if(document.getElementById('uploadFile').value == "")
  {
    alert("No File To Upload");
  }
  else
  {
		document.getElementById('PresetUploadBtn').innerText = "Uploading . ."
		document.getElementById('PresetUploadBtn').disabled = true
    var json_send;
    var set_json = new XMLHttpRequest();
    var url = "/cgi-bin/upload_preset.cgi";
    var product_name;
    fileInput  = document.getElementById('uploadFile')
    var data = fileInput.files[0];
    var file = new FormData();
    file.append('file', data);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      getPreset()
      alert(reply.trim());
			document.getElementById('PresetUploadBtn').innerText = "Upload"
			document.getElementById('PresetUploadBtn').disabled = false
    });
    set_json.open("POST", url, true);
    set_json.send(file);
  }
}

function getPreset()
{
  var get_json = new XMLHttpRequest();
  get_json.addEventListener ("load", (e) =>
  {
    var json_load = JSON.parse(e.target.responseText);
    removeOptions("PresetSelect");
    selectOptionsValue("PresetSelect",json_load,json_load);
    downloadPreset()
  }
  );
  get_json.open("GET", "/cgi-bin/fileList.cgi");
  get_json.setRequestHeader('Cache-Control', 'no-cache')
  get_json.setRequestHeader('Pragma', 'no-cache')
  get_json.setRequestHeader('Expires', '0')
  get_json.send();
}

function newPreset()
{
  if(document.getElementById('fileName').value == "")
  {
    alert("Preset Name is not Set");
  }
  else
  {
    var type = document.getElementById('filePre').value;
    var id = document.getElementById('fileName').value;
    var str_val
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/add_preset.cgi";
    var fileName = type + "-" + id;
    data.append("filename", fileName);
    data.append("type", type);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      getPreset()
      alert("Preset Saved Successfully");
    });
    set_json.open("POST", url, true);
    set_json.send(data);
  }
}

function delPreset()
{
  var file = document.getElementById('PresetSelect').value;
  if (confirm("Are You Sure You Want To Delete" + "\n\n" + file))
  {
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/del_preset.cgi";
    data.append("file", file);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      getPreset()
      alert(reply.trim());
    });
    set_json.open("POST", url, true);
    set_json.send(data);
  }
}

function setPreset()
{
  var file = document.getElementById('PresetSelect').value;
  if (confirm("Are You Sure You Want To Load" + "\n\n" + file))
  {
    var set_json = new XMLHttpRequest();
    var data = new FormData();
    var url = "/cgi-bin/set_preset.cgi";
    data.append("file", file);
    data.append("TxPresent", TxPresent);
    set_json.addEventListener ("load", (e) =>
    {
      var reply = e.target.responseText;
      alert(reply.trim());
    });
    set_json.open("POST", url, true);
    set_json.send(data);
  }
}

function downloadPreset()
{
  var url;
  if(document.getElementById('PresetSelect').value != "")
  {
    url = window.location.origin + "/preset/" + document.getElementById('PresetSelect').value
  }
  else
  {
    url = "JavaScript:void(0);"
  }
  document.getElementById('preDown').href = url
}

function mySRTCanvas()
{
	var canvas = document.getElementById("mySRTCanvas");
	var ctx = canvas.getContext("2d");
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.moveTo(srt_cnt,srt_cnt);
		srt_cnt = srt_cnt+1;

	ctx.lineTo(srt_cnt,srt_cnt);
	ctx.stroke();
	srt_cnt = srt_cnt+1;
}

function showUserManual()
{
    document.getElementById("nav_main").style.display = "none";
    document.getElementById("section_main").style.display = "none";
    document.getElementById("section_manual").style.display = "inline-block";
	var tmp_text;

	var manual_table = [
		[ "status"
		],
    [ "tx",       ["RF",              ["Output", "Mod_outputSelect"],
                                      ["Output Power", "Mod_out_pwrSelect"],
                                      ["Attenuation", "Mod_attVal"],
                                      ["Frequency", "Mod_freqVal"],
                                      ["Modulation Scheme", "Mod_schemeSelect"]],
                  ["DVB-T",           ["Bandwidth", "Dvbt_bwSelect"],
                                      ["Constellation", "Dvbt_constSelect"],
                                      ["FEC", "Dvbt_fecSelect"],
                                      ["Guard Interval", "Dvbt_giSelect"],
                                      ["Dual Pedestal", "Dvbt_dual_pedSelect"],
                                      ["Polarity", "Dvbt_polSelect"],
                                      ["4k Offset", "Dvbt_4k_offsetSelect"]],
                  ["ISDB-T",          ["Bandwidth", "Isdbt_bwSelect"],
                                      ["Constellation", "Isdbt_constSelect"],
                                      ["FEC", "Isdbt_fecSelect"],
                                      ["Guard Interval", "Isdbt_giSelect"],
                                      ["Polarity", "Isdbt_polSelect"],
                                      ["Interleaver", "Isdbt_interleaverSelect"]],
                  ["Narrowband/UMVL", ["Bandwidth", "Umvl_bwSelect"],
                                      ["Constellation", "Umvl_constSelect"],
                                      ["FEC", "Umvl_fecSelect"],
                                      ["Guard Interval", "Umvl_giSelect"],
                                      ["Dual Pedestal", "Umvl_dual_pedSelect"],
                                      ["Polarity", "Umvl_polSelect"],
                                      ["Interleaver", "Umvl_interleaverSelect"]],
    ],
		[ "video",		["Video Input",			["Video Source", "VideoSourceSelect"],
												["Sample Format", "SampleFormatSelect"],
												["QuadSync", "QuadSyncSelect"],
												["Spatial Filter", "SpatialFilter"]],
						["Input Alignment",		["", "QuadSyncAlignment"]],
						["Video Stream",		["Encoding Mode", "EncodeModeSelect"],
												["Video Format", "VideoFormatSelect"],
												["Video Bitrate Mode", "VideoBitrateSelect"],
												["Video Bitrate", "VideoBitrateVal"],
												["ASI / IP Bitrate", "SystemBitrateVal"],
												["Latency Mode", "LowDelayModeSelect"],
												["Encode Buffer", "CPBDelay"],
												["Bit Depth", "BitDepthSelect"],
												["Chroma Format", "ChromaFormatSelect"],
												["HDR/WCG Mode", "HDRWCGModeSelect"]],
						["Video Helper",		["Single HD", "VideoHelperHD"],
												["Single UHD", "VideoHelperUHD"],
												["QuadSync", "VideoHelperQuadSync"],
												["HFR Phases", "VideoHelperUHD"],
												["Video Rate", "VideoHelperRate"]],
		],
		[ "audio",		["Analogue Input",		["Reference Level", "AudioRefLevelXSelect"],
												["Gain", "AudioGainXXVal"],
												["Phantom Power", "AudioP48EnableXXSelect"]],
						["Audio Stream",		["Source", "AudioSourceXSelect"],
												["Encoding Mode", "AudioEncoderXSelect"],
												["Audio Bitrate", "AudioBitrateXSelect"]],
						["Audio Helper",		["Standard", "AudioHelperStandard"],
												["QuadSync", "AudioHelperQuadSync"]],
		],
		[ "service",	["Remux",				["Mode", "RemuxModeSelect"]],
						["Service",				["Program Number", "ProgramNumberVal"],
												["Service Name", "ServiceNameVal"],
												["PID", "XXXPidVal"]],
						["Scrambling",			["DES Mode", "DESModeSelect"],
												["DES Key", "DESKeyVal"],
												["BISS Mode", "BISSModeSelect"],
												["BISS Key", "BISSKeyVal"]],
						["Ancillary",			["Extract Mode", "AncillaryModeSelect"],
												["Ancillary Bitrate", "AncillaryBitrateVal"]],
						["Data",				["Mode", "DataModeSelect"],
												["Baud Rate", "DataBaudSelect"]],
						["Service Helper",		["PID Assignment", "ServiceHelperPIDs"]],

		],
		[ "ip",			["Stream Output",		["IP Mode", "IPStreamEnable"],
												["IP Interface", "IPStreamInterface"],
												["Stream Protocol", "IPStreamProtocol"],
												["SRT Mode", "SRTMode"],
												["SRT Delay", "SRTDelay"],
												["Stream Address", "IPStreamAddress"],
												["UDP Port Number", "IPStreamPort"],
												["TTL", "IPStreamTTL"],
												["TP per IP", "IPStreamNumTP"],
												["Use FEC", "IPFECEnable"],
												["FEC Columns", "IPFECCols"],
												["FEC Rows", "IPFECRows"]],
						["Stream Diagnostics",	["", "DTM_Diagnostics"]],
						["SRT Diagnostics",		["", "SRT_Diagnostics"]],
		],
		[ "usb",		["File Output",			["USB Record", "RecordEnable"],
                                    ["Trigger Control", "RecordControl"]],
						["File Input",			["USB Playback", "PlaybackControl"],
												["Offset", "PlaybackOffset"]],
						["File Diagnostics",	["", "File_Diagnostics"]],
		],
		[ "unit",		["Ethernet",			["DHCP Mode", "DHCPModeSelectX"],
												["IP Address", "IPAddrX"],
												["Gateway Address", "IPGatewayX"],
												["Subnet Mask", "IPMaskX"],
												["MAC Address", "ethX_macaddr"],
												["Link State ", "ethX_state_dtm"]],
						["Global",				["IP Bridging Mode", "IPBridgeSelect"],
												["Fan Mode", "FanModeSelect"],
												["Idle Fan Speed", "FanSpeedIdleSelect"],
												["Record Fan Speed", "FanSpeedRecSelect"],
												["Unit Address", "UnitAddress"],
												["Unit Name", "UnitName"],
												["Unit Mode", "UnitModeSelect"],
												["Web Password", "WebPassword"]],
						["USB Storage",			["Partition Size", "SdaXSize"],
												["File System", "SdaXType"],
												["Format Device", "SdaXFormat"]],
		],
		[ "upgrade",	["Codec Firmware",		["", "CodecFirmware"]],
						["Codec License",		["", "CodecLicense"]],
						["Transmitter Firmware",["", "TxFirmware"]],
						["Transmitter License",	["", "TxLicense"]],
            ["Camera Control License", ["", "CamrRxLicense"]],
						["Controller",			["", "ControllerUpgrade"]],
		],
		[ "presets"
		],
		[ "info"
		],
	];
	for (var k = 0; k < manual_table.length; k++)
	{
		tmp_text = "";
		for (var i = 1; i < manual_table[k].length; i++)
		{
			tmp_text += "<b>" + manual_table[k][i][0] + "</b><br><br>";
			for (var j = 1; j < manual_table[k][i].length; j++)
			{
				helpContent(manual_table[k][i][j][1]);
				if (manual_table[k][i][j][0] != "")
					tmp_text += manual_table[k][i][j][0] + "<br>";
				tmp_text += document.getElementById('help_window_text').innerHTML + "<br>";
			}
		}
		document.getElementById("manual_label_"+manual_table[k][0]).innerHTML = tmp_text;
		document.getElementById("manual_div_"+manual_table[k][0]).style.display = (manual_table[k].length <= 1)?"none":"inline-block";
	}
}

function helpContentAddRow(col1, col2)
{
	var row = "<tr>";
	if (col2)
	{
		row += "<td nowrap=\"nowrap\">" + col1 +  "</td><td></td>";
		row += "<td>" + col2 +  "</td><td></td>";
	}
	else
	{
		row += "<td>" + col1 +  "</td><td></td>";
	}
	return row + "</tr>"
}

function helpContent(item)
{
	var port1 = getNumber("IPName0");
	var port2 = getNumber("IPName1");
	var port3 = (DTM3200Present == 0)?"":"IP Module";

	var content = "<table>";
	switch(item)
	{
		// RF
		case "Mod_outputSelect": content +=   helpContentAddRow("Off", "RF output is disabled.") +
                                          helpContentAddRow("On",	 "RF output is enabled."); break;
		case "Mod_out_pwrSelect": content +=  helpContentAddRow("10mW",  "RF power output preset of 10mW (10dBm).") +
                                          helpContentAddRow("50mW",	 "RF power output preset of 50mW (17dBm).") +
                                          helpContentAddRow("100mW", "RF power output preset of 100mW (20dBm)."); break;
    case "Mod_attVal": content +=         helpContentAddRow("0.0 to 31.75dB RF attenuation in 0.25dB increments."); break;
    case "Mod_freqVal": content +=        helpContentAddRow("RF output frequency typically to 0.125MHz resolution.") +
                                          helpContentAddRow("Available tuning range is hardware dependant."); break;
    case "Mod_schemeSelect": content +=   helpContentAddRow("NB/UMVL", "Use Narrowband/UMVL modulation.") +
                                          helpContentAddRow("DVB-T",	 "Use DVB-T modulation.") +
                                          helpContentAddRow("ISDB-T",	 "Use ISDB-T modulation."); break;
    // DVB-T
    case "Dvbt_bwSelect": content +=        helpContentAddRow("Channel bandwidth used for DVB-T modulation."); break;
		case "Dvbt_constSelect": content +=     helpContentAddRow("QPSK",   "Quadrature Phase Shift Keying, most robust channel performance.") +
                                            helpContentAddRow("16-QAM", "16-point Quadrature Amplitude Modulation.") +
                                            helpContentAddRow("64-QAM", "64-point Quadrature Amplitude Modulation, highest data rate."); break;
    case "Dvbt_fecSelect": content +=       helpContentAddRow("1/2", "1:1 data to error correction ratio, most robust channel performance.") +
                                            helpContentAddRow("2/3", "2:1 data to error correction ratio.") +
                                            helpContentAddRow("3/4", "3:1 data to error correction ratio.") +
                                            helpContentAddRow("5/6", "5:1 data to error correction ratio.") +
                                            helpContentAddRow("7/8", "7:1 data to error correction ratio, highest data rate."); break;
    case "Dvbt_giSelect": content +=        helpContentAddRow("1/8",  "1/8 guard interval, most resistant to multipath channels with a large delay spread.") +
                                            helpContentAddRow("1/8",  "1/8 guard interval.") +
                                            helpContentAddRow("1/16", "1/16 guard interval.") +
                                            helpContentAddRow("1/32", "1/32 guard interval, highest data rate."); break;
    case "Dvbt_dual_pedSelect": content +=  helpContentAddRow("Off", "Standard single pedestal DVB-T output.") +
                                            helpContentAddRow("On",	 "Double bandwidth dual pedestal DVB-T output."); break;
    case "Dvbt_polSelect": content +=       helpContentAddRow("Normal",   "Standard spectum polarity output.") +
                                            helpContentAddRow("Inverted", "Inverted output to compensation for inversion somewhere else."); break;
    case "Dvbt_4k_offsetSelect": content += helpContentAddRow("Introduces a small frequency offset moving carriers away from DC."); break;
    // ISDB-T
    case "Isdbt_bwSelect": content +=           helpContentAddRow("Channel bandwidth used for ISDB-T modulation."); break;
		case "Isdbt_constSelect": content +=        helpContentAddRow("DQPSK",  "Differential Quadrature Phase Shift Keying, most robust channel performance.") +
                                                helpContentAddRow("QPSK",   "Quadrature Phase Shift Keying, most robust channel performance.") +
                                                helpContentAddRow("16-QAM", "16-point Quadrature Amplitude Modulation.") +
                                                helpContentAddRow("64-QAM", "64-point Quadrature Amplitude Modulation, highest data rate."); break;
    case "Isdbt_fecSelect": content +=          helpContentAddRow("1/2", "1:1 data to error correction ratio, most robust channel performance.") +
                                                helpContentAddRow("2/3", "2:1 data to error correction ratio.") +
                                                helpContentAddRow("3/4", "3:1 data to error correction ratio.") +
                                                helpContentAddRow("5/6", "5:1 data to error correction ratio.") +
                                                helpContentAddRow("7/8", "7:1 data to error correction ratio, highest data rate."); break;
    case "Isdbt_giSelect": content +=           helpContentAddRow("1/8",  "1/8 guard interval, most resistant to multipath channels with a large delay spread.") +
                                                helpContentAddRow("1/8",  "1/8 guard interval.") +
                                                helpContentAddRow("1/16", "1/16 guard interval.") +
                                                helpContentAddRow("1/32", "1/32 guard interval, highest data rate."); break;
    case "Isdbt_polSelect": content +=          helpContentAddRow("Normal",   "Standard spectum polarity output.") +
                                                helpContentAddRow("Inverted", "Inverted output to compensation for inversion somewhere else."); break;
    case "Isdbt_interleaverSelect": content +=  helpContentAddRow("Controls the period of time interleaving which helps robustness where large interruptions are expected."); break;
    // Narrowband/UMVL
    case "Umvl_bwSelect": content +=      helpContentAddRow("Channel bandwidth used for Narrowband/UMVL modulation."); break;
	case "Umvl_constSelect": content +=   helpContentAddRow("BPSK",   "Binary Phase Shift Keying, most robust channel performance.") +
                                          helpContentAddRow("QPSK",   "Quadrature Phase Shift Keying.") +
                                          helpContentAddRow("8-PSK",  "Eight Phase Shift Keying.") +
                                          helpContentAddRow("16-QAM", "16-point Quadrature Amplitude Modulation, highest data rate."); break;
    case "Umvl_fecSelect": content +=     helpContentAddRow("1/3", "1:2 data to error correction ratio, most robust channel performance.") +
                                          helpContentAddRow("2/3", "2:1 data to error correction ratio, highest data rate."); break;
    case "Umvl_giSelect": content +=      helpContentAddRow("1/8",  "1/8 guard interval, most resistant to multipath channels with a large delay spread.") +
                                          helpContentAddRow("1/16", "1/16 guard interval, highest data rate."); break;
    case "Umvl_dual_pedSelect": content += helpContentAddRow("Off", "Standard single pedestal UMVL output.") +
                                          helpContentAddRow("On",	 "Double bandwidth dual pedestal UMVL output."); break;
    case "Umvl_polSelect": content +=     helpContentAddRow("Normal",   "Standard spectum polarity output.") +
                                          helpContentAddRow("Inverted", "Inverted output to compensation for inversion somewhere else."); break;
    case "Umvl_interleaverSelect": content +=  helpContentAddRow("Controls the period of time interleaving which helps robustness where large interruptions are expected."); break;
        // Video Input
		case "VideoSourceSelect": content += 	helpContentAddRow("Default",			"SDI 1 used for HD modes and SDI 1-4 used for 4K modes.") +
												helpContentAddRow("QuadSync 1-4",		"Live switching of SDI 1-4 in QuadSync HD mode only.") +
												helpContentAddRow("Pattern + Tones",	"Video pattern and tones based on current configuration.") +
												helpContentAddRow("Pattern",			"Video pattern with external audio based on current configuration."); break;
		case "SampleFormatSelect": content += 	helpContentAddRow("2SI",			"4K video inputs in 2 Sample Interleave format.") +
												helpContentAddRow("SQD/HFR",		"4K video inputs in Square Division format or HD High Frame Rate phases."); break;
		case "QuadSyncSelect": content += 		helpContentAddRow("Off",			"Standard mode for single HD/UHD operation.") +
												helpContentAddRow("On",				"Flexible video input format and 4x 3G-SDI HD operation where SDI 1 is used as reference.") +
												helpContentAddRow("Freerun",		"Flexible video input format and 4x HD-SDI HD operation where no input is used as reference."); break;
		case "SpatialFilter": content += 		helpContentAddRow("Strength of softening filter applied prior to encoding, reduces detail and noise in source.") +
												helpContentAddRow("Used for lessen compression artefacts at low bitrates."); break;
		case "QuadSyncAlignment": content += 	helpContentAddRow("Displays alignment of QuadSync 1-4 sources relative to SDI 1 including conversion delay."); break;
		// Video Stream
		case "EncodeModeSelect": content += 	helpContentAddRow("H.265 HEVC",	"Highest video quality per bitrate, and lowest latency options.") +
												helpContentAddRow("H.264 AVC",	"Greater compatibility with legacy systems, and low latency option.") +
												helpContentAddRow("MPEG-2",		"Not recommended unless specifically required, limited to 8-bit 4:2:0 1080p30."); break;
		case "VideoFormatSelect": content += 	helpContentAddRow("Single HD/UHD operation video format must match that of the video input.") +
												helpContentAddRow("QuadSync operation video input is more flexible."); break;
		case "VideoBitrateSelect": content += 	helpContentAddRow("Auto",		"Recommended operation, video bitrate is adjusted based on required ASI/IP bitrate and other enabled streams.") +
												helpContentAddRow("Manual",		"Lowering video bitrate will leave unused bitrate in ASI/IP stream, raising video bitrate may increase ASI/IP bitrate."); break;
		case "VideoBitrateVal": content += 		helpContentAddRow("Auto mode displays active video bitrate.") +
												helpContentAddRow("Manual mode use to configure video bitrate."); break;
		case "SystemBitrateVal": content += 	helpContentAddRow("Sets bitrate of the ASI/IP stream."); break;
		case "LowDelayModeSelect": content += 	helpContentAddRow("Normal",		"Highest video quality per bitrate with typical end to end latency of 800-2000ms.") +
												helpContentAddRow("Low",		"Compromise between video quality, bitrate and latency with typical end to end latency of 200-1000ms.") +
												helpContentAddRow("Ultra Low",	"Requires the most bitrate but with typical end to end latency of a few frames, HEVC mode only."); break;
		case "CPBDelay": content +=				helpContentAddRow("Size of encode buffer used, provides tradeoff between latency and quality.") +
												helpContentAddRow("More buffering may be required at low bitrates to reduce pulsing effects."); break;
		case "BitDepthSelect": content += 		helpContentAddRow("8-bit",		"Lowest bitrate required.") +
												helpContentAddRow("10-bit",		"Recommended for HDR applications, and highest picture quality."); break;
		case "ChromaFormatSelect": content += 	helpContentAddRow("4:2:0",		"Lowest bitrate required.") +
												helpContentAddRow("4:2:2",		"Recommended for interlaced applications, and highest picture quality."); break;
		case "HDRWCGModeSelect": content += 	helpContentAddRow("Auto",		"HDR/WCG mode detected based on ST352 payload.") +
												helpContentAddRow("Otherwise",	"Forces HDR/WCG mode of video stream if ST352 payload is not present or incorrect."); break;
		// Video Helper
		case "VideoHelperHD": content += 		helpContentAddRow("Sets video format based on requested mode.") +
												helpContentAddRow("Disables QuadSync."); break;
		case "VideoHelperUHD": content += 		helpContentAddRow("Sets video format and sample format based on requested mode.") +
												helpContentAddRow("Disables QuadSync."); break;
		case "VideoHelperQuadSync": content += 	helpContentAddRow("Sets video format based on requested mode.") +
												helpContentAddRow("Enables QuadSync and SQD sample format."); break;
		case "VideoHelperRate": content += 		helpContentAddRow("Sets video format based on request frame max frame rate.") +
												helpContentAddRow("Select single HD/UHD, QuadSync or HFR mode first."); break;
		// Analogue Input
		case "AudioRefLevelXSelect": content +=		helpContentAddRow("Sets 0dBFS reference for analogue to digital conversion.") +
													helpContentAddRow("+24dBu not available on later hardware."); break;
		case "AudioGainXXVal": content += 			helpContentAddRow("0.0 to 40.0dB analogue gain in 0.5dB increments."); break;
		case "AudioP48EnableXXSelect": content += 	helpContentAddRow("Off",	"No phantom power.") +
													helpContentAddRow("On",		"48V phantom power."); break;
		// Audio Stream
		case "AudioSourceXSelect": content += 	helpContentAddRow("Test tone",		"-18dBFS 1kHz tone.") +
												helpContentAddRow("Analogue 1",		"First analogue input.") +
												helpContentAddRow("Analogue 2",		"Second analogue input.") +
												helpContentAddRow("SDI 1 (GXPX)",	"Embedded audio or data from specified SDI input, group and pair, QuadSync has limitations.") +
												helpContentAddRow("SDI 2-4 (GXPX)",	"Embedded audio from specified SDI input, group and pair, QuadSync mode only."); break;
		case "AudioEncoderXSelect": content += 	helpContentAddRow("LPCM",			"Ultra Low latency uncompressed audio or data. Bit depth requirements may vary for data, typically 20-bit for Dolby pass-through.") +
												helpContentAddRow("MPEG-1 L1",		"Ultra Low latency compressed audio.") +
												helpContentAddRow("MPEG-1 L2",		"Low latency compressed audio, Low/Normal latency modes use a higher quality codec on streams 1-4.") +
												helpContentAddRow("AAC-LC",			"Highest audio quality per bitrate, not available with Ultra Low latency mode."); break;
		case "AudioBitrateXSelect": content += 	helpContentAddRow("LPCM (16-bit)",	"1920kbps only.") +
												helpContentAddRow("LPCM (20-bit)",	"2304kbps only.") +
												helpContentAddRow("LPCM (24-bit)",	"2688kbps only.") +
												helpContentAddRow("MPEG-1 L1",		"192-448kbps.") +
												helpContentAddRow("MPEG-1 L2",		"96-384kbps.") +
												helpContentAddRow("AAC-LC",			"64-256kbps."); break;
		// Audio Helper
		case "AudioHelperStandard": content += 	helpContentAddRow("Sets SDI audio source for single HD/UHD operation.") +
												helpContentAddRow("Encoding mode selected based on number of channels required and video latency mode."); break;
		case "AudioHelperQuadSync": content += 	helpContentAddRow("Sets SDI audio source for QuadSync operation.") +
												helpContentAddRow("Encoding mode selected based on number of channels required and video latency mode."); break;
		// Service
		case "ProgramNumberVal": content += 	helpContentAddRow("1 to 65535 program number to be included in PAT.") +
												helpContentAddRow("Decoders may use this for identifying which service to decode."); break;
		case "ServiceNameVal": content += 		helpContentAddRow("32 character name to be included in SDT.") +
												helpContentAddRow("Decoders may use this for identifying which service to decode."); break;
		case "XXXPidVal": content += 			helpContentAddRow("32 to 8190 decimal PID to be included in PAT/PMT.") +
												helpContentAddRow("Decoders will either extract PIDs from PAT/PMT automatically or may require manual entry."); break;
		// Remux
		case "RemuxModeSelect": content += 	helpContentAddRow("Off",	"Remux mode disabled.") +
											helpContentAddRow("Relay (ASI)",	"Remux relay mode, ASI input used for TX, IP or recording source.") +
											helpContentAddRow("Relay (SDI/HANC)",	"Remux relay mode, SDI ancillary input used for TX, IP or recording source."); break;
		// Scrambling
		case "DESModeSelect": content += 	helpContentAddRow("Off",	"DES scrambling disabled.") +
											helpContentAddRow("On",		"DES scrambling enabled, active streams will be protected with DES.") +
											helpContentAddRow(" ",		"Scrambled services will require descrambling before decoding can take place."); break;
		case "DESKeyVal": content += 		helpContentAddRow("56-bit scrambling key, use 14 characters (0123456789ABCDEF) for valid key."); break;
		case "BISSModeSelect": content += 	helpContentAddRow("Off",	"BISS scrambling disabled.") +
											helpContentAddRow("On",		"BISS-1 scrambling enabled, active streams will be protected with BISS.") +
											helpContentAddRow(" ",		"Scrambled services will require descrambling before decoding can take place."); break;
		case "BISSKeyVal": content += 		helpContentAddRow("48-bit scrambling key, use 12 characters (0123456789ABCDEF) for valid key."); break;
		// Data
		case "AncillaryModeSelect": content += 	helpContentAddRow("Off",			"Ancillary channel disabled.") +
												helpContentAddRow("All Type 2",		"Ancillary VANC/HANC packets with Type 2 DID from all SDI inputs are extracted and included in ASI/IP output.") +
												helpContentAddRow("HANC Type 2",	"Ancillary HANC packets with Type 2 DID from all SDI inputs are extracted and included in ASI/IP output.") +
												helpContentAddRow("User Type 1",	"Ancillary VANC/HANC packets with Type 1 User Application DID from all SDI inputs are extracted and included in ASI/IP output."); break;
		case "AncillaryBitrateVal": content +=  helpContentAddRow("Sets amount of bitrate reserved for ancillary data.") +
												helpContentAddRow("Per camera typically 200kb/s required for only HANC packets.") +
												helpContentAddRow("Film cameras may require 1000-3000kb/s for VANC/HANC packets."); break;
		case "DataModeSelect": content += 		helpContentAddRow("Off",			"Data channel disabled.") +
												helpContentAddRow("RS-232",			"Data channel enabled using RS-232 data input.") +
												helpContentAddRow("External CFU",	"Data channel added to PMT but embedded externally.") +
												helpContentAddRow("Internal CC",	"Data channel enabled using internal camera control.") +
												helpContentAddRow("RS-232 Raw",	"Data channel enabled using RS-232 data input with no PES packetisation."); break;
		case "DataBaudSelect": content += 		helpContentAddRow("Baud rate selection for RS-232 data input."); break;
		// Service Helper
		case "ServiceHelperPIDs": content += 	helpContentAddRow("32-254",		"Use PIDs between 32 and 254 (limited for dual pedestal modulation modes).") +
												helpContentAddRow("32-8190",	"Use PIDs between 32 and 8190.") +
												helpContentAddRow("",			"PIDs are assigned in blocks of 32 based on program number."); break;
		// Stream Output
		case "IPStreamEnable": content += 		helpContentAddRow("Off",		"IP stream disabled.") +
												helpContentAddRow("Transmit",	"IP stream output enabled."); break;
		case "IPStreamInterface": content += 	((port1=="")?"":helpContentAddRow(port1,	"Stream via Ethernet " + port1 + ", supports up to 50Mbps UDP/RTP or 20Mbps SRT.")) +
												((port2=="")?"":helpContentAddRow(port2,	"Stream via Ethernet " + port2 + ", supports up to 50Mbps UDP/RTP or 20Mbps SRT.")) +
												((port3=="")?"":helpContentAddRow(port3,	"Stream via Ethernet " + port3 + ", UDP/RTP only.")); break;
		case "IPStreamProtocol": content += 	helpContentAddRow("UDP",		"MPEG TS over UDP (User Datagram Protocol).") +
												helpContentAddRow("RTP",		"MPEG TS over RTP (Real-time Transport Protocol).") +
												helpContentAddRow("SRT",		"MPEG TS over SRT (Secure Reliable Transport), recommended for lossy networks."); break;
		case "SRTMode": content += 				helpContentAddRow("Caller",		"Encoder instigates outbound connection to Listener.") +
												helpContentAddRow("Listener",	"Encoder waits for inbound connection from Caller.") +
												helpContentAddRow("Rendezvous",	"Encoder tries to instigate connection to Rendezvous.") +
												helpContentAddRow(" ",			"Typically port forwarding would be required at Listener end, Rendezvous tries to avoid forwarding by calling from both ends."); break;
		case "SRTDelay": content += 			helpContentAddRow("Worse Case Loss Rate <= 1%",		"Set delay to 3x Round-Trip Time.") +
												helpContentAddRow("Worse Case Loss Rate <= 3%",		"Set delay to 4x Round-Trip Time.") +
												helpContentAddRow("Worse Case Loss Rate <= 7%",		"Set delay to 5x Round-Trip Time.") +
												helpContentAddRow("Worse Case Loss Rate <= 10%",	"Set delay to 6x Round-Trip Time."); break;
		case "IPStreamAddress": content +=		helpContentAddRow("Target IP address for IP stream, can be unicast or multicast address."); break;
		case "IPStreamPort": content +=			helpContentAddRow("Target Port for IP stream."); break;
		case "IPStreamTTL": content +=			helpContentAddRow("Time-To-Live for multicast IP packets."); break;
		case "IPStreamNumTP": content +=		helpContentAddRow("7",		"Most efficient and recommended setting.") +
												helpContentAddRow("6",		"Reduces MTU size when streaming over networks with encapsulation overheads.") +
												helpContentAddRow("5-1",	"Typically avoid."); break;
		case "IPFECEnable": content +=			helpContentAddRow("Off",	"IP FEC output disabled.") +
												helpContentAddRow("On",		"IP FEC output enabled, SMPTE 2022-1 can be used to provide resilience to packet loss."); break;
		case "IPFECCols": content +=			helpContentAddRow("1 to 20 FEC columns generated, fewer columns adds greater resilience but also higher bitrate overheads.") +
												helpContentAddRow("FEC columns x rows must be <= 100 for FEC to be sent.") +
												helpContentAddRow("Note estimated bitrate on the stream diagnostics window."); break;
		case "IPFECRows": content +=			helpContentAddRow("4 to 20 FEC rows generated, fewer rows adds greater resilience but also higher bitrate overheads.") +
												helpContentAddRow("FEC columns x rows must be <= 100 for FEC to be sent.") +
												helpContentAddRow("Note estimated bitrate on the stream diagnostics window."); break;
		// Stream Diagnostics
		case "B110_Diagnostics": content +=		helpContentAddRow("Estimated bitrate and packet size based on current configuration."); break;
		case "DTM_Diagnostics": content +=		helpContentAddRow("Estimated bitrate and packet size based on current configuration.") +
												helpContentAddRow("No estimated bitrate shown then check ASI-IP is connected to ASI Out on Sapphire unit.") +
												helpContentAddRow("No resolved address could suggest incorrect IP address or lack of connectivity to end point."); break;
		case "SRT_Diagnostics": content +=		helpContentAddRow("A no-connection is typically caused by selecting a Mode, Address or Port Number that does not match the remote end.") +
												helpContentAddRow("Other causes of no-connection may be related to local or remote gateway/firewall rules which filter traffic for the configured Port Number.") +
												helpContentAddRow("Please make sure to add rules for the requested UDP port to any router/gateway firewall.") +
												helpContentAddRow("In cases where the connection involves a large number of router hops between encoder and decoder, a higher TTL value may be required.") +
												helpContentAddRow("If the level of packet loss or re-transmission is high, causing unrecoverable errors, consider increasing the Delay settings and/or lowering the stream bitrate.") +
												helpContentAddRow("Ensure that the actual SRT delay is larger than the required multiple of Round-Trip Time, 3-6x RTT depending on packet loss rate.") +
												helpContentAddRow("For more help and setup details please consult the SRT Deployment Guide available from the BWS FTP server's manuals folder (see Info tab)."); break;
		// File Output
		case "RecordEnable": content += 		helpContentAddRow("Off",		"Recording disabled.") +
												helpContentAddRow("On",			"Recording enabled.") +
												helpContentAddRow("Triggered",	"Recording can be triggered.") +
												helpContentAddRow(" ",			"Recording is limited to 30Mbps."); break;
    case "RecordControl": content += 		helpContentAddRow("Toggle",		"Button starts or stops recording depending on current state."); break;
		// File Input
		case "PlaybackControl": content += 		helpContentAddRow("Start",		"Button starts playback from specfied offset.") +
												helpContentAddRow("Stop",		"Button stops playback and resumes live output."); break;
		case "PlaybackOffset": content +=		helpContentAddRow("Playback offset in minutes applied with Start button."); break;
		// File Diagnostics
		case "File_Diagnostics": content +=		helpContentAddRow("Current state of USB recording/playback functionality.") +
												helpContentAddRow("Files can be downloaded from USB Storage remotely via link provided."); break;
		// Ethernet Ports
		case "DHCPModeSelectX": content +=	helpContentAddRow("Off", "Manual IP address/gateway/subnet settings.") +
											helpContentAddRow("On", "DHCP used to obtain IP address/gateway/subnet settings, DHCP service must be present."); break;
		case "IPAddrX": content +=			helpContentAddRow("IPv4 address in dotted-decimal notation, status shown if DHCP enabled."); break;
		case "IPGatewayX": content +=		helpContentAddRow("IPv4 address in dotted-decimal notation, status shown if DHCP enabled."); break;
		case "IPMaskX": content +=			helpContentAddRow("IPv4 address in dotted-decimal notation, status shown if DHCP enabled."); break;
		case "ethX_macaddr": content +=		helpContentAddRow("48-bit MAC address unique to this Ethernet port."); break;
		case "ethX_state": content +=		helpContentAddRow("Link state for this Ethernet port including RX/TX packet count."); break;
		case "ethX_state_dtm": content +=	helpContentAddRow("Link state for this Ethernet port including RX/TX packet count.") +
											helpContentAddRow("Requires IP Module software version v2.5 or greater."); break;
		// Global Settings
		case "IPBridgeSelect": content +=	helpContentAddRow("Off", "Ethernet ports 1 and 2 are independent.") +
											helpContentAddRow("On", "Ethernet ports 1 and 2 are bridged together."); break;
		case "FanModeSelect": content +=	helpContentAddRow("Record", "SDI triggered fan control, record speed can be separately defined. Uses idle speed when not triggered.") +
											helpContentAddRow("Idle", "Enable fans at idle speed, idle speed can be separately defined.") +
											helpContentAddRow("Full", "Enable fans at full speed.") +
											helpContentAddRow("", "Full speed is forced if FPGA temperature exceeds 85&deg;C."); break;
		case "FanSpeedIdleSelect": content +=	helpContentAddRow("Fan speed while in idle/non-record mode."); break;
		case "FanSpeedRecSelect": content +=	helpContentAddRow("Fan speed while in record/trigger mode."); break;
		case "UnitAddress": content +=		helpContentAddRow("ID used for remote control addressing."); break;
		case "UnitName": content +=			helpContentAddRow("Name for identification appears in webpage header and on device finder applications."); break;
		case "UnitModeSelect": content +=	helpContentAddRow("Encoder", "Unit runs as an encoder, reboot required on change.") +
											helpContentAddRow("Decoder", "Unit runs as an decoder, reboot required on change."); break;
		case "WebPassword": content +=		helpContentAddRow("Set, change or clear admin password for web interface.") +
											helpContentAddRow("Forgotten passwords can be removed by restoring default settings from a front panel interface."); break;
		// USB Storage
		case "SdaXSize": content +=		helpContentAddRow("Max capacity of target USB device partition (and current utilisation if mounted)."); break;
		case "SdaXType": content +=		helpContentAddRow("vfat", "Required for upgrading unit firmware or license, and recording functionality."); break;
		case "SdaXFormat": content +=	helpContentAddRow("Formatting the device creates a single vfat partition on the disk for recording.") +
										helpContentAddRow("Be aware this will erase all current data held on the USB device."); break;
		// Upgrades
		case "CodecFirmware": content +=	helpContentAddRow("Firmware update files are typically labelled " + BoardType.toLowerCase() + "_update_vX.X.tar.") +
											helpContentAddRow("Latest firmware can be obtained via our FTP site, for details see Info page.")  +
											helpContentAddRow("Loss of power during the upgrade process could cause the unit to become non-functional and require repair."); break;
		case "CodecLicense": content +=		helpContentAddRow("License update files are typically labelled " + BoardType.toLowerCase() + "_XXXXXXXX_00000000.lic.") +
											helpContentAddRow("Serial number of the unit found on the Info page should match that shown in the file name.")  +
											helpContentAddRow("Loading an invalid licence file could cause loss of all licensed features until correct license is restored."); break;
		case "TxFirmware": content +=		helpContentAddRow("Firmware update files are typically labelled d1500_vX.X.all.") +
											helpContentAddRow("Latest firmware can be obtained via our FTP site, for details see Info page."); break;
		case "TxLicense": content +=		helpContentAddRow("License update files are typically labelled AB123456_XXXXXXXX_00000000.lic.") +
											helpContentAddRow("Serial number of the unit found on the Info page should match that shown in the file name.")  +
											helpContentAddRow("Loading an invalid licence file could cause loss of all licensed features until correct license is restored."); break;
		case "ControllerUpgrade": content +=	helpContentAddRow("Trigger remote upgrade of front panel controller software.") +
												helpContentAddRow("This is recommmended if Software version and Controller version do not match."); break;
	}
	content += "</table>";
	document.getElementById('help_window_text').innerHTML = content;
}
