var timer = null;
var CustID;
var TxPresent = 0;
var DTM3200Present = 0;
var PresetNumber = 0;
var B120Present = 0;
var LicenseMask;
var LicDec;
var license_des;
var license_biss;
var license_enc;
var license_dec;
var license_iptx;
var license_iprx;
var license_rec;

var logo  = 'logo.jpg'

var decoder_mode = ["H.265 HEVC", "H.264 AVC", "MPEG-2"];
var vid_format = ["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"];
var video_delay_mode = ["Normal", "Low", "Ultra Low"];
var video_source = ["Decoder", "Pattern + Tones", "Pattern"];
var quad_sync_mode = ["Off", "HD-SDI 1080i", "HD-SDI 1080psf", "HD-SDI 1080p", "3G-SDI 1080p", "HD-SDI 720p"];
var sample_format = ["2SI", "SQD/HFR"];
var off_on = ["Off", "On"];
var no_yes = ["No", "Yes"];
var audio_dec = ["Off", "LPCM (16-bit)", "LPCM (20-bit)", "LPCM (24-bit)", "AAC-LC", "MPEG-1 L1", "MPEG-1 L2"];
var aud_ref = ["+24dBu", "+18dBu"];
var video_fail_mode = ["Freeze", "Blue"];
var service_select = ["Manual", "Auto"];
var genlock_mode = ["Off", "External", "Internal"];
var mode_select = ["Encoder", "Decoder"];
var tx_select = ["No", "D1550"];
var oled_type = ["SSD1307 (96x16)", "SSD1306 (96x16)", "SSD1309 (128x64)"];
var stream_enable_select = ["Off", "Receive", "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 stream_type_select = ["Unicast", "Multicast"];
var stream_rate_mode = ["PCR Estimate", "Fixed Buffer", "Stream Estimate", "Disable Buffer"];
var IPStreamProtocol_Select = ["UDP", "RTP", "SRT"];
var IPStreamProtocol_set = [1, 2, 0];
var IPStreamProtocol_get = [2, 0, 1];
var SRTMode_Select = ["Caller", "Listener", "Rendezvous"];
var FanMode_Select = ["Auto", "Off", "Full", "Idle"];
var RecordEnable_Select = ["Off", "On", "Triggered"];

var chroma_depth = ["8-bit", "10-bit"];
var chroma_format = ["4:2:0", "4:2:2"];
var data_mode = ["Off", "8-bit No Parity, 1 Stop"];
var data_baud = ["1200", "2400", "4800", "9600", "19200", "38400", "57600", "115200", "230400"];
var error_ok = ["ERROR", "OK"];
var nolock_lock = ["NO LOCK", "LOCK"];

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

var srt_cnt = 0;

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 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) && (license_iprx == 0))
    {
		document.getElementById("ipstream").style.display = "none";
    }
    else
    {
		document.getElementById("ipstream").style.display = "inline-block";
    }

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

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

    if(DTM3200Present == 0)
	{
		document.getElementById("Ethernet_Stream").style.display = "none";
		document.getElementById("IP_Hardware").style.display = "none";
	}
	else
	{
		document.getElementById("Ethernet_Stream").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 = IPStreamProtocol_get[getValue("IPStreamProtocol")];
	var SRTMode = getValue("SRTMode");
    
    if(IPStreamEnable == 1) // receive
    {
        document.getElementById("IPStreamProtocolRow").style.display = "inline-block";
        document.getElementById("IPStreamModeRow").style.display = (IPStreamProtocol != 1)?"inline-block":"none"; // not SRT           
        document.getElementById("IPStreamAddressRow").style.display = (IPStreamProtocol != 1 && getValue("IPStreamMode") == 1)?"inline-block":"none"; // not SRT and multicast
		document.getElementById("RemoteHostAddressRow").style.display = (IPStreamProtocol == 1 && SRTMode != 1)?"inline-block":"none"; // SRT and not listener
        document.getElementById("RemoteHostAddressLabel").innerHTML = "Remote Host Address";
        document.getElementById("IPStreamPortRow").style.display = "inline-block";
        document.getElementById("IPStreamTTLRow").style.display = "none";
        document.getElementById("IPStreamNumTPRow").style.display = "none";
        document.getElementById("IPStreamDelayRow").style.display = "inline-block";
        document.getElementById("IPStreamRateModeRow").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";
            document.getElementById("b110_packetsize_row").style.display = "none";
            document.getElementById("b110_jitter_tolerance_row").style.display = "inline-block";
            document.getElementById("b110_jitter_errors_row").style.display = "inline-block";
            document.getElementById("b110_lock_errors_row").style.display = "inline-block";
            document.getElementById("b110_delay_factor_row").style.display = "inline-block";

            var tmpIPStreamProtocol = IPStreamProtocol_get[getValue("IPStreamProtocol")];
            IPStreamProtocol_Select = ["UDP/RTP", "SRT"];
            IPStreamProtocol_get = [0, 1];
            IPStreamProtocol_set = [0, 1, 0];
            removeOptions("IPStreamProtocol");
            selectOptions("IPStreamProtocol",IPStreamProtocol_Select);
            setSelectValue("IPStreamProtocol",IPStreamProtocol_set[tmpIPStreamProtocol]);
        }
        else
        {
            document.getElementById("DTM_Diagnostics").style.display = "inline-block";
            document.getElementById("B110_Diagnostics").style.display = "none";
            document.getElementById("dtm_packetsize_row").style.display = "none";
            document.getElementById("dtm_overheads_row").style.display = "none";
            document.getElementById("dtm_resolved_row").style.display = "none";
            document.getElementById("dtm_fec_cols_row").style.display = "inline-block";
            document.getElementById("dtm_fec_rows_row").style.display = "inline-block";
            document.getElementById("dtm_fec_delay_row").style.display = "inline-block";
            document.getElementById("dtm_fec_before_row").style.display = "inline-block";
            document.getElementById("dtm_fec_after_row").style.display = "inline-block";
            document.getElementById("dtm_jitter_tolerance_row").style.display = "inline-block";
            document.getElementById("dtm_jitter_errors_row").style.display = "inline-block";
            document.getElementById("dtm_lock_errors_row").style.display = "inline-block";
            document.getElementById("dtm_delay_factor_row").style.display = "inline-block";

            var tmpIPStreamProtocol = IPStreamProtocol_get[getValue("IPStreamProtocol")];
            IPStreamProtocol_Select = ["UDP/RTP"];
            IPStreamProtocol_get = [0];
            IPStreamProtocol_set = [0, 0, 0];
            removeOptions("IPStreamProtocol");
            selectOptions("IPStreamProtocol",IPStreamProtocol_Select);
            setSelectValue("IPStreamProtocol",IPStreamProtocol_set[tmpIPStreamProtocol]);
        }
    }
    else if(IPStreamEnable == 2) // transmit
    {
        document.getElementById("IPStreamProtocolRow").style.display = "inline-block";
        document.getElementById("IPStreamModeRow").style.display = "none";
        document.getElementById("IPStreamAddressRow").style.display = "none";
		document.getElementById("RemoteHostAddressRow").style.display = (IPStreamProtocol != 1 || SRTMode != 1)?"inline-block":"none"; // not SRT or not listener
        document.getElementById("RemoteHostAddressLabel").innerHTML = "Stream Address";
        document.getElementById("IPStreamPortRow").style.display = "inline-block";
        document.getElementById("IPStreamTTLRow").style.display = "inline-block";
        document.getElementById("IPStreamNumTPRow").style.display = "inline-block";
        document.getElementById("IPStreamDelayRow").style.display = "none";
        document.getElementById("IPStreamRateModeRow").style.display = "none";
        
        if(IPStreamInterface != 2) // not DTM-3200
        {
            document.getElementById("DTM_Diagnostics").style.display = "none";
            document.getElementById("B110_Diagnostics").style.display = "inline-block";
            document.getElementById("b110_packetsize_row").style.display = "inline-block";
            document.getElementById("b110_jitter_tolerance_row").style.display = "none";
            document.getElementById("b110_jitter_errors_row").style.display = "none";
            document.getElementById("b110_lock_errors_row").style.display = "none";
            document.getElementById("b110_delay_factor_row").style.display = "none";

            var tmpIPStreamProtocol = IPStreamProtocol_get[getValue("IPStreamProtocol")];
            IPStreamProtocol_Select = ["UDP", "RTP", "SRT"];
            IPStreamProtocol_get = [2, 0, 1];
            IPStreamProtocol_set = [1, 2, 0];
            removeOptions("IPStreamProtocol");
            selectOptions("IPStreamProtocol",IPStreamProtocol_Select);
            setSelectValue("IPStreamProtocol",IPStreamProtocol_set[tmpIPStreamProtocol]);
        }
        else
        {
            document.getElementById("DTM_Diagnostics").style.display = "inline-block";
            document.getElementById("B110_Diagnostics").style.display = "none";
            document.getElementById("dtm_packetsize_row").style.display = "inline-block";
            document.getElementById("dtm_overheads_row").style.display = "inline-block";
            document.getElementById("dtm_resolved_row").style.display = "inline-block";
            document.getElementById("dtm_fec_cols_row").style.display = "none";
            document.getElementById("dtm_fec_rows_row").style.display = "none";
            document.getElementById("dtm_fec_delay_row").style.display = "none";
            document.getElementById("dtm_fec_before_row").style.display = "none";
            document.getElementById("dtm_fec_after_row").style.display = "none";
            document.getElementById("dtm_jitter_tolerance_row").style.display = "none";
            document.getElementById("dtm_jitter_errors_row").style.display = "none";
            document.getElementById("dtm_lock_errors_row").style.display = "none";
            document.getElementById("dtm_delay_factor_row").style.display = "none";

            var tmpIPStreamProtocol = IPStreamProtocol_get[getValue("IPStreamProtocol")];
            IPStreamProtocol_Select = ["UDP", "RTP"];
            IPStreamProtocol_get = [2, 0];
            IPStreamProtocol_set = [1, 0, 0];
            removeOptions("IPStreamProtocol");
            selectOptions("IPStreamProtocol",IPStreamProtocol_Select);
            setSelectValue("IPStreamProtocol",IPStreamProtocol_set[tmpIPStreamProtocol]);
        }
    }
    else // disabled
    {
        document.getElementById("IPStreamProtocolRow").style.display = "none";
        document.getElementById("IPStreamModeRow").style.display = "none"; 
        document.getElementById("IPStreamAddressRow").style.display = "none";  
		document.getElementById("RemoteHostAddressRow").style.display = "none";
        document.getElementById("IPStreamPortRow").style.display = "none";
        document.getElementById("IPStreamTTLRow").style.display = "none";
        document.getElementById("IPStreamNumTPRow").style.display = "none";
        document.getElementById("IPStreamDelayRow").style.display = "none";
        document.getElementById("IPStreamRateModeRow").style.display = "none";
        
        document.getElementById("DTM_Diagnostics").style.display = "none";
        document.getElementById("B110_Diagnostics").style.display = "none";     
    }
    
	if(IPStreamEnable == 0 || IPStreamInterface != 2 || IPStreamProtocol != 0) // 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";
        if(IPStreamEnable == 1) // receive
        {
            document.getElementById("IPFECColsRow").style.display = "none";
            document.getElementById("IPFECRowsRow").style.display = "none";
        }
        else
        {
            document.getElementById("IPFECColsRow").style.display = "inline-block";
            document.getElementById("IPFECRowsRow").style.display = "inline-block";
        }
	}

	if(IPStreamEnable == 0 || IPStreamProtocol != 1) // 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 showEngineering()
{
	if(document.getElementById('Unit').style.display == "inline-block")
		document.getElementById('EngineeringOptions').style.display = "inline-block"
}

function startupDec()
{
  openTabh(event, 'Status');
  selectOptions("ServiceSelSelect",service_select)
  selectOptions("DESModeSelect",off_on)
  selectOptions("BISSModeSelect",off_on)
  selectOptions("AncillaryModeSelect",off_on);
  selectOptions("VideoFormatSelect",vid_format)
  selectOptions("LowDelayModeSelect",video_delay_mode)
  selectOptions("VideoSourceSelect",video_source)
  selectOptions("SampleFormatSelect",sample_format)
  selectOptions("QuadSyncSelect",quad_sync_mode)
  selectOptions("HDDuplicateSelect",off_on)
  selectOptions("FailModeSelect",video_fail_mode)
  selectOptions("GenlockModeSelect",genlock_mode)
  selectOptions("AudRefLev0",aud_ref)
  selectOptions("AudRefLev1",aud_ref)
  //selectOptions("AudioSource0Select",off_on)
  //selectOptions("AudioSource1Select",off_on)
  //selectOptions("AudioSource2Select",off_on)
  //selectOptions("AudioSource3Select",off_on)
  //selectOptions("AudioSource4Select",off_on)
  //selectOptions("AudioSource5Select",off_on)
  //selectOptions("AudioSource6Select",off_on)
  //selectOptions("AudioSource7Select",off_on)
  selectOptions("RecordEnable",RecordEnable_Select);
  selectOptions("IPStreamEnable",stream_enable_select)
  selectOptions("IPStreamInterface",stream_interface_select)
  selectOptions("IPStreamProtocol",IPStreamProtocol_Select);
  selectOptions("IPStreamMode",stream_type_select)
  selectOptions("IPStreamRateMode",stream_rate_mode)
  selectOptions("SRTMode",SRTMode_Select);
  selectOptions("IPStreamNumTP",IPStreamNumTP_Select);
  selectOptions("IPFECEnable",off_on)
  selectOptions("DHCPModeSelect0",off_on)
  selectOptions("DHCPModeSelect1",off_on)
  selectOptions("DtmDHCPModeSelect",off_on)
  selectOptions("IPBridgeSelect",off_on)
  selectOptions("FanModeSelect",FanMode_Select)
  selectOptions("UnitModeSelect",mode_select)
  selectOptions("TxPresentSelect",tx_select);
  selectOptions("B120PresentSelect",no_yes);
  selectOptions("DTM3200PresentSelect",no_yes);
  selectOptions("OLEDTypeSelect",oled_type);
  //selectOptions(AudioDecoder0Select,audio_dec)
  //selectOptions(AudioDecoder1Select,audio_dec)
  //selectOptions(AudioDecoder2Select,audio_dec)
  //selectOptions(AudioDecoder3Select,audio_dec)
  getStatus();
  getUnit();
  getDecode();
  getStatus();
  getPreset()
  selectOptionsValue("filePre",preset_sel,preset_val);
  document.getElementById("status").click();
  var down = document.getElementById('PresetSelect')
  down.addEventListener("change",downloadPreset);
}

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-2";
  }
  else
  {
	 label += "Unknown";
  }
  document.getElementById("meter_"+(b+1)).innerHTML = label;
}

function refresh()
{
  getDecode()
}

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;
  }
  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();
  getStatus();
  getDecode();
  getUnit();

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

function timer_status_only()
{
  getStatus();
}

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

  getDecode();
  document.getElementById("apply_config").style.display = "inline-block";

  // 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("restore_def").style.display = "none";
    document.getElementById("reload_preset").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')
  {
    getDecode();
    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("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("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("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("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("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(TxPresent != 0)
	  title += " TX";
  else
	  title += " Decoder";

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

  document.getElementById('titleUp').value = title;
  document.getElementById('titleLic').value = title;
  document.getElementById('headUp').value = UnitName;
  document.getElementById('headLic').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)
  {
    setDecode();
  }
}

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

function getStatus()
{
  var get_json = new XMLHttpRequest();
  get_json.addEventListener("load", (e) =>
  {
    var json_load = JSON.parse(e.target.responseText);
    var UnitMode = json_load.UnitMode;
    var ASILock = json_load.ASILock;
    var ASIBitrate = (json_load.ASIBitrate)/1000;
    var ServiceOk =  json_load.ServiceOk;
    var NumServices =  json_load.NumServices;
    var ServiceId =  json_load.ServiceId;
    var ServiceName =  json_load.ServiceName;
    var VidDecodeOk = json_load.VidDecodeOk;
    var VideoFormat = json_load.VideoFormat;
    var VideoMode = json_load.VideoMode;
    var LowDelayMode = json_load.LowDelayMode;
    var BitDepth = json_load.BitDepth;
    var ChromaFormat = json_load.ChromaFmt;
    var SDIFormat = json_load.SDIFormat;
    var FullRange = json_load.FullRange;
    var Colour = json_load.Colour;
    var Transfer = json_load.Transfer;
    var Matrix = json_load.Matrix;
    var VideoPid1 =  json_load.VideoPid1;
    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 AudioPid8 =  json_load.AudioPid8;
    var DataPid1 =  json_load.DataPid1;
    var DataPid2 =  json_load.DataPid2;
    var DataPid3 =  json_load.DataPid3;
    var PMTPid =  json_load.PMTPid;
    var PCRPid1 =  json_load.PCRPid1;
    var DataBaud1 =  json_load.DataBaud1;
    var GenlockStatus =  json_load.GenlockStatus;
    var GenlockFormat =  json_load.GenlockFormat;
    var GenlockDelay =  json_load.GenlockDelay1;
    var genlock_mode = getValue("GenlockModeSelect");
    var SampleFormat = getText("SampleFormatSelect");
    var FPGATemp =  json_load.FPGATemp;
    var PSUTemp =  json_load.PSUTemp;
    var InVoltage =  json_load.InVoltage;
    var ControllerVersion =  json_load.ControllerVersion;
    var SoftwareVersion =  json_load.SoftwareVersion;
    var HardwareVersion =  json_load.HardwareVersion;
    var FPGAHash = json_load.FPGAHash;
    var SRTVersion =  json_load.SRTVersion;
    var SerialNumber =  json_load.SerialNumber;

    CustID = json_load.CustID;
    DTM3200Present = json_load.DTM3200Present;
    B120Present = json_load.B120Present;
    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_iprx = (LicDec&(1<<16))>>16
    license_rec = (LicDec&(1<<19))>>19

    // 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 Cineark FTX or HTX units
    if((CustID != "0000061e") && (CustID != "0000d959"))
    {
      document.getElementById("FanModeRow").style.display = "none"
    }

    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();

	var enableLevelBar0 = ((AudioPid1 == 0) || (AudioPid1 == 8191))?0:1;
	var enableLevelBar1 = ((AudioPid2 == 0) || (AudioPid2 == 8191))?0:1;
	var enableLevelBar2 = ((AudioPid3 == 0) || (AudioPid3 == 8191))?0:1;
	var enableLevelBar3 = ((AudioPid4 == 0) || (AudioPid4 == 8191))?0:1;
	var enableLevelBar4 = ((AudioPid5 == 0) || (AudioPid5 == 8191))?0:1;
	var enableLevelBar5 = ((AudioPid6 == 0) || (AudioPid6 == 8191))?0:1;
	var enableLevelBar6 = ((AudioPid7 == 0) || (AudioPid7 == 8191))?0:1;
	var enableLevelBar7 = ((AudioPid8 == 0) || (AudioPid8 == 8191))?0:1;
	updateLevelBar(enableLevelBar0,json_load.AudLevL0,json_load.AudData0,0,0,json_load.AudioMode1);
	updateLevelBar(enableLevelBar0,json_load.AudLevR0,json_load.AudData0,0,1,json_load.AudioMode1);
	updateLevelBar(enableLevelBar1,json_load.AudLevL1,json_load.AudData1,1,0,json_load.AudioMode2);
	updateLevelBar(enableLevelBar1,json_load.AudLevR1,json_load.AudData1,1,1,json_load.AudioMode2);
	updateLevelBar(enableLevelBar2,json_load.AudLevL2,json_load.AudData2,2,0,json_load.AudioMode3);
	updateLevelBar(enableLevelBar2,json_load.AudLevR2,json_load.AudData2,2,1,json_load.AudioMode3);
	updateLevelBar(enableLevelBar3,json_load.AudLevL3,json_load.AudData3,3,0,json_load.AudioMode4);
	updateLevelBar(enableLevelBar3,json_load.AudLevR3,json_load.AudData3,3,1,json_load.AudioMode4);
	updateLevelBar(enableLevelBar4,json_load.AudLevL4,json_load.AudData4,4,0,json_load.AudioMode5);
	updateLevelBar(enableLevelBar4,json_load.AudLevR4,json_load.AudData4,4,1,json_load.AudioMode5);
	updateLevelBar(enableLevelBar5,json_load.AudLevL5,json_load.AudData5,5,0,json_load.AudioMode6);
	updateLevelBar(enableLevelBar5,json_load.AudLevR5,json_load.AudData5,5,1,json_load.AudioMode6);
	updateLevelBar(enableLevelBar6,json_load.AudLevL6,json_load.AudData6,6,0,json_load.AudioMode7);
	updateLevelBar(enableLevelBar6,json_load.AudLevR6,json_load.AudData6,6,1,json_load.AudioMode7);
	updateLevelBar(enableLevelBar7,json_load.AudLevL7,json_load.AudData7,7,0,json_load.AudioMode8);
	updateLevelBar(enableLevelBar7,json_load.AudLevR7,json_load.AudData7,7,1,json_load.AudioMode8);

	for (var i = 0; i < 16; i++)
	{
        var prognum = 0, progname = "";
        switch(i) {
          case 0: prognum = json_load.ServiceId1; progname = json_load.ServiceName1; break;
          case 1: prognum = json_load.ServiceId2; progname = json_load.ServiceName2; break;
          case 2: prognum = json_load.ServiceId3; progname = json_load.ServiceName3; break;
          case 3: prognum = json_load.ServiceId4; progname = json_load.ServiceName4; break;
          case 4: prognum = json_load.ServiceId5; progname = json_load.ServiceName5; break;
          case 5: prognum = json_load.ServiceId6; progname = json_load.ServiceName6; break;
          case 6: prognum = json_load.ServiceId7; progname = json_load.ServiceName7; break;
          case 7: prognum = json_load.ServiceId8; progname = json_load.ServiceName8; break;
          case 8: prognum = json_load.ServiceId9; progname = json_load.ServiceName9; break;
          case 9: prognum = json_load.ServiceId10; progname = json_load.ServiceName10; break;
          case 10: prognum = json_load.ServiceId11; progname = json_load.ServiceName11; break;
          case 11: prognum = json_load.ServiceId12; progname = json_load.ServiceName12; break;
          case 12: prognum = json_load.ServiceId13; progname = json_load.ServiceName13; break;
          case 13: prognum = json_load.ServiceId14; progname = json_load.ServiceName14; break;
          case 14: prognum = json_load.ServiceId15; progname = json_load.ServiceName15; break;
          case 15: prognum = json_load.ServiceId16; progname = json_load.ServiceName16; break;
        }
		document.getElementById("service_"+(i+1)).style.display = (prognum == 0 && i != 0)?"none":"inline-block";
		if (prognum == 0)
			document.getElementById("service_"+(i+1)).innerHTML = "NONE";
		else
			document.getElementById("service_"+(i+1)).innerHTML = ((prognum == 0)?"-":prognum) + " : " + progname;
	}

	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_rx_sts").innerHTML = "DISABLED";
		document.getElementById("ip_rx_sts").classList.remove("low");
		document.getElementById("ip_rx_sts").classList.remove("med");
		document.getElementById("ip_rx_sts").classList.remove("high");
	}
	else if(stream_interface_get[getValue("IPStreamInterface")] == 2) // DTM-3200
	{
		var dtmStatus = json_load.DtmRxStatus;
		if((dtmStatus&0x03) == 0)
		{
			document.getElementById("ip_rx_sts").innerHTML = ((json_load.DtmRxProtocol==0)?"UDP":"RTP") + ((getValue("IPFECEnable")==0)?"":"+FEC");
			var errorLevel = "low";
			if(((dtmStatus&0x48) != 0) || ((getValue("IPFECEnable")!=0) && (json_load.DtmRxFECCols==0) && (json_load.DtmRxFECRows==0)))
				errorLevel = "med";
			if((dtmStatus&0xb4) != 0)
				errorLevel = "high";

			document.getElementById("ip_rx_sts").classList.remove("low");
			document.getElementById("ip_rx_sts").classList.remove("med");
			document.getElementById("ip_rx_sts").classList.remove("high");
			document.getElementById("ip_rx_sts").classList.add(errorLevel);
		}
		else
		{
			document.getElementById("ip_rx_sts").innerHTML = (((dtmStatus&0x03) == 1)?"DISABLED":"ERROR");
			document.getElementById("ip_rx_sts").classList.remove("low");
			document.getElementById("ip_rx_sts").classList.remove("med");
			document.getElementById("ip_rx_sts").classList.add("high");
		}
	}
	else if(IPStreamProtocol_get[getValue("IPStreamProtocol")] == 1) // SRT
	{
		var ipJitterRatio = json_load.IpRxDelayFactor / json_load.IpRxJitterTolerance;
		var ipRxStatus = json_load.IPReceiver;
		document.getElementById("ip_rx_sts").innerHTML = "SRT";
		var errorLevel = "low";
		if(ipJitterRatio>0.9)
			errorLevel = "med";
		if((ipRxStatus&0x00001)==0 || (ipRxStatus&0x30000)!=0 || document.getElementById("srt_connect").innerHTML != "Connected")
			errorLevel = "high";

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

		ASILock = ((ipRxStatus&0x00001)==0)?'0':'1';
	}
	else
	{
		var ipJitterRatio = json_load.IpRxDelayFactor / json_load.IpRxJitterTolerance;
		var ipRxStatus = json_load.IPReceiver;
		document.getElementById("ip_rx_sts").innerHTML = (((ipRxStatus&0x00006)==0)?"UDP":"RTP");
		var errorLevel = "low";
		if(ipJitterRatio>0.9)
			errorLevel = "med";
		if((ipRxStatus&0x00001)==0 || (ipRxStatus&0x30000)!=0)
			errorLevel = "high";

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

		ASILock = ((ipRxStatus&0x00001)==0)?'0':'1';
	}

    if(getValue("IPStreamEnable") != 2)
    {
        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 = ((IPStreamProtocol_get[getValue("IPStreamProtocol")]==0)?"RTP":"UDP") + ((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(IPStreamProtocol_get[getValue("IPStreamProtocol")] == 1) // 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 = ((IPStreamProtocol_get[getValue("IPStreamProtocol")]==0)?"RTP":"UDP") + ((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");
    }

    if(ASILock == '1') // may be overwriten by IP lock status
    {
      document.getElementById("asi_lock").innerHTML = ASIBitrate.toFixed(3)+" Mb/s";
	  if(ASIBitrate > 110.0)
	  {
        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");
    }

    if(VidDecodeOk == '1')
    {
      document.getElementById("vid_sts_dec").innerHTML = "OK";
      document.getElementById("vid_sts_dec").classList.add("low");
      document.getElementById("vid_sts_dec").classList.remove("med");
      document.getElementById("vid_sts_dec").classList.remove("high");
      document.getElementById("vid_sts_fmt").innerHTML = vid_format[VideoFormat];
      if(VideoFormat > 22)
      {
        var quad_sync = getValue("QuadSyncSelect");
        if(quad_sync == 0)
        {
          document.getElementById("vid_sts_sdi").innerHTML = vid_format[SDIFormat];
        }
        else
        {
          document.getElementById("vid_sts_sdi").innerHTML = vid_format[SDIFormat] + " (Quad)";
        }
      }
      else
      {
        var hd_duplication = getValue("HDDuplicateSelect");
        if(hd_duplication == 0)
        {
          document.getElementById("vid_sts_sdi").innerHTML = vid_format[SDIFormat];
        }
        else
        {
          document.getElementById("vid_sts_sdi").innerHTML = vid_format[SDIFormat] + " (4x)";
        }
      }
      document.getElementById("vid_sts_sample").innerHTML = SampleFormat;
      document.getElementById("vid_sts_delay").innerHTML = video_delay_mode[LowDelayMode];
      document.getElementById("vid_sts_depth").innerHTML = chroma_depth[BitDepth];
      document.getElementById("vid_sts_chroma").innerHTML = chroma_format[ChromaFormat];
      document.getElementById("vid_sts_mode").innerHTML = decoder_mode[VideoMode];

      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;
      }
    }
    else
    {
      document.getElementById("vid_sts_dec").innerHTML = "ERROR";
      document.getElementById("vid_sts_dec").classList.remove("low");
      document.getElementById("vid_sts_dec").classList.remove("med");
      document.getElementById("vid_sts_dec").classList.add("high");
      document.getElementById("vid_sts_fmt").innerHTML = "-";
      document.getElementById("vid_sts_sdi").innerHTML = "-";
      document.getElementById("vid_sts_sample").innerHTML = "-";
      document.getElementById("vid_sts_delay").innerHTML = "-";
      document.getElementById("vid_sts_depth").innerHTML = "-";
      document.getElementById("vid_sts_chroma").innerHTML = "-";
      document.getElementById("vid_sts_mode").innerHTML = "-";
      document.getElementById("vid_sts_range").innerHTML = "-";
      document.getElementById("vid_sts_colour").innerHTML = "-";
      document.getElementById("vid_sts_transfer").innerHTML = "-";
      document.getElementById("vid_sts_matrix").innerHTML = "-";
    }

	if(ServiceOk == '1')
    {
      document.getElementById("vid_sts_ser_ok").innerHTML = "OK";
      document.getElementById("vid_sts_ser_ok").classList.add("low");
      document.getElementById("vid_sts_ser_ok").classList.remove("med");
      document.getElementById("vid_sts_ser_ok").classList.remove("high");
    }
    else if(ServiceOk == '2')
    {
      document.getElementById("vid_sts_ser_ok").innerHTML = "NO SDT";
      document.getElementById("vid_sts_ser_ok").classList.remove("low");
      document.getElementById("vid_sts_ser_ok").classList.add("med");
      document.getElementById("vid_sts_ser_ok").classList.remove("high");
    }
    else
    {
      document.getElementById("vid_sts_ser_ok").innerHTML = "ERROR";
      document.getElementById("vid_sts_ser_ok").classList.remove("low");
      document.getElementById("vid_sts_ser_ok").classList.remove("med");
      document.getElementById("vid_sts_ser_ok").classList.add("high");
    }
    document.getElementById("vid_sts_ser_id").innerHTML = ServiceId;

    if((ServiceOk == '1') || (ServiceOk == '2') || (getValue("ServiceSelSelect") == 0))
    {
      document.getElementById("vid_sts_ser_name").innerHTML = ServiceName;
      if((PMTPid == 0) || (PMTPid == 8191))
      {
        document.getElementById("vid_sts_pmt_pid").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_pmt_pid").innerHTML = PMTPid;
      }

      if((VideoPid1 == 0) || (VideoPid1 == 8191))
      {
        document.getElementById("vid_sts_v_pid").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_v_pid").innerHTML = VideoPid1;
      }

      if((PCRPid1 == 0) || (PCRPid1 == 8191))
      {
        document.getElementById("vid_sts_pcr_pid").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_pcr_pid").innerHTML = PCRPid1;
      }

      if((AudioPid1 == 0) || (AudioPid1 == 8191))
      {
        document.getElementById("vid_sts_a_pid1").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_a_pid1").innerHTML = AudioPid1;
      }

      if((AudioPid2 == 0) || (AudioPid2 == 8191))
      {
        document.getElementById("vid_sts_a_pid2").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_a_pid2").innerHTML = AudioPid2;
      }

      if((AudioPid3 == 0) || (AudioPid3 == 8191))
      {
        document.getElementById("vid_sts_a_pid3").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_a_pid3").innerHTML = AudioPid3;
      }

      if((AudioPid4 == 0) || (AudioPid4 == 8191))
      {
        document.getElementById("vid_sts_a_pid4").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_a_pid4").innerHTML = AudioPid4;
      }

      if((AudioPid5 == 0) || (AudioPid5 == 8191))
      {
        document.getElementById("vid_sts_a_pid5").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_a_pid5").innerHTML = AudioPid5;
      }

      if((AudioPid6 == 0) || (AudioPid6 == 8191))
      {
        document.getElementById("vid_sts_a_pid6").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_a_pid6").innerHTML = AudioPid6;
      }

      if((AudioPid7 == 0) || (AudioPid7 == 8191))
      {
        document.getElementById("vid_sts_a_pid7").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_a_pid7").innerHTML = AudioPid7;
      }

      if((AudioPid8 == 0) || (AudioPid8 == 8191))
      {
        document.getElementById("vid_sts_a_pid8").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_a_pid8").innerHTML = AudioPid8;
      }

      if((DataPid1 == 0) || (DataPid1 == 8191))
      {
        document.getElementById("vid_sts_d_pid1").innerHTML = "-";
        document.getElementById("vid_sts_d_baud1").value = "";
      }
      else
      {
        document.getElementById("vid_sts_d_pid1").innerHTML = DataPid1;
        document.getElementById("vid_sts_d_baud1").value = DataBaud1;
      }

      if((DataPid2 == 0) || (DataPid2 == 8191))
      {
        document.getElementById("vid_sts_d_pid2").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_d_pid2").innerHTML = DataPid2;
      }

      if((DataPid3 == 0) || (DataPid3 == 8191))
      {
        document.getElementById("vid_sts_d_pid3").innerHTML = "-";
      }
      else
      {
        document.getElementById("vid_sts_d_pid3").innerHTML = DataPid3;
      }
    }
    else
    {
      document.getElementById("vid_sts_ser_name").innerHTML = "-";
      document.getElementById("vid_sts_pmt_pid").innerHTML = "-";
      document.getElementById("vid_sts_v_pid").innerHTML = "-";
      document.getElementById("vid_sts_pcr_pid").innerHTML = "-";
      document.getElementById("vid_sts_a_pid1").innerHTML = "-";
      document.getElementById("vid_sts_a_pid2").innerHTML = "-";
      document.getElementById("vid_sts_a_pid3").innerHTML = "-";
      document.getElementById("vid_sts_a_pid4").innerHTML = "-";
      document.getElementById("vid_sts_a_pid5").innerHTML = "-";
      document.getElementById("vid_sts_a_pid6").innerHTML = "-";
      document.getElementById("vid_sts_a_pid7").innerHTML = "-";
      document.getElementById("vid_sts_a_pid8").innerHTML = "-";
      document.getElementById("vid_sts_d_pid1").innerHTML = "-";
      document.getElementById("vid_sts_d_pid2").innerHTML = "-";
      document.getElementById("vid_sts_d_pid3").innerHTML = "-";
    }

    document.getElementById("unit_sts_temp1").innerHTML = FPGATemp+" &deg;C";
    if(FPGATemp > 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(FPGATemp > 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");
    }

    document.getElementById("unit_sts_temp2").innerHTML = PSUTemp+" &deg;C";
    if(PSUTemp > 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(PSUTemp > 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");
    }

    document.getElementById("unit_sts_volt_in").innerHTML = InVoltage+" V";
    if(InVoltage > 17.5 && InVoltage < 18)
    {
      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(InVoltage < 9.5 && InVoltage > 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(InVoltage > 17.9 || InVoltage < 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");
    }

    if(genlock_mode == 1)
    {
      if(GenlockStatus == 0)
      {
        document.getElementById("genlock_sts").classList.remove("low");
        document.getElementById("genlock_sts").classList.remove("med");
        document.getElementById("genlock_sts").classList.add("high");
        document.getElementById("genlock_sts").innerHTML = "NO LOCK";
      }
      else if(GenlockStatus < 2)
      {
        document.getElementById("genlock_sts").innerHTML = "LOCKING..";
        document.getElementById("genlock_sts").classList.remove("low");
        document.getElementById("genlock_sts").classList.add("med");
        document.getElementById("genlock_sts").classList.remove("high");
      }
      else if(GenlockStatus < 6)
      {
        document.getElementById("genlock_sts").innerHTML = "LOCKING....";
        document.getElementById("genlock_sts").classList.remove("low");
        document.getElementById("genlock_sts").classList.add("med");
        document.getElementById("genlock_sts").classList.remove("high");
      }
      else
      {
        document.getElementById("genlock_sts").innerHTML = "LOCKED";
        document.getElementById("genlock_sts").classList.add("low");
        document.getElementById("genlock_sts").classList.remove("med");
        document.getElementById("genlock_sts").classList.remove("high");
      }
    }
    else if(genlock_mode == 2)
    {
      document.getElementById("genlock_sts").innerHTML = "INTERNAL";
      document.getElementById("genlock_sts").classList.remove("low");
      document.getElementById("genlock_sts").classList.add("med");
      document.getElementById("genlock_sts").classList.remove("high");
    }
    else
    {
      document.getElementById("genlock_sts").innerHTML = "DISABLED";
      document.getElementById("genlock_sts").classList.remove("low");
      document.getElementById("genlock_sts").classList.add("med");
      document.getElementById("genlock_sts").classList.remove("high");
    }

	if((GenlockFormat & 0x200) == 0x200)
	{
	  var GenlockFormatString = "????";
	  switch(GenlockFormat & 0x0f0) {
		  case 0x000: GenlockFormatString = "1080"; break;
		  case 0x030: GenlockFormatString = "1080"; break;
		  case 0x010: GenlockFormatString = "720"; break;
		  case 0x090: GenlockFormatString = "625"; break;
		  case 0x080: GenlockFormatString = "525"; break;
	  }

	  var GenlockFrameRate = 0;
	  switch(GenlockFormat & 0x10f) {
		  case 0x102: GenlockFrameRate = 23; break;
		  case 0x103: GenlockFrameRate = 24; break;
		  case 0x105: GenlockFrameRate = 25; break;
		  case 0x106: GenlockFrameRate = 29; break;
		  case 0x107: GenlockFrameRate = 30; break;
		  case 0x104: GenlockFrameRate = 47; break;
		  case 0x108: GenlockFrameRate = 48; break;
		  case 0x109: GenlockFrameRate = 50; break;
		  case 0x10a: GenlockFrameRate = 59; break;
		  case 0x10b: GenlockFrameRate = 60; break;
		  case 0x002: GenlockFrameRate = 47; break;
		  case 0x003: GenlockFrameRate = 48; break;
		  case 0x005: GenlockFrameRate = 50; break;
		  case 0x006: GenlockFrameRate = 59; break;
		  case 0x007: GenlockFrameRate = 60; break;
		  case 0x004: GenlockFrameRate = 95; break;
		  case 0x008: GenlockFrameRate = 96; break;
		  case 0x009: GenlockFrameRate = 100; break;
		  case 0x00a: GenlockFrameRate = 119; break;
		  case 0x00b: GenlockFrameRate = 120; break;
	  }

	  if((GenlockFormat & 0x100) == 0x000)
		  GenlockFormatString += "i";
	  else
		  GenlockFormatString += "p";

	  if(GenlockFrameRate == 0)
		  GenlockFormatString += "??";
	  else
		  GenlockFormatString += GenlockFrameRate.toString();

      document.getElementById("genlock_fmt").innerHTML = GenlockFormatString;
	}
	else
	{
      document.getElementById("genlock_fmt").innerHTML = "-";
	}

    if(genlock_mode != 0)
    {
      document.getElementById("genlock_delay").innerHTML = GenlockDelay + " us";
	}
	else
	{
      document.getElementById("genlock_delay").innerHTML = "-";
	}

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

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

    document.getElementById("software_ver").innerHTML = SoftwareVersion;
    document.getElementById('hardware_ver').innerHTML = HardwareVersion;
    document.getElementById("serial_num").innerHTML = SerialNumber;
    document.getElementById("lic_msk").innerHTML = LicenseMask;
    document.getElementById('srt_ver').innerHTML = SRTVersion;

    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";

	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 IPStreamEnable = getValue("IPStreamEnable");
	var IPStreamInterface = stream_interface_get[getValue("IPStreamInterface")];
    if(IPStreamInterface != 2) // not DTM-3200
    {
        if(IPStreamEnable == 1) // receive
        {
            var IPStreamRateMode = getValue("IPStreamRateMode") ;
            if(IPStreamRateMode == 0 || IPStreamRateMode == 2)
                document.getElementById("b110_bitrate").innerHTML = (json_load.IpRxBitrate/1000000).toFixed(3) + " Mb/s";
            else
                document.getElementById("b110_bitrate").innerHTML = ASIBitrate.toFixed(3) + " Mb/s";

            document.getElementById("b110_jitter_tolerance").innerHTML = json_load.IpRxJitterTolerance + " ms";
            document.getElementById("b110_jitter_errors").innerHTML = json_load.IpRxJitterErrors;
            document.getElementById("b110_lock_errors").innerHTML = json_load.IpRxLockErrors;
            document.getElementById("b110_delay_factor").innerHTML = json_load.IpRxDelayFactor + " ms";
        }
        else if(IPStreamEnable == 2) // transmit
        {
            var bytesPerIP = (parseInt(getValue("IPStreamNumTP"))+1)*188;
            var packetSize = bytesPerIP;
            switch(parseInt(IPStreamProtocol_get[getValue("IPStreamProtocol")])) {
                case 2: packetSize += 28; break; // UDP
                case 0: packetSize += 40; break; // RTP
                case 1: packetSize += 44; break; // SRT
            }
            var estimatedBitrate = ASIBitrate*(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);

      if(IPStreamEnable == 1) // receive
      {
          document.getElementById("dtm_bitrate").innerHTML = (json_load.DtmRxBitrate/1000000).toFixed(3) + " Mb/s";
          document.getElementById("dtm_fec_cols").innerHTML = json_load.DtmRxFECCols;
          document.getElementById("dtm_fec_rows").innerHTML = json_load.DtmRxFECRows;
          document.getElementById("dtm_fec_delay").innerHTML = json_load.DtmRxFECDelay + " ms";
          document.getElementById("dtm_fec_before").innerHTML = json_load.DtmRxFECBefore;
          document.getElementById("dtm_fec_after").innerHTML = json_load.DtmRxFECAfter;
          document.getElementById("dtm_jitter_tolerance").innerHTML = json_load.DtmRxJitterTolerance + " ms";
          document.getElementById("dtm_jitter_errors").innerHTML = json_load.DtmRxJitterErrors;
          document.getElementById("dtm_lock_errors").innerHTML = json_load.DtmRxLockErrors;
          document.getElementById("dtm_delay_factor").innerHTML = (json_load.DtmRxDelayFactor/1000).toFixed(0) + " ms";
      }
      else if(IPStreamEnable == 2) // transmit
      {
          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 || IPStreamProtocol_get[getValue("IPStreamProtocol")] != 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("mbpsRecvRate").innerHTML = "-";
		document.getElementById("pktRecvTotal").innerHTML = "-";
		document.getElementById("pktRcvDropTotal").innerHTML = "-";
		document.getElementById("pktRcvLoss").innerHTML = "-";
		document.getElementById("pktRcvRetrans").innerHTML = "-";
		document.getElementById("msRcvBuf").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";
	}
	else
	{
		var RecorderRemaining = json_load.RecorderRemaining;
    var RecorderRecorded = json_load.RecorderRecorded;
		var RecorderState = json_load.RecorderState;
		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("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";
	}

    var lic_bits = parseInt(LicenseMask,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));
  }
);
get_json.open("GET", "/sts/UnitStatus.json", true);
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("mbpsRecvRate").innerHTML = "-";
		document.getElementById("pktRecvTotal").innerHTML = "-";
		document.getElementById("pktRcvDropTotal").innerHTML = "-";
		document.getElementById("pktRcvLoss").innerHTML = "-";
		document.getElementById("pktRcvRetrans").innerHTML = "-";
		document.getElementById("msRcvBuf").innerHTML = "-";
		document.getElementById("msRTT").innerHTML = "-";
    }
    else if(getValue("IPStreamEnable") == 1) // receive
    {
        var msRcvTsbPdDelay =  json_load.msRcvTsbPdDelay;
        var mbpsRecvRate =  json_load.mbpsRecvRate;
        var pktRecvTotal =  json_load.pktRecvTotal;
        var pktRcvDropTotal =  json_load.pktRcvDropTotal;
        var pktRcvLoss =  json_load.pktRcvLoss;
        var pktRcvRetrans =  json_load.pktRcvRetrans;
        var msRcvBuf =  json_load.msRcvBuf;
        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 = msRcvTsbPdDelay + " ms";
		document.getElementById("mbpsRecvRate").innerHTML = (mbpsRecvRate).toFixed(3) + " Mb/s";
		document.getElementById("pktRecvTotal").innerHTML = pktRecvTotal;
		document.getElementById("pktRcvDropTotal").innerHTML = pktRcvDropTotal;
		document.getElementById("pktRcvLoss").innerHTML = pktRcvLoss + " (" + ((pktRcvLoss/pktRecvTotal)*100).toFixed(2) + "%)";
		document.getElementById("pktRcvRetrans").innerHTML = pktRcvRetrans + " (" + ((pktRcvRetrans/pktRecvTotal)*100).toFixed(2) + "%)";
		document.getElementById("msRcvBuf").innerHTML = msRcvBuf + " ms";
		document.getElementById("msRTT").innerHTML = msRTT + " ms";
	}
	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("mbpsRecvRate").innerHTML = (mbpsSendRate).toFixed(3) + " Mb/s";
		document.getElementById("pktRecvTotal").innerHTML = pktSentTotal;
		document.getElementById("pktRcvDropTotal").innerHTML = pktSndDropTotal;
		document.getElementById("pktRcvLoss").innerHTML = pktSndLoss + " (" + ((pktSndLoss/pktSentTotal)*100).toFixed(2) + "%)";
		document.getElementById("pktRcvRetrans").innerHTML = pktRetrans + " (" + ((pktRetrans/pktSentTotal)*100).toFixed(2) + "%)";
		document.getElementById("msRcvBuf").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;
    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 ProductName = json_load.ProductName;
    var TxPresent = json_load.TxPresent;
    var B120Present = json_load.B120Present;
    var DTM3200Present = json_load.DTM3200Present;
    var OLEDType = json_load.OLEDType;

    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);

    var DtmDHCPMode = json_load.DtmDHCPMode;
    var DtmIPAddress = json_load.DtmIPAddress;
    var DtmIPGateway = json_load.DtmIPGateway;
    var DtmIPMask = json_load.DtmIPMask;

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

    setSelectValue("TxPresentSelect",TxPresent);
    setSelectValue("B120PresentSelect",B120Present);
    setSelectValue("DTM3200PresentSelect",DTM3200Present);
    setSelectValue("OLEDTypeSelect",OLEDType);

    setNumber("CustIDVal",parseInt(CustID,16));
  }
);
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 getDecode()
{
  var get_json = new XMLHttpRequest();
  get_json.addEventListener ("load", (e) =>
    {
      var json_load = JSON.parse(e.target.responseText);
      //var DecoderMode	= json_load.DecoderMode;
      //var DecoderSource = json_load.DecoderSource;
      //var VideoSource	= json_load.VideoSource;
      var VideoFormat	= json_load.VideoFormat;
      //var ChromaFormat = json_load.ChromaFormat;
      //var BitDepth = json_load.BitDepth;
      var LowDelayMode = json_load.LowDelayMode;
      var VideoSource = json_load.VideoSource;
      var SampleFormat = json_load.SampleFormat;
      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 PCRPid = json_load.PCRPid;
      var PMTPid = json_load.PMTPid;
      //var SITPid = json_load.SITPid;
      var DataPid = json_load.DataPid;
      var MetadataPid = json_load.MetadataPid;
      var AncillaryPid = json_load.AncillaryPid;
      //var IPPid = json_load.IPPid;
      var ProgramNumber = json_load.ProgramNumber;
      var DefServiceName = json_load.DefServiceName;
      //var AudioDecoder0 = json_load.AudioDecoder0;
      //var AudioSource0 = json_load.AudioSource0;
      //var AudioMode0 = json_load.AudioMode0;
      // var AudioGainLeft0 = json_load.AudioGainLeft0;
      // var AudioGainRight0 = json_load.AudioGainRight0;
      var AudioPTSOffset0 = json_load.AudioPTSOffset0;
      //var AudioDecoder1 = json_load.AudioDecoder1;
      //var AudioSource1 = json_load.AudioSource1;
      //var AudioMode1 = json_load.AudioMode1;
      // var AudioGainLeft1 = json_load.AudioGainLeft1;
      // var AudioGainRight1 = json_load.AudioGainRight1;
      var AudioPTSOffset1 = json_load.AudioPTSOffset1;
      //var AudioDecoder2 = json_load.AudioDecoder2;
      //var AudioSource2 = json_load.AudioSource2;
      //var AudioMode2 = json_load.AudioMode2;
      var AudioPTSOffset2 = json_load.AudioPTSOffset2;
      //var AudioDecoder3 = json_load.AudioDecoder3;
      //var AudioSource3 = json_load.AudioSource3;
      //var AudioMode3 = json_load.AudioMode3;
      var AudioPTSOffset3 = json_load.AudioPTSOffset3;
      //var AudioDecoder4 = json_load.AudioDecoder4;
      //var AudioSource4 = json_load.AudioSource4;
      //var AudioMode4 = json_load.AudioMode4;
      var AudioPTSOffset4 = json_load.AudioPTSOffset4;
      //var AudioDecoder4 = json_load.AudioDecoder4;
      //var AudioSource4 = json_load.AudioSource4;
      //var AudioMode4 = json_load.AudioMode4;
      var AudioPTSOffset4 = json_load.AudioPTSOffset4;
      //var AudioDecoder5 = json_load.AudioDecoder5;
      //var AudioSource5 = json_load.AudioSource5;
      //var AudioMode5 = json_load.AudioMode5;
      var AudioPTSOffset5 = json_load.AudioPTSOffset5;
      //var AudioDecoder6 = json_load.AudioDecoder6;
      //var AudioSource6 = json_load.AudioSource6;
      //var AudioMode6 = json_load.AudioMode6;
      var AudioPTSOffset6 = json_load.AudioPTSOffset6;
      //var AudioDecoder7 = json_load.AudioDecoder7;
      //var AudioSource7 = json_load.AudioSource7;
      //var AudioMode7 = json_load.AudioMode7;
      var AudioPTSOffset7 = json_load.AudioPTSOffset7;
      //var DataMode1 = json_load.DataMode1;
      //var DataFormat = json_load.DataFormat;
      //var DataType = json_load.DataType;
      var RecordEnable = json_load.RecordEnable;
      var IPStreamEnable = json_load.IPStreamEnable;
      var IPStreamInterface = json_load.IPStreamInterface-1;
      var IPStreamMode = json_load.IPStreamMode;
      var IPStreamProtocol = json_load.IPStreamProtocol;
      var IPStreamAddress = json_load.IPStreamAddress;
      var IPStreamPort = json_load.IPStreamPort;
      var IPStreamTTL = json_load.IPStreamTTL;
      var IPStreamNumTP = json_load.IPStreamNumTP-1;
      var IPStreamDelay = json_load.IPStreamDelay;
      var IPStreamRateMode = json_load.IPStreamRateMode;
      var IPFECEnable = json_load.IPFECEnable;
      var IPFECCols = json_load.IPFECCols;
      var IPFECRows = json_load.IPFECRows;
      var BufferDelay = json_load.BufferDelay;
      //var ManualMode = json_load.ManualMode;
      //var ErrorMask = json_load.ErrorMask;
      var AudioRefLevel0 = json_load.AudioRefLevel0;
      var AudioRefLevel1 = json_load.AudioRefLevel1;
      var VideoConcealLev = json_load.VideoConcealLev;
      //var VideoConcealRef = json_load.VideoConcealRef;
      var VideoFailMode1 = json_load.VideoFailMode1;
      //var VideoFailMode2 = json_load.VideoFailMode2;
      var ServiceSelect = json_load.ServiceSelect;
      var GenlockMode = json_load.GenlockMode;
      var GenlockLineOffset = json_load.GenlockLineOffset;
      var GenlockPixelOffset = json_load.GenlockPixelOffset;
      //var AudioDecoderCtrl = json_load.AudioDecoderCtrl;
      var QuadSync = json_load.SynergyMode;
      var DESMode = json_load.DESMode;
      var DESKey = json_load.DESKey;
      var AncillaryMode = json_load.AncillaryMode;
      var HdDuplication = json_load.HdDuplication;
      var BISSMode = json_load.BISSMode;
      var BISSKey = json_load.BISSKey;
      var SRTMode = json_load.SRTMode;
      var SRTRemoteAddress = json_load.SRTRemoteAddress;
      var SRTDelay = json_load.SRTDelay;

      setSelectValue("VideoFormatSelect",VideoFormat);
      setSelectValue("LowDelayModeSelect",LowDelayMode);
      setSelectValue("VideoSourceSelect",VideoSource);
      setSelectValue("SampleFormatSelect",SampleFormat);
      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("PCRPidVal",PCRPid);
      setNumber("PMTPidVal",PMTPid);
      setNumber("DataPidVal",DataPid);
      setNumber("MetadataPidVal",MetadataPid);
      setNumber("AncillaryPidVal",AncillaryPid);
      setNumber("ProgramNumberVal",ProgramNumber);
      setNumber("ServiceNameVal",DefServiceName);
      // setNumber("AudioGainL0Val",AudioGainLeft0);
      // setNumber("AudioGainR0Val",AudioGainRight0);
      // setNumber("AudioGainL1Val",AudioGainLeft1);
      // setNumber("AudioGainR1Val",AudioGainRight1);
      //setSelectValue("AudioSource0Select",AudioSource0);
      //setSelectValue("AudioSource1Select",AudioSource1);
      //setSelectValue("AudioSource2Select",AudioSource2);
      //setSelectValue("AudioSource3Select",AudioSource3);
      //setSelectValue("AudioSource4Select",AudioSource4);
      //setSelectValue("AudioSource5Select",AudioSource5);
      //setSelectValue("AudioSource6Select",AudioSource6);
      //setSelectValue("AudioSource7Select",AudioSource7);
      setNumber("AudioPTSOffset0Val",AudioPTSOffset0);
      setNumber("AudioPTSOffset1Val",AudioPTSOffset1);
      setNumber("AudioPTSOffset2Val",AudioPTSOffset2);
      setNumber("AudioPTSOffset3Val",AudioPTSOffset3);
      setNumber("AudioPTSOffset4Val",AudioPTSOffset4);
      setNumber("AudioPTSOffset5Val",AudioPTSOffset5);
      setNumber("AudioPTSOffset6Val",AudioPTSOffset6);
      setNumber("AudioPTSOffset7Val",AudioPTSOffset7);
      setSelectValue("RecordEnable",RecordEnable);
      setSelectValue("IPStreamEnable",IPStreamEnable);
      setSelectValue("IPStreamInterface",stream_interface_set[IPStreamInterface]);
      setSelectValue("IPStreamMode",IPStreamMode);
      setNumber("IPStreamAddress",IPStreamAddress);
      setNumber("IPStreamPort",IPStreamPort);
      setNumber("IPStreamTTL",IPStreamTTL);
      setSelectValue("IPStreamNumTP",IPStreamNumTP);
      setNumber("IPStreamDelay",IPStreamDelay);
      setSelectValue("IPStreamProtocol",IPStreamProtocol_set[IPStreamProtocol]);
      setSelectValue("IPStreamRateMode",IPStreamRateMode);
      setSelectValue("IPFECEnable",IPFECEnable);
      setNumber("IPFECCols",IPFECCols);
      setNumber("IPFECRows",IPFECRows)
      setNumber("BufferDelay",BufferDelay)
      setSelectValue("AudRefLev0",AudioRefLevel0)
      setSelectValue("AudRefLev1",AudioRefLevel1)
      setNumber("ErrConcealmVal",VideoConcealLev)
      setSelectValue("FailModeSelect",VideoFailMode1)
      setSelectValue("ServiceSelSelect",ServiceSelect);
      setSelectValue("GenlockModeSelect",GenlockMode);
      setNumber("GenlockLineOffsetVal",GenlockLineOffset);
      setNumber("GenlockPixelOffsetVal",GenlockPixelOffset);
      setSelectValue("QuadSyncSelect",QuadSync);
      setSelectValue("DESModeSelect",DESMode);
      setNumber("DESKeyVal",DESKey);
      setSelectValue("AncillaryModeSelect",AncillaryMode);
      setSelectValue("HDDuplicateSelect",HdDuplication);
      setSelectValue("BISSModeSelect",BISSMode);
      setNumber("BISSKeyVal",BISSKey);
      setSelectValue("SRTMode",SRTMode);
      setNumber("SRTRemoteAddress",SRTRemoteAddress);
      setNumber("SRTDelay",SRTDelay);
	  ipInterfaceChange();
    }
  );
  get_json.open("GET", "/config/DecoderParamsList.json", true);
  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")),
    DtmDHCPMode: parseInt(getValue("DtmDHCPModeSelect")),
    DtmIPAddress: getNumber("DtmIPAddress"),
    DtmIPGateway: getNumber("DtmIPGateway"),
    DtmIPMask: getNumber("DtmIPMask"),
    TxPresent: parseInt(getValue("TxPresentSelect")),
    B120Present: parseInt(getValue("B120PresentSelect")),
    DTM3200Present: parseInt(getValue("DTM3200PresentSelect")),
    OLEDType: parseInt(getValue("OLEDTypeSelect"))
  };
  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 setDecode()
{
  var json_send;
  var set_json = new XMLHttpRequest();
  var url = "/cgi-bin/set_dec_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 str_val = {
    VideoFormat: parseInt(getValue("VideoFormatSelect")),
    VideoSource: parseInt(getValue("VideoSourceSelect")),
    SampleFormat: parseInt(getValue("SampleFormatSelect")),
    LowDelayMode: parseInt(getValue("LowDelayModeSelect")),
    SynergyMode: parseInt(getValue("QuadSyncSelect")),
    VideoConcealLev: parseInt(getNumber("ErrConcealmVal")),
    VideoFailMode1: parseInt(getValue("FailModeSelect")),
    HdDuplication: parseInt(getValue("HDDuplicateSelect")),
    // AudioGainLeft0: parseInt(getNumber("AudioGainL0Val")),
    // AudioGainRight0: parseInt(getNumber("AudioGainR0Val")),
    // AudioGainLeft1: parseInt(getNumber("AudioGainL1Val")),
    // AudioGainRight1: parseInt(getNumber("AudioGainR1Val")),
    AudioRefLevel0: parseInt(getValue("AudRefLev0")),
    AudioRefLevel1: parseInt(getValue("AudRefLev1")),
    ServiceSelect: parseInt(getValue("ServiceSelSelect")),
    ProgramNumber: parseInt(getNumber("ProgramNumberVal")),
    DefServiceName: 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")),
    //AudioSource0: parseInt(getValue("AudioSource0Select")),
    //AudioSource1: parseInt(getValue("AudioSource1Select")),
    //AudioSource2: parseInt(getValue("AudioSource2Select")),
    //AudioSource3: parseInt(getValue("AudioSource3Select")),
    //AudioSource4: parseInt(getValue("AudioSource4Select")),
    //AudioSource5: parseInt(getValue("AudioSource5Select")),
    //AudioSource6: parseInt(getValue("AudioSource6Select")),
    //AudioSource7: parseInt(getValue("AudioSource7Select")),
    AudioPTSOffset0: parseInt(getNumber("AudioPTSOffset0Val")),
    AudioPTSOffset1: parseInt(getNumber("AudioPTSOffset1Val")),
    AudioPTSOffset2: parseInt(getNumber("AudioPTSOffset2Val")),
    AudioPTSOffset3: parseInt(getNumber("AudioPTSOffset3Val")),
    AudioPTSOffset4: parseInt(getNumber("AudioPTSOffset4Val")),
    AudioPTSOffset5: parseInt(getNumber("AudioPTSOffset5Val")),
    AudioPTSOffset6: parseInt(getNumber("AudioPTSOffset6Val")),
    AudioPTSOffset7: parseInt(getNumber("AudioPTSOffset7Val")),
    GenlockMode: parseInt(getValue("GenlockModeSelect")),
    GenlockLineOffset: parseInt(getNumber("GenlockLineOffsetVal")),
    GenlockPixelOffset: parseInt(getNumber("GenlockPixelOffsetVal")),
    DESMode: parseInt(getValue("DESModeSelect")),
    DESKey: des_key_val,
    BISSMode: parseInt(getValue("BISSModeSelect")),
    BISSKey: biss_key_val,
    AncillaryMode: parseInt(getValue("AncillaryModeSelect")),
    RecordEnable: parseInt(getValue("RecordEnable")),
    IPFECEnable: parseInt(getValue("IPFECEnable")),
    IPFECCols: parseInt(getNumber("IPFECCols")),
    IPFECRows: parseInt(getNumber("IPFECRows")),
    IPStreamEnable: parseInt(getValue("IPStreamEnable")),
    IPStreamInterface: parseInt(stream_interface_get[getValue("IPStreamInterface")])+1,
    IPStreamProtocol: parseInt(IPStreamProtocol_get[getValue("IPStreamProtocol")]),
    IPStreamMode: parseInt(getValue("IPStreamMode")),
    IPStreamRateMode: parseInt(getValue("IPStreamRateMode")),
    IPStreamPort: parseInt(getNumber("IPStreamPort")),
    IPStreamTTL: parseInt(getNumber("IPStreamTTL")),
    IPStreamNumTP: parseInt(getValue("IPStreamNumTP"))+1,
    IPStreamDelay: parseInt(getNumber("IPStreamDelay")),
    IPStreamAddress: getNumber("IPStreamAddress"),
    SRTMode: parseInt(getValue("SRTMode")),
    BufferDelay: parseInt(getNumber("BufferDelay")),
    SRTRemoteAddress: getNumber("SRTRemoteAddress"),
    SRTDelay: parseInt(getNumber("SRTDelay")),
  };
  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
			getDecode()
    }
  );
  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 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 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"
		],
		[ "video",		["Decoder Defaults",	["Video Format", "VideoFormatSelect"],
												["Latency Mode", "LowDelayModeSelect"],
												["Buffer Delay", "BufferDelay"]],
						["Video Output",		["Video Source", "VideoSourceSelect"],
												["Sample Format", "SampleFormatSelect"],
												["QuadSync", "QuadSyncSelect"],
												["SD/HD Duplication", "HDDuplicateSelect"],
												["Fail Mode", "FailModeSelect"],
												["Error Concealment", "ErrConcealmVal"]],
						["Genlock",				["Mode", "GenlockModeSelect"],
												["Line Offset", "GenlockLineOffsetVal"],
												["Pixel Offset", "GenlockPixelOffsetVal"]],
		],
		[ "audio",		["Analogue Output",		["Reference Level", "AudRefLevX"]],
						["Audio Stream",		["Adjust Delay", "AudioPTSOffsetXVal"]],
		],
		[ "service",	["Service",				["Service Selection", "ServiceSelSelect"],
												["Program Number", "ProgramNumberVal"],
												["Service Name", "ServiceNameVal"],
												["PID", "XXXPidVal"]],
						["Scrambling",			["DES Mode", "DESModeSelect"],
												["DES Key", "DESKeyVal"],
												["BISS Mode", "BISSModeSelect"],
												["BISS Key", "BISSKeyVal"]],
                        ["Ancillary",			["Insert Mode", "AncillaryModeSelect"]],
                        ["Data",				["Baud Rate", "DataBaudSelect"]],
		],
		[ "ip",			["Stream Input",		["IP Mode", "IPStreamEnable"],
												["IP Interface", "IPStreamInterface"],
												["Stream Protocol", "IPStreamProtocol"],
												["Stream Type", "IPStreamMode"],
												["SRT Mode", "SRTMode"],
												["SRT Delay", "SRTDelay"],
												["Remote Host Address", "SRTRemoteAddress"],
												["Multicast Address", "IPStreamAddress"],
												["UDP Port Number", "IPStreamPort"],
												["TTL", "IPStreamTTL"],
												["TP per IP", "IPStreamNumTP"],
												["Buffer Delay", "IPStreamDelay"],
												["Bitrate Control", "IPStreamRateMode"],
												["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 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"],
												["Unit Address", "UnitAddress"],
												["Unit Name", "UnitName"],
												["Unit Mode", "UnitModeSelect"],
												["Web Password", "WebPassword"]],
						["USB Storage",			["Partition Size", "SdaXSize"],
												["File System", "SdaXType"],
												["Format Device", "SdaXFormat"]],
		],
		[ "upgrade",	["Firmware",			["", "CodecFirmware"]],
						["License",				["", "CodecLicense"]],
						["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)
	{
		// Decoder Defaults
		case "VideoFormatSelect": content +=	helpContentAddRow("May speed up start time if set to match expected video stream.") +
												helpContentAddRow("Also defines the power up video format for blue screen output."); break;
		case "LowDelayModeSelect": content +=	helpContentAddRow("Controls latency mode for decoding 3rd party streams only."); break;
		case "BufferDelay": content +=			helpContentAddRow("Additional buffer delay may be required for decoding some 3rd party streams only."); break;
		// Video Output
		case "VideoSourceSelect": content += 	helpContentAddRow("Decoder",			"Decoded video and audio is output on SDI 1-4.") +
 	 	 	 	 	 	 	 	 	 	 	 	helpContentAddRow("Pattern + Tones",	"Video pattern and tones based on current configuration.") +
 	 	 	 	 	 	 	 	 	 	 	 	helpContentAddRow("Pattern", 	 	 	"Video pattern with decoded audio based on current configuration."); break;
		case "SampleFormatSelect": content += 	helpContentAddRow("2SI",		"4K video outputs in 2 Sample Interleave format.") +
												helpContentAddRow("SQD/HFR",	"4K video outputs in Square Division format or HD High Frame Rate phases."); break;
		case "QuadSyncSelect": content += 		helpContentAddRow("Off",		"Standard mode for single HD/UHD operation.") +
												helpContentAddRow("Otherwise",	"QuadSync conversion to requested standard is applied to video outputs where possible.") +
												helpContentAddRow(" ",			"Some conversions are not valid, actual output is shown on Status page."); break;
		case "HDDuplicateSelect": content += 	helpContentAddRow("Off",	"Decoded video in HD modes output on SDI 1 only.") +
												helpContentAddRow("On",		"Decoded video in HD modes output on SDI 1-4."); break;
		case "FailModeSelect": content += 		helpContentAddRow("Freeze",	"On input stream interruption last decoded frame is held, most effective when Genlock is not disabled.") +
												helpContentAddRow("Blue",	"On input stream interruption output will go to blue screen."); break;
		case "ErrConcealmVal": content += 		helpContentAddRow("High",	"Freeze frame is preferred over picture break-up.") +
												helpContentAddRow("Low",	"Picture break-up is preferred over freeze frame."); break;
		// Genlock
		case "GenlockModeSelect": content += 		helpContentAddRow("Off",		"Genlock frame buffer disabled, video output at rate recovered by PCR.") +
													helpContentAddRow("External",	"Output synchronized to external reference, must have compatible frame rate.") +
													helpContentAddRow("Internal",	"Output synchronized to internal reference, use to prevent PCR jitter transfer to SDI output."); break;
		case "GenlockLineOffsetVal": content +=		helpContentAddRow("",			"Line offset for fine alignment of output to external equipment.") +
													helpContentAddRow("480",		"0 to 524.") +
													helpContentAddRow("576",		"0 to 624.") +
													helpContentAddRow("720",		"0 to 749.") +
													helpContentAddRow("1080",		"0 to 1124."); break;
		case "GenlockPixelOffsetVal": content +=	helpContentAddRow("",					"Pixel offset for fine alignment of output to external equipment.") +
													helpContentAddRow("480-59",				"0 to 857.") +
													helpContentAddRow("576-50",				"0 to 863.") +
													helpContentAddRow("720-50",				"0 to 1979.") +
													helpContentAddRow("720-59/60",			"0 to 1649.") +
													helpContentAddRow("1080-23/24",			"0 to 2749.") +
													helpContentAddRow("1080-25/50",			"0 to 2639.") +
													helpContentAddRow("1080-29/30/59/60",	"0 to 2199."); break;
		// Analogue Output
		case "AudRefLevX": content +=			helpContentAddRow("Sets 0dBFS reference for digital to analogue conversion."); break;
		// Audio Stream
		case "AudioPTSOffsetXVal": content += 	helpContentAddRow("-1000 to 1000 ms audio delay adjustment to ~4 ms accuracy.") +
												helpContentAddRow("Negative numbers may result in loss of decoding if set earlier than actually possible."); break;
		// Service
		case "ServiceSelSelect": content += 	helpContentAddRow("Manual",	"Service decoding is based on provided PIDs.") +
												helpContentAddRow("Auto",	"Service decoding is based on program number."); break;
		case "ProgramNumberVal": content += 	helpContentAddRow("1 to 65535 program number to be searched for in PAT.") +
												helpContentAddRow("Auto service selection may use this for identifying which service to decode."); break;
		case "ServiceNameVal": content += 		helpContentAddRow("32 character name to be searched for in SDT.") +
												helpContentAddRow("Auto service selection may use this for identifying which service to decode."); break;
		case "XXXPidVal": content += 			helpContentAddRow("32 to 8190 decimal PID to be searched for in PAT/PMT.") +
												helpContentAddRow("Required for manual service mode otherwise ignored."); break;
		// Scrambling
		case "DESModeSelect": content += 	helpContentAddRow("Off",	"DES descrambling disabled.") +
											helpContentAddRow("On",		"DES descrambling enabled, active streams will be recovered with DES.") +
											helpContentAddRow(" ",		"Descrambled services are assumed to have been scrambled by a compatible standard."); break;
		case "DESKeyVal": content += 		helpContentAddRow("56-bit descrambling key, use 14 characters (0123456789ABCDEF) for valid key."); break;
		case "BISSModeSelect": content += 	helpContentAddRow("Off",	"BISS descrambling disabled.") +
											helpContentAddRow("On",		"BISS-1 descrambling enabled, active streams will be recovered with BISS.") +
											helpContentAddRow(" ",		"Descrambled services are assumed to have been scrambled by a compatible standard."); break;
		case "BISSKeyVal": content += 		helpContentAddRow("48-bit descrambling key, use 12 characters (0123456789ABCDEF) for valid key."); break;
		// Data
		case "AncillaryModeSelect": content += 	helpContentAddRow("Off",	"Ancillary channel ignored.") +
												helpContentAddRow("On",		"Ancillary data packets are inserted onto SDI outputs when stream present in ASI/IP input."); break;
        case "DataBaudSelect": content += 		helpContentAddRow("Baud rate selection for RS-232 data output."); break;
		// Stream Input
		case "IPStreamEnable": content += 		helpContentAddRow("Off",		"IP stream disabled.") +
												helpContentAddRow("Receive",	"IP stream input enabled.") +
												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 "IPStreamMode": content += 		helpContentAddRow("Unicast",	"Expects unicast stream to IP address of selected port.") +
												helpContentAddRow("Multicast",	"Expects multicast stream to multicast address on same network as selected port."); break;
		case "SRTMode": content += 				helpContentAddRow("Caller",		"Decoder instigates outbound connection to Listener.") +
												helpContentAddRow("Listener",	"Decoder waits for inbound connection from Caller.") +
												helpContentAddRow("Rendezvous",	"Decoder 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 "SRTRemoteAddress": content +=		helpContentAddRow("Target remote IP address for Caller or Rendezvous modes."); break;
		case "IPStreamAddress": content +=		helpContentAddRow("Target multicast IP address for IP stream."); 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 "IPStreamDelay": content +=		helpContentAddRow("1 to 9942 ms, increased buffering typically increases jitter tolerance but also end to end latency.") +
												helpContentAddRow("Ensure buffer delay is high enough to compensate for delay factor shown in stream diagnostics window."); break;
		case "IPStreamRateMode": content +=		helpContentAddRow("PCR Estimate",		"Bitrate is estimated using PCRs if possible, otherwise the bitrate is estimated without PCRs.") +
												helpContentAddRow("Fixed Buffer",		"Bitrate estimation is disabled; Packets are buffered, and transmitted with a fixed delay.") +
												helpContentAddRow("Stream Estimate",	"Bitrate is estimated without the use of PCRs.") +
												helpContentAddRow("Disable Buffer",		"Bitrate estimation is disabled; Packets are routed to the ASI port immediately. Recommended for VBR sources."); break;
		case "IPFECEnable": content +=			helpContentAddRow("Off",	"IP FEC input ignored.") +
												helpContentAddRow("On", 	"IP FEC input enabled, SMPTE 2022-1 can be used to provide resilience to packet loss.") +
												helpContentAddRow(" ",		"Note additional FEC delay on the stream diagnostics window."); 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.") + 
                                                helpContentAddRow("No bitrate shown then check IP address/port settings or for lack of connectivity to source.") +
												helpContentAddRow("Jitter tolerance is buffer delay, bitrate control dependant, and must exceed worst case delay factor.") +
												helpContentAddRow("Delay factor shows maximum packet jitter measured between refresh.") +
												helpContentAddRow("Lock or jitter errors will result in decoded stream interruption."); break;
		case "DTM_Diagnostics": content +=		helpContentAddRow("No bitrate shown then check IP address/port settings or for lack of connectivity to source.") +
												helpContentAddRow("No ASI bitrate shown then check ASI-IP is connected to ASI In on Sapphire unit.") +
												helpContentAddRow("Increasing packet loss counters suggest lossy network and/or stream bitrate exceeding capacity.") +
												helpContentAddRow("Jitter tolerance is buffer delay minus FEC delay, and must exceed worst case delay factor.") +
												helpContentAddRow("Delay factor shows maximum packet jitter measured between refresh.") +
												helpContentAddRow("Lock or jitter errors will result in decoded stream interruption."); 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 Diagnostics
		case "File_Diagnostics": content +=		helpContentAddRow("Current state of USB recording 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 b110_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 b110_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;
}
