<?php
    require_once 'includes/buildinfo.php';
    require_once 'includes/machineinfo.php';
    require_once 'includes/db.class.php';
    require_once 'includes/config.php';
    require_once 'includes/util.php';

    $machine = MachineInfo::Instance();
    $build = BuildInfo::Instance();
    $SELF = $_SERVER['PHP_SELF'];

    $illegal_values = array(" ","<",">","!",")","(","*","%","&","@","#","^","$","=","+","~","`",",","[","]");

    define("FILE_TRANSFER_LIVE", 0x01);
    define("FILE_TRANSFER_RECORDINGS", 0x02);
    define("FILE_TRANSFER_ALL", 0xFF);

    if (!defined("ENABLE_IPV6")) {
        define("ENABLE_IPV6", false);
    }

    if (!defined("ENABLE_CENTOS")) {
        define("ENABLE_CENTOS", 0);
    }

    if (!defined("BISS_ENABLED")) {
        define("BISS_ENABLED", 0);
    }

    if (CONFIG_MODE == 1) {// Remove support for ATSC M/H
        define("CONFIG_MODE", 0);
    }

    if (ENABLE_CENTOS) {
        date_default_timezone_set("UTC");
    }

    $enable_atsc_input = $build->hasInputInterface("DVB-API");
    if ($enable_atsc_input) {
        require_once 'includes/dvbapi.php';
        $atscAdapters = dvbapi_listAdapters();

        if (!$atscAdapters || !count($atscAdapters)) {
            global $enable_atsc_input;
            $enable_atsc_input = false;
        }
    }

    define("DEFAULT_SDP_SESSION_NAME", "encode-server");
    define("ENABLE_SOURCE_FILE_FTP", 0);

    if (!file_exists(OUTPUT_FILE_DEFAULT_PATH)) {
        exec("sudo mkdir ".OUTPUT_FILE_DEFAULT_PATH);
        if (ENABLE_CENTOS) {
            exec("sudo chown -R apache ".OUTPUT_FILE_DEFAULT_PATH);
        } else {
            exec("sudo chown -R www-data ".OUTPUT_FILE_DEFAULT_PATH);
        }
    }

    if (ENABLE_CENTOS) {
        exec("sudo chown -R apache.apache /var/www/configs");
        exec("sudo chown -R apache.apache /var/www/db");
        exec("sudo mkdir -p /etc/network/interfaces");
    }

    if (!file_exists('configs/state.db')) {
        $db = new DB('configs/state.db');
        if (!$db->connect()) {
            // Connection error, probably because the database file is in sqlite2 and not sqlite3
            if (!$db->resetDB()) {
                if ($db->getError()) {
                    echo $db->getError()->getMessage();
                }
            }
        }

        // If the file did not exist before, create its structure
        $db->createDataBase($db);
        $db->checkNumberOfChannels(MAX_CHANNELS);
        $db = null;
    }

    // Default settings
    $defaultSettings = array(
                      'config_version' => "N/A",
                      'channel_id' => "",
                      'input_resolution' => "HD1080",
                      'output_resolution' => "SAME",
                      'input_framerate' => "29.97",
                      'enable_psf' => "0",
                      'output_framerate' => "0",
                      'output_resizing' => "0",
                      'input_format' => "1",
                      'input_width' => "0",
                      'input_height' => "0",
                      'input_stream' => "SPTS",
                      'input_program_number' => "1",
                      'input_subtitle_mode' => "0",
                      'input_subtitle_pid' => "-1",
                      'input_subtitle_order' => "0",
                      'input_subtitle_delay' => "320",
                      'input_subtitle_late' => "60",
                      'enable_gpu' =>"0",
                      'crop_left' => "0",
                      'crop_top' => "0",
                      'crop_right' => "0",
                      'crop_bottom' => "0",
                      'output_format' => "2",
                      'aspect_ratio' => "0",
                      'biss_mode' => "0",
                      'biss_key' => "0",
                      'biss_session_key' => "0",
                      'quality_level' => "20",
                      'output_width' => "0",
                      'output_height' => "0",
                      'output_encoder' => "MPEG2",
                      'cpb_delay' => "100",
                      'input_interface' => "IP",
                      'output_interface' => "IP",
                      'I_P_frame_distance' => "3",
                      'GOP_length_seconds' => "1",
                      'pyramid_b' => "0",
                      'input_audio_pid0' => "0",
                      'input_audio_pid1' => "1",
                      'input_audio_pid2' => "2",
                      'output_audio_format' => "passthrough",
                      'output_audio_bitrate0' => "64000",
                      'output_audio_bitrate1' => "0",
                      'output_audio_bitrate2' => "0",
                      'output_audio_samplerate' => "48000",
                      'output_audio_volume0' => "100",
                      'output_audio_volume1' => "100",
                      'output_audio_volume2' => "100",
                      'output_audio_lang0' => "",
                      'output_audio_lang1' => "",
                      'output_audio_lang2' => "",
                      'audio_sdi_mapping_l0' => "0",
                      'audio_sdi_mapping_r0' => "1",
                      'audio_sdi_mapping_c0' => "2",
                      'audio_sdi_mapping_lfe0' => "3",
                      'audio_sdi_mapping_sl0' => "4",
                      'audio_sdi_mapping_sr0' => "5",
                      'audio_sdi_mapping_l1' => "0",
                      'audio_sdi_mapping_r1' => "0",
                      'audio_sdi_mapping_c1' => "0",
                      'audio_sdi_mapping_lfe1' => "0",
                      'audio_sdi_mapping_sl1' => "0",
                      'audio_sdi_mapping_sr1' => "0",

                      'output_ip_address' => "225.1.1.1",
                      'output_ip_address_ipv6' => "",
                      'enable_raw_output' => "0",
                      'multicast_ttl' => "16",
                      'output_port' => "9000",

                      'enable_ethernet_interface_2' => "0",
                      'ethernet_interface_2' => "default",
                      'output_ip_address_2' => "225.1.1.1",
                      'output_ip_address_ipv6_2' => "",
                      'enable_raw_output_2' => "0",
                      'multicast_ttl_2' => "16",
                      'output_port_2' => "9001",

                      'output_type' => "1",
                      'source_ethernet_interface' => "default",
                      'source_ip_address' => "0.0.0.0",
                      'source_ip_address_ipv6' => "",
                      'multicast_filter_address' => "",
                      'enable_raw_input' => "0",
                      'enable_igmp_input' => "0",
                      'source_port' => "5004",
                      'source_timeout' => "2",

                      'enable_source_input_2' => "0",
                      'source_ethernet_interface_2' => "eth1",
                      'source_ip_address_2' => "0.0.0.0",
                      'source_ip_address_ipv6_2' => "",
                      'multicast_filter_address_2' => "",
                      'enable_raw_input_2' => "0",
                      'source_port_2' => "6004",

                      'slate_enable' => "0",
                      'slate_filename' => "",
                      'slate_entry_time' => "1",
                      'slate_duration_time' => "1",
                      'slate_exit_time' => "1",
                      'slate_silence' => "0",

                      'sdp_address' => "http://192.168.1.72",
                      'sdp_filename' => "channel1.sdp",
                      'enable_rtcp' => "true",
                      'audio_only' => "0",
                      'output_video_bitrate' => "0",
                      'output_mux_rate' => "4000000",
                      'enable_output_pid_remap' => "0",
                      'output_scte35_pid' => "485",
                      'output_pmt_pid' => "480",
                      'output_video_pid' => "481",
                      'output_audio_pid' => "482",
                      'output_transport_stream_id' => "1",
                      'output_program_number' => "1",
                      'output_pat_rate' => "80",
                      'output_pmt_rate' => "350",
                      'output_pcr_rate' => "40",
                      'output_pcr_style' => "0",
                      'receive_fec' => "0",
                      'scte35_passthru' => "0",
                      'esam_server_address' => "",
                      'esam_request_endpoint' => "",
                      'esam_hostname' => "",
                      'enable_cc' => "0",
                      'enable_afd' => "0",
                      'ac3dec_compmod' => "0",
                      'prefilter_contrast' => "0",
                      'prefilter_brightness' => "0",
                      'h264_profile' => "100",
                      'rtmp_server_address' => "rtmp://localhost/live",
                      'rtmp_remote_server_address' => "live",
                      'rtmp_naming' => "auto",
                      'rtmp_username' => "",
                      'rtmp_password' => "",
                      'http_webdav_method' => "0",
                      'http_server_address' => "",
                      'http_server_username' => "",
                      'http_server_password' => "",
                      'http_webdav_method_backup' => "0",
                      'http_server_address_backup' => "",
                      'http_server_username_backup' => "",
                      'http_server_password_backup' => "",
                      'http_host_address' => "",
                      'origin_server_address' => "",
                      'origin_server_medianame' => "",
                      'origin_server_username' => "",
                      'origin_server_password' => "",
                      'file_transfer_type' => FILE_TRANSFER_ALL."",
                      'multi_output_file_mode' => "0",
                      'multi_output_file_max_size' => "0",
                      'multi_output_file_max_duration' => "0",
                      'multi_output_file_format' => "TS",
                      'multi_output_file_dir' => "/var/www/output",
                      'sdp_path' => "/var/www",
                      'sdp_session_name' => DEFAULT_SDP_SESSION_NAME."",
                      'rtp_multicast_ttl' => "16",
                      'multi_ts_multicast_ttl' => "16",
                      'multi_ts_pid_mode' => "0",
                      'ebp_enable' => "0",
                      'multi_ts_ethernet_interface1' => "eth0",
                      'multi_ts_ethernet_interface2' => "eth0",
                      'publishing_point1' => "http://localhost/video/livestream1.isml",
                      'publishing_point_auth1' => "none",
                      'publishing_point_username1' => "",
                      'publishing_point_password1' => "",
                      'publishing_point2' => "http://localhost/video/livestream2.isml",
                      'publishing_point_auth2' => "none",
                      'publishing_point_username2' => "",
                      'publishing_point_password2' => "",
                      'silverlight_caption_format' => "1",
                      'manifest_type' => "0",
                      'mp4_frag_size' => "2",
                      'segment_size' => "10",
                      'window_size' => "8",
                      'apple_master_variant' => "0",
                      'fixed_key_enable' => "0",
                      'fixed_key_0' => "00",
                      'fixed_key_1' => "00",
                      'fixed_key_2' => "00",
                      'fixed_key_3' => "00",
                      'fixed_key_4' => "00",
                      'fixed_key_5' => "00",
                      'fixed_key_6' => "00",
                      'fixed_key_7' => "00",
                      'fixed_key_8' => "00",
                      'fixed_key_9' => "00",
                      'fixed_key_10' => "00",
                      'fixed_key_11' => "00",
                      'fixed_key_12' => "00",
                      'fixed_key_13' => "00",
                      'fixed_key_14' => "00",
                      'fixed_key_15' => "00",
                      'hls_segment_rollover_mode' => "0",
                      'hls_segment_rollover_count' => "100",
                      'hls_prefix_name' => "",
                      'hls_version' => "3",
                      'hls_name_style' => "1",
                      'hls_delete_server' => "1",
                      'hls_delete_local' => "0",
                      'hls_replace_start' => "-1",
                      'hls_replace_end' => "0",
                      'stream_group_active1' => "false",
                      'stream_group_active2' => "false",
                      'stream_group_profile1' => "0",
                      'stream_group_profile2' => "0",
                      'capture_device' => "port0",
                      'capture_video_pid' => "1212",
                      'capture_audio_pid' => "1414",
                      'capture_pmt_pid' => "94",
                      'capture_audio_language' => "eng",
                      'capture_brightness' => "128",
                      'capture_hue' => "0",
                      'capture_contrast' => "68",
                      'capture_saturation' => "64",
                      'temporal_filter_strength' => "0",
                      'diagonal_smoothing_filter' => "1",
                      'galaxie_mode' => "0",
                      'enable_scene_detection' => "1",
                      'buffer_constraint' => "1000",
                      'audio_sync_delta0' => "0",
                      'audio_sync_delta1' => "0",
                      'audio_sync_delta2' => "0",
                      'audio_ac3_dialnorm0' => "31",
                      'audio_ac3_dialnorm1' => "31",
                      'audio_ac3_dialnorm2' => "31",
                      'audio_channels0' => "2",
                      'audio_channels1' => "2",
                      'audio_channels2' => "2",
                      'ethernet_interface' => "eth0",
                      'image_overlay_file' => "",
                      'image_overlay_width' => "0",
                      'image_overlay_height' => "0",
                      'image_overlay_position' => "0",
                      'image_overlay_margin_x' => "10",
                      'image_overlay_margin_y' => "10",
                      'image_overlay_alpha' => "100",
                      'enable_sdi_repeat' => "0",
                      'sdi_frame_timeout' => "30",
                      'sdi_cc_data_rate' => "503488",
                      'enable_genlock' => "0;",
                      'bottom_field_first' => "0",
                      'dvbapi_tuner_name' => "",
                      'dvbapi_adapter_index' => "0",
                      'dvbapi_device_index' => "0",
                      'dvbapi_input_type' => "",
                      'dvbapi_input_channel_name' => "",
                      'dvbapi_input_frequency' => "0",
                      'dvbapi_input_modulation' => "",
                      'dvbapi_input_program_number' => "1",
                      'dvbapi_tuning_info' => "",
                      'rtmp_input_url' => "rtmp://localhost/live",
                      'rtmp_input_stream_name' => "live0",
                      'rtmp_input_dump_files' => "0",
                      'mp4file_input_name' => "",
                      'mp4file_loop' => "1",
                      'tsfile_loop' => "1",
                      'apple_hls_input_url' => "http://",
                      'apple_hls_input_dump_files' => "0",
                      'apple_hls_input_num_prebuffer_segs' => "1",
                      'scrambling_keymode' => "NONE",
                      'scrambling_sourceAddress' => "",
                      'scrambling_sourceBasePort' => "0",
                      'scrambling_targetAddress' => "",
                      'scrambling_targetBasePort' => "0",
                      'scrambling_ecmgHost' => "",
                      'scrambling_ecmgPort' => "8888",
                      'scrambling_ecmgBackupHost' => "",
                      'scrambling_ecmgBackupPort' => "8888",
                      'scrambling_protocolVersion' => "5",
                      'scrambling_ecmId' => "1",
                      'scrambling_streamId' => "1",
                      'scrambling_channelId' => "1",
                      'scrambling_superCasId' => "1",
                      'scrambling_rekeyInterval' => "30000",
                      'scrambling_stkmSendInterval' => "1000",
                      'scrambling_stkmPort' => "12045",
                      'scrambling_fixedKeyMaterial' => "000102030405060708090A0B0C0D0E0F",
                      'scrambling_authKey' => "000102030405060708090A0B0C0D0E0F",
                      'scrambling_useAuthentication' => "false",
                      'scrambling_scrambleRTCP' => "false",
                      'scrambling_logLevel' => "WARNING",

                      'verimatrix_enable' => "0",
                      'verimatrix_encryptor_url' => "http://public-ott-nodrm.verimatrix.com:12684/CAB/keyfile",
                      'verimatrix_client_url' => "",
                      'verimatrix_max_segments' => "0",
                      'verimatrix_resource_id' => "igolgi_010",
                      'verimatrix_asset_type' => "DTV",
                      'verimatrix_iv_mode' => "1",

                      'nielsen_watermark_decoding_enable' => "0",
                      'nielsen_distributor_id' => "your name here",
                      'nielsen_breakout_code' => "0",

                      'buydrm_enable1' => "0",
                      'buydrm_userkey1' => "00000000-0000-0000-0000-000000000000",
                      'buydrm_keyid1' => "00000000-0000-0000-0000-000000000000",
                      'buydrm_contentid1' => "00000000-0000-0000-0000-000000000000",
                      'buydrm_mediaid1' => "Media Name",
                      'buydrm_enable2' => "0",
                      'buydrm_userkey2' => "00000000-0000-0000-0000-000000000000",
                      'buydrm_keyid2' => "00000000-0000-0000-0000-000000000000",
                      'buydrm_contentid2' => "00000000-0000-0000-0000-000000000000",
                      'buydrm_mediaid2' => "Media Name",

                      'output_color_range' => "auto",
                      'output_color_primaries' => "auto",
                      'output_color_trc' => "auto",
                      'output_color_space' => "auto",

// DEBUG OPTIONS BEGIN
                      'input_type' => "stream",
                      'yuv_file_name' => "test.yuv",
                      'yuv_frame_rate' => "29.97",
                      'yuv_input_buffer_size' => "2000",
                      'h264_encoder_quality' => "5",
                      'noise_filtering' => "0",
                      'delay' => "00:00:00",
                      'buffer_delay' => "1500",
                      'save_input_ts_file' => "0",
                      'save_output_ts_file' => "0",
                      'simulated_interlaced_mode' => "0"
// DEBUG OPTIONS END
                      );

    if (ENABLE_AUDIO_AGC) {
        $defaultSettings["output_audio_agc"] = "DISABLED";
    }

    for ($iStream = 0; $iStream < MAX_STREAMS; ++$iStream) {
        $defaultSettings["stream_active$iStream"] = "false";
        $defaultSettings["stream_width$iStream"] = "0";
        $defaultSettings["stream_height$iStream"] = "0";
        $defaultSettings["stream_bitrate$iStream"] = "0";
        $defaultSettings["stream_codec$iStream"] = "H264";
        $defaultSettings["stream_framerate$iStream"] = "0";
        $defaultSettings["stream_profile$iStream"] = "2";
        $defaultSettings["stream_audio_bitrate$iStream"] = "0";
        $defaultSettings["stream_audio_channels$iStream"] = "2";
        $defaultSettings["stream_audio_bitrate_rtmp$iStream"] = "0";
        $defaultSettings["stream_audio_channels_rtmp$iStream"] = "2";
        $defaultSettings["stream_audio_samplerate_rtmp$iStream"] = "48000";
        $defaultSettings["stream_audio_only$iStream"] = "false";
        $defaultSettings["stream_enable_image_overlay$iStream"] = "true";
        $defaultSettings["stream_vbr$iStream"] = "false";
        $defaultSettings["stream_max_bitrate$iStream"] = "0";
        $defaultSettings["rtp_address$iStream"] = "239.192.10.".(($iStream+1)*10);
        $defaultSettings["rtp_port$iStream"] = sprintf("%d", 15000+($iStream+1)*10);
        $defaultSettings["multi_ts_address$iStream"] = "239.192.10.".(($iStream+1)*10);
        $defaultSettings["multi_ts_port$iStream"] = sprintf("%d", 15000+($iStream+1)*10);
        $defaultSettings["rtmp_stream_name$iStream"] = "live$iStream";
        $defaultSettings["multi_output_file_active$iStream"] = "true";
    }

    if (CONFIG_MODE == 1) {
        $defaultSettings["output_audio_bitrate0"] = "24000";
        $defaultSettings["stream_group_profile1"] = "3";
    }

    function save_config_file($filename, $params) {
        global $enable_atsc_input;

        if (!isset($_POST["channel_id"])) {
            $params["channel_id"] = "";
        }

        $new_multi_output_file_dir = @$_POST["multi_output_file_dir"];
        if ($new_multi_output_file_dir) {
            $params["multi_output_file_dir"] = $new_multi_output_file_dir;

            if (strlen($new_multi_output_file_dir) > 0) {
                if (!file_exists($new_multi_output_file_dir)) {
                    exec("sudo mkdir -p ".$new_multi_output_file_dir);
                }
            }
        } else {
            $params["multi_output_file_dir"] = "";
        }

        if ($enable_atsc_input) {
            $params["dvbapi_adapter_index"] = 0;
            $params["dvbapi_device_index"] = 0;

            $new_dvbapi_frontend_path = @$_POST["dvbapi_frontend_path"];
            if ($new_dvbapi_frontend_path) {
                $adapter = new dvbapi_Adapter($new_dvbapi_frontend_path);
                if ($adapter->valid) {
                    $params["dvbapi_adapter_index"] = $adapter->adapterIndex;
                    $params["dvbapi_device_index"] = $adapter->deviceIndex;
                }
            }

            $params["dvbapi_input_type"] = "ATSC";
            $params["dvbapi_input_channel_name"] = "";
            $params["dvbapi_input_frequency"] = 0;
            $params["dvbapi_input_modulation"] = "";
            $params["dvbapi_input_program_number"] = 1;

            $new_dvbapi_tuning_info = @$_POST["dvbapi_tuning_info"];
            if ($new_dvbapi_tuning_info) {
                $channel = new dvbapi_Channel($new_dvbapi_tuning_info);
                if ($channel->valid) {
                    $params["dvbapi_input_channel_name"] = $channel->name;
                    $params["dvbapi_input_frequency"] = $channel->freq;
                    $params["dvbapi_input_modulation"] = $channel->mod;
                    $params["dvbapi_input_program_number"] = $channel->programNumber;
                }
            }
        }

        // Hard code these for now
        $params["apple_hls_input_dump_files"] = 0;
        $params["apple_hls_input_num_prebuffer_segs"] = 1;
        $params["rtmp_input_dump_files"] = 0;

        if (ENABLE_RECORD) {
            $params["file_transfer_type"] = FILE_TRANSFER_RECORDINGS;
        } else {
            $params["file_transfer_type"] = FILE_TRANSFER_ALL;
        }
        $daemon_version = "Unknown";
        exec("dpkg -l | awk '$2==\"mpeg2ts\" { print $3 }'",$output,$return_val);
        if($return_val!=-1)
        {
            $daemon_version = $output[0];
        }
        // Save setting to config file
        $handle = @fopen("configs/".$filename, "w");

        if ($handle)
        {
            fprintf($handle, "name = \"MPEG2TS Transcoder Configuration\";\n");
            fprintf($handle, "version = \"%s\";\n\n",$daemon_version);
            fprintf($handle, "global_config:\n");
            fprintf($handle, "{\n");
            $idx = 0;
            foreach ($params as $param_name => $param_val) {
                if(strpos($param_name,'num_')===0||strpos($param_name,'vid_')===0||strpos($param_name,'aud_')===0||strpos($param_name,'out_')===0)
                    continue; //Ignore these as they are master variant
                // Handle audio stream groups
                if(!strncmp($param_name, "stream_active",13))
                {
                    sscanf($param_name, "stream_active%d", $idx);

                    fprintf($handle,  "    stream$idx:{\n");
                    fprintf($handle,  "         enabled = ".$params["stream_active$idx"].";\n");
                    fprintf($handle,  "         video:\n");
                    fprintf($handle,  "         {\n");
                    fprintf($handle,  "             width = ".$params["stream_width$idx"].";\n");
                    fprintf($handle,  "             height = ".$params["stream_height$idx"].";\n");
                    fprintf($handle,  "             codec = \"".$params["stream_codec$idx"]."\";\n");
                    fprintf($handle,  "             framerate = ".$params["stream_framerate$idx"].";\n");
                    fprintf($handle,  "             profile = ".$params["stream_profile$idx"].";\n");
                    fprintf($handle,  "             rate_ctl = ".$params["stream_vbr$idx"].";\n");
                    fprintf($handle,  "             bitrate = ".$params["stream_bitrate$idx"].";\n");
                    fprintf($handle,  "             vbr_max = ".$params["stream_vbr$idx"].";\n");
                    fprintf($handle,  "             vbr_max_bitrate = ".$params["stream_max_bitrate$idx"].";\n");
                    fprintf($handle,  "         };\n");
                    fprintf($handle,  "         audio:\n");
                    fprintf($handle,  "         {\n");
                    fprintf($handle,  "             audio_only = ".$params["stream_audio_only$idx"].";\n");
                    fprintf($handle,  "             bitrate = [".$params["stream_audio_bitrate$idx"].",".$params["stream_audio_bitrate2_$idx"]."];\n");
                    fprintf($handle,  "             channels = [".$params["stream_audio_channels$idx"].",".$params["stream_audio_channels2_$idx"]."];\n");
                    fprintf($handle,  "         };\n");
                    fprintf($handle,  "};\n");
                    continue;
                }
                // Handle any special cases here
                if ($param_name == "daemon_version") {
                    continue;
                }
                if (!strncmp($param_name, "stream",6)&&strncmp($param_name,"stream_group",12)) {
                    continue;
                }
                if (!ENABLE_DVB_SUBTITLES) {
                    if (!strncmp($param_name, "input_subtitle_", 15)) {
                        continue;
                    }
                }

                if (!ENABLE_AUDIO_AGC) {
                    if ($param_name == "output_audio_agc") {
                        continue;
                    }
                }

                if (!ENABLE_OUTPUT_VIDEO_BITRATE) {
                    if ($param_name == "output_video_bitrate") {
                        continue;
                    }
                }

                if (!ENABLE_SCRAMBLING) {
                    if (!strncmp($param_name, "scrambling_", 11)) {
                        continue;
                    }
                }

                if (!ENABLE_QUALITY_LEVEL) {
                    if ($param_name == "quality_level") {
                        continue;
                    }
                }

                if ($param_name == "config_filename") {
                    continue;
                }

                if ($param_name == "mpts_discover_cache") {
                    $param_val = base64_encode($param_val);
                }

                if ($param_name == "rtmp_username" || $param_name == "rtmp_password") {
                    fprintf($handle, "    %s = \"%s\";\n", $param_name, $param_val);
                    continue;
                }

                if ($param_name == "verimatrix_resource_id") {
                    fprintf($handle, "    %s = \"%s\";\n", $param_name, $param_val);
                    continue;
                }

                if (is_numeric($param_val)) {
                    fprintf($handle, "    %s = %s;\n", $param_name, $param_val);
                } else {
                    if (!strcasecmp($param_val, "true") || !strcasecmp($param_val, "false")) {
                        fprintf($handle, "    %s = %s;\n", $param_name, $param_val);
                    } else {
                        fprintf($handle, "    %s = \"%s\";\n", $param_name, $param_val);
                    }
                }
            }

            fprintf($handle, "};\n");
            fprintf($handle, "master_variant_config:\n");
            fprintf($handle, "{\n");
            fprintf($handle, "    output_settings:\n");
            fprintf($handle, "    {\n");
            fprintf($handle, "        num_video_profiles = %d;\n",$params['num_video_profiles']);
            fprintf($handle, "        num_audio_profiles = %d;\n",$params['num_audio_profiles']);
            fprintf($handle, "        num_output_streams = %d;\n",$params['num_output_streams']);
            fprintf($handle, "    };\n");
            for($i = 0; $i < $params['num_video_profiles']; $i++){
            fprintf($handle, "    video_profile%d:\n",$i);
            fprintf($handle, "    {\n");
//            fprintf($handle, "        vid_name = \"%s\";\n");
            fprintf($handle, "        width = %d;\n",$params['vid_width'][$i+1]);
            fprintf($handle, "        height = %d;\n",$params['vid_height'][$i+1]);
            fprintf($handle, "        codec = \"%s\";\n",$params['output_encoder']);
            fprintf($handle, "        encoder_profile = %d;\n",$params['vid_encoder_profile'][$i+1]);
            fprintf($handle, "        framerate = %d;\n",$params['vid_framerate'][$i+1]);
            fprintf($handle, "        mux_target = %d;\n",$params['vid_mux_target'][$i+1]);
            fprintf($handle, "        rate_ctl = %s;\n",$params['vid_rate_ctl'][$i+1]?'true':'false');
            fprintf($handle, "        vbr_max_bitrate = %d;\n",$params['vid_vbr_max_bitrate'][$i+1]);
            fprintf($handle, "    };\n");
            }
            for($i = 0; $i < $params['num_audio_profiles']; $i++){
            fprintf($handle, "    audio_profile%d:\n", $i);
            fprintf($handle, "    {\n");
            fprintf($handle, "        source_stream = %d;\n",$params['aud_source_stream'][$i+1]);
            fprintf($handle, "        codec = \"%s\";\n",$params['aud_codec'][$i+1]);
            fprintf($handle, "        bitrate = %d;\n",$params['aud_bitrate'][$i+1]);
            fprintf($handle, "        channels = %d;\n",$params['aud_channels'][$i+1]);
            fprintf($handle, "        dialnorm = %d;\n",$params['aud_dialnorm'][$i+1]);
            fprintf($handle, "        volume = %d;\n",$params['aud_volume'][$i+1]);
            fprintf($handle, "    };\n");
            }
            $out = $params['num_output_streams'];
          if($params['output_interface'] == "APPLE") {
                for($i = 0; $i < $params['num_video_profiles']; $i++) {
                    fprintf($handle, "    output_abr_stream%d:\n", $i);
                    fprintf($handle, "    {\n");
                    fprintf($handle, "        enabled = true;\n");
                    fprintf($handle, "        video_profile%d = true;\n", $i);
                    for($j = 0; $j < $params['num_audio_profiles']; $j++){
                        fprintf($handle, "        audio_profile%d = true;\n", $j);
                    }
                    fprintf($handle, "    };\n");
                }
            } else {
                for($i = 0; $i < $params['num_output_streams']; $i++) {
                    fprintf($handle, "    output_abr_stream%d:\n", $i);
                    fprintf($handle, "    {\n");
                    if(in_array($i+1, $params['out_enabled']))
                        fprintf($handle, "        enabled= true;\n");
                    else
                        fprintf($handle, "        enabled= false;\n");
                    fprintf($handle, "        multi_ts_address = \"%s\";\n",$params['out_multi_ts_address'][$i+1]);
                    fprintf($handle, "        multi_ts_port = %d;\n",$params['out_multi_ts_port'][$i+1]);
                    // if(($params['out_img_overlay']) != null && in_array($i+1, $params['out_img_overlay']))
                    //     fprintf($handle, "        img_overlay = true;\n");
                    // else
                    //     fprintf($handle, "        img_overlay = false;\n");
                    if(intval($params['out_video_profile'][$i+1]) != -1)
                        fprintf($handle, "        video_profile%d = %s;\n",$params['out_video_profile'][$i+1],'true');
                    foreach($params["out_audio_profile".($i+1)] as $r){
                        if($r != -1)
                        {
                            fprintf($handle, "        audio_profile%d = %s;\n",$r,'true');
                        }
                    }
                    fprintf($handle, "    };\n");
                }
            }
            fprintf($handle, "};\n");
            fclose($handle);

            return 0;
        } else {
            return -1;
        }
    }

    function override_settings(&$s, $forceDefaults) {
        // For ATSC-M/H mode, force/fix certain settings
        if (CONFIG_MODE == 1) {
            // Force these values
            $s['output_interface'] = "ATSC";
            $s['output_encoder'] = "H264";
            $s['enable_gpu'] =  "0";
            $s['output_format'] = "0";
            $s['stream_group_active1'] = "true";
            $s['stream_group_active2'] = "false";
            $s['stream_active0'] = "true";
            $s['stream_active1'] = "false";
            $s['stream_active2'] = "false";
            $s['stream_active3'] = "false";
            $s['stream_active4'] = "false";
            $s['stream_active5'] = "false";
            $s['stream_active6'] = "false";
            $s['stream_active7'] = "false";
            $s['output_audio_format'] = "aac";
            $s['output_audio_bitrate2'] = "0";

            if ($forceDefaults) {
                $s['stream_width0'] = "848";
                $s['stream_height0'] = "480";
            }

            // Check for values outside ATSC-M/H constraints
            if ($forceDefaults || $s['output_framerate'] != "0" && $s['output_framerate'] != "1") {
                $s['output_framerate'] = "0";
            }
        }
    }

    override_settings($defaultSettings, true);
    $settings = $defaultSettings;

    $dir = "configs";
    $files = scandir($dir);

    // Get the config filename from the database
    $db = new DB('configs/state.db');
    if (!$db->connect()) {
        if (!$db->resetDB()) {
            if ($db->getError()) {
                echo $db->getError()->getMessage();
            }
        }
    }

    $selected_filename = $db->selectOne("val", "vars", array("varname" => "config_filename"));

    // Read settings from config file
    function read_config_file($filename) {
        global $settings;

        if (!$filename) {
            $filename = "default.cfg";
        }

        // New style:  Use config api to access config settings
        $cfg = config_load("configs/$filename");
        if ($cfg) {
            foreach ($cfg as $key => $val) {
                if (strncmp($key, "stream",6)===0 && strncmp($key,"stream_group",12)!==0)
                {
                    $idx = $key[6];
                    $settings["stream_active$idx"]= $val['enabled']?'true':'false' ;
                    $settings["stream_width$idx"]= $val['video']['width'];
                    $settings["stream_height$idx"]= $val['video']['height'];
                    $settings["stream_bitrate$idx"]= $val['video']['bitrate'];
                    $settings["stream_max_bitrate$idx"]= $val['video']['vbr_max_bitrate'];
                    $settings["stream_vbr$idx"]= $val['video']['vbr_max']?'true':'false';
                    $settings["stream_codec$idx"]= $val['video']['codec'];
                    $settings["stream_framerate$idx"]= $val['video']['framerate'];
                    $settings["stream_profile$idx"]= $val['video']['profile'];
                    $settings["stream_audio_bitrate$idx"]= $val['audio']['bitrate'][0];
                    $settings["stream_audio_bitrate2_$idx"]= trim($val['audio']['bitrate'][1]);
                    $settings["stream_audio_channels$idx"]= $val['audio']['channels'][0];
                    $settings["stream_audio_channels2_$idx"]= trim($val['audio']['channels'][1]);
                    $settings["stream_audio_only$idx"]= $val['audio']['audio_only']?'true':'false';
                }
                else
                {
                    switch ($key) {
                        case "mpts_discover_cache":
                            if ($val && strlen($val) > 0) {
                                $settings["mpts_discover_cache"] = base64_decode($val);
                            }
                            break;

                        // Backwards compat: Map the old audio_sync_delta parameter
                        // to the new individual fields
                        case "audio_sync_delta":
                            $delta = config_get_string($cfg, $key);

                            $settings['audio_sync_delta0'] = $delta;
                            $settings['audio_sync_delta1'] = $delta;
                            $settings['audio_sync_delta2'] = $delta;
                            break;

                        case "output_audio_format":
                            if ($val == "ac3_51") {
                                $settings[$key] = "ac3";
                            } else {
                                $settings[$key] = $val;
                            }
                            break;

                        default:
                            if (!strcmp($key, "master_variant_config"))
                            {
                                 foreach ($val as $key2 => $val2) {
                                     foreach($val2 as $key3 => $val3) {
                                         $settings["$key-$key2-$key3"] = $val3;
                                    }
                                 }
                            }
                            else
                               $settings[$key] = config_get_string($cfg, $key);
                            break;
                    }
                }
            }
        }

        // In some cases (such as MH mode), some settings are hidden and assumed to be
        // certain hardcoded values. At this point, try to override settings loaded from
        // the config with appropriate hardcoded values.
        override_settings($settings, false);
    }

    function get_selected_config() {
        global $settings, $selected_filename;

        read_config_file($selected_filename);
        $param_string = format_config_data($settings, $selected_filename);

        return $param_string;
    }

    function format_config_data($data, $filename) {
        $reply = "config_filename=$filename;";

        // Handle any special cases here
        foreach ($data as $key => $val) {
            switch ($key) {
                case "dvbapi_frontend_path":
                    $dvbapi_frontend_path = dvbapi_getDevicePath("frontend", $data['dvbapi_adapter_index'], $data['dvbapi_device_index']);
                    $val = $dvbapi_frontend_path;
                    break;

                default:
                    break;
            }

            $reply .= "$key=".rawurlencode($val).";";
        }

        return $reply;
    }

    if (isset($_POST['config_filename'])) {
        $new_config_filename = str_replace($illegal_values, "_", @$_POST["config_filename"]);
        if (ENABLE_CENTOS) {
            exec("sudo chown apache \"configs/$new_config_filename\"");
        } else {
            exec("sudo chown www-data \"configs/$new_config_filename\"");
        }

        $ret = save_config_file($new_config_filename, $_POST);
        if ($ret == -1) {
            echo "ERROR";
            exit;
        }

        $settings_check = config_load("configs/".$new_config_filename);
        if (isset($settings_check["has_errors"]) && $settings_check["has_errors"]) {
            echo "BADCONFIG";
        } else {
            echo "OK";
        }

        exit;
    }

    $action = @$_GET['action'];
    $config_filename = str_replace($illegal_values, "_", @$_GET["config_filename"]);

    if ($action == "get_config" || $action == "get_config_defaults") {
        global $settings, $defaultSettings;

        if ($action == "get_config") {
            //Run parser on file
            exec("sudo python3 mv_parser.py configs/ $config_filename ", $output, $return_val);
            if($return_val != 0)   {
                echo "ParserError $return_val";
                exit;
            }
            // Load settings from requested config file
            read_config_file($config_filename);
        } else if ($action == "get_config_defaults") {
            // Return the default settings
            //$settings = $defaultSettings;
            read_config_file("default.cfg");
            $config_filename = "default.cfg";
        }

        $reply = format_config_data($settings, $config_filename);
        echo $reply;
        exit;
    }

    if ($action == "save_state") {
        $db = new DB('configs/state.db');
        if (!$db->connect()) {
            // Connection error, probably because the database file is in sqlite2 and not sqlite3
            if (!$db->resetDB()) {
                if ($db->getError()) {
                    echo $db->getError()->getMessage();
                }
            }
        }

        $db->update("vars", array("val" => "$config_filename"), array("varname" => "config_filename"));
        exit;
    }

    if ($action == "get_state") {
        $db = new DB('configs/state.db');
        if (!$db->connect()) {
            // Connection error, probably because the database file is in sqlite2 and not sqlite3
            if (!$db->resetDB()) {
                if ($db->getError()) {
                    echo $db->getError()->getMessage();
                }
            }
        }

        echo $db->selectOne("val", "vars", array("varname" => "config_filename"));
        exit;
    }

    if ($action == "delete_file") {
        $filename_to_delete = "configs/".$config_filename;
        unlink($filename_to_delete);

        echo "OK";
        exit;
    }
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Control Panel</title>

    <link href="<?php echo filetimeUrl('css/smoothness/jquery-ui.css'); ?>" rel="stylesheet" type="text/css" />
    <link href="<?php echo filetimeUrl('css/styles.css'); ?>" rel="stylesheet" type="text/css" />
    <link href="<?php echo filetimeUrl('stylein.css'); ?>" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="<?php echo filetimeUrl('js/jquery.js'); ?>"></script>
    <script type="text/javascript" src="<?php echo filetimeUrl('js/jquery-ui.js'); ?>"></script>
    <script type="text/javascript" src="<?php echo filetimeUrl('js/jquery.numeric.js'); ?>"></script>
    <script type="text/javascript" src="<?php echo filetimeUrl('js/ajaxfileupload.js'); ?>"></script>

    <style type="text/css">
    select[readonly] option, select[readonly] optgroup {
       display: none;
    }
    .profiles {
        width:95%;
        border-spacing: 0 3px;
    }
    .profiles td, th{
        text-align: center;
    }
    #video-profiles, #audio-profiles, #stream-profiles {
        padding: 1em 1.4em;
    }

    #box1 {
        min-height: 800px;
        height: auto !important;
    }

    div.box {
        width: 120px;
        height: 90px;
        margin: 0;
        border-style: solid;
        border-color: #000000;
    }

    .mpts_discover_button {
        <?php if (CONFIG_MODE == 1 || !ENABLE_DISCOVER) { ?>
        display: none !important;
        <?php } ?>
    }

    #hdmi_discover_button {
        <?php if (CONFIG_MODE == 1 || HDMI_PROVIDER != "BLACKMAGIC") { ?>
        display: none !important;
        <?php } ?>
    }

    #sdi_discover_button {
        <?php if (CONFIG_MODE == 1 || SDI_PROVIDER != "BLACKMAGIC") { ?>
        display: none !important;
        <?php } ?>
    }

    .discover_throbber {
        margin-right: 8px;
        margin-left: 5px;
        font-weight: bold;
    }

    .selected_discover_program {
        background-color: #FFF1CC;
    }

    .force_hide { display: none !important; }


   select, input {
    background-color: #e7e7e7;
    border: solid 1px #d7d7d7;
    color: #000000;
    font-size: 13px;
    margin: 1px 0;
    padding: 1px 3px;
    text-align: left;
}
    </style>
</head>

<body onload="addnew_menu()">
    <div id="overlaysettings" style="display:none;">
                            <!-- Image Overlay -->
    <table>
                            <tr name="image_overlay_heading_row" id="image_overlay_heading_row" class="image_overlay_heading_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td><b>Image Overlay</b></td>
                                <td></td>
                                <td colspan="4" align="left">
                                </td>
                            </tr>

                            <tr name="image_overlay_upload_row" id="image_overlay_upload_row" class="image_overlay_heading_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Upload image</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                    <input id="stream_image_overlay_upload_box" type="file" size="45" name="fileToUpload" class="input">
                                    <button class="button" id="imageOverlayFileUploadButton" onclick="return streamImageOverlayFileUpload();">Upload</button>
                                </td>
                            </tr>

                            <tr style="height: 15px" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>><td colspan="6"></td></tr>

                            <tr name="image_overlay_image_row" id="image_overlay_image_row" class="image_overlay_heading_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Image</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                     <select name="stream_image_overlay_file" id ="stream_image_overlay_file" class="image_overlay_file">
                                        <option value="">None</option>
                                     </select>
                                     <button class="button" id="stream_image_overlay_file_delete" onclick="return streamImageOverlayFileDelete();">Delete</button>
                                </td>
                            </tr>
                            <tr name="image_overlay_position_row" id="image_overlay_position_row" class="image_overlay_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Position</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                <select name="stream_image_overlay_position" id="stream_image_overlay_position">
                                    <option value="0">Bottom Right</option>
                                    <option value="1">Bottom Left</option>
                                    <option value="2">Top Left</option>
                                    <option value="3">Top Right</option>
                                </select>
                                </td>
                            </tr>

                            <tr name="image_overlay_margin_x_row" id="image_overlay_margin_x_row" class="image_overlay_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>X Margin</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                <input type="text" id="stream_image_overlay_margin_x" size="8" value="10" class="dim_entry integer_field"></input>
                                </td>
                            </tr>

                            <tr name="image_overlay_margin_y_row" id="image_overlay_margin_y_row" class="image_overlay_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Y Margin</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                <input type="text" id="stream_image_overlay_margin_y" size="8" value="10" class="dim_entry integer_field"></input>
                                </td>
                            </tr>

                            <tr name="image_overlay_alpha_row" id="image_overlay_alpha_row" class="image_overlay_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Alpha Blend</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                <input type="text" id="stream_image_overlay_alpha" size="8" value="100" class="dim_entry integer_field"></input> 0 - 100%
                                </td>
                            </tr>

                            <tr style="height: 15px"><td colspan="6" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>></td></tr>

                            <tr name="image_overlay_preview_row" id="image_overlay_preview_row" class="image_overlay_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Preview</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                <img id="stream_image_overlay_preview_img"></img>
                                </td>
                            </tr>
                            <tr style="height: 10px" class="image_overlay_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>><td colspan="6"></td></tr>

          </table>
    </div>
    <div id="wrapper">
        <?php include("includes/header.php"); ?>
        <div id="content1">
            <div id="box1">
            <table class="head" style="float: left">
                <tr>
                    <td><h1 class="head">Application Configuration</h1></td>
                    <td><button type="button" style="width:25px; height:25px" onclick="show_help()">?</button></td>
                </tr>
            </table>
            <table style="float: right; margin-top: 0.67em">
                <tr>
                    <td><button type="button" style="line-height: 20px" onclick="reset_defaults()">Reset to defaults</button></td>
                    <td><button type="button" id="configManagerButton" style="line-height: 20px">Manage...</button></td>
                </tr>
            </table>
            <div style="clear: both"></div>
            <div id="enq" style="padding-top: 10px">
                <span id="config_data" class="force_hide"><?php echo get_selected_config(); ?></span>
                <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" name="configuration" id="configuration">
                <table style="margin-bottom: 12px;">
                    <tr style="margin-top: 10px">
                        <td style="font-size: 15px; font-weight: bold">CONFIG FILE :</td>
                        <td style="padding-left: 5px">
                             <select name="current_file" id="current_file" style="height: 26px; line-height: 26px; width: 240px" onChange="file_selected(this)">
                             <?php
                             $first_file = 1;
                             foreach($files as &$file) {
                                if (strstr($file, ".cfg")) {
                                    if ($first_file) {
                                        $first_file = 0;
                                    }

                                    if ($file == $selected_filename) {
                                        echo "<option value=\"$file\" selected>$file</option>";
                                    } else {
                                        echo "<option value=\"$file\">$file</option>";
                                    }
                                }
                             }

                             // No files found, set default
                             if ($first_file) {
                                 echo "<option value=\"default.cfg\">default.cfg</option>";
                             }
                             ?>
                             </select>
                        </td>
                        <td style="padding-left: 5px"><button type="submit" style="line-height: 20px" onclick="save_file()">Save</button></td>
                        <td><button type="submit" style="line-height: 20px" onclick="save_new_file()">Save As...</button></td>
                        <td><button type="button" style="line-height: 20px" onclick="delete_file()">Delete</button></td>
                    </tr>
                </table>

                <div id="originManager" style="display:none; font-size: 13px" title="Origin Manager">
                    <p>
                        <div style="margin-bottom: 10px;">
                        </div>
                            <div style="margin-bottom: 10px;">
                        </div>
                    </p>
                </div>

                <div id="configManager" style="display:none; font-size: 13px" title="Config Manager">
                    <p>
                        <div style="margin-bottom: 10px">
                            <div style="font-weight:bold; margin-bottom: 3px">Download archive of all config files.</div>
                        <label for="config_backup_filename">Filename:</label><input id="config_backup_filename" name="filename" type="text"><br>
                           <button id="configBackupAllButton">Backup all configs</button>
                        </div>
                        <div style="margin-bottom: 10px;">
                            <div style="font-weight:bold; margin-bottom: 3px">Restore from archive or individual .cfg file.</div>
                            <input id="configRestoreUploadBox" type="file" name="configToUpload" class="input" style="background-color:#CCCCCC;" /><br/>
                            <button id="configRestoreButton">Upload</button>
                        </div>
                        <br style="" />
                        <button id="configDeleteAllButton" style="background-color:red; color:white; font-weight:bold; height: 26px">Delete all configs</button>
                    </p>
                </div>

                <div id="tabs" style="font-size: 13px">
                    <ul id="options_row_0"></ul>
                    <div id="input-options" class="option-tab-content master-tab" style="display:none">
                        <table border="0" cellpadding="0" cellspacing="0" class="settings">
                        <?php
                            $settingGroupLevel = 1;

                            function settingGroupStart($groupId) {
                                global $settingGroupLevel;
                                if ($settingGroupLevel != 0) {
                                    trigger_error("settingGroupStart mismatched");
                                }
                                $settingGroupLevel++;
                                echo '<table class="setting_group" border="0" cellpadding="0" cellspacing="0" width="95%" align="center" style="margin-bottom:15px;" id="'.$groupId.'">';
                            }

                            function settingGroupEnd() {
                                global $settingGroupLevel;
                                if ($settingGroupLevel != 1) {
                                    trigger_error("settingGroupEnd mismatched");
                                }
                                $settingGroupLevel--;
                                echo '</table>';
                            }

                            function settingRowStart($label, $rowId=null) {
                                global $settingGroupLevel;
                                if ($settingGroupLevel != 1) {
                                    trigger_error("settingRowStart mismatched");
                                }
                                $settingGroupLevel++;
                                echo '<tr class="setting_row" style="height: 22px"'.($rowId?(' id="'.$rowId.'" name="'.$rowId.'"'):'').'>';
                                echo '<td class="setting_label" style="width: 180px">'.$label.'</td>';
                                echo '<td class="setting_spacer" style="width: 15px">'.($label == "" ? "" : ":").'</td>';
                                echo '<td class="setting_cell" colspan="4">';
                            }

                            function settingRowEnd() {
                                global $settingGroupLevel;
                                if ($settingGroupLevel != 2) {
                                    trigger_error("settingRowEnd mismatched");
                                }
                                $settingGroupLevel--;
                                echo '</td>';
                                echo '</tr>';
                            }

                            function settingWriteInputInterfaces() {
                                global $build;
                                global $enable_atsc_input;
                                $iVisible = 0;
                                foreach ($build->getInputInterfaces() as $iface) {
                                    if ($iface->enabled) {
                                        $isRowStart = ($iVisible % 3) == 0;
                                        if ($isRowStart) {
                                            // If this isn't first row, closeout previous row
                                            if ($iVisible != 0) {
                                                settingRowEnd();
                                            }
                                            settingRowStart($iVisible==0?'Input interface':'');
                                        }

                                        $enabled = true;
                                        if ($iface->id == "TSFILE") {
                                            if (ENABLE_SOURCE_FILE_FTP)
                                            {
                                                $input_files = glob(SOURCE_FILE_PATH."/*.ts");
                                                if (!count($input_files))
                                                {
                                                    $enabled = false;
                                                }
                                            }
                                        } else if ($iface->id == "MP4FILE") {
                                            if (ENABLE_SOURCE_FILE_FTP)
                                            {
                                                $input_files = glob(SOURCE_FILE_PATH."/*.{mp4,mov}",GLOB_BRACE);
                                                if (!count($input_files))
                                                {
                                                    $enabled = false;
                                                }
                                            }
                                        }
                                        else if ($iface->id == "DVB-API") {
                                            $enabled = $enable_atsc_input;

                                        }

                                        $disableAttr = "";
                                        $disableStyle = "";
                                        if (!$enabled) {
                                            $disableAttr = " disabled='disabled'";
                                            $disableStyle = "color:#888888";
                                        }

                                        echo('<div style="width:148px;float:left;">');
                                        echo('<label><input name="input_interface" value="'.$iface->id.'" type="radio" checked="checked" style="vertical-align:-2px"'.$disableAttr.'><span style="'.$disableStyle.'">'.$iface->name.'</span></label>');
                                        echo('</div>');
                                        ++$iVisible;
                                    }
                                }
                                while (($iVisible % 3) != 0) {
                                     echo('<div style="width:148px;float:left;"></div>');
                                    ++$iVisible;
                                }
                                settingRowEnd();
                            }

                            function settingWriteOutputInterfaces() {
                                global $build;
                                $iVisible = 0;
                                foreach ($build->getOutputInterfaces() as $iface) {
                                    if ($iface->enabled) {
                                        $isRowStart = ($iVisible % 3) == 0;
                                        if ($isRowStart) {
                                            // If this isn't first row, closeout previous row
                                            if ($iVisible != 0) {
                                                settingRowEnd();
                                            }
                                            settingRowStart($iVisible==0?'Output Interface':'');
                                        }

                                        $enabled = true;

                                        $disableAttr = "";
                                        $disableStyle = "";
                                        if (!$enabled) {
                                            $disableAttr = " disabled='disabled'";
                                            $disableStyle = "color:#888888";
                                        }

                                        $class = ("IP" != $iface->id) ? " class=\"disable_on_audio_only\"" : "";

                                        echo('<div style="width:148px;float:left;"'.$class.'>');
                                        echo('<label><input name="output_interface" value="'.$iface->id.'" type="radio" checked="checked" style="vertical-align:-2px"'.$disableAttr.'><span style="'.$disableStyle.'">'.$iface->name.'</span></label>');
                                        echo('</div>');
                                        ++$iVisible;
                                    }
                                }
                                while (($iVisible % 3) != 0) {
                                     echo('<div style="width:148px;float:left;"></div>');
                                    ++$iVisible;
                                }
                                settingRowEnd();
                            }

                            settingWriteInputInterfaces();
                        ?>

                            <tr style="height: 15px"></tr>
                            <tr name="apple_hls_input_tuner_row" id="apple_hls_input_tuner_row" class="apple_hls_input_row">
                                <td>Apple HLS URL</td>
                                <td>:</td>
                                <td colspan="4">
                                    <input name="apple_hls_input_url" class="entry_box" style="width:300px;text-align:left;" id="apple_hls_input_url" type="text">
                                </td>
                            </tr>
                            <tr name="apple_hls_input_num_prebuffer_segs_row" id="apple_hls_input_num_prebuffer_segs_row" class="apple_hls_input_row">
                                <td>Prebuffer Segments</td>
                                <td>:</td>
                                <td colspan="4">
                                    <select name="apple_hls_input_num_prebuffer_segs" id="apple_hls_input_num_prebuffer_segs">
                                        <option value="1">1</option>
                                        <option value="2">2</option>
                                        <option value="3">3</option>
                                        <option value="4">4</option>
                                    </select>
                                </td>
                            </tr>
                            <tr style="height: 15px" class="apple_hls_input_row"></tr>
                            <tr name="rtmp_input_row" id="rtmp_input_row" class="rtmp_input_row">
                                <td>RTMP Application URL</td>
                                <td>:</td>
                                <td colspan="4">
                                    <input name="rtmp_input_url" class="entry_box" style="width:300px;text-align:left;" id="rtmp_input_url" type="text">
                                </td>
                             </tr>
                            <tr name="rtmp_input_row" id="rtmp_input_row" class="rtmp_input_row">
                                <td>RTMP Stream Name</td>
                                <td>:</td>
                                <td colspan="4">
                                    <input name="rtmp_input_stream_name" class="entry_box" style="width:300px;text-align:left;" id="rtmp_input_stream_name" type="text">
                                </td>
                             </tr>
                          <tr style="height: 15px" class="rtmp_input_row"></tr>
                          <tr name="input_atsc_heading_row" id="input_atsc_heading_row" class="input_atsc_heading_row input_atsc_row <?php echo !$enable_atsc_input ? "force_hide" : "" ?>">
                                <td><b>ATSC Tuning</b></td>
                                <td></td>
                                <td colspan="4" align="left">
                                </td>
                            </tr>

                            <tr name="input_atsc_tuner_row" id="input_atsc_tuner_row" class="input_atsc_row <?php echo !$enable_atsc_input ? "force_hide" : "" ?>">
                                <td>Tuner</td>
                                <td>:</td>
                                <td colspan="4">
                                    <select name="input_atsc_tuner" class="entry_box" style="text-align: left; width:300px" id="input_atsc_tuner">
                                        <?php
                                        if ($enable_atsc_input)
                                        {
                                            $numAdapters = count($atscAdapters);
                                            for ($i = 0; $i < $numAdapters; ++$i)
                                            {
                                                $adapter = $atscAdapters[$i];
                                                printf("<option value='%s' data-adapterindex='%d' data-deviceindex='%d' >Tuner %d</option>\n", $adapter->frontendPath,$adapter->adapterIndex, $adapter->deviceIndex, $i+1);
                                            }
                                        }
                                        ?>
                                    </select>
                                </td>
                             </tr>

                            <tr name="input_atsc_channel_row" id="input_atsc_channel_row" class="input_atsc_row <?php echo !$enable_atsc_input ? "force_hide" : "" ?>">
                                <td>Channel</td>
                                <td>:</td>
                                <td colspan="4">
                                    <?php if ($enable_atsc_input) { ?>
                                    <select onchange='input_atsc_channel_changed();' name='input_atsc_channel' class='entry_box' style='text-align: left; width:300px' id='input_atsc_channel'>
                                    </select>
                                    <?php } ?>
                                </td>
                             </tr>

                            <tr name="input_atsc_scan_row" id="input_atsc_scan_row" class="input_atsc_row <?php echo !$enable_atsc_input ? "force_hide" : "" ?>">
                                <td></td>
                                <td></td>
                                <td colspan="4" style="padding-top: 2px">
                                <a id="input_atsc_scan_url" href="tuner.php" target="_blank" style="color: #06c; text-decoration:underline">Configuration / Scanning</a>
                                </td>
                             </tr>
                            <tr style="height: 15px" class="input_atsc_row <?php echo !$enable_atsc_input ? "force_hide" : "" ?>"></tr>
                            <tr name="source_file_list_row" id="source_file_list_row" <?php echo (CONFIG_MODE == 1 || !ENABLE_SOURCE_FILE_FTP) ? "style='display:none;'" : "" ?> class="tsfile_input_row">
                                <td>Input TS File</td>
                                <td>:</td>
                                <td colspan="4">
                                    <select name="source_file_list" class="entry_box" id="source_file_list" type="text" onchange="source_file_list_changed(this)">
                                    <?php
                                            if (ENABLE_SOURCE_FILE_FTP)
                                            {
                                                $input_files = glob(SOURCE_FILE_PATH."/*.ts");
                                                if (count($input_files))
                                                {
                                                    foreach ($input_files as $input_file)
                                                    {
                                                        if (is_file($input_file))
                                                        {
                                                            $basename = basename($input_file);
                                                            echo "<option value=\"$basename\">$basename</option>";
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    echo "<option value=\"\">No files available</option>";
                                                }
                                            }
                                        ?>
                                    <!-- <option value="">Enter path...</option> -->
                                    </select>

                                </td>
                            </tr>
                            <tr name="source_file_row" id="source_file_row" <?php echo (CONFIG_MODE == 1 || ENABLE_SOURCE_FILE_FTP) ? "style='display:none;'" : "" ?> class="tsfile_input_row">
                                <td><?php if (!ENABLE_SOURCE_FILE_FTP) echo ("Input TS File"); ?></td>
                                <td>:</td>
                                <td colspan="4"><input name="yuv_file_name" class="entry_box" style="width:300px" id="yuv_file_name" type="text"></td>
                            </tr>
                            <tr name="tsfile_loop_row" id="tsfile_loop_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="tsfile_input_row">
                                <td>Input looping</td>
                                <td>:</td>
                                <td colspan="4">
                                    <select name="tsfile_loop" id="tsfile_loop">
                                        <option value="1">On</option>
                                        <option value="0">Off</option>
                                    </select>
                                </td>
                            </tr>
                            <tr style="height: 15px" class="tsfile_input_row"></tr>
                            <tr name="mp4file_input_row0" id="mp4file_input_row0" <?php echo (CONFIG_MODE == 1 || !ENABLE_SOURCE_FILE_FTP) ? "style='display:none;'" : "" ?> class="mp4file_input_row">
                                <td>Input MP4 File</td>
                                <td>:</td>
                                <td colspan="4">
                                    <select name="mp4file_list" class="entry_box" id="mp4file_list" type="text" onchange="mp4file_list_changed(this)">
                                    <?php
                                            if (ENABLE_SOURCE_FILE_FTP)
                                            {
                                                $input_files = glob(SOURCE_FILE_PATH."/*.{mp4,mov}", GLOB_BRACE);
                                                if (count($input_files))
                                                {
                                                    foreach ($input_files as $input_file)
                                                    {
                                                        if (is_file($input_file))
                                                        {
                                                            $basename = basename($input_file);
                                                            echo "<option value=\"$basename\">$basename</option>";
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    echo "<option value=\"\">No files available</option>";
                                                }
                                            }
                                        ?>
                                    <!-- <option value="">Enter path...</option> -->
                                    </select>

                                </td>
                            </tr>
                            <tr name="mp4file_input_row" id="mp4file_input_row" <?php echo (CONFIG_MODE == 1 || ENABLE_SOURCE_FILE_FTP) ? "style='display:none;'" : "" ?> class="mp4file_input_row">
                                <td><?php if (!ENABLE_SOURCE_FILE_FTP) echo ("Input MP4 File"); ?></td>
                                <td>:</td>
                                <td colspan="4"><input name="mp4file_input_name" class="entry_box" style="width:300px" id="mp4file_input_name" type="text"></td>
                            </tr>
                            <tr name="mp4file_loop_row" id="mp4file_loop_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="mp4file_input_row">
                                <td>Input looping</td>
                                <td>:</td>
                                <td colspan="4">
                                    <select name="mp4file_loop" id="mp4file_loop">
                                        <option value="1">On</option>
                                        <option value="0">Off</option>
                                    </select>
                                </td>
                            </tr>
                            <!-- <tr style="height: 15px" class="ip_input_row"></tr>   -->
                            <tr name="ts_input_source_heading" id="ts_input_source_heading" class="ip_input_row">
                                <td colspan="6"><b>Primary Source</b></td>
                            </tr>

                            <tr name="source_interface_row" id="source_interface_row" class="ip_input_row">
                                <td style="width: 180px">Source Network Interface</td>
                                <td style="width: 15px">:</td>
                                <td colspan="4" align="left">
                                    <select name="source_ethernet_interface" id="source_ethernet_interface">
                                        <?php
                                        foreach ($machine->getNetworkInterfaces() as $eth) {
                                            if ($eth->active()) {
                                                echo ("<option value=\"{$eth->getName()}\">{$eth->getName()}</option>\n");
                                            }
                                        }
                                        ?>
                                    </select>
                                </td>
                            </tr>

                            <tr name="source_ip_address_row" id="source_ip_address_row" class="ip_input_row">
                                <td>Source IP Address (IPV4)</td>
                                <td>:</td>
                                <td colspan="3">
                                    <nobr>
                                    <input name="source_ip_address" class="entry_box" style="width:120px;" id="source_ip_address" type="text">&nbsp;
                                    <label><input name="enable_raw_input" id="enable_raw_input" type="checkbox" style='vertical-align:-2px'>Enable raw socket</label>
                                    <label style="display: none;"><input name="enable_igmp_input" id="enable_igmp_input" type="checkbox" style='display: none;vertical-align:-2px'>Enable IGMP reports</label>
                                    </nobr>
                                </td>
                            </tr>
                            <tr name="source_ip_address_ipv6_row" id="source_ip_address_ipv6_row" class="ip_input_row">
                                <?php if (ENABLE_IPV6) { ?>
                                 <td>Source IP Address (IPV6)</td>
                                <td>:</td>
                                <td colspan="3">
                                    <nobr>
                                    <input name="source_ip_address_ipv6" class="entry_box" style="width:260px;" id="source_ip_address_ipv6" type="text">&nbsp;(OPTIONAL)
                                    </nobr>
                                </td>
                                <?php } ?>
                            </tr>
                            <tr name="source_port_row" id="source_port_row" class="ip_input_row">
                                <td>Source port</td>
                                <td>:</td>
                                <td colspan="7"><input name="source_port" class="dim_entry integer_field" id="source_port" type="text"></td>
                            </tr>
                            <tr name="multicast_filter_address_row" id="multicast_filter_address_row" class="ip_input_row">
                                <td>Multicast IGMPv3 Source IP</td>
                                <td>:</td>
                                <td colspan="3">
                                    <nobr>
                                    <input name="multicast_filter_address" class="entry_box" style="width:120px;" id="multicast_filter_address" type="text">&nbsp;<span class="muted">(blank = disabled)</span></td>
                                    </nobr>
                                </td>
                            </tr>


                            <!-- ====================================================================================================================== -->
                            <!-- ==== Secondary Source ================================================================================================ -->
                            <!-- ====================================================================================================================== -->

                            <tr style="height: 15px" class="ip_input_row"></tr>
                            <tr name="ts_input_source_heading" id="ts_input_source_heading" class="ip_input_row">
                                <td colspan="6"><b>Secondary Source</b></td>
                            </tr>

                            <tr name="enable_input_row" id="enable_input_row_2" class="ip_input_row">
                                <td style="width: 180px">Enable</td>
                                <td style="width: 15px">:</td>
                                <td colspan="4" align="left">
                                    <select name="enable_source_input_2" id="enable_source_input_2">
                                        <option value="0">Off</option>
                                        <option value="1">On</option>
                                    </select>
                                </td>
                            </tr>

                            <tr class="ip_input_row_2">
                                <td style="width: 180px">Source Network Interface</td>
                                <td style="width: 15px">:</td>
                                <td colspan="4" align="left">
                                    <select name="source_ethernet_interface_2" id="source_ethernet_interface_2">
                                        <?php
                                        foreach ($machine->getNetworkInterfaces() as $eth) {
                                            if ($eth->active()) {
                                                echo ("<option value=\"{$eth->getName()}\">{$eth->getName()}</option>\n");
                                            }
                                        }
                                        ?>
                                    </select>
                                </td>
                            </tr>

                            <!-- <tr class="ip_input_row_2 force_hide"> -->
                            <tr class="ip_input_row_2">
                                <td>Source IP Address (IPV4)</td>
                                <td>:</td>
                                <td colspan="3">
                                    <nobr>
                                    <input name="source_ip_address_2" class="entry_box" style="width:120px;" id="source_ip_address_2" type="text">&nbsp;
                                    <label><input name="enable_raw_input_2" id="enable_raw_input_2" type="checkbox" style='vertical-align:-2px'>Enable raw socket</label>
                                    </nobr>
                                </td>
                            </tr>

                            <tr name="source_ip_address_ipv6_row_2" id="source_ip_address_ipv6_row_2" class="ip_input_row_2">
                                <?php if (ENABLE_IPV6) { ?>
                                 <td>Source IP Address (IPV6)</td>
                                <td>:</td>
                                <td colspan="3">
                                    <nobr>
                                    <input name="source_ip_address_ipv6_2" class="entry_box" style="width:260px;" id="source_ip_address_ipv6_2" type="text">&nbsp;(OPTIONAL)
                                    </nobr>
                                </td>
                                <?php } ?>
                            </tr>
                            <tr name="source_port_row_2" id="source_port_row_2" class="ip_input_row_2">
                                <td>Source port</td>
                                <td>:</td>
                                <td colspan="7"><input name="source_port_2" class="dim_entry integer_field" id="source_port_2" type="text"></td>
                            </tr>
                            <tr name="multicast_filter_address_row_2" id="multicast_filter_address_row_2" class="ip_input_row_2">
                                <td>Multicast IGMPv3 Source IP</td>
                                <td>:</td>
                                <td colspan="3">
                                    <nobr>
                                    <input name="multicast_filter_address_2" class="entry_box" style="width:120px;" id="multicast_filter_address_2" type="text">&nbsp;<span class="muted">(blank = disabled)</span></td>
                                    </nobr>
                                </td>
                            </tr>
                            <tr style="height: 15px" class="ip_input_row"></tr>

                            <tr class="ip_input_row_2">
                                <td>Source Timeout</td>
                                <td>:</td>
                                <td colspan="3">
                                    <nobr>
                                    <input name="source_timeout" class="entry_box" style="width:120px;" id="source_timeout" type="text">&nbsp;
                                    seconds
                                    </nobr>
                                </td>
                            </tr>

                            <!-- ====================================================================================================================== -->

                            <!-- ================================================================================== -->
                            <!-- ==== Slate Source ================================================================ -->
                            <!-- ================================================================================== -->

                            <tr name="slate_source_heading" id="slate_source_heading" <?php echo (ENABLE_SLATE == 0) ? "style='display:none;'" : "" ?>>
                                <td><b>Slate Source</b></td>
                                <td>:</td>
                                <td colspan="3">
                                    <label><input name="slate_enable" id="slate_enable" type='checkbox' style='vertical-align:-2px' onclick='slate_enable_clicked();'>Enable</label>
                                </td>
                            </tr>

                            <tr name="slate_upload_row" id="slate_upload_row" class="slate_input_row tab" <?php echo (ENABLE_SLATE == 0) ? "style='display:none;'" : "" ?>>
                                <td>Upload Slate</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                    <input id="slate_upload_box" type="file" size="45" name="fileToUpload" class="input">
                                    <button class="button" id="slateFileUploadButton" onclick="return slateFileUpload();">Upload</button>
                                </td>
                            </tr>


                            <tr name="slate_row" id="slate_row" class="slate_input_row tab" <?php echo (ENABLE_SLATE == 0) ? "style='display:none;'" : "" ?>>
                                <td>Slate</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                     <select name="slate_filename" id ="slate_filename" class="slate_filename" onChange="slate_changed()">
                                        <option value="">None</option>
                                     </select>
                                     <button class="button" id="slate_file_delete" onclick="return slateFileDelete();">Delete</button>
                                </td>
                            </tr>

                            <tr class="slate_input_row" <?php echo (ENABLE_SLATE == 0) ? "style='display:none;'" : "" ?>>
                                <td>Slate Force Audio Silence</td>
                                <td>:</td>
                                <td colspan="3">
                                    <label><input name="slate_silence" id="slate_silence" type='checkbox' style="vertical-align:-2px";>Enable</label></td>
                            </tr>

                            <tr class="slate_input_row" <?php echo (ENABLE_SLATE == 0) ? "style='display:none;'" : "" ?>>
                                <td>Slate Loss Threshold</td>
                                <td>:</td>
                                <td colspan="3">
                                    <nobr>
                                    <input name="slate_entry_time" min=5 max=100 step=5 value=50 class="entry_box integer_field" style="width:120px;" id="slate_entry_time" type="number">&nbsp;
                                    %
                                    </nobr>
                                </td>
                            </tr>

                            <tr class="slate_input_row" <?php echo (ENABLE_SLATE == 0) ? "style='display:none;'" : "" ?>>
                                <td>Slate Loss Window</td>
                                <td>:</td>
                                <td colspan="3">
                                    <nobr>
                                    <input name="slate_duration_time" min=1 max=15 value=1 class="entry_box" style="width:120px;" id="slate_duration_time" type="number">&nbsp;
                                    seconds
                                    </nobr>
                                </td>
                            </tr>

                            <tr class="slate_input_row" <?php echo (ENABLE_SLATE == 0) ? "style='display:none;'" : "" ?>>
                                <td>Slate Exit Time</td>
                                <td>:</td>
                                <td colspan="3">
                                    <nobr>
                                    <input name="slate_exit_time" min=0 max=15 value=1 class="entry_box" style="width:120px;" id="slate_exit_time" type="number">&nbsp;
                                    seconds
                                    </nobr>
                                </td>
                            </tr>

                            <!-- ================================================================================== -->


                            <tr style="height: 15px" class="ip_input_row"></tr>
                            <tr name="audio_only_row" id="audio_only_row" <?php echo ((CONFIG_MODE == 1 || !ENABLE_AUDIO_ONLY_MODE) ? "style='display:none;'" : "") ?> class="ip_input_row">
                                <td>Audio Only</td>
                                <td>:</td>
                                <td colspan="3">
                                    <label><input name="audio_only" id="audio_only" type='checkbox' style='vertical-align:-2px' onclick='audio_only_clicked();'>Enable</label></td>
                            </tr>
                          <tr id="hd_sdi_row0" class="video_setting_row hd_sdi_setting_row">
                                <td id="sdi_card_label">HD-SDI Card #</td>
                                <td>:</td>
                                <td colspan="7">
                                    <select name="sdi_card_num" id="sdi_card_num">
<?php for($card = 0; $card < SDI_CARD_COUNT; $card++){ ?>
                                        <option value="<?=$card+1?>"><?=$card+1?></option>
<?php } ?>
                                    </select>
                                </td>
                            </tr>
                         <tr id="hd_sdi_row1" class="video_setting_row hd_sdi_setting_row">
                                <td id="sdi_card_label">HD-SDI Input #</td>
                                <td>:</td>
                                <td colspan="7">
                                    <select name="sdi_card_input_num" id="sdi_card_input_num">
<?php for($card = 0; $card < SDI_CARD_INPUT_COUNT; $card++){ ?>
                                        <option value="<?=$card+1?>"><?=$card+1?></option>
<?php } ?>
                                    </select>
                                </td>
                          </tr>

                            <tr <?php echo ((CONFIG_MODE == 1) ? "style='display:none;'" : "") ?> class="ip_input_row mpts_discover_row <?php echo ((CONFIG_MODE == 1 || !ENABLE_DISCOVER) ? "force_hide" : "") ?>">
                                <td>Programs</td>
                                <td>:</td>
                                <td colspan="3" id="mpts_discover_row">
                                    <div style="float:left;">
                                        <button id="mpts_discover_button" class="mpts_discover_button discover_button">Discover Programs</button>
                                        <span id="mpts_discover_throbber" class="discover_throbber" style="display:none"><img style="vertical-align:middle" src="images/loading-small.gif"></img> Scanning input...</span>
                                    </div>
                                    <div style="float:right;padding-right:8vw;">
                                        <button id="mpts_discover_clear_button" class="mpts_discover_clear_button discover_clear_button">Clear Discover Results</button>
                                    </div>
                                    <div style="clear:both;"></div>
                                </td>
                            </tr>
                            <tr id="mpts_discover_results_row" class="mpts_discover_row <?php echo ((CONFIG_MODE == 1 || !ENABLE_DISCOVER) ? "force_hide" : "") ?>">
                                <td colspan="5" align="left">
                                    <table id="mpts_discover_results" border="0" class="gridded_table" style="width: 80vw; margin-top: 10px">
                                        <tr class="gridded_table_section_header">
                                            <th class="program_info" colspan="3">Program</th>
                                            <th class="program_info" colspan="4">Streams</th>
                                        </tr>
                                        <tr class="gridded_table_header">
                                            <th class="program_info" style="width: 150px">Name</th>
                                            <th class="program_info" style="width: 50px">Number</th>
                                            <th class="program_info" style="width: 65px">PMT PID</th>
                                            <th class="program_info" style="width: 50px">PID</th>
                                            <th class="program_info" style="width: 70px">Type</th>
                                            <th class="program_info">Description</th>
                                            <th style="width: 60px"></th>
                                        </tr>
                                        <tr class="discover_program_proto force_hide">
                                            <td class="program_info source_identity" style="text-align:center;"></td>
                                            <td class="program_info program_number" style="text-align:center;"></td>
                                            <td class="program_info program_pmt_pid" style="text-align:center;"></td>
                                            <td colspan="3" class="program_info streams stream_pid" style="text-align:center;"></td>
                                            <td><button class="program_select_btn">Select</button></td>
                                        </tr>
                                    </table>
                            </tr>
                            <tr id="deltacast_discover_results_row" class="deltacast_discover_row <?php echo ((CONFIG_MODE == 1 || !ENABLE_DISCOVER) ? "force_hide" : "") ?>">
                                <td colspan="5" align="left">
                                   <table id="deltacast_discover_results" border="0" class="gridded_table" style="width: 80vw; margin-top: 10px">
                                        <tr class="gridded_table_section_header">
                                            <th class="program_info" colspan="6">Program</th>
                                        </tr>
                                        <tr class="gridded_table_header">
                                            <th class="program_info" style="width: 150px">Resolution <input id="sdi_input_height" name="sdi_input_height" type="hidden"><input id="sdi_input_width" name="sdi_input_width" type="hidden"></th>
                                            <th class="program_info" style="width: 50px">Interlaced?</th>
                                            <th class="program_info field_order_header" style="width: 50px">Field Order</th>
                                            <th class="program_info" style="width: 65px">HD?</th>
                                            <th class="program_info" style="width: 50px">Framerate</th>
                                            <th class="program_info" style="width: 250px">Audio Streams</th>
                                            <!--<th class="program_info" style="width: 70px">Type</th>
                                            <th class="program_info">Description</th>
                                            <th style="width: 60px"></th>-->
                                        </tr>
                                        <tr class="deltacast_discover_program_proto force_hide">
                                            <td class="program_info source_identity" style="text-align:center;"></td>
                                            <td class="program_info program_number" style="text-align:center;"></td>
                                            <td colspan="1" class="program_info streams field_order" style="padding:0px; text-align:center;"></td>
                                            <td class="program_info program_pmt_pid" style="text-align:center;"></td>
                                            <td colspan="1" class="program_info streams stream_pid" style="text-align:center;"></td>
                                            <td colspan="1" class="program_info streams" id="audio_channels" style="padding:0px; text-align:center;"></td>
                                            <!--
                                            <td><button class="program_select_btn">Select</button></td>-->
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                            <tr style="height: 15px" class="ip_input_row"></tr>
                            <tr name="sdp_address_row" id="sdp_address_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="rtp_input_row">
                                <td>SDP Server Address</td>
                                <td>:</td>
                                <td colspan="3"><input name="sdp_address" class="entry_box" style="width:130px" id="sdp_address" type="text"></td>
                            </tr>
                            <tr name="sdp_filename_row" id="sdp_filename_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="rtp_input_row">
                                <td>SDP Filename</td>
                                <td>:</td>
                                <td colspan="3"><input name="sdp_filename" class="entry_box" style="width:130px" id="sdp_filename" type="text"></td>
                            </tr>
                            <tr name="enable_rtcp_row" id="enable_rtcp_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="rtp_input_row">
                                <td>Enable RTCP</td>
                                <td>:</td>
                                <td colspan="3"><input name="enable_rtcp" id="enable_rtcp" type='checkbox' style='vertical-align:-2px' onclick='rtcp_checkbox_clicked'></td>
                            </tr>
                          <tr style="height: 15px" class="rtp_input_row"></tr>
                          <tr id="hd_sdi_row" class="video_setting_row hd_sdi_setting_row">
                                <td id="sdi_input_mode_label">HD-SDI input mode</td>
                                <td>:</td>
                                <td colspan="7">
                                    <select name="sdi_input_mode" id="sdi_input_mode" onchange="sdi_input_mode_changed(this)">
                                        <option value="0">NTSC 29.97</option>
                                        <option value="1">NTSC 23.98</option>
                                        <option value="2">PAL</option>
                                        <option value="3">HD 1080p 23.98</option>
                                        <option value="4">HD 1080p 24</option>
                                        <option value="5">HD 1080p 25</option>
                                        <option value="6">HD 1080p 29.97</option>
                                        <option value="7">HD 1080p 30</option>
                                        <option value="8">HD 1080i 25</option>
                                        <option value="9">HD 1080i 29.97</option>
                                        <option value="10">HD 1080i 30</option>
                                        <option value="11">HD 720p 50</option>
                                        <option value="12">HD 720p 59.94</option>
                                        <option value="13">HD 720p 60</option>
                                        <?php if (SDI_PROVIDER != "BLACKMAGIC") { ?>
                                        <option value="14">HD 1080p 23.98 (PsF)</option>
                                        <option value="15">HD 1080p 24 (PsF)</option>
                                        <option value="16">HD 1080p 25 (PsF)</option>
                                        <option value="17">HD 1080p 29.97 (PsF)</option>
                                        <option value="18">HD 1080p 30 (PsF)</option>
                                        <option value="19">HD 720p 50 (PsF)</option>
                                        <option value="20">HD 720p 59.94 (PsF)</option>
                                        <option value="21">HD 720p 60 (PsF)</option>
                                        <?php } ?>
                                        <?php if (ENABLE_4K_INPUT) { ?>
                                        <option value="22">UltraHD 23.98</option>
                                        <option value="23">UltraHD  24</option>
                                        <option value="24">UltraHD  25</option>
                                        <option value="25">UltraHD  29.97</option>
                                        <option value="26">UltraHD  30</option>
                                        <option value="27">UltraHD  50</option>
                                        <option value="28">UltraHD  59.94</option>
                                        <option value="29">UltraHD  60</option>
                                        <option value="30">4K  23.98</option>
                                        <option value="31">4K  24</option>
                                        <option value="32">4K  25</option>
                                        <option value="33">4K 29.97</option>
                                        <option value="34">4K 30</option>
                                        <option value="35">4K 50</option>
                                        <option value="36">4K 59.94</option>
                                        <option value="37">4K 60</option>
                                        <?php } ?>
                                    </select>
                                    <button id="sdi_discover_button" class="discover_button <?php echo ((CONFIG_MODE == 1 || SDI_PROVIDER != "BLACKMAGIC") ? "force_hide" : "") ?>">Discover</button>
                                    <span id="sdi_discover_throbber" class="discover_throbber" style="display:none"><img style="vertical-align:middle" src="images/loading-small.gif"></img> Scanning input...</span>
                                </td>
                            </tr>
                            <tbody style="display:none">
                            <tr name="enable_sdi_repeat_row" id="enable_sdi_repeat_row" class="video_setting_row hd_sdi_setting_row">
                                <td>Repeat last frame when signal is missing</td>
                                <td>:</td>
                                <td colspan="3"><input name="enable_sdi_repeat" id="enable_sdi_repeat" type='checkbox' style='vertical-align:-2px'></td>
                            </tr>
                            <tr name="sdi_frame_timeout_row" id="sdi_frame_timeout_row" class="video_setting_row hd_sdi_setting_row">
                                <td>Frame repeat timeout</td>
                                <td>:</td>
                                <td colspan="3">
                                <input name="sdi_frame_timeout" class="dim_entry integer_field" id="sdi_frame_timeout" type="text"> frames <span class="muted">(0 = no timeout)</span>
                                </td>
                            </tr>
                            <tr name="enable_genlock_row" id="enable_genlock_row" class="video_setting_row hd_sdi_setting_row">
                                <td>Genlock source</td>
                                <td>:</td>
                                <td colspan="3">
                                    <select name="enable_genlock" id="enable_genlock">
                                        <option value="0">None</option>
                                        <option value="1">Incoming Signal</option>
                                        <option value="2">Black Burst</option>
                                    </select>
                                </td>
                            </tr>
                            </tbody>
                            <tr name="sdi_cc_data_rate_row" id="sdi_frame_timeout_row" class="video_setting_row hd_sdi_setting_row sd_sdi_setting_row">
                                <td>Line 21 CC data rate</td>
                                <td>:</td>
                                <td colspan="3">
                                <input name="sdi_cc_data_rate" class="dim_entry integer_field" id="sdi_cc_data_rate" type="text"> Hz
                                </td>
                            </tr>
                            <tr style="height: 15px" class="hd_sdi_setting_row"></tr>
                            <tr id="hdmi_input_mode_row" class="video_setting_row hdmi_setting_row">
                                <td>HDMI input mode</td>
                                <td>:</td>
                                <td colspan="7">
                                    <select name="hdmi_input_mode" id="hdmi_input_mode" onchange="hdmi_input_mode_changed(this)">
                                        <option value="0">NTSC 29.97</option>
                                        <option value="1">NTSC 23.98</option>
                                        <option value="2">PAL</option>
                                        <option value="3">NTSCp</option>
                                        <option value="4">PALp</option>
                                        <option value="5">HD 1080p 23.98</option>
                                        <option value="6">HD 1080p 24</option>
                                        <option value="7">HD 1080p 25</option>
                                        <option value="8">HD 1080p 29.97</option>
                                        <option value="9">HD 1080p 30</option>
                                        <option value="10">HD 1080i 25</option>
                                        <option value="11">HD 1080i 29.97</option>
                                        <option value="12">HD 1080i 30</option>
                                        <option value="13">HD 720p 50</option>
                                        <option value="14">HD 720p 59.94</option>
                                        <option value="15">HD 720p 60</option>
                                    </select>
                                    <button id="hdmi_discover_button" class="discover_button <?php echo ((CONFIG_MODE == 1 || HDMI_PROVIDER != "BLACKMAGIC") ? "force_hide" : "") ?>">Discover</button>
                                    <span id="hdmi_discover_throbber" class="discover_throbber" style="display:none"><img style="vertical-align:middle" src="images/loading-small.gif"></img> Scanning input...</span>
                                </td>
                            </tr>
                            <tr style="height: 15px" class="hdmi_setting_row"></tr>
                            <tr id="input_row_0" class="video_setting_row">
                                <td>Input resolution preset</td>
                                <td>:</td>
                                <td colspan="7" align="left">
                                     <select name="input_resolution" id="input_resolution" onchange="input_resolution_changed(this)">
<?php
if (ENABLE_HD_INPUT == 1 || ENABLE_4K_INPUT == 1) {
    if(ENABLE_4K_INPUT == 1 ) {
                                     echo "<option value=\"4K\">4K (4096x2160)</option>\n";
                                     echo "<option value=\"UltraHD\">UltraHD (3840x2160)</option>\n";
    }
                                     echo "<option value=\"HD1080\">HD (1920x1080)</option>\n";
                                     echo "<option value=\"HD720\">HD (1280x720)</option>\n";
                                     echo "<option value=\"PAL\">PAL (704x576)</option>\n";
                                     echo "<option value=\"PAL720\">PAL (720x576)</option>\n";
                                     echo "<option value=\"NTSC\">NTSC (704x480)</option>\n";
                                     echo "<option value=\"NTSC720\">NTSC (720x480)</option>\n";
                                     echo "<option value=\"VGA\">VGA (640x480)</option>\n";
                                     echo "<option value=\"USER\">User Override</option>\n";
} else {
                                     echo "<option value=\"PAL\">PAL (704x576)</option>\n";
                                     echo "<option value=\"PAL720\">PAL (720x576)</option>\n";
                                     echo "<option value=\"NTSC\">NTSC (704x480)</option>\n";
                                     echo "<option value=\"VGA\">VGA (640x480)</option>\n";
                                     echo "<option value=\"USER\">User Override</option>\n";
}
?>
                                     </select>
                                </td>
                            </tr>
                            <tr id="input_row_1" class="video_setting_row">
                                <td>Input resolution override</td>
                                <td>:</td>
                                <td colspan="7">
                                    <input name="input_width" class="dim_entry integer_field" id="input_width" type="text">
                                    x
                                    <input name="input_height" class="dim_entry integer_field" id="input_height" type="text">
                                </td>
                            </tr>
                            <tr id="input_row_2" class="video_setting_row">
                                <td>Input format</td>
                                <td>:</td>
                                <td colspan="7" align="left">
                                     <select name="input_format" id="input_format" onChange="$('.baseband_setting_row').toggle(parseInt(this.value)==1)">
                                         <option value="0">Progressive</option>
                                         <option value="1">Interlaced</option>
                                     </select>
                                </td>
                            </tr>
                            <tr name="bottom_field_first_row" id="bottom_field_first_row" class="video_setting_row baseband_setting_row">
                                <td>Field order</td>
                                <td>:</td>
                                <td colspan="7">
                                    <select name="bottom_field_first" id="bottom_field_first">
                                        <option value="0">Top Field First</option>
                                        <option value="1">Bottom Field First</option>
                                    </select>
                                </td>
                            </tr>
                            <tr id="input_row_3" class="video_setting_row">
                                <td>Input framerate</td>
                                <td>:</td>
                                <td colspan="7">
                                     <select name="input_framerate" id="input_framerate">
                                         <option value="15">15</option>
                                         <option value="23.98">23.98</option>
                                         <option value="24">24</option>
                                         <option value="25">25</option>
                                         <option value="29.97">29.97</option>
                                         <option value="30">30</option>
<?php
if (ENABLE_HD_INPUT == 1 || ENABLE_4K_INPUT == 1) {
                                         echo "<option value=\"50\">50</option>\n";
                                         echo "<option value=\"59.94\">59.94</option>\n";
                                         echo "<option value=\"60\">60</option>\n";
}
?>
                                     </select>
                                     <select name="enable_psf" id="enable_psf" style="visibility:hidden;">
                                         <option value="0">0</option>
                                         <option value="1">1</option>
                                     </select>
                                </td>
                            </tr>
                            <tr id="input_stream_row" class="mpts_input_row">
                                <td><?php echo ((CONFIG_MODE == 1) ? "Input program number" : "Input program index") ?></td>
                                <td>:</td>
                                <td colspan="7">
                                    <span id="input_number_label" class="force_hide">Program Number</span>
                                     <select name="input_stream" id="input_stream">
                                         <?php if (CONFIG_MODE != 1) { ?>
                                         <option value="NUMBER">Enter Program Number</option>
                                         <?php } ?>
                                         <option value="SPTS">SPTS</option>
                                         <option value="MPTS0">MPTS Prog-0</option>
                                         <option value="MPTS1">MPTS Prog-1</option>
                                         <option value="MPTS2">MPTS Prog-2</option>
                                         <option value="MPTS3">MPTS Prog-3</option>
                                         <option value="MPTS4">MPTS Prog-4</option>
                                         <option value="MPTS5">MPTS Prog-5</option>
                                         <option value="MPTS6">MPTS Prog-6</option>
                                         <option value="MPTS7">MPTS Prog-7</option>
                                         <option value="MPTS8">MPTS Prog-8</option>
                                         <option value="MPTS9">MPTS Prog-9</option>
                                         <option value="MPTS10">MPTS Prog-10</option>
                                         <option value="MPTS11">MPTS Prog-11</option>
                                         <option value="MPTS12">MPTS Prog-12</option>
                                         <option value="MPTS13">MPTS Prog-13</option>
                                         <option value="MPTS14">MPTS Prog-14</option>
                                         <option value="MPTS15">MPTS Prog-15</option>
                                         <option value="MPTS16">MPTS Prog-16</option>
                                         <option value="MPTS17">MPTS Prog-17</option>
                                         <option value="MPTS18">MPTS Prog-18</option>
                                         <option value="MPTS19">MPTS Prog-19</option>
                                         <option value="MPTS20">MPTS Prog-20</option>
                                         <option value="MPTS21">MPTS Prog-21</option>
                                         <option value="MPTS22">MPTS Prog-22</option>
                                         <option value="MPTS23">MPTS Prog-23</option>
                                         <option value="MPTS24">MPTS Prog-24</option>
                                         <option value="MPTS25">MPTS Prog-25</option>
                                         <option value="MPTS26">MPTS Prog-26</option>
                                         <option value="MPTS27">MPTS Prog-27</option>
                                         <option value="MPTS28">MPTS Prog-28</option>
                                         <option value="MPTS29">MPTS Prog-29</option>
                                         <option value="MPTS30">MPTS Prog-30</option>
                                         <option value="MPTS31">MPTS Prog-31</option>
                                         <option value="MPTS32">MPTS Prog-32</option>
                                         <option value="MPTS33">MPTS Prog-33</option>
                                         <option value="MPTS34">MPTS Prog-34</option>
                                         <option value="MPTS35">MPTS Prog-35</option>
                                         <option value="MPTS36">MPTS Prog-36</option>
                                         <option value="MPTS37">MPTS Prog-37</option>
                                         <option value="MPTS38">MPTS Prog-38</option>
                                         <option value="MPTS39">MPTS Prog-39</option>
                                         <option value="MPTS40">MPTS Prog-40</option>
                                         <option value="MPTS41">MPTS Prog-41</option>
                                         <option value="MPTS42">MPTS Prog-42</option>
                                         <option value="MPTS43">MPTS Prog-43</option>
                                         <option value="MPTS44">MPTS Prog-44</option>
                                         <option value="MPTS45">MPTS Prog-45</option>
                                         <option value="MPTS46">MPTS Prog-46</option>
                                         <option value="MPTS47">MPTS Prog-47</option>
                                         <option value="MPTS48">MPTS Prog-48</option>
                                         <option value="MPTS49">MPTS Prog-49</option>
                                         <option value="MPTS50">MPTS Prog-50</option>
                                         <option value="MPTS51">MPTS Prog-51</option>
                                         <option value="MPTS52">MPTS Prog-52</option>
                                         <option value="MPTS53">MPTS Prog-53</option>
                                         <option value="MPTS54">MPTS Prog-54</option>
                                         <option value="MPTS55">MPTS Prog-55</option>
                                         <option value="MPTS56">MPTS Prog-56</option>
                                         <option value="MPTS57">MPTS Prog-57</option>
                                         <option value="MPTS58">MPTS Prog-58</option>
                                         <option value="MPTS59">MPTS Prog-59</option>
                                         <option value="MPTS60">MPTS Prog-60</option>
                                         <option value="MPTS61">MPTS Prog-61</option>
                                         <option value="MPTS62">MPTS Prog-62</option>
                                         <option value="MPTS63">MPTS Prog-63</option>
                                         <option value="MPTS64">MPTS Prog-64</option>
                                         <option value="MPTS65">MPTS Prog-65</option>
                                         <option value="MPTS66">MPTS Prog-66</option>
                                         <option value="MPTS67">MPTS Prog-67</option>
                                         <option value="MPTS68">MPTS Prog-68</option>
                                         <option value="MPTS69">MPTS Prog-69</option>
                                         <option value="MPTS70">MPTS Prog-70</option>
                                         <option value="MPTS71">MPTS Prog-71</option>
                                         <option value="MPTS72">MPTS Prog-72</option>
                                         <option value="MPTS73">MPTS Prog-73</option>
                                         <option value="MPTS74">MPTS Prog-74</option>
                                         <option value="MPTS75">MPTS Prog-75</option>
                                         <option value="MPTS76">MPTS Prog-76</option>
                                         <option value="MPTS77">MPTS Prog-77</option>
                                         <option value="MPTS78">MPTS Prog-78</option>
                                         <option value="MPTS79">MPTS Prog-79</option>
                                         <option value="MPTS80">MPTS Prog-80</option>
                                         <option value="MPTS81">MPTS Prog-81</option>
                                         <option value="MPTS82">MPTS Prog-82</option>
                                         <option value="MPTS83">MPTS Prog-83</option>
                                         <option value="MPTS84">MPTS Prog-84</option>
                                         <option value="MPTS85">MPTS Prog-85</option>
                                         <option value="MPTS86">MPTS Prog-86</option>
                                         <option value="MPTS87">MPTS Prog-87</option>
                                         <option value="MPTS88">MPTS Prog-88</option>
                                         <option value="MPTS89">MPTS Prog-89</option>
                                         <option value="MPTS90">MPTS Prog-90</option>
                                         <option value="MPTS91">MPTS Prog-91</option>
                                         <option value="MPTS92">MPTS Prog-92</option>
                                         <option value="MPTS93">MPTS Prog-93</option>
                                         <option value="MPTS94">MPTS Prog-94</option>
                                         <option value="MPTS95">MPTS Prog-95</option>
                                         <option value="MPTS96">MPTS Prog-96</option>
                                         <option value="MPTS97">MPTS Prog-97</option>
                                         <option value="MPTS98">MPTS Prog-98</option>
                                         <option value="MPTS99">MPTS Prog-99</option>
                                     </select>
                                    <input name="input_program_number" class="dim_entry integer_field" id="input_program_number" type="text" <?php echo ((CONFIG_MODE == 1) ? "style='display:none;'" : "style='margin-left: 3px'") ?>>
                                </td>
                            </tr>
                            <?php if (ENABLE_DVB_SUBTITLES == 1) { ?>
                            <tr id="enable_dvb_subtitles" class="ip_input_row dvbasi_input_row">
                                <td style="vertical-align: top; padding-top: 6px;">Input subtitles</td>
                                <td style="vertical-align: top; padding-top: 6px;">:</td>
                                <td colspan="7" align="left" style="vertical-align: top; padding-top: 2px;">
                                    <div style="line-height: 26px">
                                        <label><input id="input_subtitle_mode0" name="input_subtitle_mode" value="0" type="radio" class="input_subtitle_mode" style="vertical-align:-2px" onclick="subtitle_mode_selected(0)" checked>Off</label>
                                    </div>
                                    <div style="line-height: 26px">
                                        <label><input id="input_subtitle_mode3" name="input_subtitle_mode" value="3" type="radio" class="input_subtitle_mode" style="vertical-align:-2px" onclick="subtitle_mode_selected(3)" checked>Passthrough</label>
                                    </div>
                                    <div style="line-height: 26px">
                                        <label style="display: inline-block; width: 125px"><input id="input_subtitle_mode1" name="input_subtitle_mode" value="1" type="radio" class="input_subtitle_mode" style="vertical-align:-2px" onclick="subtitle_mode_selected(1)">Language List</label>
                                        <select id="input_subtitle_pid" name="input_subtitle_pid" disabled>
                                            <option value="-1" selected>None</option>
                                        </select>
                                    </div>
                                    <div style="line-height: 26px">
                                        <label style="display: inline-block; width: 125px"><input id="input_subtitle_mode2" name="input_subtitle_mode" value="2" type="radio" class="input_subtitle_mode" style="vertical-align:-2px" onclick="subtitle_mode_selected(2)">PMT Order</label>
                                        <select id="input_subtitle_order" name="input_subtitle_order" disabled>
                                            <option value="0" selected>First</option>
                                            <option value="1">Second</option>
                                            <option value="2">Third</option>
                                            <option value="3">Fourth</option>
                                            <option value="4">Fifth</option>
                                            <option value="5">Sixth</option>
                                            <option value="6">Seventh</option>
                                            <option value="7">Eighth</option>
                                        </select>
                                    </div>
                                    <div style="line-height: 26px">
                                        <label style="display: inline-block; width: 125px">Subtitle Delay</label>
                                        <select id="input_subtitle_delay" name="input_subtitle_delay">
                                            <option value="180">Low (1-2s)</option>
                                            <option value="240">Medium (3-4s)</option>
                                            <option value="320">High (5-6s)</option>
                                            <option value="480">Very High (7-8s)</option>
                                        </select>
                                    </div>
                                    <div style="line-height: 26px">
                                        <label style="display: inline-block; width: 125px">Drop Subtitle If Late</label>
                                        <select id="input_subtitle_late" name="input_subtitle_late">
                                            <option value="0">Off</option>
                                            <option value="15">15 frames</option>
                                            <option value="30">30 frames</option>
                                            <option value="45">45 frames</option>
                                            <option value="60">60 frames</option>
                                            <option value="75">75 frames</option>
                                            <option value="90">90 frames</option>
                                            <option value="105">105 frames</option>
                                            <option value="120">120 frames</option>
                                        </select>
                                    </div>
                                </td>
                            </tr>
                            <?php } ?>
                            <tr style="height: 15px"></tr>
                            <tr id="fec_on_input_row">
                                <td>FEC on input</td>
                                <td>:</td>
                                <td colspan="2" align="left">
                                     <select name="receive_fec" id="receive_fec">
                                     <option value="1">On</option>
                                     <option value="0">Off</option>
                                     </select>
                                </td>
                            </tr>
                           <tr style="height: 15px"></tr>
                            <tr name="prefilter_contrast_row" id="prefilter_contrast_row" class="video_setting_row" style="visibility:hidden">
                            <td>Contrast</td>
                                <td>:</td>
                                <td colspan="3">
                                <input name="prefilter_contrast" class="dim_entry integer_field" id="prefilter_contrast" type="text"> <span class="muted">(0 - 255) default = 0</span>
                                </td>
                            </tr>
                            <tr name="prefilter_brightness_row" id="prefilter_brightness_row" class="video_setting_row" style="visibility:hidden">
                                <td>Brightness</td>
                                <td>:</td>
                                <td colspan="3">
                                <input name="prefilter_brightness" class="dim_entry integer_field" id="prefilter_brightness" type="text"> <span class="muted">(0 - 16) default = 0</span>
                                </td>
                            </tr>
                            <tr style="height: 15px"></tr>

                            <tr id="input_stream_row">
                                <td>Input cropping</td>
                                <td>:</td>
                                <td >
                                    <label><input id='enable_crop' type='checkbox' style='vertical-align:-2px'>Enable</label>
                                </td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td colspan="3">
                                    <table>
                                        <tr><td style="text-align: center">
                                            <div style="text-align: center">
                                                <div>Top</div>
                                                <input id="crop_top" name="crop_top" class="dim_entry integer_field" style="text-align: center" type="text">
                                            </div>
                                        </td></tr>
                                        <tr><td style="text-align: center">
                                            <div style="float: left; padding-top: 23px; padding-right: 6px">
                                                <div style="text-align: center">Left</div>
                                                <input id="crop_left" name="crop_left" class="dim_entry integer_field" style="text-align: center" type="text">
                                            </div>
                                            <div class="box" style="float: left"></div>
                                            <div style="float: left; padding-top: 23px; padding-left: 6px">
                                                <div style="text-align: center">Right</div>
                                                <input id="crop_right" name="crop_right" class="dim_entry integer_field" style="text-align: center" type="text">
                                            </div>
                                            <div style="clear: both; text-align: center"></div>
                                        </td></tr>
                                        <tr><td style="text-align: center">
                                            <input id="crop_bottom" name="crop_bottom" class="dim_entry integer_field" style="text-align: center" type="text">
                                            <div>Bottom</div>
                                        </td></tr>
                                    </table>
                                <td>
                            </tr>
                        </table>
                    </div>

                    <div id="output-options" class="option-tab-content master-tab" style="display:none">
                        <table border="0" cellpadding="0" cellspacing="0" class="settings">
                        <?php settingWriteOutputInterfaces(); ?>

                        <tr style="height: 15px" id="audio_only_output_warning" style="display:none; color:black;">
                            <td></td>
                            <td>:</td>
                            <td colspan="8">
                            Note: Some output interfaces are disabled due to &quot;audio only&quot; enabled on input.
                            </td>
                        </tr>

                        <div id="video-options" style="font-size:12px">
                            <tr style="height: 15px"></tr>
                            <tr id="output_video_encoder_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : ""; ?> class="video_setting_row">
                                <td>Output video encoder</td>
                                <td>:</td>
                                <td>
                                    <select name="output_encoder" id="output_encoder" onchange="video_encoder_changed(this)">
                                    </select>
                                </td>
                            </tr>
                           <tr id="cpb_delay_row" <?php echo (ENABLE_SOCIO == 0) ? "style='display:none;'" : ""; ?> class="video_setting_row">
                                <td>CPB Delay</td>
                                <td>:</td>
                                <td>
                                     <select id="cpb_delay" name="cpb_delay">
                                         <option value="100">100 ms</option>
                                         <option value="200">200 ms</option>
                                         <option value="500">500 ms</option>
                                         <option value="800">800 ms</option>
                                         <option value="900">900 ms</option>
                                         <option value="1000">1.0 sec</option>
                                         <option value="1500">1.5 sec</option>
                                         <option value="2000">2.0 sec</option>
                                         <!--
                                         <option value="2500">2.5 sec</option>
                                         <option value="3000">3.0 sec</option>
                                         -->
                                     </select>
                                </td>
                            </tr>
                            <tr id="enable_gpu_row" <?php echo (ENABLE_MEDIASDK != 1 || CONFIG_MODE == 1) ? "style='display:none;'" : ""; ?> class="video_setting_row">
                                <td>Enable GPU</td>
                                <td>:</td>
                                <td>
                                    <input name="enable_gpu" id="enable_gpu" type="checkbox" />
                                </td>
                            </tr>
                            <tr id="h264_profile_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="video_setting_row">
                                <td>H.264 Profile</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                    <select name="h264_profile" id="h264_profile" onchange="h264_profile_changed(this);">
                                        <option value="66">BASELINE</option>
                                        <option value="77">MAIN</option>
                                        <option value="100">HIGH</option>
                                    </select>
                                </td>
                            </tr>
                            <tr id="h264_constraint_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="video_setting_row">
                                <td>H.264 encoder buffer constraint</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                    <select name="buffer_constraint" id="buffer_constraint">
                                        <option value="100">100 ms</option>
                                        <option value="250">250 ms</option>
                                        <option value="500">500 ms</option>
                                        <option value="1000">1000 ms</option>
                                        <option value="1500">1500 ms</option>
                                        <option value="2000">2000 ms</option>
                                    </select>
                                </td>
                            </tr>
                            <?php if (ENABLE_PYRAMID_B == 1) { ?>
                            <tr id="h264_pyramid_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="video_setting_row">
                                <td>Pyramidal B-Frames</td>
                                <td>:</td>
                                <td>
                                    <select name="pyramid_b" id="pyramid_b">
                                    <option value="0">Disabled</option>
                                    <option value="1">Enabled</option>
                                    </select>
                                </td>
                            </tr>
                            <?php } ?>
                            <tr style="display:none" class="video_setting_row">
                                <td>H.264 encoder quality</td>
                                <td>:</td>
                                <td>
                                     <select name="h264_encoder_quality" id="h264_encoder_quality">
                                     <option value="1">1</option>
                                     <option value="2">2</option>
                                     <option value="3">3</option>
                                     <option value="4">4</option>
                                     <option value="5">5</option>
                                     <option value="6">6</option>
                                     <option value="7">7</option>
                                     <option value="8">8</option>
                                     <option value="9">9</option>
                                     <option value="10">10</option>
                                     <option value="11">11</option>
                                     <option value="12">12</option>
                                     <option value="13">13</option>
                                     <option value="14">14</option>
                                     <option value="15">15</option>
                                     <option value="16">16</option>
                                     <option value="17">17</option>
                                     </select>
                                </td>
                            </tr>
<!--
-->
                            <tr id="i_p_frame_distance_row" class="video_setting_row hideforhdsdi">
                                <td>I/P Frame Distance</td>
                                <td>:</td>
                                <td><input name="I_P_frame_distance" class="dim_entry integer_field" id="I_P_frame_distance" type="text" style="text-align:left"></td>
                            </tr>
                            <tr id="gop_length_row" class="video_setting_row hideforhdsdi">
                                <td>GOP Length (seconds)</td>
                                <td>:</td>
                                <td><input name="GOP_length_seconds" class="dim_entry decimal_field" id="GOP_length_seconds" type="text" style="text-align:left"></td>
                            </tr>
                            <tr id="output_video_format_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="video_setting_row">
                                <td>Output Video Format</td>
                                <td>:</td>
                                <td>
                                     <select id="output_format" name="output_format">
                                         <option value="2">Same as input</option>
                                         <option value="0" <?php echo (CONFIG_MODE == 1) ? "selected" : "" ?>>Progressive</option>
                                         <option value="1">Interlaced</option>
                                     </select>
                                </td>
                            </tr>
                            <tr class="video_setting_row">
                                <td>Output Video Aspect Ratio</td>
                                <td>:</td>
                                <td>
                                     <select name="aspect_ratio" id="aspect_ratio">
                                         <option value="0">Passthrough</option>
                                         <option value="1">Force 4:3</option>
                                         <option value="2">Force 16:9</option>
                                     </select>
                                </td>
                            </tr>
                       <div id="biss-options" style="font-size:12px; <?php if(!BISS_ENABLED){echo "display:none";}?>">
                                <tr class="output_encrypt_mode_row" style=" <?php if(!BISS_ENABLED){echo "display:none";}?>">
                                    <td class="setting_label">BISS Mode</td>
                                    <td class="setting_spacer">:</td>
                                    <td>
                                        <select name="biss_mode" id="biss_mode" class="entry_box scrambled biss" style="width:150px" onchange="updateBiss(0)">
                                        <option value="0">Disabled</option>
                                        <option value="1">Encrypt - BISS1-1</option>
                                        <option value="2">Encrypt - BISS1-E</option>
                                        <option value="3">Encrypt - BISS2-1</option>
                                        <option value="4">Encrypt - BISS2-E</option>
                                        </select>
                                    </td>
                               </tr>
                               <tr class="input_decrypt_mode_row bissopts" style=" <?php if(!BISS_ENABLED){echo "display:none";}?>">
                                    <td class="setting_label">BISS Key</td>
                                    <td class="setting_spacer">:</td>
                                    <td>
                                        <input name="biss_key" id="biss_key" class="entry_box biss_key" style="width:145px" type="text">
                                    </td>
                                </tr>
                                 <tr class="input_decrypt_mode_row bissopts bisse" style=" <?php if(!BISS_ENABLED){echo "display:none";}?>">
                                    <td class="setting_label">BISS-E Session Key</td>
                                    <td class="setting_spacer">:</td>
                                    <td>
                                        <input name="biss_session_key" id="biss_session_key" class="entry_box biss_key" style="width:145px" type="text">
                                    </td>
                                </tr>
                       </div>

                            <?php if (ENABLE_QUALITY_LEVEL) { ?>
                            <tr class="video_setting_row">
                                <td><?=!strcasecmp(VENDOR,"ccur")||!strcasecmp(VENDOR,"ccur")?"VQX":"Output quality"?></td>
                                <td>:</td>
                                <td>
                                     <select name="quality_level" id="quality_level">
                                    <?php if (0 == strcasecmp(VENDOR, "edbox")) { ?>
                                         <option value="5">Low</option>
                                         <option value="10">Medium</option>
                                         <option value="20">High</option>
                                    <?php } else if (0 == strcasecmp(VENDOR, "india2")) { ?>
                                         <option value="5">Super Low</option>
                                         <option value="10">Low</option>
                                         <option value="20">Medium</option>
                                         <option value="30">High</option>
                                         <option value="35">Super High</option>
                                    <?php } else { ?>
                                         <option value="3" id="extremelowoption" style="display:none">Extreme Low</option>
                                         <option value="5">Super Low</option>
                                         <option value="10">Low</option>
                                         <option value="20">Medium</option>
                                         <option value="30">High</option>
                                         <option value="35">Super High</option>
                                         <option value="36">Extreme</option>
                                    <?php } ?>
                                     </select>
                                </td>
                            </tr>
                            <?php } ?>
                            <tr class="hideforhdsdi">
                                <td>Transport Layer Buffer Delay</td>
                                <td width="15px">:</td>
                                <td colspan="4" align="left">
                                    <select name="buffer_delay" id="buffer_delay">
                                        <option value="250">250ms</option>
                                        <option value="500">500ms</option>
                                        <option value="1000">1.0s</option>
                                        <option value="1500">1.5s</option>
                                        <option value="2000">2.0s</option>
                                        <option value="2500">2.5s</option>
                                    </select>
                                </td>
                            </tr>
                            <tr id="enable_cc_row" class="video_setting_row hideforhdsdi">
                                <td>Closed Captioning</td>
                                <td>:</td>
                                <td colspan="2" align="left">
                                     <select name="enable_cc" id="enable_cc">
                                     <option value="1">On</option>
                                     <option value="0">Off</option>
                                     </select>
                                </td>
                            </tr>
                            <tr id="enable_afd_row" class="video_setting_row hideforhdsdi">
                                <td>Active Format Descriptor</td>
                                <td>:</td>
                                <td colspan="2" align="left">
                                     <select name="enable_afd" id="enable_afd">
                                     <option value="1">On</option>
                                     <option value="0">Off</option>
                                     </select>
                                </td>
                            </tr>
                            <tr id="ac3dec_compmod_row" class="hideforhdsdi">
                                <td>AC3 DRC mode</td>
                                <td>:</td>
                                <td colspan="2" align="left">
                                     <select name="ac3dec_compmod" id="ac3dec_compmod">
                                     <option value="0">Custom A (default)</option>
                                     <option value="1">Custom D</option>
                                     <option value="2">Line</option>
                                     <option value="3">RF</option>
                                     </select>
                                </td>
                            </tr>

                            <tr id="temporal_filter_strength_mode" class="video_setting_row hideforhdsdi">
                                <td>Temporal Filter Strength</td>
                                <td>:</td>
                                <td>
                                     <select name="temporal_filter_strength" id="temporal_filter_strength">
                                         <option value="0">0</option>
                                         <option value="1">1</option>
                                         <option value="2">2</option>
                                         <option value="3">3</option>
                                         <option value="4">4</option>
                                         <option value="5">5</option>
                                     </select>
                                </td>
                            </tr>
                            <tr id="diagonal_smoothing_filter_mode" class="video_setting_row hideforhdsdi">
                                <td>Diagonal Smoothing Filter</td>
                                <td>:</td>
                                <td>
                                     <select name="diagonal_smoothing_filter" id="diagonal_smoothing_filter">
                                         <option value="0">Off</option>
                                         <option value="1">On</option>
                                     </select>
                                </td>
                            </tr>
                            <tr id="low_video_frame_rate_mode" class="video_setting_row hideforhdsdi">
                                <td>Low Video Frame Rate Mode</td>
                                <td>:</td>
                                <td>
                                     <select name="galaxie_mode" id="galaxie_mode">
                                         <option value="0">Off</option>
                                         <option value="1">On</option>
                                     </select>
                                </td>
                            </tr>
                            <tr id="scene_detection_mode" class="video_setting_row">
                                <td>Scene Detection</td>
                                <td>:</td>
                                <td>
                                     <select name="enable_scene_detection" id="enable_scene_detection">
                                         <option value="0">Off</option>
                                         <option value="1">On</option>
                                     </select>
                                </td>
                            </tr>

                            <tr id="output_color_range_row">
                                <td>Output Color Range</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                    <select id="output_color_range" name="output_color_range">
                                        <option value="auto" selected>AUTO</option>
<!--                                        <option value="limited">LIMITED</option>
                                        <option value="full">FULL</option>
-->
                                    </select>
                                </td>
                            </tr>

                            <tr id="output_color_primaries_row">
                                <td>Output Color Primaries</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                    <select id="output_color_primaries" name="output_color_primaries">
                                        <option value="auto" selected>AUTO</option>
<!--
                                        <option value="unspecified">UNSPECIFIED</option>
                                        <option value="bt709">BT709</option>
                                        <option value="bt470bg">BT470BG</option>
                                        <option value="smpte170m">SMPTE170M</option>
                                        <option value="smpte240m">SMPTE240M</option>
                                        <option value="bt2020">BT2020</option>
                                        <option value="film">FILM</option>->
                                        <option value="bt470m">BT470M</option>
                                        <option value="smpte428">SMPTE428</option>
                                        <option value="smpte431">SMPTE431</option>
                                        <option value="smpte432">SMPTE432</option>
                                        <option value="jedecp22">JEDEC P22</option>
-->
                                    </select>
                                </td>
                            </tr>

                            <tr id="output_color_trc_row">
                                <td>Output Color Transfer Characteristics</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                    <select id="output_color_trc" name="output_color_trc">
                                        <option value="auto" selected>AUTO</option>
<!--
                                        <option value="unspecified">UNSPECIFIED</option>
                                        <option value="bt709">BT709</option>
                                        <option value="bt601">BT601</option>
                                        <option value="smpte170m">SMPTE170M</option>
                                        <option value="smpte240m">SMPTE240M</option>
                                        <option value="smpte2084">SMPTE ST 2084 </option>
                                        <option value="bt2020_10">BT2020 10-bit</option>
                                        <option value="gama22">GAMMA22</option>
                                        <option value="gama28">GAMMA28</option>
                                        <option value="iec61966_2_1">IEC 61966-2-1</option>
                                        <option value="linear">LINEAR</option>
                                        <option value="log">LOG</option>
                                        <option value="log_sqrt">LOG_SQRT</option>
                                        <option value="iec61966_2_4">IEC 61966-2-4</option>
                                        <option value="bt1361_ecg">ITU-R BT1361 Extended Colour Gamut</option>
                                        <option value="smpte428">SMPTE ST 428-1 </option>
                                        <option value="arib_std_b67">ARIB STD-B67</option>
-->
                                    </select>
                                </td>
                            </tr>

                            <tr id="output_color_space_row">
                                <td>Output Color Space</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                    <select id="output_color_space" name="output_color_space">
                                        <option value="auto" selected>AUTO</option>
                                        <option value="unspecified">UNSPECIFIED</option>
<!--
                                        <option value="bt709">BT709</option>
                                        <option value="bt601">BT601</option>
                                        <option value="smpte170">SMPTE170M </option>
                                        <option value="smpte240m">SMPTE240M </option>
                                        <option value="smpte2085">SMPTE 2005</option>
                                        <option value="bt2020_ncl">BT2020 non-constant luminance</option>
                                        <option value="bt2020_cl">BT2020 constant luminance</option>
                                        <option value="bt470bg">BT470BG</option>
                                        <option value="ycg0">ITU-T SG16</option>
-->
                                    </select>
                                </td>
                            </tr>

                            <?php if (ENABLE_MCTF) {
                                echo "<tr class=\"video_setting_row\">";
                            } else {
                                echo "<tr class=\"video_setting_row\" hidden=\"true\">";
                            }
                            ?>
                                <td>Noise Filter</td>
                                <td>:</td>
                                <td>
                                     <select name="noise_filtering" id="noise_filtering">
                                     <option value="0">Off</option>
                                     <option value="2">2</option>
                                     <option value="4">4</option>
                                     <option value="8">8</option>
                                     <option value="16">16</option>
                                     <option value="32">32</option>
                                     </select>
                                </td>
                            </tr>
                        </div>

                        <div id="placeholder-options" style="font-size:18px">
                            <tr style="height: 15px"> </tr>
                        </div>
                        <div id="audio-options" style="font-size:12px">
                            <tr id="output_audio_format_row">
                                <td>Output Audio Encoder</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                         <?php
                                        // If we are in the ATSC mode, not all the options should be displayed
                                        if(CONFIG_MODE != 1)
                                        {
                                        ?>
                                        <select id="output_audio_format" name="output_audio_format" onchange="audio_format_selected(this)">
                                         <?php if (OUTPUT_MUX_TYPE != 2) { ?>
                                         <option value="passthrough">Passthrough</option>
                                         <option value="passthroughmax">Passthrough (Compatibility Mode)</option>
                                         <option value="aac">AAC</option>
                                         <option value="mp11">MPEG-1 Layer 1</option>
                                         <option value="mp12">MPEG-1 Layer 2</option>
                                         <option value="mp21">MPEG-2 Layer 1</option>
                                         <option value="mp22">MPEG-2 Layer 2</option>
                                         <option value="mp3">MP3</option>
                                         <?php } ?>
                                         <?php if (ENABLE_AC3_ENCODE) { ?>
                                         <option value="ac3">AC3</option>
                                         <?php } ?>

                                         <?php
                                        }
                                        else
                                        {
                                        ?>
                                         <select id="output_audio_format" name="output_audio_format" onchange="audio_format_selected(this)" disabled>
                                         <option value="aac" selected>MPEG4 HE-AAC v2</option>
                                         <?php
                                        }
                                        ?>

                                     </select>
                                </td>
                            </tr>

                            <tr class="muted" style="display:none;">
                                <td>Output audio samplerate</td>
                                <td>:</td>
                                <td colspan="4"><input name="output_audio_samplerate" class="dim_entry muted" id="output_audio_samplerate" type="text" disabled="true"> Hz</td>
                            </tr>

                            <tr id="output_audio_agc_row">
                                <td>Output audio CALM</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                    <select id="output_audio_agc" name="output_audio_agc">
                                        <option value="DISABLED" selected>Disabled</option>
                                        //                                    <?php if (ENABLE_AUDIO_AGC) { ?>
                                        <option value="TV_5B_GEN">TV_5B_GEN</option>
                                        <option value="TV_5B_LIGHT">TV_5B_LIGHT</option>
                                        <option value="TV_5B_HEAVY">TV_5B_HEAVY</option>
                                        <option value="TV_5B_LOUD">TV_5B_LOUD</option>
                                        <option value="ITU_LOUD_LMT">ITU_LOUD_LMT</option>
                                        <option value="PROTECT_LMT">PROTECT_LMT</option>
                                        //                                    <?php } ?>
                                    </select>
                                </td>
                            </tr>

                            <tr style="height: 15px"><td colspan="6"></td></tr>

                            <tr name="audio_heading_row0" id="audio_heading_row0" class="audio0_heading_row">
                                <td><b>Primary Audio</b></td>
                                <td></td>
                                <td colspan="4" align="left"></td>
                            </tr>
                            <tr name="audio_pid_row0" id="audio_pid_row0" class="audio0_setting_row">
                                <td>Input Audio ID</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                    <select id="input_audio_pid0" name="input_audio_pid0" onMouseOver="disableSelectedAudioOptions(0)">
                                    <option value="-1" selected>Unselected</option>
                                    </select>
                                </div>
                                </td>
                            </tr>
                            <tr name="audio_bitrate_row0" id="audio_bitrate_row0" class="audio0_heading_row">
                                <td>Output Audio Bitrate</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                     <select name="output_audio_bitrate0" id="output_audio_bitrate0">
                                     </select>
                                </td>
                            </tr>
                            <tr name="audio_channels_row0" id="audio_channels_row0" class="audio0_setting_row">
                                <td>Output Audio Channels</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                     <select name="audio_channels0" id="audio_channels0">
                                        <option value="2">Stereo (2.0)</option>
                                        <option value="6">5.1 (L,R,C,LFE,SL,SR)</option>
                                     </select>
                                </td>
                            </tr>
                            <tr name="audio_volume_row0" id="audio_volume_row0" class="audio0_setting_row">
                                <td>Output Audio Volume</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="output_audio_volume0" class="dim_entry integer_field" id="output_audio_volume0" type="text"> % <span class="muted">(0 - 200)</span></td>
                            </tr>
                            <tr name="audio_lang_row0" id="audio_lang_row0" class="audio0_setting_row output_audio_lang">
                                <td>Output Audio Language</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="output_audio_lang0" class="dim_entry" id="output_audio_lang0" type="text" maxlength="3"><span class="muted"> (ISO 639-2 alpha-3 code or blank to omit)</span></td>
                            </tr>
                            <tr name="audio_sync_delta_row0" id="audio_sync_delta_row0" class="audio0_setting_row hideforhdsdi">
                                <td>Audio Sync Delta</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="audio_sync_delta0" class="dim_entry signed_integer_field" id="audio_sync_delta0" type="text"><span class="muted"> (sync units [-10 to 10])</span></td>
                            </tr>

                            <tr name="audio_ac3_dialnorm_row0" id="audio_ac3_dialnorm_row0" class="audio0_setting_row audio0_ac3_setting_row">
                                <td>AC3 Dialnorm</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="audio_ac3_dialnorm0" class="dim_entry integer_field" id="audio_ac3_dialnorm0" type="text"> -dB<span class="muted"> (1 - 31, 0 = reserved)</span></td>
                            </tr>
                            <tr name="audio0_sdi_mapping_row0" id="audio0_sdi_mapping_row0" class="audio0_setting_row audio0_sdi_setting_row audio0_ac3_setting_row audio0_5_1_setting_row">
                                <td>SDI Audio Mapping</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                    <table>
                                    <tr>
                                    <td width="60" align="center">LEFT</td>
                                    <td>
                                        <select name="audio_sdi_mapping_l0" id="audio_sdi_mapping_l0">
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                         </select>
                                    </td>
                                    <td width="60" align="center">RIGHT</td>
                                    <td>
                                        <select name="audio_sdi_mapping_r0" id="audio_sdi_mapping_r0">
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                         </select>
                                     </td>
                                     </tr>
                                     </table>
                                </td>
                            </tr>
                            <tr name="audio0_sdi_mapping_row1" id="audio0_sdi_mapping_row1" class="audio0_setting_row audio0_sdi_setting_row audio0_ac3_setting_row audio0_5_1_setting_row">
                                <td></td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                    <table>
                                    <tr>
                                    <td width="60" align="center">CENTER</td>
                                    <td>
                                        <select name="audio_sdi_mapping_c0" id="audio_sdi_mapping_c0">
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                         </select>
                                     </td>
                                    <td width="60" align="center">LFE</td>
                                    <td>
                                        <select name="audio_sdi_mapping_lfe0" id="audio_sdi_mapping_lfe0">
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                         </select>
                                     </td>
                                     </tr>
                                     </table>
                                </td>
                            </tr>

                            <tr name="audio0_sdi_mapping_row2" id="audio0_sdi_mapping_row2" class="audio0_setting_row audio0_sdi_setting_row audio0_ac3_setting_row audio0_5_1_setting_row">
                                <td></td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                    <table>
                                    <td width="60" align="center">SL</td>
                                    <td>
                                        <select name="audio_sdi_mapping_sl0" id="audio_sdi_mapping_sl0">
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                            <!--
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            -->
                                         </select>
                                     </td>
                                    <td width="60" align="center">SR</td>
                                    <td>
                                        <select name="audio_sdi_mapping_sr0" id="audio_sdi_mapping_sr0">
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                         </select>
                                     </td>
                                     </tr>
                                     </table>
                                </td>
                            </tr>
                            <tr style="height: 10px" class="audio0_heading_row"><td colspan="6"></td></tr>
                            <tbody id="nonprimaryaudio">
                            <tr name="audio_heading_row1" id="audio_heading_row1" class="audio1_heading_row">
                                <td><b>Secondary Audio</b></td>
                                <td></td>
                                <td colspan="4" align="left"></td>
                            </tr>
                            <tr name="audio_pid_row1" id="audio_pid_row1" class="audio1_setting_row">
                                <td>Input Audio ID</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                    <select id="input_audio_pid1" name="input_audio_pid1" onMouseOver="disableSelectedAudioOptions(1)">
                                    <option value="-1" selected>Default</option>
                                    </select>
                                </div>
                                </td>
                            </tr>
                            <tr name="audio_bitrate_row1" id="audio_bitrate_row1" class="audio1_heading_row">
                                <td>Output Audio Bitrate</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                     <select name="output_audio_bitrate1" id ="output_audio_bitrate1" onChange="disableSelectedAudioOptions(1)">
                                     </select>
                                </td>
                            </tr>
                            <tr name="audio_channels_row1" id="audio_channels_row1" class="audio1_setting_row">
                                <td>Output Audio Channels</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                     <select name="audio_channels1" id="audio_channels1">
                                        <option value="2">Stereo (2.0)</option>
                                        <option value="6">5.1 (L,R,C,LFE,SL,SR)</option>
                                     </select>
                                </td>
                            </tr>
                            <tr name="audio_volume_row1" id="audio_volume_row1" class="audio1_setting_row">
                                <td>Output Audio volume</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="output_audio_volume1" class="dim_entry integer_field" id="output_audio_volume1" type="text"> %<span class="muted"> (0 - 200)</span></td>
                            </tr>
                            <tr name="audio_lang_row1" id="audio_lang_row1" class="audio1_setting_row output_audio_lang">
                                <td>Output Audio Language</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="output_audio_lang1" class="dim_entry" id="output_audio_lang1" type="text" maxlength="3"><span class="muted"> (ISO 639-2 alpha-3 code or blank to omit)</span></td>
                            </tr>
                            <tr name="audio_sync_delta_row1" id="audio_sync_delta_row1" class="audio1_setting_row">
                                <td>Audio Sync Delta</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="audio_sync_delta1" class="dim_entry signed_integer_field" id="audio_sync_delta1" type="text"><span class="muted"> (sync units [-10 to 10])</span></td>
                            </tr>
                            <tr name="audio_ac3_dialnorm_row1" id="audio_ac3_dialnorm_row1" class="audio1_setting_row audio1_ac3_setting_row">
                                <td>AC3 Dialnorm</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="audio_ac3_dialnorm1" class="dim_entry integer_field" id="audio_ac3_dialnorm1" type="text"> -dB<span class="muted"> (1 - 31, 0 = reserved)</span></td>
                            </tr>

                            <tr name="audio1_sdi_mapping_row0" id="audio1_sdi_mapping_row0" class="force_hide audio1_setting_row audio1_sdi_setting_row audio1_ac3_setting_row audio1_5_1_setting_row">
                                <td>SDI Audio Mapping</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                    <table>
                                    <tr>
                                    <td width="60" align="center">LEFT</td>
                                    <td>
                                        <select name="audio_sdi_mapping_l1" id="audio_sdi_mapping_l1">
                                            <!-- <option value="0" selected="selected">Auto</option>  -->
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                         </select>
                                     </td>
                                    <td width="60" align="center">RIGHT</td>
                                    <td>
                                        <select name="audio_sdi_mapping_r1" id="audio_sdi_mapping_r1"
                                            <!-- <option value="0" selected="selected">Auto</option> -->
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                         </select>
                                     </td>
                                     </tr>
                                     </table>
                                </td>
                            </tr>
                            <tr name="audio1_sdi_mapping_row1" id="audio1_sdi_mapping_row1" class="audio1_setting_row audio0_sdi_setting_row audio1_ac3_setting_row audio1_5_1_setting_row">
                                <td></td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                    <table>
                                    <tr>
                                    <td width="60" align="center">CENTER</td>
                                    <td>
                                        <select name="audio_sdi_mapping_c1" id="audio_sdi_mapping_c1">
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                         </select>
                                     </td>
                                    <td width="60" align="center">LFE</td>
                                    <td>
                                        <select name="audio_sdi_mapping_lfe1" id="audio_sdi_mapping_lfe1">
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                         </select>
                                     </td>
                                     </tr>
                                     </table>
                                </td>
                            </tr>

                            <tr name="audio1_sdi_mapping_row2" id="audio1_sdi_mapping_row2" class="audio1_setting_row audio1_sdi_setting_row audio1_ac3_setting_row audio1_5_1_setting_row">
                                <td></td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                    <table>
                                    <td width="60" align="center">SL</td>
                                    <td>
                                        <select name="audio_sdi_mapping_sl1" id="audio_sdi_mapping_sl1">
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                            <!--
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            -->
                                         </select>
                                     </td>
                                    <td width="60" align="center">SR</td>
                                    <td>
                                        <select name="audio_sdi_mapping_sr1" id="audio_sdi_mapping_sr1">
                                            <option value="0">Group 1 Slot 1</option>
                                            <option value="1">Group 1 Slot 2</option>
                                            <option value="2">Group 1 Slot 3</option>
                                            <option value="3">Group 1 Slot 4</option>
                                            <option value="4">Group 2 Slot 1</option>
                                            <option value="5">Group 2 Slot 2</option>
                                            <option value="6">Group 2 Slot 3</option>
                                            <option value="7">Group 2 Slot 4</option>
                                            <option value="8"> Group 3 Slot 1</option>
                                            <option value="9"> Group 3 Slot 2</option>
                                            <option value="10">Group 3 Slot 3</option>
                                            <option value="11">Group 3 Slot 4</option>
                                            <option value="12">Group 4 Slot 1</option>
                                            <option value="13">Group 4 Slot 2</option>
                                            <option value="14">Group 4 Slot 3</option>
                                            <option value="15">Group 4 Slot 4</option>
                                         </select>
                                     </td>
                                     </tr>
                                     </table>
                                </td>
                            </tr>
                            <tr style="height: 10px" class="audio1_heading_row"><td colspan="6"></td></tr>

                            <tr name="audio_heading_row2" id="audio_heading_row2" class="audio2_heading_row">
                                <td><b>Third Audio</b></td>
                                <td></td>
                                <td colspan="4" align="left"></td>
                            </tr>
                            <tr name="audio_pid_row2" id="audio_pid_row2" class="audio2_setting_row">
                                <td>Input Audio ID</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                    <select id="input_audio_pid2" name="input_audio_pid2" onMouseOver="disableSelectedAudioOptions(2)">
                                    <option value="-1" selected>Default</option>
                                    </select>
                                </div>
                                </td>
                            </tr>
                            <tr name="audio_bitrate_row2" id="audio_bitrate_row2" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="audio2_heading_row">
                                <td>Output Audio Bitrate</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                     <select name="output_audio_bitrate2" id ="output_audio_bitrate2" onChange="disableSelectedAudioOptions(2)">
                                     </select>
                                </td>
                            </tr>
                            <tr name="audio_channels_row2" id="audio_channels_row2" class="audio2_setting_row">
                                <td>Output Audio Channels</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                     <select name="audio_channels2" id="audio_channels2">
                                        <option value="2">Stereo (2.0)</option>
                                        <!-- <option value="6">5.1 (L,R,C,LFE,SL,SR)</option> -->
                                     </select>
                                </td>
                            </tr>
                            <tr name="audio_volume_row2" id="audio_volume_row2" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?> class="audio2_setting_row">
                                <td>Output Audio Volume</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="output_audio_volume2" class="dim_entry integer_field" id="output_audio_volume2" type="text"> %<span class="muted"> (0 - 200)</span></td>
                            </tr>
                            <tr name="audio_lang_row2" id="audio_lang_row2" class="audio2_setting_row output_audio_lang">
                                <td>Output Audio Language</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="output_audio_lang2" class="dim_entry" id="output_audio_lang2" type="text" maxlength="3"><span class="muted"> (ISO 639-2 alpha-3 code or blank to omit)</span></td>
                            </tr>
                            <tr name="audio_sync_delta_row2" id="audio_sync_delta_row2" class="audio2_setting_row">
                                <td>Audio Sync Delta</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="audio_sync_delta2" class="dim_entry signed_integer_field" id="audio_sync_delta2" type="text"><span class="muted"> (sync units [-10 to 10])</span></td>
                            </tr>
                            <tr name="audio_ac3_dialnorm_row2" id="audio_ac3_dialnorm_row2" class="audio2_setting_row audio2_ac3_setting_row">
                                <td>AC3 Dialnorm</td>
                                <td>:</td>
                                <td colspan="4" align="left"><input name="audio_ac3_dialnorm2" class="dim_entry integer_field" id="audio_ac3_dialnorm2" type="text"> -dB<span class="muted"> (1 - 31, 0 = reserved)</span></td>
                            </tr>

                            <tr style="height: 10px" class="audio_heading_row2"><td colspan="6"></td></tr>
                            </tbody>
                            <tbody class="hideforhdsdi">
                            <!-- Image Overlay -->
                            <tr name="image_overlay_heading_row" id="image_overlay_heading_row" class="image_overlay_heading_row tab_overlay_settings" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td><b>Image Overlay</b></td>
                                <td></td>
                                <td colspan="4" align="left">
                                </td>
                            </tr>

                            <tr name="image_overlay_upload_row" id="image_overlay_upload_row" class="image_overlay_heading_row tab_overlay_settings" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Upload image</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                    <input id="image_overlay_upload_box" type="file" size="45" name="fileToUpload" class="input">
                                    <button class="button" id="imageOverlayFileUploadButton" onclick="return imageOverlayFileUpload();">Upload</button>
                                </td>
                            </tr>

                            <tr style="height: 15px" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>><td colspan="6"></td></tr>

                            <tr name="image_overlay_image_row" id="image_overlay_image_row" class="image_overlay_heading_row tab_overlay_settings" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Image</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                     <select name="image_overlay_file" id ="image_overlay_file" class="image_overlay_file">
                                        <option value="">None</option>
                                     </select>
                                     <button class="button" id="image_overlay_file_delete" onclick="return imageOverlayFileDelete();">Delete</button>
                                </td>
                            </tr>
                            <tr name="image_overlay_position_row" id="image_overlay_position_row" class="image_overlay_row tab_overlay_settings" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Position</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                <select name="image_overlay_position" id="image_overlay_position">
                                    <option value="0">Bottom Right</option>
                                    <option value="1">Bottom Left</option>
                                    <option value="2">Top Left</option>
                                    <option value="3">Top Right</option>
                                </select>
                                </td>
                            </tr>

                            <tr name="image_overlay_margin_x_row" id="image_overlay_margin_x_row" class="image_overlay_row tab_overlay_settings" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>X Margin</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                <input type="text" id="image_overlay_margin_x" size="8" value="10" class="dim_entry integer_field"></input>
                                </td>
                            </tr>

                            <tr name="image_overlay_margin_y_row" id="image_overlay_margin_y_row" class="image_overlay_row tab_overlay_settings" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Y Margin</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                <input type="text" id="image_overlay_margin_y" size="8" value="10" class="dim_entry integer_field"></input>
                                </td>
                            </tr>

                            <tr name="image_overlay_alpha_row" id="image_overlay_alpha_row" class="image_overlay_row tab_overlay_settings" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Alpha Blend</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                <input type="text" id="image_overlay_alpha" size="8" value="100" class="dim_entry integer_field"></input> 0 - 100%
                                </td>
                            </tr>

                            <tr style="height: 15px"><td colspan="6" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>></td></tr>

                            <tr name="image_overlay_preview_row" id="image_overlay_preview_row" class="image_overlay_row tab_overlay_settings" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>>
                                <td>Preview</td>
                                <td>:</td>
                                <td colspan="8" align="left">
                                <img id="image_overlay_preview_img"></img>
                                </td>
                            </tr>
                            </tbody>
                            <tr style="height: 10px" class="image_overlay_row" <?php echo (CONFIG_MODE == 1) ? "style='display:none;'" : "" ?>><td colspan="6"></td></tr>
                        </div>
                      </table>
                    </div>

                    <div id="capture-options" class="option-tab-content master-tab" style="display:none">
                        <table border="0" cellpadding="0" cellspacing="0">
                            <tr>
                                <td>Capture device</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                <select name="capture_device" id="capture_device">
                                <?php
                                    // Logic for 4 input cards
                                    $num_capture_cards = ANALOG_CHANNELS/4;

                                    for ($card = 0; $card < $num_capture_cards; ++$card) {
                                        if ($num_capture_cards > 1) {
                                            echo "<optgroup label='Card $card'>";
                                        }
                                        for ($port = $card*4; $port < ($card*4+4); ++$port) {
                                            echo "<option value='port$port'>Interface $port (/dev/video$port)</option>";
                                        }
                                        if ($num_capture_cards > 1) {
                                            echo "</optgroup>";
                                        }
                                    }
/*
                                    // Logic for 3 input cards
                                    $num_capture_cards = ANALOG_CHANNELS/3;

                                    for ($card = 0; $card < $num_capture_cards; ++$card) {
                                        if ($num_capture_cards > 1) {
                                            echo "<optgroup label='Card $card'>";
                                        }
                                        for ($port = $card*3; $port < ($card*3+3); ++$port) {
                                            echo "<option value='port$port'>Interface $port (/dev/video$port)</option>";
                                        }
                                        if ($num_capture_cards > 1) {
                                            echo "</optgroup>";
                                        }
                                    }
*/

                                    // Logic for 2 input cards
                                    /*
                                    $num_capture_cards = ANALOG_CHANNELS/2;

                                    for ($card = 0; $card < $num_capture_cards; ++$card) {
                                        if ($num_capture_cards > 1) {
                                            echo "<optgroup label='Card $card'>";
                                        }
                                        for ($port = $card*2; $port < ($card*2+2); ++$port) {
                                            echo "<option value='port$port'>Interface $port (/dev/video$port)</option>";
                                        }
                                        if ($num_capture_cards > 1) {
                                            echo "</optgroup>";
                                        }
                                    }
                                    */
                                    ?>
                                </select>
                                </td>
                            </tr>
                            <tr>
                                <td style="padding-right: 15px">Preferred Video PID</td>
                                <td style="width: 15px">:</td>
                                <td><input name="capture_video_pid" class="dim_entry integer_field" id="capture_video_pid" type="text"></td>
                            </tr>
                            <tr>
                                <td>Preferred Audio PID</td>
                                <td>:</td>
                                <td><input name="capture_audio_pid" class="dim_entry integer_field" id="capture_audio_pid" type="text"></td>
                            </tr>
                            <tr>
                                <td>Preferred PMT PID</td>
                                <td>:</td>
                                <td><input name="capture_pmt_pid" class="dim_entry integer_field" id="capture_pmt_pid" type="text"></td>
                            </tr>
<!--
                            <tr>
                                <td>Channel Name</td>
                                <td>:</td>
                                <td><input name="channel_name" class="entry_box" style="width:130px" id="channel_name" type="text"></td>
                            </tr>
                            <tr>
                                <td">Service Provider</td>
                                <td">:</td>
                                <td><input name="service_provider" class="entry_box" style="width:130px" id="service_provider" type="text"></td>
                            </tr>
-->
                            <tr>
                                <td>Audio language</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                <table border="0">
                                <tr>
                                <select name="capture_audio_language" id="capture_audio_language">
                                    <option value="eng">English (eng)</option>
                                    <option value="spa">Spanish (spa)</option>
                                    <option value="fre">French (fre)</option>
                                    <option value="ita">Italian (ita)</option>
                                    <option value="ger">German (ger)</option>
                                    <option value="und">Undefined (und)</option>
                                </select>
                                </tr>
                                </table>
                                </td>
                            </tr>
                            <tr>
                                <td>Brightness</td>
                                <td>:</td>
                                <td><input name="capture_brightness" class="dim_entry integer_field" id="capture_brightness" type="text"><span class="muted">&nbsp;(0 - 255)</span></td>
                            </tr>
                            <tr>
                                <td>Hue</td>
                                <td>:</td>
                                <td><input name="capture_hue" class="dim_entry signed_integer_field" id="capture_hue" type="text"><span class="muted">&nbsp;(-128 - 127)</span></td>
                            </tr>
                            <tr>
                                <td>Contrast</td>
                                <td>:</td>
                                <td><input name="capture_contrast" class="dim_entry integer_field" id="capture_contrast" type="text"><span class="muted">&nbsp;(0 - 127)</span></td>
                            </tr>
                            <tr>
                                <td>Saturation</td>
                                <td>:</td>
                                <td><input name="capture_saturation" class="dim_entry integer_field" id="capture_saturation" type="text"><span class="muted">&nbsp;(0 - 127)</span></td>
                            </tr>
                        </table>
                    </div>
                    <div id="streaming-options" class="option-tab-content master-tab" style="display:none">
                        <table border="0" cellpadding="0" cellspacing="0">
                            <tr id="row_output_0" class="video_setting_row">
                                <td style="width: 180px">Output resolution preset</td>
                                <td style="width: 15px">:</td>
                                <td colspan="4" align="left">
                                    <select name="output_resolution" id="output_resolution" onchange="output_resolution_changed(this)">
                                    </select>
                                </td>
                            </tr>
                            <tr id="row_output_override" class="video_setting_row">
                                <td>Output resolution override</td>
                                <td>:</td>
                                <td colspan="3" align="left">
                                <table border="0">
                                <tr>
                                <td><input name="output_width" class="dim_entry integer_field" id="output_width" type="text"></td>
                                <td align="center">x</td>
                                <td><input name="output_height" class="dim_entry integer_field" id="output_height" type="text" style="text-align: left"></td>
                                </tr>
                                </table>
                                </td>
                            </tr>
                            <?php
                            if( CONFIG_MODE != 1)
                            {
                            ?>
                            <tr class="video_setting_row">
                                <td>Output framerate</td>
                                <td>:</td>
                                <td colspan="4" align="left">
                                     <select name="output_framerate" id="output_framerate" onchange="output_framerate_changed(this)">
                                        <option value="0">Same as input</option>
                                        <option value="1">1/2 of input</option>
                                        <?php if(CONFIG_MODE != 1) { ?>
                                        <option value="3">2x input</option>
                                        <option value="2">25 to 29.97</option>
                                        <option value="10">29.97 to 25</option>
                                        <option value="6">29.97 to 30</option>
                                        <!--
                                        <option value="7">30 to 29.97</option>
                                        <option value="8">59.94 to 60</option>
                                        <option value="4">50 to 59.94</option>
                                        <option value="5">59.94 to 50</option>
                                        <option value="9">60 to 59.94</option>
                                        -->
                                        <?php } ?>
                                     </select>
                                </td>
                            </tr>
                            <?php
                            }
                            ?>

<?php
    if (ENABLE_OUTPUT_VIDEO_BITRATE == 1)
    {
?>
                            <tr id="output_video_bitrate_row" class="video_setting_row">
                                <td>Output video bitrate</td>
                                <td>:</td>
                                <td colspan="3" align="left">
                                    <input name="output_video_bitrate" class="dim_entry integer_field" id="output_video_bitrate" type="text">
                                    bps <span class="muted">(0 = automatic)</span>
                                </td>
                            </tr>
<?php } ?>
                            <tr id="output_mux_rate_row" class="video_setting_row">
                                <td>Output mux rate</td>
                                <td>:</td>
                                <td colspan="2" align="left">
                                    <input name="output_mux_rate" class="dim_entry integer_field" id="output_mux_rate" type="text"> bps
                                </td>
                                <td><span id="estbps">Calculated video rate: <input type="text" id="videobps" class="dim_entry integer_field" readonly> bps, Calculated audio rate: <input type="text" id="audiobps" class="dim_entry integer_field" readonly> bps</span>
                                </td>
                            </tr>

                            <tr id="ip_output_type_row">
                                <td>IP output type</td>
                                <td>:</td>
                                <td colspan="2" align="left">
                                     <select name="output_type" id="output_type" onchange='ip_output_type_selected(this)'>
                                     <option value="1">UDP output</option>
<?php if(!FUSION_BUILD){?>
                                     <option value="0">RTP output</option>
<?php }?>
                                     </select>
                                </td>
                            </tr>

                            <!-- Repetition Rate stuff -->

                            <tr style="height: 15px"<td colspan="6"></td></tr>
                            <tbody class="hideforhdsdi">
                            <tr name="ts_output_repetition_rate_heading" id="ts_output_repetition_rate_heading" class="ts_output_repetition_rate_heading_row">
                                <td><b>Repetition Rate</b></td>
                                <td></td>
                                <td colspan="4" align="left"></td>
                            </tr>
                            <tr class="ts_output_repetition_rate_setting_row">
                                <td>PAT</td>
                                <td>:</td>
                                <td colspan="3" align="left">
                                     <input name="output_pat_rate" class="dim_entry integer_field" style="width:48px" id="output_pat_rate" type="text">&nbsp;<span class="muted">(20 - 100 ms)</span></td>
                            </tr>
                            <tr class="ts_output_repetition_rate_setting_row">
                                <td>PMT</td>
                                <td>:</td>
                                <td colspan="3" align="left">
                                     <input name="output_pmt_rate" class="dim_entry integer_field" style="width:48px" id="output_pmt_rate" type="text">&nbsp;<span class="muted">(50 - 400 ms)</span></td>
                            </tr>
                            <tr class="ts_output_repetition_rate_setting_row">
                                <td>PCR</td>
                                <td>:</td>
                                <td colspan="3" align="left">
                                     <input name="output_pcr_rate" class="dim_entry integer_field" style="width:48px" id="output_pcr_rate" type="text">&nbsp;<span class="muted">(20 - 100 ms)</span></td>
                            </tr>
                            <tr class="ts_output_repetition_rate_setting_row">
                                <td>PCR style</td>
                                <td>:</td>
                                <td>
                                    <select id="output_pcr_style" name="output_pcr_style">
                                         <option value="0">Broadcast (Defined repetition rate)</option>
                                         <option value="1">IPTV/Cable (Per video frame)</option>
                                         <option value="2">Both</option>
                                    </select>
                                </td>
                            </tr>
                            <tr style="height: 15px"><td colspan="6"></td></tr>


                            <tr>
                                <td><b>Passthru Settings</b></td>
                                <td></td>
                                <td colspan="4" align="left"></td>
                            </tr>
                            <tr id="scte35_passthru_row">
                                <td>SCTE35 Passthru</td>
                                <td>:</td>
                                <td colspan="2" align="left">
                                    <select name="scte35_passthru" id="scte35_passthru">
                                         <option value="0">Disable</option>
                                         <option value="1">Enable</option>
                                    </select>
                                </td>
                                <td name="vbr_output_estimate" id="vbr_output_estimate"></td>
                            </tr>
                            <tr style="height: 15px"><td colspan="6"></td></tr>


                            <?php if (OUTPUT_MUX_TYPE != 2) {
                            echo "<tr name=\"output_pid_remap_heading\" id=\"output_pid_remap_heading\" class=\"output_pid_remap_heading_row\">";
                            } else {
                            echo "<tr name=\"output_pid_remap_heading\" id=\"output_pid_remap_heading\" class=\"output_pid_remap_heading_row\" hidden=\"true\">";
                            }
                            ?>
                                <td><b>PID Remapping</b></td>
                                <td></td>
                                <td colspan="4" align="left"></td>
                            </tr>
                            <?php if (OUTPUT_MUX_TYPE != 2) {
                            echo "<tr class=\"output_pid_remap_heading_row\">";
                            } else {
                            echo "<tr class=\"output_pid_remap_heading_row\" hidden=\"true\">";
                            }
                            ?>
                                <td>Enable</td>
                                <td>:</td>
                                <td>
                                     <select id="enable_output_pid_remap" name="enable_output_pid_remap">
                                         <option value="0">Off</option>
                                         <option value="1">On</option>
                                     </select>
                                </td>
                            </tr>
                            <tr style="height: 15px"><td colspan="6"></td></tr>



                            <tr class="output_pid_remap_setting_row">
                                <td>PMT PID</td>
                                <td>:</td>
                                <td>
                                    <input name="output_pmt_pid" class="dim_entry integer_field" style="width:48px" id="output_pmt_pid" type="text">
                                    <span class="muted"><nobr>&nbsp;(1-8191)</nobr></span>
                                </td>
                            </tr>
                            <tr class="output_pid_remap_setting_row">
                                <td>Video PID</td>
                                <td>:</td>
                                <td>
                                    <input name="output_video_pid" class="dim_entry integer_field" style="width:48px" id="output_video_pid" type="text">
                                    <span class="muted"><nobr>&nbsp;(1-8191)</nobr></span>
                                </td>
                            </tr>
                            <tr class="output_pid_remap_setting_row">
                                <td>Audio base PID</td>
                                <td>:</td>
                                <td>
                                    <input name="output_audio_pid" class="dim_entry integer_field" style="width:48px" id="output_audio_pid" type="text">
                                    <span class="muted"><nobr>&nbsp;(1-8191)</nobr></span>
                                </td>
                            </tr>
                            <tr id="output_scete35_pid_row" class="output_pid_remap_setting_row">
                                <td>SCTE35 PID</td>
                                <td>:</td>
                                <td>
                                    <input name="output_scete35_pid" class="dim_entry integer_field" style="width:48px" id="output_scte35_pid" type="text">
                                    <span class="muted"><nobr>&nbsp;(1-8191)</nobr></span>
                                </td>
                            </tr>
                            <tr class="output_pid_remap_setting_row">
                                <td>Transport stream ID</td>
                                <td>:</td>
                                <td colspan="3" align="left">
                                    <input name="output_transport_stream_id" class="dim_entry integer_field" style="width:48px" id="output_transport_stream_id" type="text">
                                    <span class="muted">&nbsp;(1-8191)</span>
                                </td>
                            </tr>
                          <tr class="output_pid_remap_setting_row">
                                <td>Program number</td>
                                <td>:</td>
                                <td colspan="3" align="left">
                                    <input name="output_program_number" class="dim_entry integer_field" style="width:48px" id="output_program_number" type="text">
                                    <span class="muted">&nbsp;(1-8191)</span>
                                </td>
                            </tr>

                            <!-- This defines the primary interface -->

                            <tr style="height: 15px"<td colspan="6"></td></tr>
                            <tr name="ts_output_repetition_rate_heading" id="ts_output_repetition_rate_heading" class="ts_output_repetition_rate_heading_row">
                                <td colspan="6"><b>Primary Output Interface</b></td>
                            </tr>

                            <tr name="preferred_output_row" id="preferred_output_row">
                                <td style="width: 180px">Output network interface</td>
                                <td style="width: 15px">:</td>
                                <td colspan="4" align="left">
                                    <select name="ethernet_interface" id="ethernet_interface">
                                        <?php
                                        foreach ($machine->getNetworkInterfaces() as $eth) {
                                            if ($eth->active()) {
                                                echo ("<option value=\"{$eth->getName()}\">{$eth->getName()}</option>\n");
                                            }
                                        }
                                        ?>
                                    </select>
                                </td>
                            </tr>
                            <tr id="output_ip_address_row">
                                <td>Output IP Address</td>
                                <td>:</td>
                                <td colspan="3">
                                <input name="output_ip_address" class="entry_box" style="width:130px" id="output_ip_address" type="text">&nbsp;
                                <label><input name="enable_raw_output" id="enable_raw_output" type="checkbox" style='vertical-align:-2px'>Enable raw socket</label>
                                </td>
                            </tr>
                            <?php if (ENABLE_IPV6) { ?>
                            <tr id="output_ip_address_ipv6_row">
                                <td>Output IP Address (IPV6)</td>
                                <td>:</td>
                                <td colspan="3">
                                <input name="output_ip_address_ipv6" class="entry_box" style="width:320px" id="output_ip_address_ipv6" type="text"> &nbsp;(OPTIONAL)
                                </td>
                            </tr>
                            <?php } ?>
                            <tr id="output_port_row">
                                <td>Output port</td>
                                <td>:</td>
                                <td><input name="output_port" class="dim_entry integer_field" id="output_port" type="text"></td>
                            </tr>
                            <tr id="multicast_ttl_row" >
                                <td>Multicast TTL</td>
                                <td>:</td>
                                <td><input name="multicast_ttl" class="dim_entry integer_field" id="multicast_ttl" type="text" value="16"></td>
                            </tr>
                            <tr style="height: 15px"<td colspan="6"></td></tr>


                            <!-- This defines the secondary interface -->

                            <tr name="ts_output_repetition_rate_heading" id="ts_output_repetition_rate_heading_2" class="ts_output_repetition_rate_heading_row">
                                <td colspan="6"><b>Secondary Output Interface</b></td>
                            </tr>

                            <tr name="enable_output_row" id="enable_output_row_2">
                                <td style="width: 180px">Enable</td>
                                <td style="width: 15px">:</td>
                                <td colspan="4" align="left">
                                    <select name="enable_ethernet_interface_2" id="enable_ethernet_interface_2">
                                        <option value="0">Off</option>
                                        <option value="1">On</option>
                                    </select>
                                </td>
                            </tr>

                            <tr class="output_ethernet_interface_2">
                                <td style="width: 180px">Output network interface</td>
                                <td style="width: 15px">:</td>
                                <td colspan="4" align="left">
                                    <select name="ethernet_interface_2" id="ethernet_interface_2">
                                        <?php
                                        foreach ($machine->getNetworkInterfaces() as $eth) {
                                            if ($eth->active()) {
                                                echo ("<option value=\"{$eth->getName()}\">{$eth->getName()}</option>\n");
                                            }
                                        }
                                        ?>
                                    </select>
                                </td>
                            </tr>

                            <tr class="output_ethernet_interface_2">
                                <td>Output IP Address</td>
                                <td>:</td>
                                <td colspan="3">
                                <input name="output_ip_address_2" class="entry_box" style="width:130px" id="output_ip_address_2" type="text">&nbsp;
                                <label><input name="enable_raw_output_2" id="enable_raw_output_2" type="checkbox" style='vertical-align:-2px'>Enable raw socket</label>
                                </td>
                            </tr>

                            <?php if (ENABLE_IPV6) { ?>
                            <tr class="output_ethernet_interface_2">
                                <td>Output IP Address (IPV6)</td>
                                <td>:</td>
                                <td colspan="3">
                                <input name="output_ip_address_ipv6_2" class="entry_box" style="width:320px" id="output_ip_address_ipv6_2" type="text"> &nbsp;(OPTIONAL)
                                </td>
                            </tr>
                            <?php } ?>
                            <tr class="output_ethernet_interface_2">
                                <td>Output port</td>
                                <td>:</td>
                                <td><input name="output_port_2" class="dim_entry integer_field" id="output_port_2" type="text"></td>
                            </tr>
                            <tr class="output_ethernet_interface_2" >
                                <td>Multicast TTL</td>
                                <td>:</td>
                                <td><input name="multicast_ttl_2" class="dim_entry integer_field" id="multicast_ttl_2" type="text" value="16"></td>
                            </tr>

                            <!-- end of secondary interface definition -->
                            <!-- Set file writing options -->

                            <tr style="height: 15px" class="output_file_option"><td colspan="6"></td></tr>
                            </tbody>
                        </table>
                    </div>
                    <div id="apple-streaming-options" class="option-tab-content master-tab" style="display:none">
                        <div id="apple-flash-tabs" style=width:690px">
                            <ul id="multirate-tabs">
                                <?php
                                if(CONFIG_MODE == 0)
                                {
                                ?>
                                    <li id="rtmp_options_tab"><a href="#rtmp-options">RTMP</a></li>
                                    <li id="apple_options_tab"><a href="#apple-options">Apple</a></li>
                                    <li id="silverlight_options_tab"><a href="#silverlight-options">Smooth Streaming/DASH</a></li>
                                <?php
                                }
                                ?>

                            <li id="rtp_options_tab"><a href="#rtp-options">RTP</a></li>

                            <?php if(CONFIG_MODE == 0) { ?>
                            <?php if(ENABLE_MULTITS == 1) { ?>
                                <li id="multits_options_tab"><a href="#multirate_ts-options">Multirate TS</a></li>
                            <?php } ?>
                            <?php } ?>

                            </ul>
                            <div id="rtmp-options" style="<?php echo (CONFIG_MODE == 1) ? "display:none;" : "" ?>">
                                <table border='0' cellpadding='0' cellspacing='0'>
                                    <tr>
                                        <td>Server Address</td>
                                        <td>:</td>
                                        <td><input name="rtmp_server_address" class="entry_box" style="width:480px;text-align:left" id="rtmp_server_address" type="text"></td>
                                    </tr>
                                    <tr>
                                        <td>Stream Naming</td>
                                        <td>:</td>
                                        <td>
                                        <select id="rtmp_naming" name="rtmp_naming">
                                        <option value="auto">Automatic</option>
                                        <option value="manual">Manual</option>
                                        </select>
                                        </td>
                                    </tr>
                                    <tr id="rtmp_remote_server_address_row" name="rtmp_remote_server_address_row">
                                        <td style="padding-right: 15px">Stream Name Prefix</td>
                                        <td style="width: 15px">:</td>
                                        <td>
                                        <input name="rtmp_remote_server_address" class="entry_box" style="width:240px;text-align:left" id="rtmp_remote_server_address" type="text">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>Publishing Username (optional)</td>
                                        <td>:</td>
                                        <td><input name="rtmp_username" class="entry_box" style="width:120px;text-align:left" id="rtmp_username" type="text"></td>
                                    </tr>
                                    <tr>
                                        <td>Publishing Password (optional)</td>
                                        <td>:</td>
                                        <td><input name="rtmp_password" class="entry_box" style="width:120px;text-align:left" id="rtmp_password" type="text"></td>
                                    </tr>

                                    <?php
                                    for ($iGroup = 1; $iGroup <= MAX_STREAM_GROUPS; $iGroup++) {
                                        echo "<tr class='stream_group{$iGroup}_row' id='rtmp_stream_name_group{$iGroup}_row'>\n";
                                        echo "    <td align='left' width='170px'><b>Stream Group $iGroup</b></td>\n";
                                        echo "    <td align='left' width='15px'></td>\n";
                                        echo "    <td align='left'></td>\n";
                                        echo "</tr>\n";

                                        for ($iStreamInGroup = 0; $iStreamInGroup < MAX_VIDEO_STREAMS; $iStreamInGroup++) {
                                            $iStream = (($iGroup - 1) * MAX_VIDEO_STREAMS) + ($iStreamInGroup - 0);

                                            echo "<tr id='rtmp_stream_name{$iStream}_row' name='rtmp_stream_name{$iStream}_row' class='stream_group{$iGroup}_row'>\n";
                                            echo "    <td align='left' width='170px'>RTMP Stream ".($iStreamInGroup+1)." Name</td>\n";
                                            echo "    <td align='left' width='15px'>:</td>\n";
                                            echo "    <td align='left'><input name='rtmp_stream_name{$iStream}' class='entry_box' style='width:540px;text-align:left' id='rtmp_stream_name{$iStream}' type='text'></td>\n";
                                            echo "</tr>\n";
                                        }
                                    }
                                    ?>
                                </table>
                            </div>
                            <div id="apple-options">
                                <table border='0' cellpadding='0' cellspacing='0' class="settings">
                                    <tr>
                                        <td style="width: 150px">Segment size</td>
                                        <td style="width: 15px">:</td>
                                        <td><input name="segment_size" class="entry_box integer_field" style="width:40px" id="segment_size" type="text">&nbsp;seconds</td>
                                    </tr>
                                    <tr>
                                        <td>Window size</td>
                                        <td>:</td>
                                        <td><input name="window_size" class="entry_box integer_field" style="width:40px" id="window_size" type="text">&nbsp;segments</td>
                                    </tr>
                                    <tr style="height: 15px"><td colspan="3"></td></tr>
                                    <tr id="apple_master_variant_row">
                                        <td>Master Variant Mode</td>
                                        <td>:</td>
                                        <td>
                                            <select name="apple_master_variant" id="apple_master_variant" class="entry_box">
                                                <option value="0">Muxed Audio</option>
                                                <option value="1">Separate Audio</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr id="apple_enable_encryption_row">
                                        <td>Enable HLS Encryption</td>
                                        <td>:</td>
                                        <td>
                                            <select name="fixed_key_enable" id="fixed_key_enable" class="entry_box">
                                                <option value="0">Disable</option>
                                                <option value="1">Enable</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr id="apple_encryption_key_row">
                                    <td>Fixed Key [ 0.. 3]</td>
                                    <td class="setting_spacer">:</td>
                                    <td>
                                         <span style="margin-right: 2px">0x</span><input id="fixed_key_0" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_1" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_2" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_3" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                    </td>
                                    </tr>
                                    <tr>
                                    <td>Fixed Key [ 4.. 7]</td>
                                    <td class="setting_spacer">:</td>
                                    <td>
                                         <span style="margin-right: 2px">0x</span><input id="fixed_key_4" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_5" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_6" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_7" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                    </td>
                                    </tr>
                                    <tr>
                                    <td>Fixed Key [ 8..11]</td>
                                    <td class="setting_spacer">:</td>
                                    <td>
                                         <span style="margin-right: 2px">0x</span><input id="fixed_key_8" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_9" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_10" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_11" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                    </td>
                                    </tr>
                                    <tr>
                                    <td>Fixed Key [12..15]</td>
                                    <td class="setting_spacer">:</td>
                                    <td>
                                         <span style="margin-right: 2px">0x</span><input id="fixed_key_12" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_13" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_14" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                         <span style="margin-left: 10px; margin-right: 2px">0x</span><input id="fixed_key_15" type="text" class="entry_box fixed_key hex" style="width: 20px" maxlength="2">
                                    </td>
                                    </tr>

                                    <tr id="hls_segment_rollover_row">
                                        <td>Segment rollover</td>
                                        <td>:</td>
                                        <td>
                                            <select name="hls_segment_rollover_mode" id="hls_segment_rollover_mode" class="entry_box">
                                                <option value="0">Automatic</option>
                                                <option value="1">Manual Simple (Normal Overwrite)</option>
                                                <!-- <option value="2">Directory<?=strcasecmp(VENDOR,"ccur")&&strcasecmp(VENDOR,"ccur2")?" (Akamai Compatibility)":""?></option> -->
                                                <option value="3">Time/Date Naming</option>
                                                <!--
                                                // Unlimited mode works but there are some disk space concerns so disable it until requested by someone.
                                                <option value="4">Unlimited</option>
                                                -->
                                            </select>
                                        </td>
                                    </tr>
                                    <tr id="hls_segment_rollover_count_row">
                                        <td>Rollover count</td>
                                        <td>:</td>
                                        <td><input name="hls_segment_rollover_count" class="entry_box integer_field" style="width:80px" id="hls_segment_rollover_count" type="text">&nbsp;segments</td>
                                    </tr>
                                    <tr>
                                        <td>Rollover time estimate</td>
                                        <td>:</td>
                                        <td><span id="hls_segment_rollover_estimate"></span></td>
                                    </tr>
                                    <tr style="height: 15px"><td colspan="3"></td></tr>
                                    <tr id="http_host_address_row">
                                        <td>Host Address</td>
                                        <td>:</td>
                                        <td><input name="http_host_address" class="entry_box" style="width:120px" id="http_host_address" text="text"></td>
                                    </tr>
                                    <tr id="hls_prefix_row">
                                        <td>HLS Prefix Name</td>
                                        <td>:</td>
                                        <td><input name="hls_prefix_name" class="entry_box" style="text-align: left; width: 400px" id="hls_prefix_name" text="text" maxlength="50"></td>
                                    </tr>
                                    <tr id="hls_version_row">
                                        <td>HLS Version</td>
                                        <td>:</td>
                                        <td>
                                            <select name="hls_version" id="hls_version">
                                                <option value="1">1</option>
                                                <option value="2">2</option>
                                                <option value="3">3</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr id="hls_name_style_row">
                                        <td>HLS File Naming Format</td>
                                        <td>:</td>
                                        <td>
                                            <select name="hls_name_style" id="hls_name_style">
                                              <!-- <option value="1">Channel Based (prefix_group#_ch#.m3u8)</option> -->
                                                <option value="2">Generic (prefix_master.m3u8)</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr id="hls_delete_server_row">
                                        <td>Issue remote server delete?</td>
                                        <td>:</td>
                                        <td>
                                            <select name="hls_delete_server" id="hls_delete_server">
                                                <option value="0">No</option>
                                                <option value="1">Yes</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr id="hls_delete_local_row">
                                        <td>Issue local server delete?</td>
                                        <td>:</td>
                                        <td>
                                            <select name="hls_delete_local" id="hls_delete_local">
                                                <option value="0">No</option>
                                                <option value="1">Yes</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>URL</td>
                                        <td>:</td>
                                        <td><a id="hls-url" href="#" style="color: blue"></span></td>
                                        <script>
                                            function updateHlsUrl() {
                                                const p = document.getElementById('hls_prefix_name').value;
                                                const url = `${window.location.origin}/hls/${p}_hls/${p}_master.m3u8`;
                                                const e = document.getElementById('hls-url')
                                                e.textContent = url;
                                                e.href = url;
                                            }
                                            window.addEventListener('DOMContentLoaded', () => {
                                                updateHlsUrl();
                                                document.getElementById('hls_prefix_name').addEventListener('input', updateHlsUrl);
                                            });
                                        </script>
                                    </tr>
                                    <tr id="hls_replace_start_row" style="visibility:hidden;">
                                        <td>HLS Replace Start</td>
                                        <td>:</td>
                                        <td>
                                            <select name="hls_replace_start" id="hls_replace_start" class="entry_box">
                                                <option value="-1">Disabled</option>
                                                <option value="10">Every 10 minutes</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr id="hls_replace_end_row" style="visibility:hidden;">
                                        <td>HLS Replace End (Duration)</td>
                                        <td>:</td>
                                        <td>
                                            <select name="hls_replace_end" id="hls_replace_end" class="entry_box">
                                                <option value="1">1 minute</option>
                                                <option value="3">3 minutes</option>
                                                <option value="5">5 minutes</option>
                                            </select>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            <div id="silverlight-options">
                                <table border='0' cellpadding='0' cellspacing='0'>
                                    <tr>
                                        <td colspan="3" class="stream_group1_row" style="font-weight: bold; padding-bottom: 3px">Stream Group 1</td>
                                    </tr>
                                    <tr class="stream_group1_row silverlight-only">
                                        <td style="padding-left: 10px; padding-right: 15px">Publishing Point</td>
                                        <td style="width: 15px">:</td>
                                        <td><input name="publishing_point1" class="entry_box" style="width:460px;text-align:left" id="publishing_point1" type="text"></td>
                                    </tr>
                                    <tr class="stream_group1_row silverlight-only">
                                        <td style="padding-left: 10px">Authentication</td>
                                        <td>:</td>
                                        <td>
                                            <select name="publishing_point_auth1" id="publishing_point_auth1">
                                                <option value="none">None</option>
                                                <option value="basic">Basic</option>
                                                <option value="digest">Digest</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr class="stream_group1_row publishing_point_auth1_setting_row silverlight-only">
                                        <td style="padding-left: 10px" align="left">Username</td>
                                        <td>:</td>
                                        <td>
                                            <input name="publishing_point_username1" class="entry_box" style="width:120px;text-align:left" id="publishing_point_username1" type="text">
                                        </td>
                                    </tr>
                                    <tr class="stream_group1_row publishing_point_auth1_setting_row silverlight-only">
                                        <td style="padding-left: 10px" align="left">Password</td>
                                        <td>:</td>
                                        <td>
                                            <input name="publishing_point_password1" class="entry_box" style="width:120px;text-align:left" id="publishing_point_password1" type="text">
                                        </td>
                                    </tr>
                                    <tr style="height: 15px; display:none;"><td colspan="3"></td></tr>
                                    <tr>
                                        <td colspan="3" class="stream_group2_row" style="display:none; font-weight: bold; padding-bottom: 3px">Stream Group 2</td>
                                    </tr>
                                    <tr class="stream_group2_row" style="display:none;">
                                        <td style="padding-left: 10px">Publishing Point</td>
                                        <td>:</td>
                                        <td><input name="publishing_point2" class="entry_box" style="width:460px;text-align:left" id="publishing_point2" type="text"></td>
                                    </tr>
                                    <tr class="stream_group2_row" style="display:none">
                                        <td style="padding-left: 10px">Authentication</td>
                                        <td>:</td>
                                        <td>
                                            <select name="publishing_point_auth2" id="publishing_point_auth2">
                                                <option value="none">None</option>
                                                <option value="basic">Basic</option>
                                                <option value="digest">Digest</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr class="stream_group2_row publishing_point_auth2_setting_row" style="display:none">
                                        <td style="padding-left: 10px">Username</td>
                                        <td>:</td>
                                        <td>
                                            <input name="publishing_point_username2" class="entry_box" style="width:120px;text-align:left" id="publishing_point_username2" type="text">
                                        </td>
                                    </tr>
                                    <tr class="stream_group2_row publishing_point_auth2_setting_row" style="display:none">
                                        <td style="padding-left: 10px">Password</td>
                                        <td>:</td>
                                        <td>
                                            <input name="publishing_point_password2" class="entry_box" style="width:120px;text-align:left" id="publishing_point_password2" type="text">
                                        </td>
                                    </tr>
                                    <tr style="height: 15px"><td colspan="3"></td></tr>
                                    <tr>
                                        <td>Manifest type:</td>
                                        <td>:</td>
                                        <td>
                                            <select id="manifest_type" name="manifest_type">
                                                <option value="0">DASH only</option>
                                                <option value="1">fMP4 HLS only</option>
                                                <option value="2">DASH and fMP4 HLS</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr style="height: 15px"><td colspan="3"></td></tr>
                                           <tr>
                                        <td>Fragment size</td>
                                        <td>:</td>
                                        <td>
                                            <select id="mp4_frag_size" name="mp4_frag_size">
                                                <option value="2">2</option>
                                                <option value="3">3</option>
                                                <option value="4">4</option>
                                            </select>
                                            &nbsp;second(s)
                                        </td>
                                    </tr>
                                    <tr style="height: 15px"><td colspan="3"></td></td>
                                    <tr>
                                        <td>Caption type</td>
                                        <td>:</td>
                                        <td>
                                            <select id="silverlight_caption_format" name="silverlight_caption_format">
                                                <option value="1">TTML</option>
                            <option value="2">SEI</option>
                            <option value="3">TTML and SEI</option>
                            <option value="4">WebVTT</option>
                                        </select>
                                        </td>
                                    </td>
                                </table>
                            </div>
                            <div id="rtp-options">
                                <table border='0' cellpadding='0' cellspacing='0'>
                                    <?php
                                    for ($iGroup = 1; $iGroup <= MAX_STREAM_GROUPS; $iGroup++) {
                                        echo "<tr class='stream_group{$iGroup}_row' id='rtp_stream_name_group{$iGroup}_row'>\n";
                                        echo "    <td style='padding-bottom: 3px; font-weight: bold' colspan='7'>Stream Group $iGroup</td>\n";
                                        echo "</tr>\n";

                                        for ($iStreamInGroup = 0; $iStreamInGroup < MAX_VIDEO_STREAMS; $iStreamInGroup++) {
                                            $iStream = (($iGroup - 1) * MAX_VIDEO_STREAMS) + ($iStreamInGroup - 0);

                                            echo "<tr class='stream_group{$iGroup}_row".((CONFIG_MODE == 1 && $iStream>0) ? "style='display:none;'" : "")."'>\n";
                                            echo "    <td style='padding-left: 10px;'>Stream ".($iStreamInGroup+1)."&nbsp;</td>\n";
                                            echo "    <td style='text-align: center; width: 40px'>&rarr;</td>\n";
                                            echo "    <td style='padding-right: 8px'>Address</td>";
                                            echo "    <td><input name='rtp_address{$iStream}' class='entry_box' style='width:110px' id='rtp_address{$iStream}' type='text'></td>\n";
                                            echo "    <td style='width: 30px'></td>\n";
                                            echo "    <td style='padding-right: 8px'>Base Port</td>\n";
                                            echo "    <td><input name='rtp_port{$iStream}' class='entry_box integer_field' style='width:50px' id='rtp_port{$iStream}' type='text'></td>\n";
                                            echo "</tr>\n";
                                        }
                                        echo "<tr style='height: 15px'><td colspan='3'></td></tr>\n";
                                    }

                                    ?>

                                <table border='0' cellpadding='0' cellspacing='0'>
                                    <tr>
                                        <td>SDP Path</td>
                                        <td>:</td>
                                        <td colspan="5"><input name="sdp_path" class="entry_box" style="width:280px" id="sdp_path" type="text"></td>
                                    </tr>
                                    <tr>
                                        <td style="padding-right: 15px">SDP Session Name</td>
                                        <td style="width: 15px">:</td>
                                        <td colspan="5"><input name="sdp_session_name" class="entry_box" style="width:280px" id="sdp_session_name" type="text"></td>
                                    </tr>
                                    <tr>
                                        <td>Multicast TTL</td>
                                        <td>:</td>
                                        <td colspan="5"><input name="rtp_multicast_ttl" class="entry_box integer_field" style="width:50px" id="rtp_multicast_ttl" type="text"></td>
                                    </tr>
                                </table>
                            </div>
                            <div id="multirate_ts-options" <?php if (CONFIG_MODE == 1 || ENABLE_MULTITS == 0) echo "class='force_hide'" ?>>
                                <table border='0' cellpadding='0' cellspacing='0'>
                                    <?php
/*
                                    for ($iGroup = 1; $iGroup <= MAX_STREAM_GROUPS; $iGroup++) {
                                        echo "<tr class='stream_group{$iGroup}_row' id='multi_ts_stream_name_group{$iGroup}_row'>\n";
                                        echo "    <td colspan='7' style='font-weight: bold; padding-bottom: 3px'>Stream Group $iGroup</td>\n";
                                        echo "</tr>\n";

                                            echo "<tr class='stream_group{$iGroup}_row".((CONFIG_MODE == 1 && $iStream>0) ? "style='display:none;'" : "")."'>\n";
                                            echo "    <td align='left' style='padding-left: 10px' colspan=3>Output network interface:</td>\n";
                                            echo "    <td colspan=4>";?>
                                                    <select name="multi_ts_ethernet_interface<?=$iGroup?>" id="multi_ts_ethernet_interface<?=$iGroup?>">
                                                        <?php
                                                        foreach ($machine->getNetworkInterfaces() as $eth) {
                                                            if ($eth->active()) {
                                                                echo ("<option value=\"{$eth->getName()}\">{$eth->getName()}</option>\n");
                                                            }
                                                        }
                                                        ?>
                                                    </select>
                                    <?php   echo "    </td>\n";
                                            echo "</tr>\n";
                                        for ($iStreamInGroup = 0; $iStreamInGroup < MAX_VIDEO_STREAMS; $iStreamInGroup++) {
                                            $iStream = (($iGroup - 1) * MAX_VIDEO_STREAMS) + ($iStreamInGroup - 0);

                                            echo "<tr class='stream_group{$iGroup}_row".((CONFIG_MODE == 1 && $iStream>0) ? "style='display:none;'" : "")."'>\n";
                                            echo "    <td align='left' style='padding-left: 10px'>Stream ".($iStreamInGroup+1)."</td>\n";
                                            echo "    <td style='text-align: center; width: 40px'>&rarr;</td>\n";
                                            echo "    <td style='padding-right: 8px'>Address</td>\n";
                                            echo "    <td align='left'><input name='multi_ts_address{$iStream}' class='entry_box' style='width:110px' id='multi_ts_address{$iStream}' type='text'></td>\n";
                                            echo "    <td width='30px'></td>\n";
                                            echo "    <td style='padding-right: 8px'>Base Port</td>\n";
                                            echo "    <td><input name='multi_ts_port{$iStream}' class='entry_box integer_field' style='width:50px' id='multi_ts_port{$iStream}' type='text'></td>\n";
                                            echo "</tr>\n";
                                        }
                                        echo "<tr style='height: 10px'><td colspan='3'></td></tr>\n";
                                    }
*/
                                ?><table border='0' cellpadding='0' cellspacing='0'>
<?php
                                            echo "<tr>\n";
                                            echo "    <td>Output network interface</td>\n";
                                            echo "    <td>:</td>\n";
                                            echo "    <td colspan=5>";?>
                                                    <select name="multi_ts_ethernet_interface1" id="multi_ts_ethernet_interface1">
                                                        <?php
                                                        foreach ($machine->getNetworkInterfaces() as $eth) {
                                                            if ($eth->active()) {
                                                                echo ("<option value=\"{$eth->getName()}\">{$eth->getName()}</option>\n");
                                                            }
                                                        }
                                                        ?>
                                                    </select>
                                    <?php   echo "    </td>\n";
                                            echo "</tr>\n";
                                   ?>
                                    <tr>
                                        <td>Multicast TTL</td>
                                        <td>:</td>
                                        <td colspan="5"><input name="multi_ts_multicast_ttl" class="entry_box integer_field" style="width:50px" id="multi_ts_multicast_ttl" type="text"></td>
                                    </tr>
                                    <tr style="height: 28px">
                                        <td style="padding-right: 15px">PID Generation</td>
                                        <td style="width: 15px">:</td>
                                        <td colspan="5">
                                            <select id="multi_ts_pid_mode" name="multi_ts_pid_mode">
                                                <option value="0">Same PID values for all streams</option>
                                                <option value="1">Unique PID values for each stream</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr style="height: 28px">
                                        <td style="padding-right: 15px">Encoder Boundary Points</td>
                                        <td style="width: 15px">:</td>
                                        <td colspan="5">
                                            <select id="ebp_enable" name="ebp_enable">
                                                <option value="0">Disable</option>
                                                <option value="1">Enable</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr style="height: 28px">
                                        <td style="padding-right: 15px">SCTE35 Passthru</td>
                                        <td style="width: 15px">:</td>
                                        <td colspan="5">
                                            <select id="mv_scte35_passthru" name="mv_scte35_passthru">
                                                <option value="0">Disable</option>
                                                <option value="1">Enable</option>
                                            </select>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>


                        <br>
                        <hr/>
<div id="video-profiles" class="ui-tabs ui-widget ui-widget-content ui-corner-all">
<b>Video Profiles</b>
<?php

   $max_width = 1920;
   $max_height = 1080;

   if(ENABLE_4K_OUTPUT)
   {
       $max_width = 4096;
       $max_height = 2160;
   }
echo "<table class='profiles' border='0' cellpadding='0' cellspacing='0'>\n";
echo "    <tr height='35px'>\n";
echo "        <th>Name</th>\n";
echo "        <th>Width</th>\n";
echo "        <th>Height</th>\n";
echo "        <th>Framerate</th>\n";
echo "        <th>Encoder Profile</th>\n";
echo "        <th>Bitrate (kbps)</th>\n";
echo "        <th style='display:none'>Rate Control</th>\n";
echo "        <th style='display:none'>VBR Max<br>Bitrate</th>\n";
echo "    </tr>\n";
echo "    <tr height='35px' id='videos_proto' class='videos' style='display:none'>\n";
echo "        <td><input class='vid_names' name='vid_name[]' type='text' readonly onfocus='this.blur()' style='border:0px'></input></td>\n";
echo "        <td><input type='number' name='vid_width[]' min=1 max=$max_width  value=1920 class='vid_width entry_box stream_setting stream_video_setting integer_field' style='width: 45px; color: black;'></td>\n";
echo "        <td><input type='number' name='vid_height[]' min=1 max=$max_height value=1080  class='vid_height entry_box stream_setting stream_video_setting integer_field' style='width: 45px; color: black;'></td>\n";
echo "        <td><select type='number' name='vid_framerate[]'  class='vid_framerate entry_box stream_setting stream_video_setting integer_field' style='width: 160px; color: black;'><option value='0'>Full (same as input)</option><option value='1'>1/2</option><option value='2'>1/4</option><option value='3'>2</option></select></td>\n";
echo "        <td><select type='number' name='vid_encoder_profile[]'  class='vid_encoder_profile entry_box stream_setting stream_video_setting integer_field' style='width: 60px; color: black;'><option value='0'>Base</option><option value='1'>Main</option><option value='2'>High</option></select></td>\n";
echo "        <td><input type='number' name='vid_mux_target[]' min=1 max=9999999 value=2000 class='vid_mux_target entry_box stream_setting stream_video_setting integer_field' style='width: 60px; color: black;'></td>\n";
echo "        <td style='display:none'><select name='vid_rate_ctl[]' class='vid_rate_ctl'><option value=0>CBR</option><option value=1>VBR</option></select></td>\n";
echo "        <td style='display:none'><input type='number' name='vid_vbr_max_bitrate[]' value=0 class='vid_vbr_max_bitrate entry_box stream_setting stream_video_setting integer_field' style='width: 45px; color: black;'></td>\n";
echo "    </tr>\n";
echo "</table>\n";
?>
<button id="add_vid" type="button">Add new</button>
<button id="rem_vid" type="button">Remove row</button>
</div>
<br>
<div id="audio-profiles" class="ui-tabs ui-widget ui-widget-content ui-corner-all">
<b>Audio Profiles</b>
<?php
echo "<table class='profiles' border='0' cellpadding='0' cellspacing='0'>\n";
echo "    <tr height='35px'>\n";
echo "        <th>Name</th>\n";
echo "        <th>Source Stream</th>\n";
echo "        <th>Codec</th>\n";
echo "        <th>Bitrate</th>\n";
echo "        <th>Channels</th>\n";
echo "        <th>AC3 Dialnorm</th>\n";
echo "        <th>Volume<br>(0-200%)</th>\n";
echo "    </tr>\n";
echo "    <tr id='audios_proto' class='audios' style='display:none' height='35px'>\n";
echo "        <td><input name='aud_names[]' class='aud_names' type='text' readonly onfocus='this.blur()' style='border:0px'></input></td>\n";
echo "        <td><select name='aud_source_stream[]' class='aud_source_stream'>";
echo "                <option value=\"0\">Primary Audio</option>\n";
echo "                <option value=\"1\">Secondary Audio</option>\n";
echo "                <option value=\"2\">Third Audio</option>\n";
echo "            </select></td>\n";
echo "        <td><select name='aud_codec[]' class='aud_codec' onChange='stream_audio_populate()'><option val='AAC'>AAC</option></select></td>\n";
echo "        <td><select name='aud_bitrate[]' class='aud_bitrate'></select></td>\n";
echo "        <td><select name='aud_channels[]' class='aud_channels'>\n";
echo "            <option value=\"2\">Stereo (2.0)</option>\n";
echo "            <!--<option value=\"6\">5.1 (L,R,C,LFE,SL,SR)</option> -->\n";
echo "        </select></td>\n";
echo "        <td><select name='aud_dialnorm[]' class='aud_dialnorm'>\n";
echo "            <option value=\"-1\">Passthrough</option>\n";
echo "            <option value=\"0\">Reserved</option>\n";
for($i=1; $i < 32; $i++){
echo "            <option value=\"$i\">$i</option>\n";
}
echo "        </select></td>\n";
echo "        <td><input name='aud_volume[]' class='aud_volume' min=0 max=200 value=100 class='entry_box integer_field' style='width:50px' type='number'></td>\n";
echo "    </tr>\n";
echo "</table>\n";
?>
<!-- Apr 23, 2025: Supporting only one audio profile -->
<!-- May 14, 2025 undoing -->
<button id="add_aud" type="button">Add new</button>
<button id="rem_aud" type="button">Remove row</button>
</div>
<br>
<div id="stream-profiles" class="ui-tabs ui-widget ui-widget-content ui-corner-all">
<b>Stream Profiles</b>
<?php
echo "<table class='profiles' border='0' cellpadding='0' cellspacing='0'>\n";
echo "    <tr height='35px'>\n";
echo "        <th>Enabled</th>\n";
echo "        <th>IP</th>\n";
echo "        <th>Port</th>\n";
echo "        <th>Video Profile</th>\n";
echo "        <th>Audio Profiles<br><small>Ctrl-Click to select multiple or deselect</small></th>\n";
echo "    </tr>\n";
echo "    <tr id='outputs_proto' class='outputs' style='display:none' height='35px'>\n";
echo "        <td><input name='out_enabled[]' class='out_enabled' type='checkbox'></td>\n";
echo "        <td><input name='out_multi_ts_address[]' type='text' class='out_multi_ts_address entry_box' style='width: 110px; color: black;'></input></td>\n";
echo "        <td><input name='out_multi_ts_port[]' type='number' class='out_multi_ts_port entry_box integer_field' style='width: 60px; color: black;'></input></td>\n";
echo "        <td><select name='out_video_profile[]' class='out_video_profile'></select></td>\n";
echo "        <td><select name='out_audio_profile[]' class='out_audio_profile' multiple style='width:200px;'></select></td>\n";
echo "    </tr>\n";
echo "</table>\n";
?>
<button id="add_out" type="button">Add new</button>
<button id="rem_out" type="button">Remove row</button>
</div>

<?php
for ($num = 1; $num <= MAX_STREAM_GROUPS; $num++)
{
if( CONFIG_MODE == 1)
{
    echo "<div style='line-height: 25px; margin-left: 3px'>";
    echo "    <span>Output framerate : </span>";
    echo "    <select name='output_framerate' id='output_framerate' onchange='output_framerate_changed(this)'>";
    echo "    <option value='0'>Same as input</option>";
    echo "    <option value='1'>1/2 of input</option>";
    echo "    </select>";
    echo "</div>";
}
echo "<table style='display:none' border='0' cellpadding='0' cellspacing='0'>\n";
echo "    <tr height='35px'>\n";
echo "        <td>\n";
echo "            <label><input id='stream_group_checkbox$num' type='checkbox' style='vertical-align:-2px' onclick='group_checkbox_clicked(this, $num)'>Stream Group $num</label>\n";
echo "        </td>\n";
echo "        <td style='padding-left: 8px'>\n";
echo "            <select id='stream_group_select$num' onchange='group_preset_selected(this, $num)'>\n";
if( CONFIG_MODE != 1)
{
    echo "            <option value='0'>iPod Touch/iPhone</option>\n";
    echo "            <option value='1'>iPad</option>\n";
    echo "            <option value='2'>PC (High profile)</option>\n";
    echo "            <option value='3'>PC (Main profile)</option>\n";
    echo "            <option value='4'>Smartphone (Baseline profile)</option>\n";
}
else
{
    echo "            <option value='3'>H.264 Main Profile</option>\n";
    echo "            <option value='4'>H.264 Baseline Profile</option>\n";
}
echo "            </select>\n";
echo "        </td>\n";
echo "    </tr>\n";
echo "</table>\n";
echo "<table id='stream_group_streams$num' border='0' cellpadding='0' cellspacing='0' style='display:none;width: ".(CONFIG_MODE == 1 ? "70%" : "100%")."'>\n";
echo "    <tr>\n";
echo "        <td colspan='5'></td>\n";
echo "        <td colspan='".(CONFIG_MODE != 1 ? 6 : 4)."' style='border-bottom:1px solid black; text-align:center; padding-left:2px; padding-bottom: 3px'>Video Format</td>\n";
echo "        <td></td>\n";
echo "        <td colspan='2' style='border-bottom:1px solid black; text-align:center; padding-left:2px; padding-bottom: 3px'>Audio Format</td>\n";
echo "        <td></td>\n";
echo "        <td colspan='3' style='border-bottom:1px solid black; text-align:center; padding-left:2px; padding-bottom: 3px'>Bitrate (kbps)</td>\n";
echo "        <td></td>\n";
echo "    </tr>\n";
echo "    <tr style='font-size:12px'>\n";
echo "        <td colspan='3'></td>\n";
echo "        <td style='text-align: center'>Audio<br>Only</td>\n";
echo "        <td width='10px'></td>\n";
echo "        <td>Preset</td>\n";
echo "        <td style='text-align: right'>Width</td>\n";
echo "        <td style='text-align: right'>Height</td>\n";
echo "        <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: center'").">\n";
echo "            Codec </td>\n";
echo "        <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: right'").">\n";
echo "            Framerate </td>\n";
echo "        <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: center'").">\n";
echo "            Profile </td>\n";
echo "        <td width='10px'></td>\n";
echo "        <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: center'").">\n";
echo "            Bitrate </td>\n";
echo "        <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: center'").">\n";
echo "            Channels </td>\n";
echo "        <td width='10px'></td>\n";
echo "        <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "").">\n";
echo "            Rate<br>Control</td>\n";
echo "        <td class='cbr_bitrate_field' style='text-align: right'>Mux Target</td>\n";
echo "        <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: right'").">\n";
echo "            VBR Max</td>\n";
echo "        <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: center'").">\n";
echo "            Image<br>Overlay</td>\n";
echo "    </tr>\n";
    for ($stream = 1; $stream <= MAX_VIDEO_STREAMS; $stream++)
    {
        $idx = (($num - 1) * MAX_VIDEO_STREAMS) + ($stream - 1);

echo "<tr class='stream_row' id='stream_row$idx'>\n";
echo "    <td width='12px'></td>\n";
echo "    <td>\n";
echo "        <label id='stream_active_label$idx'><input name='stream_active$idx' id='stream_active$idx' type='checkbox' style='vertical-align:-2px'><nobr>".(CONFIG_MODE!=1 ? "Stream" : "Stream")." $stream</nobr></label>\n";
echo "    </td>\n";
echo "    <td width='10px'></td>\n";
echo "    <td style='text-align: center'>\n";
echo "        <input name='stream_audio_only$idx' class='stream_setting' id='stream_audio_only$idx' type='checkbox' style='vertical-align:-2px'>\n";
echo "    </td>\n";
echo "    <td style='width: 5px'></td>\n";
echo "    <td>\n";
echo "        <select id='stream_preset$idx' class='stream_setting stream_video_setting' onChange='video_preset_selected(this, $idx)'>\n";
echo "         </select>\n";
echo "    </td>\n";
echo "    <td style='text-align: right'>\n";
echo "        <input id='stream_width$idx' name='stream_width$idx' class='entry_box stream_setting stream_video_setting integer_field' style='width:45px' type='text'>";
echo "    </td>\n";
echo "    <td style='text-align: right'>\n";
echo "        <input id='stream_height$idx' name='stream_height$idx' class='entry_box stream_setting stream_video_setting integer_field' style='width:45px' type='text'>";
echo "    </td>\n";
echo "    <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: right'").">\n";
echo "                                    <select name=\"stream_codec$idx\" id=\"stream_codec$idx\"></select>";
echo "    </td>\n";
echo "    <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: right'").">\n";
echo "        <select id='stream_framerate$idx' name='stream_framerate$idx' class='stream_setting stream_video_setting' style='width:60px;'>";
echo "    </td>\n";
echo "    <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "").">\n";
echo "        <select id='stream_profile$idx' name='stream_profile$idx' class='stream_setting stream_video_setting'>\n";
echo "            <option value='0'>Base</option>\n";
echo "            <option value='1'>Main</option>\n";
echo "            <option value='2'>High</option>\n";
echo "        </select>\n";
echo "    </td>\n";
echo "    <td></td>\n";
echo "    <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: left'").">\n";
echo "                                    <b class=\"stream_audio2\">Primary:</b><br> <select name=\"stream_audio_bitrate$idx\" id=\"stream_audio_bitrate$idx\" class=\"stream_audio_bitrate stream_audio_select\" style=\"width:100%;\"></select><br>";
echo "                                    <b class=\"stream_audio2\">Secondary:</b><br> <select name=\"stream_audio_bitrate2_$idx\" id=\"stream_audio_bitrate2_$idx\" class=\"stream_audio_bitrate2 stream_audio_select stream_audio2\"style=\"width:100%;\"></select>";
echo "    </td>\n";
echo "    <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: right'").">\n";
echo "        <br><select name=\"stream_audio_channels$idx\" id=\"stream_audio_channels$idx\" onChange=\"stream_audio_populate()\" style=\"width:100%\">";
echo "            <option value=\"2\">Stereo (2.0)</option>\n";
echo "            <option value=\"6\">5.1 (L,R,C,LFE,SL,SR)</option>\n";
echo "        </select><br><br>\n";
echo "        <select name=\"stream_audio_channels2_$idx\" id=\"stream_audio_channels2_$idx\" class=\"stream_audio2\" onChange=\"stream_audio_populate()\" style=\"width:100%\">";
echo "            <option value=\"2\">Stereo (2.0)</option>\n";
echo "        </select>\n";
echo "    </td>\n";
echo "    <td></td>\n";
echo "    <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "").">\n";
echo "        <select id='stream_vbr$idx' name='stream_vbr$idx' class='stream_setting stream_video_setting'>\n";
echo "            <option value='0'>CBR</option>\n";
echo "            <option value='1'>VBR</option>\n";
echo "        </select>\n";
echo "    </td>\n";
echo "    <td style='text-align: right'>\n";
echo "        <input id='stream_bitrate$idx' name='total_bitrate$idx' class='entry_box stream_setting stream_video_setting integer_field' style='width:50px' type='text'>";
echo "    </td>\n";
echo "    <td ".(CONFIG_MODE == 1 ? "style='display: none'" : "style='text-align: right'").">\n";
echo "        <input id='stream_max_bitrate$idx' name='stream_max_bitrate$idx' class='stream_setting stream_video_setting entry_box integer_field' style='width:50px' type='text'>";
echo "    </td>\n";
echo "    <td ".(CONFIG_MODE == 1 ? "style='display: none; text-align: right'" : "style='text-align: center'").">\n";
echo "        <input name='stream_enable_image_overlay$idx' id='stream_enable_image_overlay$idx' class='stream_setting stream_video_setting' type='checkbox' style='vertical-align:-2px'> <a class=\"overlay_set_link\" onclick='show_overlay($idx)' style='color:blue';cursor: pointer;'>Set</a><input type=\"hidden\" id=\"image_overlay_params$idx\" name=\"image_overlay_params$idx\">\n";
echo "    </td>\n";
echo "</tr>\n";
echo "<td colspan='21' style='border-bottom:1px solid black; text-align:center; padding-left:2px; padding-bottom: 3px'></td>\n";

    }
echo "<tr height='10px'></tr>\n";
echo "</table>\n";
if ($num == 1)
echo "<hr/>\n";
}
?>

                        <!-- Multirate TS Segment File Archival -->
                        <div id="multi-output-options-div" style="margin-left: 16px; width:95%"<?php if (CONFIG_MODE==1) echo(' class="force_hide"'); ?>>
                           <div id="multi-output-options">
                                <div style="font-weight:bold; margin-bottom:.8em;">
                                Origin Server Publish
                                </div>
                                <table border='0' cellpadding='0' cellspacing='0'>
                                    <tr>
                                        <td style="padding-right: 15px">Origin Server URL</td>
                                        <td width="15px">:</td>
                                        <td><input name="origin_server_address" class="entry_box" style="width:400px" id="origin_server_address" type="text"><span class="muted"> (http://IP:PORT) </span></td>
                                    </tr>
                                    <tr>
                                        <td style="padding-right: 15px">Origin Server Medianame</td>
                                        <td width="15px">:</td>
                                        <td><input name="origin_server_medianame" class="entry_box" style="width:200px" id="origin_server_medianame" type="text"><span class="muted"> (Must be unique)</td>
                                    </tr>
                                    <tr>
                                        <td>Username</td>
                                        <td>:</td>
                                        <td><input name="origin_server_username" class="entry_box" style="width:120px" id="origin_server_username" type="text"><span> (recommended)</span></td>
                                    </tr>
                                    <tr>
                                        <td>Password</td>
                                        <td>:</td>
                                        <td><input name="origin_server_password" class="entry_box" style="width:120px" id="origin_server_password" type="text"><span> (recommended)</span></td>
                                    </tr>
                                </table>
                                <button type="button" id="testOriginButton" style="line-height: 20px">Check Origin Server Connectivity</button>

                                <!-- Put the ESAM Server stuff here -->

                                <hr>
                                <div style="font-weight:bold; margin-bottom:.8em;">
                                ESAM Server
                                </div>
                                <table border='0' cellpadding='0' cellspacing='0'>
                                    <tr>
                                        <td style="padding-right: 15px">ESAM Server URL</td>
                                        <td width="15px">:</td>
                                        <td><input name="esam_server_address" class="entry_box" style="width:400px" id="esam_server_address" type="text"></td>
                                    </tr>
                                    <tr>
                                        <td>Request Endpoint</td>
                                        <td>:</td>
                                        <td><input name="esam_request_endpoint" class="entry_box" style="width:240px" id="esam_request_endpoint" type="text"></td>
                                    </tr>
                                    <tr>
                                        <td>Hostname</td>
                                        <td>:</td>
                                        <td><input name="esam_hostname" class="entry_box" style="width:240px" id="esam_hostname" type="text"></td>
                                    </tr>
                                </table>



                <div id="segment-file-archival-div">
                                <hr/>
                                <div style="font-weight:bold; margin-bottom:.8em;">
                                Segment File Archival
                                </div>
                                <table border='0' cellpadding='0' cellspacing='0'>
                                    <tr id="multi_output_file_mode_row" class="multi_output_file_option">
                                        <td valign="top">Mode</td>
                                        <td valign="top">:</td>
                                        <td valign="top"colspan="6">
                                            <table style="margin-top: -3px">
                                                <tr>
                                                    <td><label><input name="multi_output_file_mode" value="0" id="multi_output_file_mode" type="radio" style="vertical-align:-2px" onclick="multi_output_file_mode_selected(0)">Disabled</label></td>
                                                    <td></td>
                                                </tr>
                                                <tr>
                                                    <td><label><input name="multi_output_file_mode" value="1" id="multi_output_file_mode" type="radio" style="vertical-align:-2px" onclick="multi_output_file_mode_selected(1)">Duration</label></td>
                                                    <td id="multi_output_file_max_duration_row"><input name="multi_output_file_max_duration" class="entry_box integer_field" style="width:60px" id="multi_output_file_max_duration" type="text"> minutes</td>
                                                </tr>
                                                <tr class="force_hide">
                                                    <td><label><input name="multi_output_file_mode" value="2" id="multi_output_file_mode" type="radio" style="vertical-align:-2px" onclick="multi_output_file_mode_selected(2)">Max file size</label></td>
                                                    <td  id="multi_output_file_max_size_row"><input name="multi_output_file_max_size" class="entry_box integer_field" style="width:60px" id="multi_output_file_max_size" type="text"> MB</td>
                                                </tr>
                                                <tr class="force_hide">
                                                    <td><label><input name="multi_output_file_mode" value="3" id="multi_output_file_mode" type="radio" style="vertical-align:-2px" onclick="multi_output_file_mode_selected(3)">Unlimited</label></td>
                                                    <td></td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                    <tr id="multi_output_file_format_row" class="multi_output_file_option">
                                        <td style="padding-right: 15px">File format</td>
                                        <td style="width: 15px">:</td>
                                        <td colspan="6">
                                            <select name="multi_output_file_format" id="multi_output_file_format">
                                                <option value="TS">TS</option>
                                                <option value="MP4">MP4</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr id="xx_multi_output_file_active_row" name="xx_multi_output_file_active_row" class="xx_multi_output_file_active_option force_hide">
                                        <td valign="top">Stream Archiving</td>
                                        <td valign="top">:</td>
                                        <td colspan="6">
                                        <?php
                                        // This is unimplemented in the encoder so just output some hidden hardcoded values
                                        for ($iStream = 0; $iStream < MAX_STREAMS; ++$iStream) {
                                            echo("<input name='multi_output_file_active$iStream' id='multi_output_file_active$iStream' type='hidden' checked='checked' style='vertical-align:-2px'>\n");
                                        }
                                        ?>
                                        </td>
                                    </tr>
                                    <tr id="multi_output_file_link_row" class="multi_output_file_option">
                                        <td></td>
                                        <td></td>
                                        <td colspan="6"><a style="color: #06c; text-decoration:underline" href="/output" target="_blank">View output files</a></td>
                                    </tr>
                                </table>
                            </div>
                            </div>
                        </div>
                        <div id="remote-http-options-div" style="margin: 15px">
                        <br>
                        <!-- File Transfer Options -->
                        <hr/>
                           <div style="font-weight:bold; margin-bottom: 10px">File Transfer Options</div>
                           <div style="margin-bottom: 10px">Automatic transfer of metadata, manifest and content files to a remote server.</div>
                           <div style="font-weight:bold; margin-bottom: 10px; margin-top: 10px; text-decoration:underline">Primary Server</div>
                           <div id="remote-http-options">
                                <table border='0' cellpadding='0' cellspacing='0'>
                                    <tr>
                                        <td style="padding-right: 15px">Publishing Address</td>
                                        <td width="15px">:</td>
                                        <td><input name="http_server_address" class="entry_box" style="width:400px" id="http_server_address" type="text"><span class="muted"> (http://, ftp://)</span></td>
                                    </tr>
                                    <tr>
                                        <td style="padding-right: 15px">HTTP Publishing Method</td>
                                        <td width="15px">:</td>
                                        <td>
                                            <select name="http_webdav_method" id="http_webdav_method">
                                                <option value="0">PUT</option>
                                                <option value="1">POST</option>
                                            </select>
                                            <span> (only applies if http://)</span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>Username</td>
                                        <td>:</td>
                                        <td><input name="http_server_username" class="entry_box" style="width:120px" id="http_server_username" type="text"><span> (recommended)</span></td>
                                    </tr>
                                    <tr>
                                        <td>Password</td>
                                        <td>:</td>
                                        <td><input name="http_server_password" class="entry_box" style="width:120px" id="http_server_password" type="text"><span> (recommended)</span></td>
                                    </tr>
                                </table>
                            </div>
                            <div id="remote-http-options-backup" <?php if(!ENABLE_HLS_BACKUP_PUBLISHING){ ?>style="display:none" <?php } ?>>
                            <div style="font-weight:bold; margin-bottom: 10px; margin-top: 10px; text-decoration:underline">Secondary Server (OPTIONAL)</div>
                                <table border='0' cellpadding='0' cellspacing='0'>
                                    <tr>
                                        <td style="padding-right: 15px">Publishing Address</td>
                                        <td width="15px">:</td>
                                        <td><input name="http_server_address_backup" class="entry_box" style="width:400px" id="http_server_address_backup" type="text"><span class="muted"> (http://, ftp://)</span></td>
                                    </tr>
                                    <tr>
                                        <td style="padding-right: 15px">HTTP Publishing Method</td>
                                        <td width="15px">:</td>
                                        <td>
                                            <select name="http_webdav_method_backup" id="http_webdav_method_backup">
                                                <option value="0">PUT</option>
                                                <option value="1">POST</option>
                                            </select>
                                            <span> (only applies if http://)</span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>Username</td>
                                        <td>:</td>
                                        <td><input name="http_server_username_backup" class="entry_box" style="width:120px" id="http_server_username_backup" type="text"></td>
                                    </tr>
                                    <tr>
                                        <td>Password</td>
                                        <td>:</td>
                                        <td><input name="http_server_password_backup" class="entry_box" style="width:120px" id="http_server_password_backup" type="text"></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div id="scrambling-options"  class="option-tab-content master-tab" style="display:none">
                        <table>
                        <tr>
                            <td style="width: 180px">Scrambling Mode</td>
                            <td style="width: 15px">:</td>
                            <td>
                                <select id="scrambling_keymode" onchange="scramblingKeyModeChanged();">
                                <option value="NONE">Disable</option>
                                <option value="DYNAMIC">Dynamic Key</option>
                                <!-- <option value="FIXEDTEK">Fixed TEK</option> -->
                            </select>
                            </td>
                        </tr>
                        <tr class="spacerRow"><td colspan="3"></td></tr>

                        <!-- Source/target Address Options -->
                        <tr style="display:none;">
                            <td></td><td>:</td>
                            <td>
                            In typical scenarios, the encoder output should be directed to the scrambler source input
                            and the target address of the scrambler should be set to the desired destination address
                            for the stream.
                            </td>
                        </tr>

                        <tr style="display:none;">
                            <td>Source Address</td><td>:</td>
                            <td>
                            <input id="scrambling_sourceAddress" class="entry_box" type="text" style="width:200px" />
                            <a style="text-decoration:underline;" href="javascript:void(0)" onclick="$('#scrambling_sourceAddress').val($('#rtp_address0').val());return false;">Copy from encoder</a>
                            </td>
                        </tr>

                        <tr style="display:none;">
                            <td>Source Base Port</td><td>:</td>
                            <td>
                            <input id="scrambling_sourceBasePort" class="entry_box integer_field" type="text" style="width:200px" />
                            <a style="text-decoration:underline;" href="javascript:void(0)" onclick="$('#scrambling_sourceBasePort').val($('#rtp_port0').val());return false;">Copy from encoder</a>
                            </td>
                        </tr>

                        <tr style="display:none;">
                            <td>Target Address</td><td>:</td>
                            <td>
                            <input id="scrambling_targetAddress" class="entry_box" type="text" style="width:200px" />
                            </td>
                        </tr>

                        <tr style="display:none;">
                            <td>Target Base Port</td><td>:</td>
                            <td>
                            <input id="scrambling_targetBasePort" class="entry_box integer_field" type="text" style="width:200px" />
                            </td>
                        </tr>

                        <!--
                        <tr class="scrambleModeOption scrambleGeneralOption">
                            <td>Stream Count</td><td>:</td>
                            <td>
                            <input id="scrambling_streamCount" class="entry_box" type="text" style="width:200px" />
                            </td>
                        </tr>
                        -->

                        <tr class="scrambleGeneralOption">
                            <td>Scramble RTCP</td><td>:</td>
                            <td>
                            <label><input type="checkbox" id="scrambling_scrambleRTCP" style="vertical-align: -2px" />Enable</label>
                            </td>
                        </tr>

                        <tr class="scrambleModeOption scrambleGeneralOption spacerRow"><td colspan="3"></td></tr>

                        <!-- Dynamic Key Options -->
                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>ECMG Server Host</td><td>:</td>
                            <td>
                            <input id="scrambling_ecmgHost" class="entry_box" type="text" style="width:200px" />
                            </td>
                        </tr>
                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>ECMG Server Port</td><td>:</td>
                            <td>
                            <input id="scrambling_ecmgPort" class="entry_box integer_field" type="text" style="width:66px" />
                            </td>
                        </tr>

                        <tr class="scrambleModeOption scrambleDynamicOption spacerRow"><td colspan="3"></td></tr>

                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>ECMG Server Host (Backup)</td><td>:</td>
                            <td>
                            <input id="scrambling_ecmgBackupHost" class="entry_box" type="text" style="width:200px" />
                            </td>
                        </tr>
                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>ECMG Server Port (Backup)</td><td>:</td>
                            <td>
                            <input id="scrambling_ecmgBackupPort" class="entry_box integer_field" type="text" style="width:66px" />
                            </td>
                        </tr>

                        <tr class="scrambleModeOption scrambleDynamicOption spacerRow"><td colspan="3"></td></tr>

                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>Protocol Version</td><td>:</td>
                            <td>
                            <select id="scrambling_protocolVersion">
                                <option value="4">1.4.1</option>
                                <option value="5" selected="">1.5.1</option>
                            </select>
                            </td>
                        </tr>

                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>ECM ID</td><td>:</td>
                            <td>
                            <input id="scrambling_ecmId" class="entry_box integer_field" type="text" style="width:66px" />
                            </td>
                        </tr>
                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>Stream ID</td><td>:</td>
                            <td>
                            <input id="scrambling_streamId" class="entry_box integer_field" type="text" style="width:66px" />
                            </td>
                        </tr>
                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>Channel ID</td><td>:</td>
                            <td>
                            <input id="scrambling_channelId" class="entry_box integer_field" type="text" style="width:66px" />
                            </td>
                        </tr>
                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>Super CAS ID</td><td>:</td>
                            <td>
                            <input id="scrambling_superCasId" class="entry_box integer_field" type="text" style="width:66px" />
                            </td>
                        </tr>

                        <tr class="scrambleModeOption scrambleDynamicOption spacerRow"><td colspan="3"></td></tr>

                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>TEK Rekey Interval (ms)</td><td>:</td>
                            <td>
                            <input id="scrambling_rekeyInterval" class="entry_box integer_field" type="text" style="width:66px" />
                            </td>
                        </tr>

                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>STKM Send Interval (ms)</td><td>:</td>
                            <td>
                            <input id="scrambling_stkmSendInterval" class="entry_box integer_field" type="text" style="width:66px" />
                            </td>
                        </tr>

                        <tr class="scrambleModeOption scrambleDynamicOption">
                            <td>STKM Port</td><td>:</td>
                            <td>
                            <input id="scrambling_stkmPort" class="entry_box integer_field" type="text" style="width:66px" />
                            </td>
                        </tr>


                        <!-- Fixed Key Options -->
                        <tr class="scrambleModeOption scrambleFixedTekOption">
                            <td><span style="color:red">Warning</span></td><td>:</td>
                            <td>
                            Fixed keys are typically only used for testing purposes. Use with
                            caution on production systems.
                            </td>
                        </tr>

                        <tr class="scrambleModeOption scrambleFixedTekOption spacerRow"><td colspan="3"></td></tr>

                        <tr class="scrambleModeOption scrambleFixedTekOption">
                            <td>Transport Encryption Key</td><td>:</td>
                            <td>
                            <input id="scrambling_fixedKeyMaterial" class="entry_box" type="text" style="width:300px" />
                            </td>
                        </tr>

                        <tr class="scrambleModeOption scrambleFixedTekOption">
                            <td>Service Authentication Key</td><td>:</td>
                            <td>
                            <input id="scrambling_authKey" class="entry_box" type="text" style="width:300px" />
                            </td>
                        </tr>

                        <tr class="scrambleModeOption scrambleDynamicOption scrambleFixedTekOption">
                            <td>Stream Authentication</td><td>:</td>
                            <td>
                            <label><input id="scrambling_useAuthentication" type="checkbox" style="vertical-align: -2px" />Enable</label>
                            </td>
                        </tr>

                        <!-- General/Shared Options -->
                        <tr class="scrambleModeOption scrambleGeneralOption spacerRow force_hide"><td colspan="3"></td></tr>

                        <tr class="scrambleModeOption scrambleGeneralOption force_hide">
                            <td>Log Level</td><td>:</td>
                            <td>
                            <select id="scrambling_logLevel">
                                <option value="">None</option>
                                <option value="">Errors</option>
                                <option value="" selected="">Warnings</option>
                                <option value="">Info</option>
                                <option value="">Debug</option>
                            </select>
                            </td>
                        </tr>


                        </table>
                    </div>

                    <style>
                        .help_row { color: #777777; height: inherit !important }
                    </style>

                    <div id="verimatrix-options"  class="option-tab-content master-tab" style="display:none">
                        <table>
                        <tr>
                            <td style="width: 180px">Enable Verimatrix</td>
                            <td style="width: 15px">:</td>
                            <td>
                                <select id="verimatrix_enable" onchange="verimatrixEnableChanged();">
                                <option value="0">Disable</option>
                                <option value="1">Enable</option>
                            </select>
                            </td>
                        </tr>
                        <tr class="spacerRow"><td colspan="3"></td></tr>
                        <tr class="verimatrixOption">
                            <td>ACSM Server Encryptor URL</td>
                            <td>:</td>
                            <td>
                            <input id="verimatrix_encryptor_url" class="entry_box" type="text" style="width:400px;text-align:left" />
                            </td>
                        </tr>
                        <tr class="verimatrixOption">
                            <td>ACSM Server Client URL</td><td>:</td>
                            <td>
                            <input id="verimatrix_client_url" class="entry_box" type="text" style="width:400px;text-align:left" />
                            </td>
                        </tr>
                        <tr class="verimatrixOption help_row">
                            <td colspan="2"></td><td>Leave blank to retrieve with key request (recommended).</td>
                        </tr>
                        <tr class="verimatrixOption spacerRow"><td colspan="3"></td></tr>
                        <tr class="verimatrixOption force_hide">
                            <td>Asset Type</td><td>:</td>
                            <td>
                                <select id="verimatrix_asset_type">
                                <option value="VOD">VOD</option>
                                <option value="DTV">DTV</option>
                            </select>
                            </td>
                        </tr>
                        <tr class="verimatrixOption">
                            <td>Resource ID</td><td>:</td>
                            <td>
                            <input id="verimatrix_resource_id" class="entry_box" type="text" style="width:200px;text-align:left" />
                            </td>
                        </tr>
                        <tr class="verimatrixOption spacerRow"><td colspan="3"></td></tr>
                        <tr class="verimatrixOption">
                            <td>Maximum Segments</td><td>:</td>
                            <td>
                            <input id="verimatrix_max_segments" class="entry_box integer_field" type="text" style="width:66px;text-align:left" /> (0 = fixed key)
                            </td>
                        </tr>
                        <tr class="verimatrixOption help_row">
                            <td colspan="2"></td><td>Number of segments to encrypt with a single key.  Use 0 for fixed key.</td>
                        </tr>
                        <tr class="verimatrixOption spacerRow"><td colspan="3"></td></tr>
                        <tr class="verimatrixOption">
                            <td>IV Mode</td><td>:</td>
                            <td>
                                <select id="verimatrix_iv_mode">
                                <option value="1">Sequence Number</option>
                                <option value="2">Random</option>
                            </select>
                            </td>
                        </tr>
                        <tr class="verimatrixOption help_row">
                            <td colspan="2"></td>
                            <td>
                                 If Random, a cryptographically strong pseudo-random IV is generated and incremented for each segment.
                                 If Media Sequence, the HLS Media Sequence value for the segment will be used.
                        </tr>
                        </table>
                    </div>

                    <div id="nielsen-options"  class="option-tab-content master-tab" style="display:none">
                        <table>
                        <tr>
                            <td style="width: 180px">Nielsen Watermark Decoding</td>
                            <td style="width: 15px">:</td>
                            <td>
                                <select id="nielsen_watermark_decoding_enable" onchange="nielsenEnableChanged();">
                                <option value="0">Disable</option>
                                <option value="1">Enable</option>
                            </select>
                            </td>
                        </tr>
                        <tr class="nielsenOption">
                            <td>Destributor ID</td><td>:</td>
                            <td>
                            <input id="nielsen_distributor_id" class="entry_box" type="text" style="width:200px;text-align:left" />
                            </td>
                        </tr>
                        <tr class="nielsenOption spacerRow"><td colspan="3"></td></tr>
                        <tr class="nielsenOption">
                            <td>Breakout Code</td><td>:</td>
                            <td>
                                <!-- <input id="nielsen_breakout_code" class="entry_box integer_field" type="text" style="width:66px;text-align:left" />  -->
                                <select id="nielsen_breakout_code">
                                <option value="0">0 = Live Content Same TV Ads</option>
                                <option value="3">3 = Content with Same TV Ads for 3 days</option>
                                <option value="7">7 = Content with Same TV Ads for 7 days</option>
                                <option value="9">9 = Content without same TV Ads</option>
                                </select>
                            </td>
                        </tr>
                        <tr class="nielsenOption help_row">
                            <td colspan="2"></td><td>Specifies the Nielsen Crediting Model</td>
                        </tr>
                        <tr class="nielsenOption spacerRow"><td colspan="3"></td></tr>
                        </table>
                    </div>

                    <div id="buydrm-options"  class="option-tab-content master-tab" style="display:none">
                        <table>
                        <tr class="buydrmOption stream_group1_row">
                            <td><b>Stream Group 1</b></td><td></td><td></td>
                        </tr>

                        <tr class="buydrmOption stream_group1_row">
                            <td style="padding-right: 15px">Enable BuyDRM</td><td style="width: 15px">:</td>
                            <td>
                                <select id="buydrm_enable1" onchange="buydrmEnableChanged();">
                                <option value="0">Disable</option>
                                <option value="1">Enable</option>
                            </select>
                            </td>
                        </tr>
                        <tr class="buydrmOption spacerRow"><td colspan="3"></td></tr>

                        <tr class="buydrmOption buydrmOption1">
                            <td>User Key GUID</td><td>:</td>
                            <td>
                            <input id="buydrm_userkey1" class="entry_box" type="text" style="width:300px;text-align:left" />
                            </td>
                        </tr>

                        <tr class="buydrmOption stream_group1_row buydrmOption1">
                            <td>Key ID GUID</td><td>:</td>
                            <td>
                            <input id="buydrm_keyid1" class="entry_box" type="text" style="width:300px;text-align:left" />
                            <button class="guidgen_button">Generate</button>
                            </td>
                        </tr>

                        <tr class="buydrmOption stream_group1_row buydrmOption1">
                            <td>Content ID GUID</td><td>:</td>
                            <td>
                            <input id="buydrm_contentid1" class="entry_box" type="text" style="width:300px;text-align:left" />
                            <button class="guidgen_button">Generate</button>
                            </td>
                        </tr>

                        <tr class="buydrmOption stream_group1_row buydrmOption1">
                            <td>Media ID</td><td>:</td>
                            <td>
                            <input id="buydrm_mediaid1" class="entry_box" type="text" style="width:300px;text-align:left" />
                            </td>
                        </tr>

                        <tr class="buydrmOption spacerRow buydrmOption1"><td colspan="3"></td></tr>


                        <tr class="buydrmOption stream_group2_row">
                            <td><b>Stream Group 2</b></td><td></td><td></td>
                        </tr>

                        <tr class="buydrmOption stream_group2_row">
                            <td>Enable BuyDRM</td><td>:</td>
                            <td>
                                <select id="buydrm_enable2" onchange="buydrmEnableChanged();">
                                <option value="0">Disable</option>
                                <option value="1">Enable</option>
                            </select>
                            </td>
                        </tr>
                        <tr class="buydrmOption spacerRow"><td colspan="3"></td></tr>

                        <tr class="buydrmOption buydrmOption2">
                            <td>User Key GUID</td><td>:</td>
                            <td>
                            <input id="buydrm_userkey2" class="entry_box" type="text" style="width:300px;text-align:left" />
                            </td>
                        </tr>

                        <tr class="buydrmOption stream_group2_row buydrmOption2">
                            <td>Key ID GUID</td><td>:</td>
                            <td>
                            <input id="buydrm_keyid2" class="entry_box" type="text" style="width:300px;text-align:left" />
                            <button class="guidgen_button">Generate</button>
                            </td>
                        </tr>

                        <tr class="buydrmOption stream_group2_row buydrmOption2">
                            <td>Content ID GUID</td><td>:</td>
                            <td>
                            <input id="buydrm_contentid2" class="entry_box" type="text" style="width:300px;text-align:left" />
                            <button class="guidgen_button">Generate</button>
                            </td>
                        </tr>

                        <tr class="buydrmOption stream_group2_row buydrmOption2">
                            <td>Media ID</td><td>:</td>
                            <td>
                            <input id="buydrm_mediaid2" class="entry_box" type="text" style="width:300px;text-align:left" />
                            </td>
                        </tr>

                        <tr class="buydrmOption spacerRow buydrmOption2"><td colspan="3"></td></tr>

                        <tr class="buydrmOption help_row">
                            <td colspan="2"></td>
                            <td>
                                GUID parameters must be a 16-byte GUID in one of the following forms:
                                <ul>
                                    <li>Hyphenated hex: 00000000-0000-0000-0000-000000000000</li>
                                    <li>Hex: 00000000000000000000000000000000</li>
                                    <li>Base64: AAAAAAAAAAAAAAAAAAAAAA==</li>
                                </ul>
                            </td>
                        </tr>

                        <tr class="buydrmOption spacerRow"><td colspan="3"></td></tr>
                        </table>

                    </div>


                    <!-- DEBUG OPTIONS BEGIN -->
                    <div id="debug-options" class="option-tab-content master-tab" style="display:none">
                        <table border="0" cellpadding="0" cellspacing="0" class="settings">
                            <tr>
                                <td width="180px">Save input TS</td>
                                <td width="15px">:</td>
                                <td width="70px"><input name="save_input_ts_file" id="save_input_ts_file" type="checkbox"></td>
                                <td width="30px"></td>
                                <td width="70px"></td>
                                <td>&nbsp;</td>
                            </tr>
                            <tr>
                                <td>Save output TS</td>
                                <td>:</td>
                                <td><input name="save_output_ts_file" id="save_output_ts_file" type="checkbox"></td>
                            </tr>
                            <tr>
                                <td>Input type</td>
                                <td>:</td>
                                <td colspan="2" align="left">
                                     <select name="input_type" id="input_type">
                                         <option value="stream">Stream</option>
                                         <option value="file">File</option>
                                     </select>
                                </td>
                            </tr>
<!--
                            <tr>
                                <td>YUV input file</td>
                                <td>:</td>
                                <td colspan="4"><input name="yuv_file_name" class="entry_box" style="width:300px" id="yuv_file_name" type="text"></td>
                            </tr>
-->
                            <tr>
                                <td>YUV input frame rate</td>
                                <td>:</td>
                                <td><input name="yuv_frame_rate" class="dim_entry" id="yuv_frame_rate" type="text"></td>
                                <td>fps</td>
                            </tr>
                            <tr>
                                <td>YUV input buffer size</td>
                                <td>:</td>
                                <td><input name="yuv_input_buffer_size" class="dim_entry" id="yuv_input_buffer_size" type="text"></td>
                                <td>MB</td>
                            </tr>
<!--
                            <tr>
                                <td>H264 encoder quality</td>
                                <td>:</td>
                                <td>
                                     <select name="h264_encoder_quality">
                                     <option value="1">1</option>
                                     <option value="2">2</option>
                                     <option value="3">3</option>
                                     <option value="4">4</option>
                                     <option value="5">5</option>
                                     <option value="6">6</option>
                                     <option value="7">7</option>
                                     <option value="8">8</option>
                                     <option value="9">9</option>
                                     <option value="10">10</option>
                                     <option value="11">11</option>
                                     <option value="12">12</option>
                                     <option value="13">13</option>
                                     <option value="14">14</option>
                                     <option value="15">15</option>
                                     <option value="16">16</option>
                                     <option value="17">17</option>
                                     </select>
                                </td>
                            </tr>
-->
                            <tr>
                                <td>Delay</td>
                                <td>:</td>
                                <td><input name="delay" class="dim_entry" id="delay" type="text"></td>
                                <td colspan="2" align="left">(HH:MM:SS)</td>
                            </tr>
<!--
                            <tr>
                                <td>Buffer delay</td>
                                <td>:</td>
                                <td><input name="buffer_delay" class="dim_entry" id="buffer_delay" type="text"></td>
                                <td>ms</td>
                            </tr>
-->
                            <tr>
                                <td>Simulated interlaced mode</td>
                                <td>:</td>
                                <td>
                                     <select name="simulated_interlaced_mode" id="simulated_interlaced_mode">
                                     <option value="0">Off</option>
                                     <option value="1">On</option>
                                     </select>
                                </td>
                            </tr>

                        </table>
                    </div>
<!-- DEBUG OPTIONS END -->
                </div>
            </form>
            </div>
        </div>
    </div>
</div>

    <script type="text/JavaScript">
    $('input[name="output_interface"]').bind('change', function(event) {
        const appleHLSMode = $('input[name="output_interface"]:checked').filter(() => $(this).val().includes('APPLE')).length > 0;
        $("#stream-profiles").toggle(!appleHLSMode);
    })

    String.prototype.myStartsWith = function(str){
     if(this.indexOf(str)===0){
      return true;
     }else{
       return  false;
     }
    };
    function updateRates(){
        var audio_mode = $("#output_audio_format").val();
        var output_mux_rate = $("#output_mux_rate").val();
        if(output_mux_rate > 0 && audio_mode != "passthrough" && audio_mode != "passthroughmax")
        {
                var audio_rate = parseInt($("#output_audio_bitrate0").val()) + parseInt($("#output_audio_bitrate1").val());
                //TODO: Add third audio bitrates
                var pat_rate = (1000/$("#output_pat_rate").val())*188;
                var pmt_rate = (1000/$("#output_pmt_rate").val())*188;
                var pcr_rate = (1000/$("#output_pcr_rate").val())*188;
                if(pat_rate > 0 && pmt_rate > 0 && pcr_rate > 0)
                {
                    var pid_rate = (pat_rate + pmt_rate + pcr_rate);
                    $("#videobps").val(Math.floor((output_mux_rate-audio_rate-pid_rate)*184/188));
                    if($("#videobps").val()<0)
                        $("#videobps").val(0);
                    $("#audiobps").val(audio_rate);
                }
             $("#estbps").show();
        }
        else{
             $("#estbps").hide();
        }
    }

    function disableSelectedAudioOptions(id)
    {
        /* */
        var val_pid = $(".aud_source_stream").map(function(){return $(this).val()}).get(); //Save values
        console.log("enter disableSelectedAudioOptions");
        console.log("val_pid = " + val_pid);

        $(".aud_source_stream").find("option").remove();


        audio_output_names = ["Primary Audio", "Secondary Audio", "Third Audio"];
        const showSecondaryAudio = document.querySelector('.stream_table').textContent.includes('Audio2')
        for(var idx=0; idx < 3; idx++){
           if($("#output_audio_bitrate"+idx).val() != 0 || (idx == 1 && showSecondaryAudio))
               $(".aud_source_stream").append("<option value='" + (idx) + "'>" + audio_output_names[idx] + "</option>");
        }

        if ($(".aud_source_stream").find("option").length == 0) {
            $(".aud_source_stream").append("<option value='-1'>Default</option>").attr("disabled", "disabled");
            $(".aud_source_stream").attr("disabled", "disabled");
        } else {
            $(".aud_source_stream").removeAttr("disabled");
        }
        //Restore previous values
        $.each(val_pid, function(i, s) {
            $(".aud_source_stream").eq(i).val(s);
        });
    }

    function getQueryParameters(str) {
     return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
    }
    function show_overlay(channel) {
          var display_channel = channel+1;
          var params = getQueryParameters($("#image_overlay_params"+channel).val());

          $("#stream_image_overlay_file").val(params["stream_overlay_file" + channel]);
          stream_image_overlay_file_changed();
          $("#stream_image_overlay_position").val(params["stream_overlay_position" + channel]);
          $("#stream_image_overlay_margin_x").val(params["stream_overlay_margin_x" + channel]);
          $("#stream_image_overlay_margin_y").val(params["stream_overlay_margin_y" + channel]);

          $("#stream_image_overlay_alpha").val(params["stream_overlay_alpha" + channel]);
          $("#stream_image_overlay_alpha").change();
          $("#overlaysettings").data("channel", channel).dialog("open").dialog("option","title","Stream "+display_channel+" Image Overlay");
    }
    function save_overlay(channel) {
          var params = "stream_overlay_file" + channel + "=" + $("#stream_image_overlay_file").val()+"";
          params += "&stream_overlay_position" + channel + "=" + $("#stream_image_overlay_position").val();
          params += "&stream_overlay_margin_x" + channel + "=" + $("#stream_image_overlay_margin_x").val();
          params += "&stream_overlay_margin_y" + channel + "=" + $("#stream_image_overlay_margin_y").val();
          params += "&stream_overlay_alpha" + channel + "=" + $("#stream_image_overlay_alpha").val();
            var overlay_width = 0;
            var overlay_height = 0;
            var file = $("#stream_image_overlay_file").val();
            if (file && file.length)
            {
                var image_overlay_res = file.split(".");
                image_overlay_res = image_overlay_res[image_overlay_res.length-2].split("x");
                overlay_width = image_overlay_res[0];
                overlay_height = image_overlay_res[1];
            }

          params += "&stream_overlay_width" + channel + "=" + overlay_width;
          params += "&stream_overlay_height" + channel + "=" + overlay_height;
          $("#image_overlay_params"+channel).val(params);
    }


    var jsonUrl = "json/index.php?" + new Date().getTime();
        function updateBiss()

        {
           if($("#biss_mode").val() == 0 ) //Passthrough
           {
                $(".bissopts").hide();
           }
           else
           {
                $(".bissopts").show();
                if($("#biss_mode").val() == 1 || $("#biss_mode").val() == 2)
                    $(".bisse").hide();
                else
                    $(".bisse").show();
           }
        }
    function trim(str) {
            return str.replace(/^\s+|\s+$/g,"");
    }

    var MAX_STREAMS = <?php echo MAX_STREAMS; ?>;
    var MAX_VIDEO_STREAMS = "<?php echo MAX_VIDEO_STREAMS;?>";
    var MAX_STREAM_GROUPS = "1";//"<?php echo MAX_STREAM_GROUPS;?>";
    var ENABLE_HD_OUTPUT = <?php echo ENABLE_HD_OUTPUT;?>;
    var ENABLE_HD_INPUT = "<?php echo ENABLE_HD_INPUT;?>";
    var ENABLE_4K_OUTPUT = <?php echo ENABLE_4K_OUTPUT;?>;
    var ENABLE_4K_INPUT = "<?php echo ENABLE_4K_INPUT;?>";
    var ENABLE_MULTIRATE = "<?php echo ENABLE_MULTIRATE;?>";
    var ANALOG_CHANNELS = "<?php echo ANALOG_CHANNELS;?>";
    var mpts_discover_cache = null;

    function guid() {
        function _p8(s) {
            var p = (Math.random().toString(16)+"000000000").substr(2,8);
            return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
        }
        return _p8() + _p8(true) + _p8(true) + _p8();
    }

    function is_audio_passthrough(output_audio_format) {
        return output_audio_format == "passthrough" || output_audio_format == "passthroughmax";
    }

    function enable_output_audio_channel(channel, enable)
    {
        $(".audio"+channel+"_heading_row").toggleClass("force_hide", !enable);
        update_audio_controls();
    }

    function update_audio_controls() {
        var input_interface = get_active_input_interface();
        var output_interface = get_active_output_interface();
        var isHdSdiInput = "HD-SDI" == input_interface;
        var output_audio_format = $("#output_audio_format").val();

        // Global audio settings
        var allowPassthrough = "HD-SDI" != input_interface && "HDMI" != input_interface  && "CAPTURE" != input_interface || output_interface == "HDSDI";
        if (!allowPassthrough) {
            if ($("#output_audio_format option[value='passthrough']").length > 0) {
                $("#output_audio_format option[value='passthrough']").remove();
                $("#output_audio_format option[value='passthroughmax']").remove();
            }
            if (output_audio_format == "passthrough" || output_audio_format == "passthroughmax") {
                $("#output_audio_format").val("aac").change();
            }
        } else {
            <?php if (OUTPUT_MUX_TYPE != 2) { ?>
            if ($("#output_audio_format option[value='passthrough']").length == 0) {
                $("<option value='passthroughmax'>Passthrough (Compatibility Mode)</option>").prependTo("#output_audio_format");
                $("<option value='passthrough'>Passthrough</option>").prependTo("#output_audio_format");
            }
            <?php } ?>
        }

        // Per-channel settings
        var enable_volume = !is_audio_passthrough(output_audio_format);
        var isAC3 = output_audio_format == "ac3";
        var isAAC = output_audio_format == "aac";
        var enableStereoMapping = output_audio_format == "ac3" && isHdSdiInput;

        var enableLang = false;
        if (output_interface == "IP" && (input_interface == "HD-SDI" || input_interface == "CAPTURE"))
            enableLang = true;
        else if (output_interface == "RTP" || output_interface == "ATSC")
            enableLang = true

        var NUM_AUDIO_CHANNELS = 3;
        for (var ch = 0; ch < NUM_AUDIO_CHANNELS; ++ch) {
            var chVisible = !$(".audio"+ch+"_heading_row").hasClass("force_hide");
            var bitrate = $("#output_audio_bitrate"+ch);
            var enabled = bitrate.is(":enabled") && bitrate.val() != 0 && chVisible || ch == 0;

            if (ch == 2) {
                var prev_bitrate = $("#output_audio_bitrate1");
                var prev_chVisible = !$(".audio1_heading_row").hasClass("force_hide");
                var prev_enabled = prev_bitrate.is(":enabled") && prev_bitrate.val() != 0 && prev_chVisible;
                if (prev_enabled) {
                    $(".audio"+ch+"_setting_row").toggleClass("force_hide", !enabled);
                    $("#audio_bitrate_row2").toggleClass("force_hide", false);
                    $(".audio2_heading_row").toggleClass("force_hide", false);//Show third audio for now
                    if(output_interface == "MULTITS")
                        $(".stream_audio2").show();
                } else {
                    $("#audio_bitrate_row2").toggleClass("force_hide", true);
                    $(".audio"+ch+"_setting_row").toggleClass("force_hide", true);
                    $(".audio2_heading_row").toggleClass("force_hide", true);
                    $(".stream_audio2").hide();
                }
            } else {
                $(".audio"+ch+"_setting_row").toggleClass("force_hide", !enabled);
            }
            $("#audio_sync_delta_row"+ch).hide();
            if (enabled) {
                enable_option("audio_volume_row"+ch, $("#output_audio_volume"+ch)[0], enable_volume);
                $("#audio_channels_row"+ch).toggleClass("force_hide", !isAC3 && !isAAC);
                $(".audio"+ch+"_ac3_setting_row").toggleClass("force_hide", !isAC3);
                $(".audio"+ch+"_sdi_setting_row").toggleClass("force_hide", !enableStereoMapping);
                $(".audio"+ch+"_5_1_setting_row").toggleClass("force_hide", !(enableStereoMapping && 6 == $("#audio_channels"+ch).val()));
                if (2 == $("#audio_channels"+ch).val())
                    $("#audio"+ch+"_sdi_mapping_row0").toggleClass("force_hide", !(enableStereoMapping && 2 == $("#audio_channels"+ch).val()));

                $("#audio_lang_row"+ch).toggleClass("force_hide", !enableLang);
            }
        }
        if(isHdSdiInput)
        {
            $("#ac3dec_compmod_row").hide();
        }
    }

    function stream_image_overlay_file_changed()
    {
        var selectedFile = $("#stream_image_overlay_file").val();
        var enabled = !!selectedFile && selectedFile.length > 0;
        if (enabled)
        {
            $("#stream_image_overlay_preview_img").attr("src", "json/image_overlay.php?action=preview&file="+selectedFile+"&t="+(new Date()).getTime());
        }

        $(".image_overlay_row").toggleClass("force_hide", !enabled);
        $("#stream_image_overlay_file_delete").attr('disabled',!enabled);
    }

    function image_overlay_file_changed()
    {
        var selectedFile = $("#image_overlay_file").val();
        var enabled = !!selectedFile && selectedFile.length > 0;
        if (enabled)
        {
            $("#image_overlay_preview_img").attr("src", "json/image_overlay.php?action=preview&file="+selectedFile+"&t="+(new Date()).getTime());
        }

        $(".image_overlay_row").toggleClass("force_hide", !enabled);
        $("#image_overlay_file_delete").attr('disabled',!enabled);
    }

    function slate_changed()
    {
        var selectedFile = $("#slate_filename").val();
        //No slate preview desired at this point
        var enabled = !!selectedFile && selectedFile.length > 0;
/*        if (enabled)
        {
            $("#slate_preview_img").attr("src", "json/image_overlay.php?action=preview&file="+selectedFile+"&t="+(new Date()).getTime());
        }*/

        $(".slate_row").toggleClass("force_hide", !enabled);
        $("#slate_file_delete").attr('disabled',!enabled);
    }

    function rtmp_sync_controls() {
        var frm = document.configuration;
        var naming_elem = $("#rtmp_naming");
        var prefix_elem = $("#rtmp_remote_server_address");
        var auto_naming = "auto" == naming_elem.val();

        $("#rtmp_remote_server_address_row").toggleClass("force_hide", !auto_naming);

        var iGroup;
        var iStreamInGroup;

        for (iGroup = 0; iGroup < MAX_STREAM_GROUPS; ++iGroup)
        {
            $("#rtmp_stream_name_group"+(iGroup+1)+"_row").toggleClass("force_hide", auto_naming);

            var group_enabled = $("#stream_group_checkbox"+(iGroup+1)).is(":checked");
            for (iStreamInGroup = 0; iStreamInGroup < MAX_VIDEO_STREAMS; ++iStreamInGroup)
            {
                var iStream = iGroup*MAX_VIDEO_STREAMS + iStreamInGroup;
                var stream_active = frm.elements["stream_active"+iStream];
                if (stream_active)
                {
                    var stream_enabled = group_enabled && stream_active.checked;
                    var stream_name_elem = $("#rtmp_stream_name"+iStream);
                    $("#rtmp_stream_name"+iStream+"_row").toggleClass("force_hide", auto_naming);
                }
            }
        }
    }
        function renameRows(type){
                var name = type.substr(0,type.length-1);
                if(name == "output")
                    $(".out_audio_profile").each(function(i,el){$(el).attr("name","out_audio_profile"+i+"[]")});
                else {
                    var short_name = name.substr(0,3);
                    $("."+short_name+"_names").each(function(i,el){$(el).val(name+"_profile"+i)});
                }
        }
        function addRows(type,numRows,clear=false){
            var rows = $('.'+type), last, newRow;
            if(clear) {
                 rows.slice(1).remove();
                 rows = $('.'+type);
            }

            var num_rows = rows.length;
                num_rows += numRows - 1;
            if(is_multirate_output()){
                if((num_rows > 8) && (type == "audios" || type == "videos"))
                {
                    alert("Maximum of 8 "+type+" rows");
                    return;
                }
                else if((num_rows > 12) && type == "outputs") {
                    alert("Maximum of 12 output stream rows");
                    return;
                }
            }

            for(var i =0; i<numRows; i++){
                last   = $('.'+type).filter(':last');
                newRow = $('#'+type+'_proto').clone();
                newRow.show().insertAfter(last);
                $('.'+type).filter(':last').find('input:not([type="checkbox"])').attr("required","required");
                if(type == "outputs")
                    newRow.find('.out_enabled').val(rows.length+i);

                //newRow.find('.out_img_overlay').val(rows.length+i);
            }

            renameRows(type);

            if(type !=  "outputs")
            {
                updateOutputOptions();
            }

            $("input").bind("invalid", function(){
                var index = $(this).closest('.master-tab').index() - 1;
                switch(index){
                   case 0:
                        select_option0();
                        break;
                   case 1:
                        select_option1();
                        break;
                   case 2:
                        select_option2();
                        break;
                  case 3:
                        select_option3();
                        break;
                  case 4:
                        select_option4();
                        break;
                  case 5:
                        select_option5();
                        break;
                  case 6:
                        select_option6();
                        break;
                }
            });
        }

        function remRows(type){
            $('.'+type).filter(':last').remove();
            if(type != "outputs")
               updateOutputOptions();
        }

        function updateOutputOptions()
        {
            var sel = $(".out_video_profile");
            var sel_clone = $(".out_video_profile :selected").clone();
            var selectValues = $(".vid_names");
            sel.empty();
            $.each(selectValues,function(i,el){
            var val = (i-1)+" - "+$(this).val();
            if(i == 0)
                val = "None";
            sel.append($("<option></option>")
                    .attr("value",(i-1))
                    .text(val));
            });
            sel.each(function(i,el){$(this).val(sel_clone.eq(i).val());});

            sel = $(".out_audio_profile");
            sel_clone = [];
            $(".out_audio_profile").each(function(i,el){sel_clone.push($(this).val());});
            selectValues = $(".aud_names");
            sel.empty();
            $.each(selectValues,function(i,el){
            var val = (i-1)+" - "+$(this).val();
            if(i == 0)
                val = "None";
                sel.append($("<option></option>")
                    .attr("value",(i-1))
                    .text(val));
            if(i == 0)
                sel.val(-1);
            });
            sel.each(function(i,el){$(this).val(sel_clone[i]);});
            sel.css("height",(selectValues.length)*18+"px");

        }

    $().ready(function() {
        get_config_list();
        //Store data as prev value
        var sel = $(".out_video_profile");
        sel.each(function(){$(this).data("prev",$(this).val())});
        sel.change(function(data){
            $(this).data("prev",$(this).val());
        });
        sel = $(".out_audio_profile");
        sel.each(function(){$(this).data("prev",$(this).val());
            $(this).change(function(data){
            $(this).data("prev",$(this).val());
        })});

        $("#output_mux_rate").change(updateRates);
        $("#output_pmt_rate").change(updateRates);
        $("#output_pcr_rate").change(updateRates);
        $("#output_pat_rate").change(updateRates);
        $("#output_audio_bitrate0").change(updateRates);
        $("#output_audio_bitrate1").change(updateRates);
        $("#overlaysettings").dialog({
                autoOpen: false,
                modal: true,
                draggable: true,
                resizable: false,
                width: "auto",
                buttons: {
                     "Back": function() { $(this).dialog("close"); },
                     "Set": function() {save_overlay($(this).data("channel"));$(this).dialog("close");}
                } } ).dialog("widget")
                .find(".ui-dialog-titlebar-close")
                .hide();
        $(".integer_field").numeric({ decimal: false, negative: false });
        $(".signed_integer_field").numeric({ decimal: false, negative: true });
        $(".decimal_field").numeric({ negative: false });

        $('#sdi_input_mode').keyup(function(){
            $(this).blur().focus();
        });

        $( "#output_audio_lang0,#output_audio_lang1,#output_audio_lang2" ).autocomplete({
            source: "json/util.php?action=iso639&ts="+(new Date()).getTime(),
            minLength: 1
        }).click(function() { $(this).select(); });
        $("#add_vid").click( function(e) {
            e.preventDefault();
            addRows('videos',1);
        });
        $("#add_aud").click( function(e) {
            e.preventDefault();
            addRows('audios',1);
        });
        $("#add_out").click( function(e) {
            e.preventDefault();
            addRows('outputs',1);
        });
        $("#rem_vid").click( function(e) {
            e.preventDefault();
            remRows('videos',1);
        });
        $("#rem_aud").click( function(e) {
            e.preventDefault();
            remRows('audios',1);
        });
        $("#rem_out").click( function(e) {
            e.preventDefault();
            remRows('outputs',1);
        });
        $("#configManager").dialog({
            autoOpen: false,
            modal: true,
            draggable: false,
            resizable: false,
            width: "400px",
             "buttons": { "Close": function() { $(this).dialog("close"); } }
            });

        $("#configManagerButton").click(function() {
                $( "#configManager" ).dialog( "open" );
                return false;
        });

        $("#originManager").dialog({
            autoOpen: false,
            modal: true,
            draggable: false,
            resizable: false,
            width: "400px",
             "buttons": { "Close": function() { $(this).dialog("close"); } }
             });

        $("#testOriginButton").click(function() {
            $("#testOriginButton").attr("disabled", "disabled");

            var obj = document.getElementById("origin_server_address");
            var originserverAddress = obj.value;

            if (originserverAddress == "") {
                window.alert("No origin server specified");
                $("#testOriginButton").removeAttr("disabled");
            } else {
                $.getJSON("json/origin.php", { action: "check", url: originserverAddress, dt: (new Date()).getTime() }, function(resp) {
                if (resp.status == "OK") {
                    window.alert("Server Responded To Request");
                } else {
                    window.alert("Unable to Connect\nOrigin Server Unavailable");
                }
                $("#testOriginButton").removeAttr("disabled");
            });
            }
            return false;
        });
        $("#configBackupAllButton").click(function() {
            var filename = $("#config_backup_filename").val();
            $.getJSON("json/config.php", { action: "list_configs", dt: (new Date()).getTime() }, function(resp) {
                if (resp.status == "OK" && resp.data.configs.length > 0) {
                    window.location.href = "download.php?type=configs&filename="+filename;
                } else {
                    window.alert("No configs exist to backup!");
                }
            });
        });

        $("#configRestoreButton").click(function() {
            if (confirm("Any existing configs with the same name will be replaced with restored config. Continue?")) {
                $.ajaxFileUpload
                (
                    {
                        url:'json/config.php?action=restore',
                        secureuri:false,
                        fileElementId:'configRestoreUploadBox',
                        dataType: 'json',
                        data:{ t: (new Date()).getTime() },
                        success: function (data, status)
                        {
                            if(data.error && data.error.length > 0)
                            {
                                alert("Error: " + data.error);
                            }
                            else
                            {
                                alert("Configs successfully restore.  This page will now refresh.");
                                window.location = window.location;
                            }
                        },
                        error: function (data, status, e)
                        {
                            alert(e);
                        }
                    }
                );
            }
        });

        $("#configDeleteAllButton").click(function() {
            $.getJSON("json/config.php", { action: "list_configs", dt: (new Date()).getTime() }, function(resp) {
                if (resp.status == "OK" && resp.data.configs.length > 0) {
                    if (confirm("This will erase ALL existing configs!\n\nAre you sure?")) {
                        $.getJSON("json/config.php", { action: "delete_all", dt: (new Date()).getTime() }, function(resp) {
                            alert("Configs deleted.  This page will now refresh.");
                            window.location = window.location;
                        });
                    }
                } else {
                    window.alert("No configs exist to delete!");
                }
            });
        });

        $(".discover_button").button({
            icons: {
                primary: "ui-icon-search"
            }
        }).click(function(e) {
            discover();
            e.preventDefault();
        });

        $("#input_audio_pid0").find("option").remove();
        $("#input_audio_pid0").append("<option value='0'>Audio1</option>");
        $("#input_audio_pid0").append("<option value='1'>Audio2</option>");
        $("#input_audio_pid0").append("<option value='2'>Audio3</option>");
        $("#input_audio_pid0").val(0);

        $("#input_audio_pid1").find("option").remove();
        $("#input_audio_pid1").append("<option value='0'>Audio1</option>");
        $("#input_audio_pid1").append("<option value='1'>Audio2</option>");
        $("#input_audio_pid1").append("<option value='2'>Audio3</option>");
        $("#input_audio_pid1").val(1);

        $(".mpts_discover_clear_button").button().click(function(e) {
            mpts_discover_enable_results(false);
            mpts_discover_cache = null;

            <?php if (ENABLE_DVB_SUBTITLES == 1) { ?>
            var subtitle_mode = $(".input_subtitle_mode:checked").val();
            if (subtitle_mode != 0) {
                $("#input_subtitle_mode0").click();
            }
            $("#input_subtitle_pid").find("option").remove();
            $("#input_subtitle_pid").append("<option value='-1'>None</option>");
            $("#input_subtitle_pid").val(-1);
            <?php } ?>

            $("#input_audio_pid0").find("option").remove();
            $("#input_audio_pid0").append("<option value='0'>Audio1</option>");
            $("#input_audio_pid0").append("<option value='1'>Audio2</option>");
            $("#input_audio_pid0").append("<option value='2'>Audio3</option>");
            $("#input_audio_pid0").val(0).mouseover();

            $("#input_audio_pid1").find("option").remove();
            $("#input_audio_pid1").append("<option value='0'>Audio1</option>");
            $("#input_audio_pid1").append("<option value='1'>Audio2</option>");
            $("#input_audio_pid1").append("<option value='2'>Audio3</option>");
            $("#input_audio_pid1").val(1).mouseover();

            $("#input_audio_pid2").find("option").remove();
            $("#input_audio_pid2").append("<option value='0'>Audio1</option>");
            $("#input_audio_pid2").append("<option value='1'>Audio2</option>");
            $("#input_audio_pid2").append("<option value='2'>Audio3</option>");
            $("#input_audio_pid2").val(2).mouseover();

            e.preventDefault();
        });

        $('#enable_gpu').click(function(){
           if($(this).is(':checked')){
               $('#extremelowoption').show();
           } else {
               $('#extremelowoption').hide();
               if($("#quality_level").attr('selectedIndex')==0)
               {
                    window.alert("GPU setting disabled, updating quality setting from Extreme Low to Super Low setting");
                    $("#quality_level").attr('selectedIndex',1);
               }
           }
        });

        $("#input_stream").change(function() {
            var val = $(this).val();
            $("#input_program_number").toggleClass("force_hide", val != "NUMBER");
        });


        $("#input_atsc_tuner").change(function() { input_atsc_tuner_changed(null); });

        $("#rtmp_naming").change(rtmp_sync_controls);
        $("#rtmp_remote_server_address").keyup(rtmp_sync_controls);
        for (var iGroup = 0; iGroup < MAX_STREAM_GROUPS; ++iGroup)
        {
            $("#stream_group_checkbox"+(iGroup+1)).change(rtmp_sync_controls);
            for (var iStreamInGroup = 0; iStreamInGroup < MAX_VIDEO_STREAMS; ++iStreamInGroup)
            {
                var iStream = iGroup*MAX_VIDEO_STREAMS + iStreamInGroup;
                $("#stream_active"+iStream).change(rtmp_sync_controls);
            }
        }

        $("#hls_segment_rollover_mode,#hls_segment_rollover_count,#segment_size").bind("change keyup", function() {
            var rollover_mode = parseInt($("#hls_segment_rollover_mode").val());
            var seg_size = parseInt($("#segment_size").val());

            $("#hls_segment_rollover_count_row").toggleClass("force_hide", rollover_mode == 0 || rollover_mode == 3);

            var rollover_count = -1;
            if (rollover_mode == 0) {
                rollover_count = 100;
            } else if (rollover_mode == 1 || rollover_mode == 2) {
                rollover_count = parseInt($("#hls_segment_rollover_count").val());
            } else if (rollover_mode == 4) {
                rollover_count = -1;
            } else if (rollover_mode == 3) {
                rollover_count = -1;
            }

            var rollover_est = "";
            if (rollover_count < 0) {
                rollover_est = "Never";
            } else {
                var rollover_secs = rollover_count * seg_size;
                var hh = Math.floor(rollover_secs / 3600);
                var mm = Math.floor((rollover_secs - (hh * 3600)) / 60);
                var ss = rollover_secs - (hh * 3600) - (mm * 60);

                if (hh > 0) {
                    rollover_est += hh + " hours";
                }
                if (mm > 0) {
                    if (rollover_est.length > 0) {
                        rollover_est += ", ";
                    }
                    rollover_est += mm + " minutes";
                }
                if (ss > 0) {
                    if (rollover_est.length > 0) {
                        rollover_est += ", ";
                    }
                    rollover_est += ss + " seconds";
                }
            }

            $("#hls_segment_rollover_estimate").text(rollover_est);
        });

        $("#publishing_point_auth1").change(function() {
            $(".publishing_point_auth1_setting_row").toggle(this.value != "none");
        });

        $("#publishing_point_auth2").change(function() {
            $(".publishing_point_auth2_setting_row").toggle(this.value != "none");
        });

        $("select[name=copv3_row],select[name=copv3_column],select[name=fec2d],#output_mux_rate").change(function() {
            var overheadElem = $("#fec_overhead");
            var output_type = parseInt($("select[name=output_type]").val());
            var row = parseInt($("select[name=copv3_row]").val());
            var col = parseInt($("select[name=copv3_column]").val());
            var fec2d = parseInt($("select[name=fec2d]").val());
            var enabled = output_type == 0 && col > 0;

            var rowOverhead = 0;
            var colOverhead = 0;
            if (enabled) {
                if (fec2d && row > 0) {
                    rowOverhead = 1.0/row;
                }
                if (col > 0) {
                    colOverhead = 1.0/col;
                }
            }

            var totOverhead = rowOverhead+colOverhead;
            var overheadText = Math.round(100.0 * totOverhead, 1) + "%";

            var mux_rate = parseInt($("#output_mux_rate").val());
            if (!mux_rate || isNaN(mux_rate)) {
                mux_rate = 0;
            }

            if (mux_rate > 0) {
                overheadText += " ~ " + Math.floor(totOverhead * mux_rate).toLocaleString() + " bps";
            }

            overheadElem.text(overheadText);
        });

        $("#image_overlay_file").change(image_overlay_file_changed);
        $("#stream_image_overlay_file").change(stream_image_overlay_file_changed);
        $("#stream_image_overlay_alpha").keypress(function(event) {
            if (event.keyCode == '13') {
                event.preventDefault();
            }
            setTimeout(function() { $("#stream_image_overlay_alpha").change(); }, 200);
        });
        $("#image_overlay_alpha").keypress(function(event) {
            if (event.keyCode == '13') {
                event.preventDefault();
            }
            setTimeout(function() { $("#image_overlay_alpha").change(); }, 200);
        });

        $("#stream_image_overlay_alpha").change(function() {
            var alpha = $(this).val();
            if (alpha >= 0 && alpha <= 100)
            {
                alpha = alpha / 100.0;
                $("#stream_image_overlay_preview_img").fadeTo('fast', alpha);
            }
        });

       $("#image_overlay_alpha").change(function() {
            var alpha = $(this).val();
            if (alpha >= 0 && alpha <= 100)
            {
                alpha = alpha / 100.0;
                $("#image_overlay_preview_img").fadeTo('fast', alpha);
            }
        });

        $("#scte35_passthru").change(function(){
            if($("#scte35_passthru").val() != 0 &&$("#enable_output_pid_remap").val() != 0){
                $("#output_scete35_pid_row").show();
            } else{
                $("#output_scete35_pid_row").hide();
            }
        });

        $("#enable_output_pid_remap").change(function() {
            var enabled = $(this).val() != "0";
            $(".output_pid_remap_setting_row").toggleClass("force_hide", !enabled);
            $("#scte35_passthru").change();
        });


        $("#enable_source_input_2").change(function() {
            var enabled = $(this).val() != "0";
            if (enabled)
                $(".ip_input_row_2").show();
            else
                $(".ip_input_row_2").hide();
        });

        $("#enable_ethernet_interface_2").change(function() {
            var enabled = $(this).val() != "0";
            $(".output_ethernet_interface_2").toggleClass("force_hide", !enabled);
        });

        // Add the change event handler to the input_interface
        $("input[name=input_interface]:radio").change(function()
        {
            var input_interface = $("input[name=input_interface]:checked").val();
            input_interface_selected(input_interface);
            //refresh_output_interface();

            if ("HD-SDI" == input_interface)
            {
                // This enables the HD-SDI dropdown but disables the individual res controls so the disabled controls
                // need to be set to the current value of the hd-sdi box.
                sdi_input_mode_changed($("#sdi_input_mode")[0]);
            } else if ("HDMI" == input_interface) {
                hdmi_input_mode_changed($("#hdmi_input_mode")[0]);
            }
        });

        $("input[name=output_interface]:radio").change(function()
        {
            var output_interface= $("input[name=output_interface]:checked").val();
            output_interface_selected(output_interface);

       });


        $("#tabs").tabs();

        $("#apple-flash-tabs").tabs();
        $("#multirate-tabs").hide(); //Hide tab nav header (Only one tab enabled at a time
        $("#output_audio_bitrate1,#output_audio_bitrate2,#output_audio_bitrate3"+
        ",#audio_channels0,#audio_channels1,#audio_channels2"
        ).change(function() {
            update_audio_controls();
        });

        $(".stream_row").each(function (i, row) {
            $(row).find(".stream_setting,#stream_active"+i).change(function () {
                var stream_group = Math.floor(i / MAX_VIDEO_STREAMS) + 1;
                var stream_group_enabled = $("#stream_group_checkbox" + stream_group).is(":checked");

                set_stream_controls(i, !stream_group_enabled);

                if ((i + 1) % MAX_VIDEO_STREAMS != 0) {
                    var is_curr_stream_active = $("#stream_active" + i).is(":checked");
                    // If we are disabling a stream, also disable all streams that
                    // follow the current stream
                    if (!is_curr_stream_active) {
                        for (var strm = i + 1; strm < (stream_group * MAX_VIDEO_STREAMS); strm++){
                            $("#stream_active" + strm).attr("checked", false).change();
                        }
                    } else {
                        set_stream_controls(i + 1, !stream_group_enabled);
                    }
                }
            });
        });

        $(".guidgen_button").click(function() {
            $(this).siblings("input").val(guid());
            return false;
        });

        $("#enable_raw_input").attr('title', 'RAW SOCKETS SHOULD ONLY BE USED FOR SPECIAL CIRCUMSTANCES');
        $("#multicast_filter_address").attr('title', 'LOCK TO MULTICAST TRAFFIC BASED ON SOURCE ADDRESS');
        $("#enable_afd").attr('title', 'ACTIVE FORMAT DESCRIPTOR (AFD)');
        $("#I_P_frame_distance").attr('title','IP DISTANCE (FOR 1-BFRAME SET TO 2, FOR 2-BFRAMES SET TO 3, ETC.)');
        $("#GOP_length").attr('title','SETS HOW OFTEN INTRA FRAMES ARE INSERTED');
        $("#GOP_length_seconds").attr('title','SETS HOW OFTEN INTRA FRAMES ARE INSERTED');
        $("#cpb_delay").attr('title','sets the coded picture buffer delay (cpb) of the encoder');

        <?php
        // If we are in ATSC mode, the tab MPEG2TS streaming should be hidden, and strangely, the easiest way
        // to do it, is to call this function with this output aas parameter
        if(CONFIG_MODE == 1)
        {
        ?>
                output_interface_selected("ATSC");
        <?php
        }
        ?>

        imageOverlayRefreshFiles();

        var config_data = $("#config_data").text().split(";");
        update_form(config_data);
    });

    function mpts_discover_enable_results(enable) {
        var input_source = get_active_input_interface();
        $("#mpts_discover_results_row").toggleClass("force_hide", !enable || input_source=="HD-SDI");
        $("#deltacast_discover_results_row").toggleClass("force_hide", !enable || input_source!="HD-SDI");
        $("#input_stream").toggleClass("force_hide", enable);
        $("#input_number_label").toggleClass("force_hide", !enable);
        $("#mpts_discover_clear_button").toggleClass("force_hide", !enable);
        if (!enable) {
            $("#mpts_discover_results_row").find(".discover_program").remove();
        }
    }

    var discover_in_process = false;
    function discover_deltacast_update_input(fps,w,h,interlaced,PsF){
        var val = 1;
        if(h == 480 /*NTSC*/)
        {
                switch(fps)
                {
                        case 2997:
                            val = 0;
                            break;
                        case 2398:
                            val = 1;
                            break;
                        default:
                            val = -1;
                }
        } else if(h == 576 /*PAL*/) {
                val = 2;
        } else if(h == 1080 && interlaced) {
                switch(fps)
                {
                        case 2500:
                            val = 8;
                            break;
                        case 2997:
                            val = 9;
                            break;
                        case 3000:
                            val = 10;
                            break;
                        default:
                            val = -1;
                }
        } else if(h == 720) {
                if(!PsF){
                        switch(fps)
                        {
                                case 5000:
                                    val = 11;
                                    break;
                                case 5994:
                                    val = 12;
                                    break;
                                case 6000:
                                    val = 13;
                                    break;
                                default:
                                    val = -1;
                        }
                } else {
                        switch(fps)
                        {
                                case 5000:
                                    val = 19;
                                    break;
                                case 5994:
                                    val = 20;
                                    break;
                                case 6000:
                                    val = 21;
                                    break;
                                default:
                                    val = -1;
                        }
                }
        } else if(h == 1080 && !interlaced) {
             if(!PsF){
                switch(fps)
                {
                        case 2398:
                            val = 3;
                            break;
                        case 2400:
                            val = 4;
                            break;
                        case 2500:
                            val = 5;
                            break;
                        case 2997:
                            val = 6;
                            break;
                        case 3000:
                            val = 7;
                            break;

                        default:
                            val = -1;
                }
             } else //PsF
             {
                switch(fps)
                {
                        case 2398:
                            val = 14;
                            break;
                        case 2400:
                            val = 15;
                            break;
                        case 2500:
                            val = 16;
                            break;
                        case 2997:
                            val = 17;
                            break;
                        case 3000:
                            val = 18;
                            break;
                        default:
                            val = -1;
                }
            }
        }else if(w == 3840) {
                switch(fps)
                {
                        case 2398:
                            val = 22;
                            break;
                        case 2400:
                            val = 23;
                            break;
                        case 2500:
                            val = 24;
                            break;
                        case 2997:
                            val = 25;
                            break;
                        case 3000:
                            val = 26;
                            break;
                        case 5000:
                            val = 27;
                            break;
                        case 5994:
                            val = 28;
                            break;
                        case 6000:
                            val = 29;
                            break;
                        default:
                            val = -1;
                }

        } else if(w == 4096/*4K*/) {
                switch(fps)
                {
                        case 2398:
                            val = 30;
                            break;
                        case 2400:
                            val = 31;
                            break;
                        case 2500:
                            val = 32;
                            break;
                        case 2997:
                            val = 33;
                            break;
                        case 3000:
                            val = 34;
                            break;
                        case 5000:
                            val = 35;
                            break;
                        case 5994:
                            val = 36;
                            break;
                        case 6000:
                            val = 37;
                            break;
                        default:
                            val = -1;
                }
        } else {
                val = -1;
        }
     $("#sdi_input_mode").val(val).change();
}
       function discover_deltacast() {        $(".discover_button").hide();
        var brdid = $("#sdi_card_num").val()-1;
        var sltid = $("#sdi_card_input_num").val()-1;
        $(".discover_throbber").show();
        $.ajax({url:'json/discover.php?action=discover&type=sdi&sltid='+sltid+'&brdid='+brdid,dataType: "json", success: function(data){
                $(".discover_button").show();
                $(".discover_throbber").hide();
                 if(data.status=="ERROR")
                {
                        alert(data.error);
                }
                 else
                {
                        mpts_discover_set_results_deltacast(data.data.data,true);
                }
                discover_in_process = false;
                }});
    }
    function mpts_discover_set_results_deltacast(data, syncSettings) {
        mpts_discover_cache = data;
        $(".deltacast_discover_row").show();
        $(".deltacast_discover_row").removeClass("force_hide");

        $(".discover_program").remove();
        var proto = $(".deltacast_discover_program_proto");

        var firstProgram = -1;
        var activeProgram = -1;
        var hasActiveProgram = false;
        if ($("#input_stream").val() == "NUMBER") {
            activeProgram = $("#input_program_number").val();
        }
        var programs = data.programs;
        if(programs){
        $.each(programs, function(i, program) {
            var row = proto.clone();
            row.removeClass("discover_program_proto").removeClass("force_hide");
            row.addClass("discover_program");

            if (firstProgram == -1) {
                firstProgram = program.program_number;
            }

            if (program.program_number == activeProgram) {
                hasActiveProgram = true;
            }

            if(program.ishd == 1 || program.video_height >= 720)
                row.find(".program_pmt_pid").text("HD");
            else
                row.find(".program_pmt_pid").text("SD");
            var name = "-";
            if (program.actual_program_name && program.actual_program_name.length > 0) {
                name = program.actual_program_name;
            } else if (program.alternate_program_name && program.alternate_program_name.length > 0) {
                name = program.alternate_program_name;
            } else if (program.source_identity && program.source_identity.length > 0) {
                name = program.source_identity;
            }
            var interlaced = program.video_interlaced;
            if(typeof(program.interlaced)!="undefined");
                interlaced = program.interlaced;
            if(program.video_height == 1080 && interlaced) {
                $("option[value='NTSC1280']").show();
                $("option[value='NTSC1280']").attr('hidden',false);
            } else{
                $("option[value='NTSC1280']").hide();
                $("option[value='NTSC1280']").attr('hidden',true);
            }
            name = "Video "+(i+1);
            row.find(".source_identity").text(program.video_width+"x"+program.video_height);
            $("#sdi_input_width").val(program.video_width);
            $("#sdi_input_height").val(program.video_height);
            var fps = program.video_framerate;

            if(typeof(fps)=="string")
                fps = parseFloat(fps);
            fps = fps.toFixed(2);
            row.find(".stream_pid").text(fps);
            if(interlaced == 1){
                 row.find(".program_number").text("Interlaced");
                if(typeof(program.video_top_field_first)!="undefined"){
                    row.find(".field_order").text((program.video_top_field_first)?"Top field first":"Bottom Field First");
                } else {
                    //if SDI-HD TFF, else BFF
                    row.find(".field_order").text((program.video_height >= 720)?"Top field first":"Bottom Field First");
                }
                $(".field_order_header").text("Field Order");
            }else if(interlaced==0){
                $(".field_order_header").text("");
                row.find(".program_number").text("Progressive");
            }else{
                row.find(".program_number").text("Unknown");
                                                                                               }
            var PsF = program.ispsf;
            discover_deltacast_update_input(Math.floor(fps*100),program.video_width,program.video_height,interlaced,PsF);

            var audioNum = 0;
            if (program.streams && program.streams.length > 0) {

                var table = "<table class='stream_table' width='100%' cellpadding='0' cellspacing='0' border='0'>";
                var has6ChannelAudio = 0;
                table += "<tr class='gridded_table_header'><th class='program_info'>PID</th><th>Ch</th><th>Codec</th></tr>";
                $.each(program.streams, function(j, stream) {
                    if (stream.type=="Audio") {
                        table += "<tr><td style='width: 50px;'>";
                        table += stream.pid||"-";
                        table += "</td>";
                        table += "<td style='width: 70px;'>";
                        table += (stream.channels && stream.channels.length > 0)?stream.channels:"-";
                        if(stream.channels == "6")
                            $("#audio_channels"+audioNum+" option[value=6]").show();
                        else
                            $("#audio_channels"+audioNum+" option[value=6]").hide();

                        table += "</td>";
                        table += "<td width='width:200px'>";
                        table += (stream.codec && stream.codec.length > 0)?stream.codec:"-";

                        if (stream.codec && stream.codec.length > 0 && stream.format && stream.format.length > 0) {
                            table += "<br/>" + stream.format;
                        }

                        table += "</td></tr>";
                        audioNum++;
                                            }
                });
                table += "</table>";
                row.find("#audio_channels").html(table);
            } else {
                row.find(".stream_pid"+i).html("-");
            }

            row.data("program", program);
            proto.before(row);
        });
        }
        //selectDiscoverProgram(hasActiveProgram ? activeProgram : firstProgram, syncSettings);

        $(".program_select_btn").click(function(e) {
            e.preventDefault();
                                                                      var btn = $(this);
            var row = btn.closest(".discover_program");
            var num = row.find(".program_number").text();
           // selectDiscoverProgram(num, true);
        });

        var showingResults = $("#mpts_discover_results_row").hasClass("force_hide");
        //mpts_discover_enable_results(true);
        if (showingResults && syncSettings) {
            $("#input_stream").val("NUMBER").change();
        }
    }


    function discover() {
        if (discover_in_process) {
            return;
        }

        discover_in_process = true;

        var input_source = get_active_input_interface();

        var controlRow;
        var source = null;

        if (input_source == "IP") {
            controlRow = $("#mpts_discover_row");
            source = "ip";
        } else if (input_source == "DVBASI") {
            //controlRow = $("#input_stream_row");
            //source = "asi";
        } else if (input_source == "DVB-API") {
            controlRow = $("#mpts_discover_row");
            source = "api";
        } else if (input_source == "HDMI") {
            controlRow = $("#hdmi_input_mode_row");
            source = "hdmi";
        <?php if (SDI_PROVIDER == "BLACKMAGIC" || SDI_PROVIDER == "DELTACAST") { ?>
        } else if (input_source == "HD-SDI") {
            controlRow = $("#hd_sdi_row");
            source = "sdi";
            <?php if (SDI_PROVIDER == "DELTACAST"){ ?>
                discover_deltacast();
                return;
            <?php } ?>
        <?php } ?>
        }
        if (!input_source) {
            alert("Discover not implemented for this input interface!");
            discover_in_process = false;
            return;
        }

        controlRow.find(".discover_throbber").show();
        controlRow.find(".discover_button").button("option", "disabled", true);
        controlRow.find(".discover_clear_button").button("option", "disabled", true);

        var params = {
            "action": "discover",
            "type": source,
            "ts": (new Date().getTime())
            };

        if (input_source == "IP") {
            //var nicIndex =$("#source_ethernet_interface").val();
            //var nic = $("#source_ethernet_interface").find("option[value='" + nicIndex + "']").text()
            var nicName =$("#source_ethernet_interface").val();
            var ip =$("#source_ip_address").val();
            var port = $("#source_port").val();
            var filter = $("#multicast_filter_address").val();
            $.extend(params, {
                "nic": nicName,
                "ip": ip,
                "port": port,
                "filter": filter
            });
        } else if (input_source == "DVB-API") {
            params["type"] = "8vsb";
            params["adapter"] = $("#input_atsc_tuner option:selected").attr("data-adapterindex");
            params["device"] = $("#input_atsc_tuner option:selected").attr("data-deviceindex");
            params["freq"] = $("#input_atsc_channel option:selected").attr("data-freq");

        }

        $.getJSON("json/discover.php",
            params,
            function(data) {
                controlRow.find(".discover_button").button("option", "disabled", false);
                controlRow.find(".discover_clear_button").button("option", "disabled", false);
                controlRow.find(".discover_throbber").hide();
                discover_in_process = false;

                var error = false;
                if (data && data.status == "OK") {
                    if (source == "ip" || source == "asi" || source=="api") {
                        if (data.data.programs) {
                            mpts_discover_set_results(data.data, true);
                        }
                    } else if (source == "hdmi" ||source == "sdi") {
                        var mode_select = source == "hdmi" ? $("#hdmi_input_mode") : $("#sdi_input_mode");

                        var found_group = source == "hdmi" ? $("#hdmi_found_group") : $("#sdi_found_group");
                        if (found_group.length == 0) {
                            if (source == "hdmi") {
                                $("<optgroup id='hdmi_found_group' label='Signal Found'></optgroup>").appendTo(mode_select);
                                found_group = $("#hdmi_found_group");
                            } else {
                                $("<optgroup id='sdi_found_group' label='Signal Found'></optgroup>").appendTo(mode_select);
                                found_group = $("#sdi_found_group");
                            }
                        }

                        var not_found_group = source == "hdmi" ? $("#hdmi_not_found_group") : $("#sdi_not_found_group");
                        if (not_found_group.length == 0) {
                            if (source == "hdmi") {
                                $("<optgroup id='hdmi_not_found_group' label='No Signal'></optgroup>").appendTo(mode_select);
                                not_found_group = $("#hdmi_not_found_group");
                            } else {
                                $("<optgroup id='sdi_not_found_group' label='No Signal'></optgroup>").appendTo(mode_select);
                                not_found_group = $("#sdi_not_found_group");
                            }
                        }

                        var modes = data.data.modes;

                        var first_found_val = -1;
                        var selected_val = mode_select.val();
                        var selected_found = false;
                        var num_found = 0;
                        var found_label = "";

                        mode_select.find("option").each(function(i, opt) {
                            opt = $(opt).detach();
                            if (modes && modes[opt.val()]) {
                                if (-1 == first_found_val) {
                                    first_found_val = opt.val();
                                }
                                found_group.append(opt);
                                if (selected_val == opt.val()) {
                                    selected_found = true;
                                }
                                found_label = opt.attr("label");
                                ++num_found;
                            } else {
                                not_found_group.append(opt);
                            }
                        });

                        if (!num_found) {
                            window.alert("No signal found on interface.");
                            found_group.remove();
                        } else {
                            if (selected_found) {
                                mode_select.val(selected_val).change();
                            } else if (-1 != first_found_val) {
                                mode_select.val(first_found_val).change();
                            }
                            if (num_found > 1) {
                                window.alert("Signal found for multiple modes. Please select the correct mode for your input signal.");
                            } else {
                                window.alert("Signal found!\n"+found_label);
                            }
                        }
                    }
                } else {
                    var error = data.error ? data.error : "Unknown error";
                    alert("Discover failed.\n\n"+error);
                }
            });
    }

    function mpts_discover_set_results(data, syncSettings) {
        if(data.source.type=="sdi")
           return;
        mpts_discover_cache = data;

        $(".discover_program").remove();
        var proto = $(".discover_program_proto");

        var firstProgram = -1;
        var activeProgram = -1;
        var hasActiveProgram = false;
        if ($("#input_stream").val() == "NUMBER") {
            activeProgram = $("#input_program_number").val();
        }

        var programs = data.programs;
        $.each(programs, function(i, program) {
            var row = proto.clone();
            row.removeClass("discover_program_proto").removeClass("force_hide");
            row.addClass("discover_program");

            if (firstProgram == -1) {
                firstProgram = program.program_number;
            }

            if (program.program_number == activeProgram) {
                hasActiveProgram = true;
            }

            row.find(".program_number").text(program.program_number);
            row.find(".program_pmt_pid").text(program.pmt_pid);

            var name = "-";
            if (program.actual_program_name && program.actual_program_name.length > 0) {
                name = program.actual_program_name;
            } else if (program.alternate_program_name && program.alternate_program_name.length > 0) {
                name = program.alternate_program_name;
            } else if (program.source_identity && program.source_identity.length > 0) {
                name = program.source_identity;
            }
            row.find(".source_identity").text(name);

            if (program.streams && program.streams.length > 0) {
                var table = "<table class='stream_table' width='100%' cellpadding='0' cellspacing='0' border='0'>";
                var audio_cnt = 0;
                $.each(program.streams, function(j, stream) {
                    if (stream.type) {
                        table += "<tr><td style='width: 50px;'>";
                        table += stream.pid||"-";
                        table += "</td>";
                        table += "<td style='width: 70px;'>";
                        if (stream.type && stream.type.length > 0) {
                            if (stream.type == "Audio") {
                                stream.type = "Audio" + ++audio_cnt;
                            }
                        }

                        table += (stream.type && stream.type.length > 0)?stream.type:"-";

                        table += "</td>";
                        table += "<td>";
                        table += (stream.codec && stream.codec.length > 0)?stream.codec:"-";

                        if (stream.codec && stream.codec.length > 0 && stream.format && stream.format.length > 0) {
                            table += "<br/>" + stream.format;
                        }

                        table += "</td></tr>";
                    }
                });
                table += "</table>";
                row.find(".stream_pid").html(table);
            } else {
                row.find(".stream_pid"+i).html("-");
            }
            row.data("program", program);
            proto.before(row);
        });

        selectDiscoverProgram(hasActiveProgram ? activeProgram : firstProgram, syncSettings);

        $(".program_select_btn").click(function(e) {
            e.preventDefault();
            var btn = $(this);
            var row = btn.closest(".discover_program");
            var num = row.find(".program_number").text();
            selectDiscoverProgram(num, true);
        });

        var showingResults = $("#mpts_discover_results_row").hasClass("force_hide");
        mpts_discover_enable_results(true);
        if (showingResults && syncSettings) {
            $("#input_stream").val("NUMBER").change();
        }
    }

    function selectDiscoverProgram(program_num, syncSettings) {
        $(".discover_program").removeClass("selected_discover_program").each(function(i, row) {
            var num = $(row).find(".program_number").text();
            if (num == program_num) {
                var program = $(row).data("program");
                $(row).addClass("selected_discover_program");

                $("#input_stream").val("NUMBER").change();
                $("#input_program_number").val(num);

                <?php if (ENABLE_DVB_SUBTITLES == 1) { ?>
                $("#input_subtitle_pid").find("option").remove();
                $.each(program.streams, function(i, s) {
                    if (s.type == "Subtitle") {
                        $("#input_subtitle_pid").append("<option value='" + s.pid + "'>" + s.codec + "</option>");
                    }
                });

                if ($("#input_subtitle_pid").find("option").length == 0) {
                    $("#input_subtitle_pid").append("<option value='-1'>None</option>").attr("disabled", "disabled");
                    $("#input_subtitle_mode1").attr("disabled", "disabled");
                    $("#input_subtitle_mode1").parent().css("color", "gray");
                } else {
                    $("#input_subtitle_pid").removeAttr("disabled");
                    $("#input_subtitle_mode1").removeAttr("disabled");
                    $("#input_subtitle_mode1").parent().css("color", "black");
                }
                <?php } ?>

                var val_pid0 = $("#input_audio_pid0").val();
                var val_pid1 = $("#input_audio_pid1").val();
                var val_pid2 = $("#input_audio_pid2").val();



              //
              // setup input audio 0
              //
                $("#input_audio_pid0").find("option").remove();
                for (let i=0; i<3; i++) {
                    var stream_num = i+1;
                    $("#input_audio_pid0").append("<option value='" + i + "'>"+ "Audio" + stream_num +"</option>");
                }
                $("#input_audio_pid0").append("<option value='-1'>Unselected</option>").attr("disabled", "disabled");
                $("#input_audio_pid0").removeAttr("disabled");

              //
              // setup input audio 1
              //
                $("#input_audio_pid1").find("option").remove();
                for (let i=0; i<3; i++) {
                    var stream_num = i+1;
                    $("#input_audio_pid1").append("<option value='" + i + "'>"+ "Audio" + stream_num +"</option>");
                }
                $("#input_audio_pid1").append("<option value='-1'>Unselected</option>").attr("disabled", "disabled");
                $("#input_audio_pid1").removeAttr("disabled");

              //
              // setup input audio 2
              //
                $("#input_audio_pid2").find("option").remove();
                for (let i=0; i<3; i++) {
                    var stream_num = i+1;
                    $("#input_audio_pid2").append("<option value='" + i + "'>"+ "Audio" + stream_num +"</option>");
                }
                $("#input_audio_pid2").append("<option value='-1'>Unselected</option>").attr("disabled", "disabled");
                $("#input_audio_pid2").removeAttr("disabled");

              //
              // reset the values in the input audio sections
              //
                if (val_pid0 != null)
                    $("#input_audio_pid0").val(val_pid0);
                if (val_pid1 != null)
                    $("#input_audio_pid1").val(val_pid1);
                if (val_pid2 != null)
                    $("#input_audio_pid2").val(val_pid2);


                $("#input_audio_pid0").mouseover();
                $("#input_audio_pid1").mouseover();
                $("#input_audio_pid2").mouseover();

                if (syncSettings) {
                    var hasAudio = false;
                    var hasVideo = false;
                    $.each(program.streams, function(i, s) {
                        if (s.type == "Video") {
                            hasVideo = true;
                        } else if (s.type == "Audio") {
                            hasAudio = true;
                        }
                    });

                    if (hasVideo) {
                        $("#audio_only")[0].checked = false;
                        audio_only_clicked();

                        var width = program.video_width;
                        var height = program.video_height;
                        var fps = program.video_framerate;
                        var format = program.video_interlaced;
                        var top_field = program.video_top_field_first;
                        var res = "USER";
                        if (width == 1920 && height == 1080)
                        {
                            res = "HD1080";
                        }
                        else if (width == 1280 && height == 720)
                        {
                            res = "HD720";
                        }
                        else if (width == 704 && height == 576)
                        {
                            res = "PAL";
                        }
                        else if (width == 720 && height == 576)
                        {
                            res = "PAL720";
                        }
                        else if (width == 704 && height == 480)
                        {
                            res = "NTSC";
                        }
                        else if (width == 720 && height == 480)
                        {
                            res = "NTSC720";
                        }
                        else if (width == 640 && height == 480)
                        {
                            res = "VGA";
                        }

                        if ($("#input_resolution option[value='"+res+"']").length === 0) {
                            res = "USER";
                        }

                        $("#bottom_field_first").val(!top_field).change();

                        $("#input_resolution").val(res).change();
                        $("#input_width").val(width);
                        $("#input_height").val(height);
                        $("#input_format").val(format).change();

                        // Map discovered frame rate to available options accounting for rounding
                        var selectedFps = "29.97";
                        <?php if (ENABLE_HD_INPUT == 1) { ?>
                        if (fps >= 60.0) {
                            selectedFps = "60";
                        } else if (fps >= 59.93) {
                            selectedFps = "59.94";
                        } else if (fps >= 50.0) {
                            selectedFps = "50";
                        } else if (fps >= 30.0) {
                            selectedFps = "30";
                        } else if (fps >= 29.96) {
                            selectedFps = "29.97";
                        } else if (fps >= 25.0) {
                            selectedFps = "25";
                        } else if (fps >= 24.0) {
                            selectedFps = "24";
                        } else if (fps >= 23.97) {
                            selectedFps = "23.98";
                        } else if (fps >= 15) {
                            selectedFps = "15";
                        }
                        <?php } else { ?>
                        if (fps >= 30.0) {
                            selectedFps = "30";
                        } else if (fps >= 29.96) {
                            selectedFps = "29.97";
                        } else if (fps >= 25.0) {
                            selectedFps = "25";
                        } else if (fps >= 24.0) {
                            selectedFps = "24";
                        } else if (fps >= 23.97) {
                            selectedFps = "23.98";
                        } else if (fps >= 15) {
                            selectedFps = "15";
                        }
                        <?php } ?>
                        $("#input_framerate").val(selectedFps);
                    }

                    if (!hasVideo && hasAudio) {
                        $("#audio_only")[0].checked = true;
                        audio_only_clicked();

                    }
                }
                return false;
            }
        });
    }

    function is_int(elem)
    {
        var numeric_exp = /^[0-9]+$/;
        if (elem.value.match(numeric_exp))
        {
            // Don't allow any numbers that start with a leading 0
            if (elem.value.length > 1 && elem.value.charAt(0) == '0')
            {
                return false;
            }
            return true;
        }

        return false;
    }

    function is_float(elem)
    {
        var num = elem.value;

        if (isNaN(parseFloat(num)))
        {
            return false;
        }

        return true;
    }

    function is_valid_ip_address(addr)
    {
        var ip_pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
        var ip_array = addr.match(ip_pattern);
        var val;

        if (ip_array == null)
        {
            return false;
        }

        for (i = 0; i < 4; i++)
        {
            val = ip_array[i];
            if (val > 255)
            {
                return false;
            }
        }

        return true;
    }

    function get_active_output_interface()
    {
        var output_interface = $("input[name='output_interface']:checked");
        return output_interface.val();
    }

    function set_active_output_interface(value)
    {
        var output_interfaces = $("input[name=output_interface]");
        output_interfaces.each(function (j, elem) {
            elem.checked = elem.value == value;
            if (elem.checked) {
                output_interface_selected(value);
            }
        });
        $("#stream-profiles").toggle(get_active_output_interface() != "APPLE")
     }

    function get_active_input_interface()
    {
        var input_interface = $("input[name='input_interface']:checked");
        return input_interface.val();
    }

    function set_active_input_interface(value)
    {
        var input_interfaces = $("input[name=input_interface]");
        input_interfaces.each(function (j, elem) {
            elem.checked = elem.value == value;
            if (elem.checked) {
                input_interface_selected(value);
            }
        });
     }

     function is_multirate_output(output_interface)
     {
        if (!output_interface) {
            output_interface = get_active_output_interface();
        }
        switch (output_interface) {
            case "RTP":
            case "RTMP":
            case "APPLE":
            case "APPLEVOD":
            case "SILVERLIGHT":
            case "DASH":
            case "ATSC":
            case "MULTITS":
                return true;

        }
        return false;
     }

     function get_stream_vbr(iStream)
     {
        var frm = document.configuration;
        var stream_vbr = frm.elements["stream_vbr"+iStream];
        return !!parseInt(stream_vbr.options[stream_vbr.selectedIndex].value);
     }

     function is_valid_guid(guid)
     {
         if (!guid || !guid.length) {
             return false;
         }
         var pattern = /(^[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}$)|(^[0-9a-fA-F]{32}$)|(^[a-zA-Z0-9+/]{22}={0,2}$)/;
         var array = guid.match(pattern);
         return array != null;
     }

     function form_is_valid()
     {

        var frm = document.configuration;

        var input_interface = get_active_input_interface();
        var output = get_active_output_interface();
        var isMPEG2LD = frm.output_encoder.value == "MPEG2LD";

        var input_format = parseInt(frm.input_format.value);
        var output_format = parseInt(frm.output_format.value);
        if (output_format == 2) {
            output_format = input_format;
        }
        var failed = false;
        //Skip first proto row i = 0
        $(".vid_width").each(function(i,el){
            var max_w = 1920;
            if (ENABLE_4K_OUTPUT)
                max_w=3840;

            if(i && (!$(el).val() || $(el).val() > max_w)){
                alert("Invalid input width specified, cannot be higher than " + max_w);
                $(el).focus();
                failed = true;
                return false;
            }
        });
        if(failed)
           return false;
           $(".vid_height").each(function(i,el){
                var max_h = 1080;
                if (ENABLE_4K_OUTPUT)
                    max_h=2160;

                if(i && (!$(el).val() || $(el).val() > max_h)){
                    alert("Invalid input height specified, cannot be higher than than " + max_h);
                    $(el).focus();
                    failed = true;
                    return false;
                }
        });
        if(failed)
            return false;
            $(".vid_mux_target").each(function(i, el){
                if(i && !$(el).val()){
                    alert("Invalid bitrate specified");
                    $(el).focus();
                    failed = true;
                    return false;
                }
        });
        if(failed)
            return false;
            $(".out_video_profile").each(function(i,el){
                if(i && ($(".out_enabled").eq(i).is(":checked") && $(el).val() == -1 && $(".out_audio_profile").eq(i).val() == -1)){
                    alert("Stream cannot be set to no audio and no video");
                    $(el).focus();
                    failed = true;
                    return false;
                }
        });
        if(failed)
           return false;

        if (!(frm.input_type.value == "stream" || frm.input_type.value == "file")) {
            frm.input_type.value = "stream";
        }

        if (frm.input_resolution.value == "USER") {
            if (frm.input_width.value == "") {
                alert("Invalid input width specified");
                frm.input_width.focus();
                return false;
            }

            if (frm.input_height.value == "") {
                alert("Invalid input height specified");
                frm.input_height.focus();
                return false;
            }
        }

        if (frm.output_resolution.value == "USER") {
            if (frm.output_width.value == "") {
                alert("Invalid output width specified");
                frm.output_width.focus();
                return false;
            }

            if (frm.output_height.value == "") {
                alert("Invalid output height specified");
                frm.output_height.focus();
                return false;
            }
        }

        if ( frm.input_audio_pid0.value >= 0 &&
             frm.input_audio_pid1.value >= 0 &&
             frm.input_audio_pid0.value == frm.input_audio_pid1.value) {
             alert("Primary and Secondary audio selection must be different");
             frm.input_audio_pid1.focus();
             return false;
        }

/*        if ( frm.input_audio_pid0.value >= 0 &&
             frm.input_audio_pid2.value >= 0 &&
             frm.input_audio_pid0.value == frm.input_audio_pid2.value) {
             alert("Primary and Third audio selection must be different");
             frm.input_audio_pid2.focus();
             return false;
        }
*/

/*        if ( frm.input_audio_pid1.value >= 0 &&
             frm.input_audio_pid2.value >= 0 &&
             frm.input_audio_pid1.value == frm.input_audio_pid2.value) {
             alert("Secondary and Third audio selection must be different");
             frm.input_audio_pid2.focus();
             return false;
        }
*/

        if (frm.input_stream.value == "NUMBER") {
            if (frm.input_program_number.value == "") {
                alert("Invalid input program number specified");
                frm.input_program_number.focus();
                return false;
            }
        }

        if (output != "HDSDI" && !is_multirate_output()) {
            if (input_format == 0 && output_format == 1 && (frm.output_resolution.value != "NTSC720" && frm.output_resolution.value != "NTSC" && frm.output_resolution.value != "LETTERBOX")) {
                alert("Progressive input to interlaced output is not supported.");
                frm.output_format.focus();
                return false;
            }
        }

        if (frm.I_P_frame_distance.value == '' ||
           !is_int(frm.I_P_frame_distance)    ||
           frm.I_P_frame_distance.value < 1   ||
           frm.I_P_frame_distance.value > 9)
        {
           alert("Invalid I/P frame distance specified");
           frm.I_P_frame_distance.focus();
           return false;
        }

        if (frm.GOP_length_seconds.value == '' ||
           !is_float(frm.GOP_length_seconds)    ||
           frm.GOP_length_seconds.value < 0   ||
           frm.GOP_length_seconds.value > 120)
        {
           alert("Invalid GOP length specified");
           frm.GOP_length_seconds.focus();
           return false;
        }

        if (frm.output_audio_bitrate0.value == '' || !is_int(frm.output_audio_bitrate0))
        {
            alert("Invalid audio bitrate specified");
            frm.output_audio_bitrate0.focus();
            return false;
        }

        if (frm.output_audio_samplerate.value == '' || !is_int(frm.output_audio_samplerate))
        {
            alert("Invalid audio samplerate specified");
            frm.output_audio_samplerate.focus();
            return false;
        }

        if (frm.output_audio_volume0.value == '' || !is_int(frm.output_audio_volume0))
        {
            alert("Invalid audio volume specified");
            frm.output_audio_volume0.focus();
            return false;
        }

        if (frm.output_audio_lang0.value.length > 0 && frm.output_audio_lang0.value.length != 3)
        {
            alert("Invalid audio language specified. Must be ISO 639-2 alpha-3 code such as 'eng' or 'spa'.");
            frm.output_audio_lang0.focus();
            frm.output_audio_lang0.select();
            return false;
        }

        if (frm.output_audio_lang1.value.length > 0 && frm.output_audio_lang1.value.length != 3)
        {
            alert("Invalid audio language specified. Must be ISO 639-2 alpha-3 code such as 'eng' or 'spa'.");
            frm.output_audio_lang1.focus();
            frm.output_audio_lang1.select();
            return false;
        }

        if (frm.output_audio_lang2.value.length > 0 && frm.output_audio_lang2.value.length != 3)
        {
            alert("Invalid audio language specified. Must be ISO 639-2 alpha-3 code such as 'eng' or 'spa'.");
            frm.output_audio_lang2.focus();
            frm.output_audio_lang2.select();
            return false;
        }

        if (frm.audio_channels0.value == 6) {
            var used = Array();
            var slot;
            for (slot = 0; slot < 20; ++slot) {
                used[slot] = false;
            }

            slot = parseInt(frm.audio_sdi_mapping_r0.value);
            if (used[slot]) {
                alert("Each SDI audio channel must be unique");
                frm.audio_sdi_mapping_r0.focus();
                return false;
            }
            used[slot] = true;

            slot = parseInt(frm.audio_sdi_mapping_l0.value);
            if (used[slot]) {
                alert("Each SDI audio channel must be unique");
                frm.audio_sdi_mapping_l0.focus();
                return false;
            }
            used[slot] = true;

            slot = parseInt(frm.audio_sdi_mapping_c0.value);
            if (used[slot]) {
                alert("Each SDI audio channel must be unique");
                frm.audio_sdi_mapping_c0.focus();
                return false;
            }
            used[slot] = true;

            slot = parseInt(frm.audio_sdi_mapping_lfe0.value);
            if (used[slot]) {
                alert("Each SDI audio channel must be unique");
                frm.audio_sdi_mapping_lfe0.focus();
                return false;
            }
            used[slot] = true;

            slot = parseInt(frm.audio_sdi_mapping_sr0.value);
            if (used[slot]) {
                alert("Each SDI audio channel must be unique");
                frm.audio_sdi_mapping_sr0.focus();
                return false;
            }
            used[slot] = true;

            slot = parseInt(frm.audio_sdi_mapping_sl0.value);
            if (used[slot]) {
                alert("Each SDI audio channel must be unique");
                frm.audio_sdi_mapping_sl0.focus();
                return false;
            }
            used[slot] = true;
        }
        <?php if (ENABLE_IPV6) { ?>
        if (frm.output_ip_address_ipv6.value == '') {
            if (frm.output_ip_address.value == '' || !is_valid_ip_address(frm.output_ip_address.value))
            {
                alert("Invalid output IP address specified");
                frm.output_ip_address.focus();
                return false;
            }
        }
        <?php } ?>
        if (!is_int(frm.multicast_ttl) ||
            frm.multicast_ttl.value < 0 ||
            frm.multicast_ttl.value > 16)
        {
            alert("Invalid multicast TTL specified. Must be 0-16.");
            frm.multicast_ttl.focus();
            return false;
        }

        if (!is_int(frm.rtp_multicast_ttl) ||
            frm.rtp_multicast_ttl.value < 0 ||
            frm.rtp_multicast_ttl.value > 16)
        {
            alert("Invalid multicast TTL specified for RTP mode. Must be 0-16.");
            frm.rtp_multicast_ttl.focus();
            return false;
        }

        if (!is_int(frm.multi_ts_multicast_ttl) ||
            frm.multi_ts_multicast_ttl.value < 0 ||
            frm.multi_ts_multicast_ttl.value > 16)
        {
            alert("Invalid multicast TTL specified for Multirate TS mode. Must be 0-16.");
            frm.multi_ts_multicast_ttl.focus();
            return false;
        }

        if (frm.output_port.value == '' ||
            !is_int(frm.output_port)    ||
            frm.output_port.value < 1   ||
            frm.output_port.value > 65535)
        {
            alert("Invalid primary output port specified");
            frm.output_port.focus();
            return false;
        }

        if (frm.enable_ethernet_interface_2.value == 1) {
            if (frm.output_port_2.value == '' ||
                !is_int(frm.output_port_2) ||
                frm.output_port_2.value < 1 ||
                frm.output_port_2.value > 65535) {

                alert("Invalid secondary output port specified");
                frm.output_port_2.focus();
                return false;
            }

            if (frm.output_ip_address_2.value == '' || !is_valid_ip_address(frm.output_ip_address_2.value)) {
                alert("Invalid secondary output IP address specified");
                frm.output_ip_address_2.focus();
                return false;
            }

            if (frm.output_ip_address_2.value == frm.output_ip_address.value &&
                frm.output_port_2.value == frm.output_port.value &&
                frm.ethernet_interface_2.value == frm.ethernet_interface.value) {
                alert("Secondary output is duplicate of first");
                frm.ethernet_interface_2.focus();
                return false;
            }
        }

        if (frm.enable_source_input_2.value == 1) {
            if (frm.source_port_2.value == '' ||
                !is_int(frm.source_port_2) ||
                frm.source_port_2.value < 1 ||
                frm.source_port_2.value > 65535) {

                alert("Invalid secondary output port specified");
                frm.source_port_2.focus();
                return false;
            }

            if (frm.source_ip_address_2.value == '' || !is_valid_ip_address(frm.source_ip_address_2.value)) {
                alert("Invalid secondary source IP address specified");
                frm.source_ip_address_2.focus();
                return false;
            }

            if (frm.source_ip_address_2.value == frm.source_ip_address.value &&
                frm.source_port_2.value == frm.source_port.value &&
                frm.source_ethernet_interface_2.value == frm.source_ethernet_interface.value &&
                frm.multicast_filter_address.value == frm.multicast_filter_address_2.value
                ) {
                alert("Secondary source is duplicate of first");
                frm.source_ethernet_interface_2.focus();
                return false;
            }
        }

        <?php if (ENABLE_IPV6) { ?>
        if (frm.source_ip_address_ipv6.value == '') {
        <?php } ?>
            if (frm.source_ip_address.value == '' || !is_valid_ip_address(frm.source_ip_address.value))
            {
                alert("Invalid source IP address specified");
                frm.source_ip_address.focus();
                return false;
            }
        <?php if (ENABLE_IPV6) { ?>
        }
        <?php } ?>

        if (!!frm.multicast_filter_address.value && !is_valid_ip_address(frm.multicast_filter_address.value))
        {
            alert("Invalid primary multicast filter address specified");
            frm.multicast_filter_address.focus();
            return false;
        }

        if (!!frm.multicast_filter_address_2.value && !is_valid_ip_address(frm.multicast_filter_address_2.value))
        {
            alert("Invalid secondary multicast filter address specified");
            frm.multicast_filter_address_2.focus();
            return false;
        }


        if (output != "IP" && output != "DVBASI" && (frm.output_encoder.value == "MPEG2" || frm.output_encoder.value == "MPEG2LD") )
        {
            alert("Invalid output encoder specified, MPEG2 not allowed for this format");
            frm.output_encoder.focus();
            return false;
        }

        if (output == "RTMP" && frm.output_encoder.value == "H264LD") {
            alert("Invalid output encoder specified, H264 Low Delay not allowed for this format");
            frm.output_encoder.focus();
            return false;
        }


        if (isMPEG2LD)
        {
            if (frm.output_mux_rate.value == ''     ||
                !is_int(frm.output_mux_rate)        ||
                frm.output_mux_rate.value < 150000 ||
                frm.output_mux_rate.value > 45000001)
            {
                alert("Invalid output mux rate specified. Must be between 150 kbps and 45 Mbps");
                frm.output_mux_rate.focus();
                return false;
            }
        }
        else
        {
            if (frm.output_mux_rate.value == ''     ||
                !is_int(frm.output_mux_rate)        ||
                frm.output_mux_rate.value < 150000 ||
                frm.output_mux_rate.value > 20000001)
            {
                alert("Invalid output mux rate specified. Must be between 150 kbps and 20 Mbps");
                frm.output_mux_rate.focus();
                return false;
            }
        }

<?php if (ENABLE_OUTPUT_VIDEO_BITRATE == 1) { ?>
        if (!is_int(frm.output_video_bitrate) && frm.output_video_bitrate.value != '' ||
            is_int(frm.output_video_bitrate) && frm.output_video_bitrate.value != 0 && (frm.output_video_bitrate.value < 150000 || frm.output_video_bitrate.value > 20000000))
        {
            alert("Invalid output video bitrate specified");
            frm.output_video_bitrate.focus();
            return false;
        }

        if (is_int(frm.output_video_bitrate) &&
            is_int(frm.output_mux_rate) &&
            parseInt(frm.output_video_bitrate.value) > parseInt(frm.output_mux_rate.value))
        {
            alert("Output video bitrate must be less than output mux rate");
            frm.output_video_bitrate.focus();
            return false;
        }
<?php } ?>

        if (!is_int(frm.audio_ac3_dialnorm0) ||
            frm.audio_ac3_dialnorm0.value < 0 ||
            frm.audio_ac3_dialnorm0.value > 31)
        {
            alert("Invalid AC3 dialnorm specified for Primary Audio. Must be 0-31.");
            frm.audio_ac3_dialnorm0.focus();
            return false;
        }

        if (!is_int(frm.audio_ac3_dialnorm1) ||
            frm.audio_ac3_dialnorm1.value < 0 ||
            frm.audio_ac3_dialnorm1.value > 31)
        {
            alert("Invalid AC3 dialnorm specified for Secondary Audio. Must be 0-31.");
            frm.audio_ac3_dialnorm1.focus();
            return false;
        }

        if (!is_int(frm.audio_ac3_dialnorm2) ||
            frm.audio_ac3_dialnorm2.value < 0 ||
            frm.audio_ac3_dialnorm2.value > 31)
        {
            alert("Invalid AC3 dialnorm specified for Third Audio. Must be 0-31.");
            frm.audio_ac3_dialnorm2.focus();
            return false;
        }

        if (!is_int(frm.output_scte35_pid) || !(1 <= frm.output_scte35_pid.value && frm.output_scte35_pid.value <= 8191))
        {
            alert("Output SCTE35 PID must be a decimal integer between 1 and 8191");
            frm.output_scte35_pid.focus();
            return false;
        }

       if (!is_int(frm.output_pmt_pid) || !(1 <= frm.output_pmt_pid.value && frm.output_pmt_pid.value <= 8191))
        {
            alert("Output PMT PID must be a decimal integer between 1 and 8191");
            frm.output_pmt_pid.focus();
            return false;
        }

        if (!is_int(frm.output_video_pid) || !(1 <= frm.output_video_pid.value && frm.output_video_pid.value <= 8191))
        {
            alert("Output video PID must be a decimal integer between 1 and 8191");
            frm.output_video_pid.focus();
            return false;
        }

        if (!is_int(frm.output_audio_pid) || !(1 <= frm.output_audio_pid.value && frm.output_audio_pid.value <= 8191))
        {
            alert("Output audio base PID must be a decimal integer between 1 and 8191");
            frm.output_audio_pid.focus();
            return false;
        }

        if (!is_int(frm.output_transport_stream_id) || !(1 <= frm.output_transport_stream_id.value && frm.output_transport_stream_id.value <= 8191))
        {
            alert("Output transport stream ID must be a decimal integer between 1 and 8191");
            frm.output_transport_stream_id.focus();
            return false;
        }

        if (!is_int(frm.output_program_number) || !(1 <= frm.output_program_number.value && frm.output_program_number.value <= 8191))
        {
            alert("Output program number must be a decimal integer between 1 and 8191");
            frm.output_program_number.focus();
            return false;
        }

        if (!is_int(frm.output_pat_rate) || !(20 <= frm.output_pat_rate.value && frm.output_pat_rate.value <= 100))
        {
            alert("Output PAT repetition rate number must be a decimal integer between 20 and 100");
            frm.output_pat_rate.focus();
            frm.output_pat_rate.select();
            return false;
        }

        if (!is_int(frm.output_pmt_rate) || !(50 <= frm.output_pmt_rate.value && frm.output_pmt_rate.value <= 400)) //!!DBA TODO
        {
            alert("Output PMT repetition rate number must be a decimal integer between 50 and 400");
            frm.output_pmt_rate.focus();
            frm.output_pmt_rate.select();
            return false;
        }

        if (!is_int(frm.output_pcr_rate) || !(20 <= frm.output_pcr_rate.value && frm.output_pcr_rate.value <= 100)) //!!DBA TODO
        {
            alert("Output PCR repetition rate number must be a decimal integer between 20 and 100");
            frm.output_pcr_rate.focus();
            frm.output_pcr_rate.select();
            return false;
        }

        var output_scte35_pid = frm.output_scte35_pid.value;
        var output_pmt_pid = frm.output_pmt_pid.value;
        var output_video_pid = frm.output_video_pid.value;
        var output_audio_pid = frm.output_audio_pid.value;
        if (output_pmt_pid == output_video_pid || output_pmt_pid == output_audio_pid || output_video_pid == output_audio_pid || output_scte35_pid == output_pmt_pid || output_scte35_pid == output_video_pid || output_scte35_pid == output_audio_pid )
        {
            alert("Output PID values must not be equal");
            frm.output_pmt_pid.focus();
            return false;
        }


/*
        if (frm.rtmp_server_address.value == '' || !is_valid_ip_address(frm.rtmp_server_address.value))
        {
            alert("Invalid RTMP server IP address specified");
            frm.rtmp_server_address.focus();
            return false;
        }
        if (frm.rtmp_remote_server_address.value == '' || !is_valid_ip_address(frm.rtmp_remote_server_address.value))
        {
            alert("Invalid remote RTMP server name specified");
            frm.rtmp_remote_server_address.focus();
            return false;
        }
*/
        if ("APPLE" == input_interface) {
            var prefix = "http://";
            var val = frm.apple_hls_input_url && frm.apple_hls_input_url.value;
            if (!val || !val.length || (val.length < prefix.length + 1) || val.substr(0,prefix.length) != prefix) {
                alert("Invalid Apple HLS URL specified");
                frm.apple_hls_input_url.focus();
                frm.apple_hls_input_url.select();
                return false;
            }
        }

        if ("RTMP" == input_interface) {
            var prefix = "rtmp://";
            var val = frm.rtmp_input_url && frm.rtmp_input_url.value;
            if (!val || !val.length || (val.length < prefix.length + 1) || val.substr(0,prefix.length) != prefix) {
                alert("Invalid RTMP input URL specified");
                frm.rtmp_input_url.focus();
                frm.rtmp_input_url.select();
                return false;
            }
            var val = frm.rtmp_input_stream_name && frm.rtmp_input_stream_name.value;
            if (!val || !val.length) {
                alert("Invalid RTMP input stream name specified");
                frm.rtmp_input_stream_name.focus();
                frm.rtmp_input_stream_name.select();
                return false;
            }
        }

        if (frm.hls_segment_rollover_count.value == '' || !is_int(frm.hls_segment_rollover_count) || frm.hls_segment_rollover_count.value < 100 || frm.hls_segment_rollover_count.value > 50000) {
            alert("HLS segment rollover count must be an integer between 100 and 50000.");
            frm.hls_segment_rollover_count.focus();
            frm.hls_segment_rollover_count.select();
            return false;
        }

        if (frm.rtmp_server_address.value == '')
        {
            alert("Invalid RTMP server IP address specified");
            frm.rtmp_server_address.focus();
            return false;
        }

        if ($("#verimatrix_enable").val() == "1") {
            var val = frm.verimatrix_encryptor_url && frm.verimatrix_encryptor_url.value;
            if (!val || !val.length || val.search(/^http:\/\/.*/) != 0 && val.search(/^https:\/\/.*/) != 0) {
                alert("Invalid Verimatrix encryptor URL specified.");
                frm.verimatrix_encryptor_url.focus();
                frm.verimatrix_encryptor_url.select();
                return false;
            }

            val = frm.verimatrix_client_url && frm.verimatrix_client_url.value;
            if (val && val.length > 0 && val.search(/^http:\/\/.*/) != 0 && val.search(/^https:\/\/.*/) != 0) {
                alert("Invalid Verimatrix client URL specified.");
                frm.verimatrix_client_url.focus();
                frm.verimatrix_client_url.select();
                return false;
            }

            if (!is_int(frm.verimatrix_max_segments))
            {
                alert("Verimatrix max segments value must be integer.");
                frm.verimatrix_max_segments.focus();
                frm.verimatrix_max_segments.select();
                return false;
            }

            /*
            if (!is_int(frm.verimatrix_resource_id))
            {
                alert("Verimatrix resource ID must be integer.");
                frm.verimatrix_resource_id.focus();
                frm.verimatrix_resource_id.select();
                return false;
            }
            */
        } else {
            if (!is_int(frm.verimatrix_max_segments)) {
                frm.verimatrix_max_segments.value = 3;
            }
            /*
             *if (!is_int(frm.verimatrix_resource_id)) {
                frm.verimatrix_resource_id.value = 0;
            } */
        }

        if ($("#buydrm_enable1").val() == "1") {
            var group1_enabled = $("#stream_group_checkbox1").is(":checked");
            if (group1_enabled) {
                if (!is_valid_guid(frm.buydrm_userkey1.value)) {
                    alert("BuyDRM User Key is not a valid GUID. Please obtain your user key from BuyDRM.");
                    frm.buydrm_userkey1.focus();
                    frm.buydrm_userkey1.select();
                    return false;
                }
                if (frm.buydrm_userkey1.value == "00000000-0000-0000-0000-000000000000") {
                    alert("BuyDRM User Key must not be zeros. Please obtain your user key from BuyDRM.");
                    frm.buydrm_userkey1.focus();
                    frm.buydrm_userkey1.select();
                    return false;
                }

                if (!is_valid_guid(frm.buydrm_keyid1.value)) {
                    alert("BuyDRM Key ID is not a valid GUID.");
                    frm.buydrm_keyid1.focus();
                    frm.buydrm_keyid1.select();
                    return false;
                }
                if (frm.buydrm_keyid1.value == "00000000-0000-0000-0000-000000000000") {
                    alert("BuyDRM Key ID must not be zeros. Please enter valid ID or click Generate to create one.");
                    frm.buydrm_keyid1.focus();
                    frm.buydrm_keyid1.select();
                    return false;
                }

                if (!is_valid_guid(frm.buydrm_contentid1.value)) {
                    alert("BuyDRM Content ID is not a valid GUID.");
                    frm.buydrm_contentid1.focus();
                    frm.buydrm_contentid1.select();
                    return false;
                }
                if (frm.buydrm_contentid1.value == "00000000-0000-0000-0000-000000000000") {
                    alert("BuyDRM Content ID must not be zeros. Please enter valid ID or click Generate to create one.");
                    frm.buydrm_contentid1.focus();
                    frm.buydrm_contentid1.select();
                    return false;
                }

                val = frm.buydrm_mediaid1.value;
                if (!val || !val.length) {
                    alert("BuyDRM Media ID is not a valid string.");
                    frm.buydrm_mediaid1.focus();
                    frm.buydrm_mediaid1.select();
                    return false;
                }
            }
        }

        if ($("#buydrm_enable2").val() == "1") {
            var group2_enabled = $("#stream_group_checkbox2").is(":checked");
            if (group2_enabled) {
                if (!is_valid_guid(frm.buydrm_userkey2.value)) {
                    alert("BuyDRM User Key is not a valid GUID. Please obtain your user key from BuyDRM.");
                    frm.buydrm_userkey2.focus();
                    frm.buydrm_userkey2.select();
                    return false;
                }
                if (frm.buydrm_userkey2.value == "00000000-0000-0000-0000-000000000000") {
                    alert("BuyDRM User Key must not be zeros. Please obtain your user key from BuyDRM.");
                    frm.buydrm_userkey2.focus();
                    frm.buydrm_userkey2.select();
                    return false;
                }

                if (!is_valid_guid(frm.buydrm_keyid2.value)) {
                    alert("BuyDRM Key ID is not a valid GUID.");
                    frm.buydrm_keyid2.focus();
                    frm.buydrm_keyid2.select();
                    return false;
                }
                if (frm.buydrm_keyid2.value == "00000000-0000-0000-0000-000000000000") {
                    alert("BuyDRM Key ID must not be zeros. Please enter valid ID or click Generate to create one.");
                    frm.buydrm_keyid2.focus();
                    frm.buydrm_keyid2.select();
                    return false;
                }

                if (!is_valid_guid(frm.buydrm_contentid2.value)) {
                    alert("BuyDRM Content ID is not a valid GUID.");
                    frm.buydrm_contentid2.focus();
                    frm.buydrm_contentid2.select();
                    return false;
                }
                if (frm.buydrm_contentid2.value == "00000000-0000-0000-0000-000000000000") {
                    alert("BuyDRM Key ID must not be zeros. Please enter valid ID or click Generate to create one.");
                    frm.buydrm_contentid2.focus();
                    frm.buydrm_contentid2.select();
                    return false;
                }

                val = frm.buydrm_mediaid2.value;
                if (!val || !val.length) {
                    alert("BuyDRM Media ID is not a valid string.");
                    frm.buydrm_mediaid2.focus();
                    frm.buydrm_mediaid2.select();
                    return false;
                }
            }
        }

        var rtmp_naming_elem = $("#rtmp_naming");
        var rtmp_prefix_elem = $("#rtmp_remote_server_address");
        var rtmp_auto_naming = "auto" == rtmp_naming_elem.val();

        if (rtmp_auto_naming) {
            if (frm.rtmp_remote_server_address.value == '')
            {
                alert("Invalid RTMP stream name prefix specified");
                frm.rtmp_remote_server_address.focus();
                return false;
            }
        } else {
            var iGroup;
            var iStreamInGroup;
            for (iGroup = 0; iGroup < MAX_STREAM_GROUPS; ++iGroup)
            {
                var group_enabled = $("#stream_group_checkbox"+(iGroup+1)).is(":checked");
                if (group_enabled) {
                    for (iStreamInGroup = 0; iStreamInGroup < MAX_VIDEO_STREAMS; ++iStreamInGroup)
                    {
                        var iStream = iGroup*MAX_VIDEO_STREAMS + iStreamInGroup;
                        var stream_active = frm.elements["stream_active"+iStream];
                        if (stream_active)
                        {
                            var stream_enabled = group_enabled && stream_active.checked;
                            if (stream_enabled) {
                                var stream_name_elem = $("#rtmp_stream_name"+iStream);
                                var stream_name = stream_name_elem.val();
                                if (!stream_name || !stream_name.length) {
                                    alert("Invalid RTMP stream name specified");
                                    stream_name_elem.focus();
                                    return false;

                                }
                            }
                        }
                    }
                }
            }
        }


/*
        if (frm.http_server_address.value != '')
        {
            var addr = frm.http_server_address.value;
            if (addr.search(/sftp:\/\//g) != -1)
            {
                var ip = addr.slice(7, addr.length);

                if (!is_valid_ip_address(ip))
                {
                    alert("Invalid HTTP server IP address specified");
                    frm.http_server_address.focus();
                    return false;
                }
            }
            else
            {
                if (!is_valid_ip_address(frm.http_server_address.value))
                {
                    alert("Invalid HTTP server IP address specified");
                    frm.http_server_address.focus();
                    return false;
                }
            }
        }
 */

        var isMultirateOutput = is_multirate_output();

        var nGroupsEnabled = 0;
        var nAudioOnly = 0;
        var special1fpsMode = 0;

        for (var iGroup = 0; iGroup < MAX_STREAM_GROUPS; ++iGroup)
        {
            var nStreamsEnabled = 0;
            var group_enabled = $("#stream_group_checkbox"+(iGroup+1)).is(":checked");
            if (group_enabled) {
                ++nGroupsEnabled;
            }
            for (var iStreamInGroup = 0; iStreamInGroup < MAX_VIDEO_STREAMS; ++iStreamInGroup)
            {
                var iStream = iGroup*MAX_VIDEO_STREAMS + iStreamInGroup;

                var stream_active = frm.elements["stream_active"+iStream];
                if (stream_active)
                {
                    var stream_enabled = stream_active.checked && group_enabled;
                    if (stream_enabled)
                        ++nStreamsEnabled;

                    var stream_width_elem = frm.elements["stream_width"+iStream];
                    var stream_height_elem = frm.elements["stream_height"+iStream];
                    var stream_bitrate_elem = frm.elements["stream_bitrate"+iStream];
                    var stream_codec_elem = frm.elements["stream_codec"+iStream];
                    var stream_fps_elem = frm.elements["stream_framerate"+iStream];
                    var stream_profile_elem = frm.elements["stream_profile"+iStream];
                    var stream_audio_bitrate_elem = frm.elements["stream_audio_bitrate"+iStream];
                    var stream_audio_channels_elem = frm.elements["stream_audio_channels"+iStream];

                    var audio_only = $("#stream_audio_only"+iStream).is(":checked");
                    var video_enabled =  stream_enabled && !audio_only;

                    if (stream_enabled && audio_only) {
                        ++nAudioOnly;
                    }

                    <?php if (0 == strcasecmp(VENDOR, "CSIX")) { ?>
                    if (iStream == 0 && stream_enabled) {
                        special1fpsMode = stream_fps_elem.value == 101;
                    } else if (iStream > 0 && special1fpsMode && stream_enabled) {
                        alert("When 1 FPS mode is selected, only Stream 1 can be enabled.");
                        stream_active.focus();
                        return false;
                    }
                    <?php } ?>

                    if (stream_width_elem.value == '' || !is_int(stream_width_elem))
                    {
                        alert("Invalid video stream width value for Group "+(iGroup+1)+" Stream "+(iStreamInGroup+1));
                        stream_width_elem.focus();
                        return false;
                    }
                    if (video_enabled && (stream_width_elem.value > 3840 || stream_width_elem.value < 64))
                    {
                        alert("Invalid video stream width value for Group "+(iGroup+1)+" Stream "+(iStreamInGroup+1));
                        stream_width_elem.focus();
                        return false;
                    }


                    if (stream_height_elem.value == '' || !is_int(stream_height_elem))
                    {
                        alert("Invalid video stream height value for Group "+(iGroup+1)+" Stream "+(iStreamInGroup+1));
                        stream_height_elem.focus();
                        return false;
                    }
                    if (video_enabled && (stream_height_elem.value > 2160 || stream_height_elem.value < 64))
                    {
                        alert("Invalid video stream height value for Group "+(iGroup+1)+" Stream "+(iStreamInGroup+1));
                        stream_height_elem.focus();
                        return false;
                    }

                    if (stream_bitrate_elem.value == '' || !is_int(stream_bitrate_elem))
                    {
                        alert("Invalid video stream bitrate value for Group "+(iGroup+1)+" Stream "+(iStreamInGroup+1));
                        stream_bitrate_elem.focus();
                        return false;
                    }
                    if (video_enabled && (stream_bitrate_elem.value > 25000 || stream_bitrate_elem.value < 32))
                    {
                        alert("Invalid video stream bitrate value for Group "+(iGroup+1)+" Stream "+(iStreamInGroup+1));
                        stream_bitrate_elem.focus();
                        return false;
                    }

                    var stream_max_bitrate_elem = frm.elements["stream_max_bitrate"+iStream];
                    if (stream_max_bitrate_elem) {
                        var is_vbr = get_stream_vbr(iStream);
                        if (stream_max_bitrate_elem.value == '' || !is_int(stream_max_bitrate_elem))
                        {
                            alert("Invalid max video stream bitrate value for Group "+(iGroup+1)+" Stream "+(iStreamInGroup+1));
                            stream_max_bitrate_elem.focus();
                            stream_max_bitrate_elem.select();
                            return false;
                        }

                        if (video_enabled && is_vbr && (stream_max_bitrate_elem.value > 25000 || stream_max_bitrate_elem.value < 32 || parseInt(stream_max_bitrate_elem.value) < stream_bitrate_elem.value))
                        {
                            alert("Invalid max video stream bitrate value for Group "+(iGroup+1)+" Stream "+(iStreamInGroup+1));
                            stream_max_bitrate_elem.focus();
                            stream_max_bitrate_elem.select();
                            return false;
                        }

                    }
                }
            }
/*            if (group_enabled && nStreamsEnabled == 0 && isMultirateOutput) {
                alert("Multirate stream group "+(iGroup+1)+" is enabled but no streams are enabled.");
                var group_box = $("#stream_group_checkbox"+(iGroup+1))[0];
                group_box.focus();
                group_box.select();
                return false;
            }
*/
        }

/*        if (nGroupsEnabled == 0 && isMultirateOutput) {
            alert("No multirate stream groups are enabled.");
            var group_box = $("#stream_group_checkbox1")[0];
            group_box.focus();
            group_box.select();
            return false;
        }

        if (nAudioOnly > 1 && isMultirateOutput) {
            alert("Multiple audio-only streams not permitted.");
            return false;
        }
  */
        if (output == "TSFILE")
        {
            var filename = frm.output_filename.value;
            if (!filename || !filename.length)
            {
                alert("Output filename must be specified");
                frm.output_filename.focus();
                return false;
            }

        }
        else if (output == "SILVERLIGHT")
        {
            if (frm.publishing_point1.value.search(/http:\/\/[a-zA-Z0-9\-_.]+(:[0-9]{1,5}){0,1}\/(\w+\/)*\w+\.isml/) == -1)
            {
                alert("Invalid publishing point (Group 1) specified.\nMost be of the form:\nhttp://host/path/name.isml (optional host:port)");
                frm.publishing_point1.focus();
                return false;
            }

            if (trim(frm.publishing_point1.value) == trim(frm.publishing_point2.value))
            {
                alert("Invalid publishing point specified.  Publishing points must be unique.");
                frm.publishing_point2.focus();
                return false;
            }

            if (frm.publishing_point_auth1.value != "none")
            {
                if (!frm.publishing_point_username1.value || !frm.publishing_point_username1.value.length) {
                    alert("Publishing point username must be specified if authentication is enabled.");
                    frm.publishing_point_username1.focus();
                    return false;
                }
                if (!frm.publishing_point_password1.value || !frm.publishing_point_password1.value.length) {
                    alert("Publishing point password must be specified if authentication is enabled.");
                    frm.publishing_point_password1.focus();
                    return false;
                }
            }
        }

/*        if (frm.output_file_max_size.value != "" && !is_int(frm.output_file_max_size))
        {
            alert("Output max file size must be an integer");
            frm.output_file_max_size.focus();
            return false;
        }

        if (frm.output_file_max_duration.value != "" && !is_int(frm.output_file_max_duration))
        {
            alert("Output max duration must be an integer");
            frm.output_file_max_duration.focus();
            return false;
        }
*/
        // Multi TS file options
        if (frm.multi_output_file_max_size.value != "" && !is_int(frm.multi_output_file_max_size))
        {
            alert("Output max file size must be an integer");
            frm.multi_output_file_max_size.focus();
            return false;
        }

        if (frm.multi_output_file_max_duration.value != "" && !is_int(frm.multi_output_file_max_duration))
        {
            alert("Output max duration must be an integer");
            frm.multi_output_file_max_duration.focus();
            return false;
        }

        if (output == "MULTITS")
        {
            multi_output_file_mode = parseInt($('input[name=multi_output_file_mode]:checked').val());
            switch (multi_output_file_mode)
            {
                case 0: // None
                    break;
                case 1: // Duration
                    if (!parseInt(frm.multi_output_file_max_duration.value))
                    {
                        alert("Output max duration must be specifed");
                        frm.multi_output_file_max_duration.focus();
                        return false;
                    }
                    break;
                case 2: // Size
                    if (!parseInt(frm.multi_output_file_max_size.value))
                    {
                        alert("Output max file size must be specifed");
                        frm.multi_output_file_max_size.focus();
                        return false;
                    }
                    break;
                case 3: // Unlimited
                    break;
            }
            if(frm.origin_server_address.value.endsWith("/"))
            {
                alert("Please remove trailing slashes from the origin server address.");
                return false;
            }
        }

// DEBUG OPTIONS BEGIN
        if (frm.yuv_file_name.value == '')
        {
            alert("Invalid YUV input file specified");
            frm.yuv_file_name.focus();
            return false;
        }

        if (frm.yuv_frame_rate.value == '' || !is_float(frm.yuv_frame_rate))
        {
            alert("Invalid YUV input frame rate specified");
            frm.yuv_frame_rate.focus();
            return false;
        }

        if (frm.yuv_input_buffer_size.value == '' || !is_int(frm.yuv_input_buffer_size))
        {
            alert("Invalid YUV input buffer size specified");
            frm.yuv_input_buffer_size.focus();
            return false;
        }

        if (frm.delay.value == '')
        {
            alert("Invalid delay specified");
            frm.delay.focus();
            return false;
        }

        if (frm.buffer_delay.value == '' || !is_int(frm.buffer_delay))
        {
            alert("Invalid buffer delay specified");
            frm.buffer_delay.focus();
            return false;
        }
// DEBUG OPTIONS END


        input_preset = frm.input_resolution.value;
        output_preset = frm.output_resolution.value;
        output_framerate = frm.output_framerate.value;

        if (isMPEG2LD)
        {
            // Check if user manually entered HD1080 or HD720 manually or as Same as input
            if (output_preset == "USER")
            {
                var w = frm.output_width.value;
                var h = frm.output_height.value;
                if (w == 1920 && h == 1080)
                    output_preset = "HD1080";
                else if (w == 1280 && h == 720)
                    output_preset = "HD720";
            }
            else if (output_preset == "SAME")
            {
                if (input_preset == "HD1080")
                    output_preset = "HD1080";
                else if (input_preset == "HD720")
                    output_preset = "HD720";
                else if (input_preset == "USER")
                {
                    var w = frm.input_width.value;
                    var h = frm.input_height.value;
                    if (w == 1920 && h == 1080)
                        output_preset = "HD1080";
                    else if (w == 1280 && h == 720)
                        output_preset = "HD720";
                }
            }

            var validOutputRes = false;
            if (output_preset == "HD1080" && output_format == 1)
                validOutputRes = true;
            else if (output_preset == "HD720" && output_format == 0)
                validOutputRes = true;

            if (!validOutputRes)
            {
                alert("Invalid output resolution.  Must be HD1080i or HD720p for MPEG2 Low Delay output");
                frm.output_format.focus();
                return false;
            }
        }

        // PAL-to-NTSC, output height must be 480
//        if (frm.input_format[1].checked == true &&
//            frm.output_format[0].checked == true)
//        {
//            if (frm.input_width.value != frm.output_width.value)
//            {
//                alert("Output width must be equal to input width");
//                frm.output_width.value = frm.input_width.value;
//                frm.output_width.focus();
//                return false;
//            }
//
//            if (frm.output_height.value != 480)
//            {
//                alert("Output height must be 480 for PAL-to-NTSC conversion");
//                frm.output_height.value = 480;
//                frm.output_height.focus();
//                return false;
//            }
//        }
//        else if (frm.input_format[0].checked == true &&
//                 frm.output_format[1].checked == true)
//        {
//            alert("NTSC-to-PAL conversion is not supported");
//            return false;
//        }
//        else
//        {
//            if (frm.input_width.value != frm.output_width.value ||
//                frm.input_height.value != frm.output_height.value)
//            {
//                alert("Output resolution must be equal to the input resolution");
//                frm.output_width.value = frm.input_width.value;
//                frm.output_height.value = frm.input_height.value;
//                return false;
//            }
//        }


        if (frm.prefilter_contrast.value == '' ||
           !is_int(frm.prefilter_contrast)    ||
           frm.prefilter_contrast.value < 0   ||
           frm.prefilter_contrast.value > 255)
        {
           alert("Contrast must be between 0 and 255");
           frm.prefilter_contrast.focus();
           frm.prefilter_contrast.select();
           return false;
        }

        if (frm.prefilter_brightness.value == '' ||
           !is_int(frm.prefilter_brightness)    ||
           frm.prefilter_brightness.value < 0   ||
           frm.prefilter_brightness.value > 16)
        {
           alert("Brightness must be between 0 and 16");
           frm.prefilter_brightness.focus();
           frm.prefilter_brightness.select();
           return false;
        }

        // Do the crop dimension checks whether cropping is enabled or not to prevent user from
        // entering something weird like 'abc' and saving it which could result in a corrupt config.

        if (!is_int(frm.crop_top))
        {
            alert("Invalid input cropping value for top.");
            frm.crop_top.focus();
            return false;
        }

        if (!is_int(frm.crop_left))
        {
            alert("Invalid input cropping value for left.");
            frm.crop_left.focus();
            return false;
        }

        if (!is_int(frm.crop_right))
        {
            alert("Invalid input cropping value for right.");
            frm.crop_right.focus();
            return false;
        }

        if (!is_int(frm.crop_bottom))
        {
            alert("Invalid input cropping value for bottom.");
            frm.crop_bottom.focus();
            return false;
        }

        if (frm.enable_crop.checked)
        {
            var crop_top = frm.crop_top.value;
            var crop_left = frm.crop_left.value;
            var crop_right = frm.crop_right.value;
            var crop_bottom = frm.crop_bottom.value;

            if (crop_top == 0 && crop_bottom == 0 && crop_left == 0 && crop_right == 0)
            {
                alert("Valid cropping dimensions must be specified when input cropping is enabled.");
                frm.crop_top.focus();
                return false;
            }
        }

        if (!is_int(frm.image_overlay_alpha) || frm.image_overlay_alpha.value < 0 || frm.image_overlay_alpha.value > 100)
        {
            alert("Invalid image overlay alpha blending value. Must be between 0 and 100.");
            frm.image_overlay_alpha.focus();
            return false;
        }

        if (!is_int(frm.sdi_frame_timeout) || frm.sdi_frame_timeout.value < 0)
        {
            alert("Invalid SDI frame timeout. Must be between integer greater than 0.");
            frm.sdi_frame_timeout.focus();
            return false;
        }

        if (!is_int(frm.sdi_cc_data_rate) || frm.sdi_cc_data_rate.value <= 0)
        {
            alert("Invalid SDI CC data rate. Must be between integer greater than 0.");
            frm.sdi_cc_data_rate.focus();
            return false;
        }

        if (!is_int(frm.image_overlay_margin_x) || frm.image_overlay_margin_x.value < 0 || frm.image_overlay_margin_x.value > 2000)
        {
            alert("Invalid image overlay X margin value.");
            frm.image_overlay_margin_x.focus();
            return false;
        }

        if (!is_int(frm.image_overlay_margin_y) || frm.image_overlay_margin_y.value < 0 || frm.image_overlay_margin_y.value > 2000)
        {
            alert("Invalid image overlay Y margin value.");
            frm.image_overlay_margin_y.focus();
            return false;
        }

        if (frm.sdp_session_name.value.indexOf('=') != -1 || frm.sdp_session_name.value.indexOf('&') != -1)
        {
            alert("SDP session name cannot contain: = &");
            frm.sdp_session_name.focus();
            return false;
        }

//        if(!$("#configuration")[0].checkValidity())
//        {
//            alert("Please correct errors in form before saving.");
//            return false;
//        }

        return  true;
    }
    $('#configuration').submit(function(event){
        event.preventDefault();
     });
    function save_file()
    {
        var select_obj = document.getElementById("current_file");
        $("#configuration").submit();
        if (form_is_valid())
        {
            save_form(select_obj.value);
        }
    }

    function delete_file()
    {
        var select_obj = document.getElementById("current_file");
        var config = select_obj.value;
        $.getJSON(jsonUrl,
        {
                fName: "IsConfigRunning",
                config: config
        },
        function GetData(data)
        {
            if(data)
            {
                if(data.data != "0")
                {
                    alert("Config file " + config + " cannot be deleted because it is currently in use");
                    return;
                }
                delete_form(select_obj.value);
                location.reload(true);
            }
        });
    }

    function reset_defaults()
    {
        if (!confirm("This will reset the current configuration values to default settings.\n\nYou will lose any changes to this configuration that you have made since saving.  Continue?"))
            return;

        var frm = document.configuration;
        if (window.XMLHttpRequest)
        {
            var xmlhttp = new XMLHttpRequest();
            var current_time = new Date();
            xmlhttp.open('GET', '<?php echo $SELF; ?>?action=get_config_defaults&ts='+current_time.getTime(), false);
            xmlhttp.send();

            results = xmlhttp.responseText.split(";");

            // Override the default.cfg filename with the currently selected config name
            update_form(results, $(frm.current_file).val());
        }
    }

    function save_new_file()
    {
        if (!form_is_valid()) {
            return;
        }

        var cur_config_name = $("#current_file").val();
        if (!cur_config_name || !cur_config_name.length)
            cur_config_name = "default.cfg";

        var filename = prompt('Enter configuration filename:', cur_config_name);
        var frm = document.configuration;

        if (filename != null)
        {
            // Check that the filename has the correct extension
            if (filename.lastIndexOf(".cfg") ==-1)
            {
                filename += ".cfg";
            }
            if (form_is_valid())
            {
                save_form(filename);
                frm.current_file.options[frm.current_file.options.length] = new Option(filename, filename, false, true);
                save_state();
            }
        }
    }

    function delete_form(filename)
    {
        if (window.XMLHttpRequest)
        {
            var xmlhttp;
            var current_time = new Date();

            xmlhttp = new XMLHttpRequest();
            xmlhttp.open('GET', '<?php echo $SELF; ?>?action=delete_file&config_filename='+filename+'&ts='+current_time.getTime(), false);
            xmlhttp.setRequestHeader("Connection", "close");
            xmlhttp.send();

            if (xmlhttp.responseText == "OK")
            {
                alert("Configuration file deleted.");
            }
            else
            {
                alert("Error deleting configuration.");
            }
        }
    }

    function save_form(filename)
    {
        if (window.XMLHttpRequest)
        {
            var frm = document.configuration;
            var params;
            var j;

            params = "config_filename=" + filename;

            params += "&input_resolution=" + frm.input_resolution.value;
            params += "&output_resolution=" + frm.output_resolution.value;
            params += "&input_framerate=" + frm.input_framerate.value;
            params += "&enable_psf=" + frm.enable_psf.value;
            params += "&output_framerate=" + frm.output_framerate.value;
            if (frm.enable_crop.checked == true)
            {
                params += "&output_resizing=2";
            }
            else
            {
                params += "&output_resizing=0";
            }
            params += "&input_format=" + frm.input_format.value;
            params += "&input_width=" + frm.input_width.value;
            params += "&input_height=" + frm.input_height.value;
            params += "&input_stream=" + frm.input_stream.value;
            params += "&input_program_number=" + frm.input_program_number.value;

            <?php if (ENABLE_DVB_SUBTITLES == 1) { ?>
            var subtitle_mode = $(".input_subtitle_mode:checked").val();
            if (subtitle_mode < 0 || subtitle_mode > 3) {
                subtitle_mode = 0;
            }
            params += "&input_subtitle_mode=" + subtitle_mode;

            var subtitle_pid = frm.input_subtitle_pid.value;
            if (subtitle_pid == "") {
                subtitle_pid = -1;
            }
            params += "&input_subtitle_pid=" + subtitle_pid;
            params += "&input_subtitle_order=" + frm.input_subtitle_order.value;
            params += "&input_subtitle_delay=" + frm.input_subtitle_delay.value;
            params += "&input_subtitle_late=" + frm.input_subtitle_late.value;
            <?php } ?>
            params += "&crop_left=" + frm.crop_left.value;
            params += "&crop_top=" + frm.crop_top.value;
            params += "&crop_right=" + frm.crop_right.value;
            params += "&crop_bottom=" + frm.crop_bottom.value;
            params += "&enable_gpu=" + (frm.enable_gpu.checked ? "1" : "0");
            params += "&output_format=" + frm.output_format.value;
            params += "&aspect_ratio=" + frm.aspect_ratio.value;
            params += "&biss_mode=" + frm.biss_mode.value;
            params += "&biss_key=" + frm.biss_key.value;
            params += "&biss_session_key=" + frm.biss_session_key.value;
            <?php if (ENABLE_QUALITY_LEVEL == 1) { ?>
            params += "&quality_level=" + frm.quality_level.value;
            <?php } ?>
            params += "&output_width=" + frm.output_width.value;
            params += "&output_height=" + frm.output_height.value;
            params += "&output_encoder=" + frm.output_encoder.value;
            params += "&cpb_delay=" + frm.cpb_delay.value;

            var input_interface = get_active_input_interface();
            params += "&input_interface=" + input_interface;

            var output_interface = get_active_output_interface();
            params += "&output_interface=" + output_interface;

            params += "&I_P_frame_distance=" + frm.I_P_frame_distance.value;
            params += "&GOP_length_seconds=" + frm.GOP_length_seconds.value;

            params += "&output_audio_agc=" + frm.output_audio_agc.value;

            params += "&output_audio_format=" + frm.output_audio_format.value;
            params += "&output_audio_bitrate0=" + frm.output_audio_bitrate0.value;
            params += "&output_audio_bitrate1=" + frm.output_audio_bitrate1.value;
            params += "&output_audio_bitrate2=" + frm.output_audio_bitrate2.value;

            params += "&input_audio_pid0=" + frm.input_audio_pid0.value;
            // May 16, 2025 disabling audio bitrate check for secondary audio
            // params += "&input_audio_pid1=" + (frm.output_audio_bitrate1.value != 0?frm.input_audio_pid1.value:-1);
            params += "&input_audio_pid1=" + frm.input_audio_pid1.value;

            params += "&input_audio_pid2=" + (frm.output_audio_bitrate2.value != 0?frm.input_audio_pid2.value:-1);
            params += "&output_audio_samplerate=" + frm.output_audio_samplerate.value;
            params += "&output_audio_volume0=" + frm.output_audio_volume0.value;
            params += "&output_audio_volume1=" + frm.output_audio_volume1.value;
            params += "&output_audio_volume2=" + frm.output_audio_volume2.value;
            params += "&output_audio_lang0=" + frm.output_audio_lang0.value;
            params += "&output_audio_lang1=" + frm.output_audio_lang1.value;
            params += "&output_audio_lang2=" + frm.output_audio_lang2.value;
            params += "&audio_sdi_mapping_l0=" + frm.audio_sdi_mapping_l0.value;
            params += "&audio_sdi_mapping_r0=" + frm.audio_sdi_mapping_r0.value;
            params += "&audio_sdi_mapping_c0=" + frm.audio_sdi_mapping_c0.value;
            params += "&audio_sdi_mapping_lfe0=" + frm.audio_sdi_mapping_lfe0.value;
            params += "&audio_sdi_mapping_sl0=" + frm.audio_sdi_mapping_sl0.value;
            params += "&audio_sdi_mapping_sr0=" + frm.audio_sdi_mapping_sr0.value;
            params += "&audio_sdi_mapping_l1=" + frm.audio_sdi_mapping_l1.value;
            params += "&audio_sdi_mapping_r1=" + frm.audio_sdi_mapping_r1.value;
            params += "&audio_sdi_mapping_c1=" + frm.audio_sdi_mapping_c1.value;
            params += "&audio_sdi_mapping_lfe1=" + frm.audio_sdi_mapping_lfe1.value;
            params += "&audio_sdi_mapping_sl1=" + frm.audio_sdi_mapping_sl1.value;
            params += "&audio_sdi_mapping_sr1=" + frm.audio_sdi_mapping_sr1.value;
            params += "&audio_sdi_mapping_l1=" + frm.audio_sdi_mapping_l1.value;
            params += "&audio_sdi_mapping_r1=" + frm.audio_sdi_mapping_r1.value;

            params += "&output_ip_address=" + frm.output_ip_address.value;
            <?php if (ENABLE_IPV6) { ?>
            params += "&output_ip_address_ipv6=" + frm.output_ip_address_ipv6.value;
            <?php } ?>
            params += "&multicast_ttl=" + frm.multicast_ttl.value;
            params += "&enable_raw_output=" + (frm.enable_raw_output.checked ? "1" : "0");
            params += "&output_port=" + frm.output_port.value;

            params += "&enable_ethernet_interface_2=" + frm.enable_ethernet_interface_2.value;
            params += "&ethernet_interface_2=" + frm.ethernet_interface_2.value;
            params += "&output_ip_address_2=" + frm.output_ip_address_2.value;
            <?php if (ENABLE_IPV6) { ?>
            params += "&output_ip_address_ipv6_2=" + frm.output_ip_address_ipv6_2.value;
            <?php } ?>
            params += "&multicast_ttl_2=" + frm.multicast_ttl_2.value;
            params += "&enable_raw_output_2=" + (frm.enable_raw_output_2.checked ? "1" : "0");
            params += "&output_port_2=" + frm.output_port_2.value;

            params += "&output_type=" + frm.output_type.value;
            params += "&source_ethernet_interface=" + frm.source_ethernet_interface.value;
            params += "&source_ip_address=" + frm.source_ip_address.value;
            <?php if (ENABLE_IPV6) { ?>
            params += "&source_ip_address_ipv6=" + frm.source_ip_address_ipv6.value;
            <?php } ?>
            params += "&multicast_filter_address=" + frm.multicast_filter_address.value;
            params += "&enable_raw_input=" + (frm.enable_raw_input.checked ? "1" : "0");
            params += "&enable_igmp_input=" + (frm.enable_igmp_input.checked ? "1" : "0");
            params += "&source_port=" + frm.source_port.value;
            params += "&source_timeout=" + frm.source_timeout.value;

            params += "&enable_source_input_2=" + frm.enable_source_input_2.value;
            params += "&source_ethernet_interface_2=" + frm.source_ethernet_interface_2.value;
            params += "&source_ip_address_2=" + frm.source_ip_address_2.value;
            <?php if (ENABLE_IPV6) { ?>
            params += "&source_ip_address_ipv6_2=" + frm.source_ip_address_ipv6_2.value;
            <?php } ?>
            params += "&multicast_filter_address_2=" + frm.multicast_filter_address_2.value;
            params += "&enable_raw_input_2=" + (frm.enable_raw_input_2.checked ? "1" : "0");
            params += "&source_port_2=" + frm.source_port_2.value;

            <?php if(ENABLE_SLATE == 1) { ?>
            params += "&slate_enable=" + (frm.slate_enable.checked ? "1" : "0");
            params += "&slate_filename=" + frm.slate_filename.value;
            params += "&slate_entry_time=" + frm.slate_entry_time.value;
            params += "&slate_duration_time=" + frm.slate_duration_time.value;
            params += "&slate_exit_time=" + frm.slate_exit_time.value;
            params += "&slate_silence=" + (frm.slate_silence.checked ? "1" : "0");
            <?php } ?>

            params += "&sdp_address=" + frm.sdp_address.value;
            params += "&sdp_filename=" + frm.sdp_filename.value;
            params += "&enable_rtcp=" + frm.enable_rtcp.checked;
            params += "&audio_only=" + (frm.audio_only.checked ? "1" : "0");
            params += "&sdi_card_num=" + frm.sdi_card_num.value;
            params += "&sdi_card_input_num=" + frm.sdi_card_input_num.value;
            <?php if (ENABLE_OUTPUT_VIDEO_BITRATE == 1) { ?>
            params += "&output_video_bitrate=" + frm.output_video_bitrate.value;
            <?php } ?>
            params += "&output_mux_rate=" + frm.output_mux_rate.value;
            params += "&enable_output_pid_remap=" + frm.enable_output_pid_remap.value;
            params += "&output_scte35_pid=" + frm.output_scte35_pid.value;
            params += "&output_pmt_pid=" + frm.output_pmt_pid.value;
            params += "&output_video_pid=" + frm.output_video_pid.value;
            params += "&output_audio_pid=" + frm.output_audio_pid.value;
            params += "&output_transport_stream_id=" + frm.output_transport_stream_id.value;
            params += "&output_program_number=" + frm.output_program_number.value;
            params += "&output_pat_rate=" + frm.output_pat_rate.value;
            params += "&output_pmt_rate=" + frm.output_pmt_rate.value;
            params += "&output_pcr_rate=" + frm.output_pcr_rate.value;
            params += "&output_pcr_style=" + frm.output_pcr_style.value;
            params += "&receive_fec=" + frm.receive_fec.value;
            params += "&scte35_passthru=" + frm.scte35_passthru.value;
            params += "&enable_cc=" + frm.enable_cc.value;
            params += "&enable_afd=" + frm.enable_afd.value;
            params += "&ac3dec_compmod=" + frm.ac3dec_compmod.value;
            params += "&prefilter_contrast=" + frm.prefilter_contrast.value;
            params += "&prefilter_brightness=" + frm.prefilter_brightness.value;
            params += "&h264_profile=" + frm.h264_profile.value;
            params += "&rtmp_server_address=" + encodeURIComponent(frm.rtmp_server_address.value);
            params += "&rtmp_remote_server_address=" + encodeURIComponent(frm.rtmp_remote_server_address.value);
            params += "&rtmp_naming=" + encodeURIComponent(frm.rtmp_naming.value);
            params += "&rtmp_username=" + frm.rtmp_username.value;
            params += "&rtmp_password=" + frm.rtmp_password.value;
            params += "&http_webdav_method=" + frm.http_webdav_method.value;
            params += "&http_server_address=" + encodeURIComponent(frm.http_server_address.value);
            params += "&http_server_username=" + encodeURIComponent(frm.http_server_username.value);
            params += "&http_server_password=" + encodeURIComponent(frm.http_server_password.value);
            params += "&http_webdav_method_backup=" + frm.http_webdav_method_backup.value;
            params += "&http_server_address_backup=" + encodeURIComponent(frm.http_server_address_backup.value);
            params += "&http_server_username_backup=" + encodeURIComponent(frm.http_server_username_backup.value);
            params += "&http_server_password_backup=" + encodeURIComponent(frm.http_server_password_backup.value);
            params += "&http_host_address=" + frm.http_host_address.value;
            params += "&origin_server_address=" + encodeURIComponent(frm.origin_server_address.value);
            params += "&origin_server_medianame=" + encodeURIComponent(frm.origin_server_medianame.value);
            params += "&origin_server_username=" + encodeURIComponent(frm.origin_server_username.value);
            params += "&origin_server_password=" + encodeURIComponent(frm.origin_server_password.value);

            // Currently hardcoded internally
            //params += "&file_transfer_type=" + frm.file_transfer_type.value;

            for (j = 0; j < frm.multi_output_file_mode.length; j++)
            {
                if (frm.multi_output_file_mode[j].checked == true)
                {
                    params += "&multi_output_file_mode=" + frm.multi_output_file_mode[j].value;
                    break;
                }
            }
            params += "&multi_output_file_max_duration=" + parseInt(frm.multi_output_file_max_duration.value)*60;
            params += "&multi_output_file_max_size=" + parseInt(frm.multi_output_file_max_size.value);
            params += "&multi_output_file_format=" + frm.multi_output_file_format.value;

            params += "&sdp_path=" + frm.sdp_path.value;
            params += "&sdp_session_name=" + frm.sdp_session_name.value;
            params += "&rtp_multicast_ttl=" + frm.rtp_multicast_ttl.value;
            params += "&multi_ts_multicast_ttl=" + frm.multi_ts_multicast_ttl.value;
            params += "&multi_ts_pid_mode=" + frm.multi_ts_pid_mode.value;
            params += "&ebp_enable=" + frm.ebp_enable.value;
            params += "&scte35_passthru=" + frm.mv_scte35_passthru.value;
            params += "&esam_server_address=" + encodeURIComponent(frm.esam_server_address.value);
            params += "&esam_request_endpoint=" + encodeURIComponent(frm.esam_request_endpoint.value);
            params += "&esam_hostname=" + encodeURIComponent(frm.esam_hostname.value);
            params += "&publishing_point1=" + encodeURIComponent(frm.publishing_point1.value);
            params += "&publishing_point_auth1=" + encodeURIComponent(frm.publishing_point_auth1.value);
            params += "&publishing_point_username1=" + encodeURIComponent(frm.publishing_point_username1.value);
            params += "&publishing_point_password1=" + encodeURIComponent(frm.publishing_point_password1.value);
            params += "&publishing_point2=" + encodeURIComponent(frm.publishing_point2.value);
            params += "&publishing_point_auth2=" + encodeURIComponent(frm.publishing_point_auth2.value);
            params += "&publishing_point_username2=" + encodeURIComponent(frm.publishing_point_username2.value);
            params += "&publishing_point_password2=" + encodeURIComponent(frm.publishing_point_password2.value);
            params += "&manifest_type=" + frm.manifest_type.value;
            params += "&mp4_frag_size=" + frm.mp4_frag_size.value;
            params += "&silverlight_caption_format=" + frm.silverlight_caption_format.value;
            params += "&segment_size=" + frm.segment_size.value;
            params += "&window_size=" + frm.window_size.value;
            params += "&apple_master_variant=" + frm.apple_master_variant.value;
            params += "&fixed_key_enable=" + frm.fixed_key_enable.value;
            params += "&fixed_key_0=" + frm.fixed_key_0.value;
            params += "&fixed_key_1=" + frm.fixed_key_1.value;
            params += "&fixed_key_2=" + frm.fixed_key_2.value;
            params += "&fixed_key_3=" + frm.fixed_key_3.value;
            params += "&fixed_key_4=" + frm.fixed_key_4.value;
            params += "&fixed_key_5=" + frm.fixed_key_5.value;
            params += "&fixed_key_6=" + frm.fixed_key_6.value;
            params += "&fixed_key_7=" + frm.fixed_key_7.value;
            params += "&fixed_key_8=" + frm.fixed_key_8.value;
            params += "&fixed_key_9=" + frm.fixed_key_9.value;
            params += "&fixed_key_10=" + frm.fixed_key_10.value;
            params += "&fixed_key_11=" + frm.fixed_key_11.value;
            params += "&fixed_key_12=" + frm.fixed_key_12.value;
            params += "&fixed_key_13=" + frm.fixed_key_13.value;
            params += "&fixed_key_14=" + frm.fixed_key_14.value;
            params += "&fixed_key_15=" + frm.fixed_key_15.value;
            params += "&hls_segment_rollover_mode=" + frm.hls_segment_rollover_mode.value;
            params += "&hls_segment_rollover_count=" + frm.hls_segment_rollover_count.value;
            params += "&hls_prefix_name=" + frm.hls_prefix_name.value;
            params += "&hls_version=" + frm.hls_version.value;
            params += "&hls_name_style=" + frm.hls_name_style.value;
            params += "&hls_delete_server=" + frm.hls_delete_server.value;
            params += "&hls_delete_local=" + frm.hls_delete_local.value;
            params += "&hls_replace_start=" + frm.hls_replace_start.value;
            params += "&hls_replace_end=" + frm.hls_replace_end.value;

            var nullValue = 0;
            var val = null;

            if(frm.stream_group_checkbox1)
                val = frm.stream_group_checkbox1.checked;
            else
                val = "false";
            params += "&stream_group_active1=" + val;

            if(frm.stream_group_checkbox2)
                val = frm.stream_group_checkbox2.checked;
            else
                val = "false";
            params += "&stream_group_active2=" + val;
            if(frm.stream_group_select1)
                val = frm.stream_group_select1.value;
            else
                val = nullValue;
            params += "&stream_group_profile1=" + val;
            if(frm.stream_group_select2)
                val = frm.stream_group_select2.value;
            else
                val = nullValue;
            params += "&stream_group_profile2=" + val;

<?php       for ($iGroup = 1; $iGroup <= MAX_STREAM_GROUPS; $iGroup++) {?>
            params += "&multi_ts_ethernet_interface<?=$iGroup?>=" + $("#multi_ts_ethernet_interface<?=$iGroup?>")[0].value;
<?php       }?>

/*            for (var iStream = 0; iStream < MAX_STREAMS; ++iStream)
            {
                var stream_active = $("#stream_active"+iStream);
                var exists = stream_active.length > 0;
                params += "&stream_active"+iStream+"=" + (exists ? stream_active[0].checked : "false");
                params += "&stream_width"+iStream+"=" + (exists ? $("#stream_width"+iStream)[0].value : nullValue);
                params += "&stream_height"+iStream+"=" + (exists ? $("#stream_height"+iStream)[0].value : nullValue);
                params += "&stream_bitrate"+iStream+"=" + (exists ? $("#stream_bitrate"+iStream)[0].value : nullValue);

                params += "&stream_codec"+iStream+"=" + (exists ? $("#stream_codec" + iStream).val() : nullValue);

                var framerate = $("#stream_framerate" + iStream).val();
                if (framerate == null) {
                    framerate = "0";
                }

                params += "&stream_framerate"+iStream+"=" + (exists ? framerate : "0");
                params += "&stream_profile"+iStream+"=" + (exists ? $("#stream_profile"+iStream).val() : "0");
                params += "&stream_audio_bitrate"+iStream+"=" + (exists ? $("#stream_audio_bitrate"+iStream).val() : "0");
                params += "&stream_audio_channels"+iStream+"=" + (exists ? $("#stream_audio_channels"+iStream).val() : "0");
                params += "&stream_audio_bitrate2_"+iStream+"=" + (exists ? $("#stream_audio_bitrate2_"+iStream).val() : "0");
                params += "&stream_audio_channels2_"+iStream+"=" + (exists ? $("#stream_audio_channels2_"+iStream).val() : "0");
                params += "&stream_audio_only"+iStream+"=" + (exists ? $("#stream_audio_only"+iStream)[0].checked : "false");
                params += "&stream_enable_image_overlay"+iStream+"=" + (exists ? $("#stream_enable_image_overlay"+iStream)[0].checked : "true");
                params += "&"+$("#image_overlay_params"+iStream).val();
                params += "&stream_vbr"+iStream+"=" + (exists ? get_stream_vbr(iStream) : "false");
                params += "&stream_max_bitrate"+iStream+"=" + (exists ? $("#stream_max_bitrate"+iStream)[0].value : nullValue);
                params += "&multi_output_file_active"+iStream+"=" + (exists ? $("#multi_output_file_active"+iStream)[0].checked : "false");

                params += "&rtp_address"+iStream+"=" + (exists ? $("#rtp_address"+iStream)[0].value : "");
                val = $("#rtp_port"+iStream).val();
                if (!val)
                    val = 0;
                params += "&rtp_port"+iStream+"=" + val;

                params += "&multi_ts_address"+iStream+"=" + (exists ? $("#multi_ts_address"+iStream)[0].value : "");
                val = $("#multi_ts_port"+iStream).val();
                if (!val)
                    val = 0;
                params += "&multi_ts_port"+iStream+"=" + val;

                params += "&rtmp_stream_name"+iStream+"=" + (exists ? encodeURIComponent($("#rtmp_stream_name"+iStream)[0].value) : "");
            }*/
            params += "&multi_ts_port1=" + val;
            const numVideo_profiles = ($(".vid_names").size()-1);
            params += "&num_video_profiles="+numVideo_profiles+"&"+$("#video-profiles :input").serialize();
            params += "&num_audio_profiles="+($(".aud_names").size()-1)+"&"+$("#audio-profiles :input").serialize();
            if(get_active_output_interface() == "APPLE") {
                params += "&num_output_streams="+numVideo_profiles;
            } else {
                params += "&num_output_streams="+($(".out_enabled").size()-1)+"&"+$("#stream-profiles :input").serialize();
            }
            params += "&capture_device=" + frm.capture_device.value;
            params += "&capture_video_pid=" + frm.capture_video_pid.value;
            params += "&capture_audio_pid=" + frm.capture_audio_pid.value;
            params += "&capture_pmt_pid=" + frm.capture_pmt_pid.value;
            params += "&capture_audio_language=" + frm.capture_audio_language.value;
            params += "&capture_brightness=" + frm.capture_brightness.value;
            params += "&capture_hue=" + frm.capture_hue.value;
            params += "&capture_contrast=" + frm.capture_contrast.value;
            params += "&capture_saturation=" + frm.capture_saturation.value;
            params += "&temporal_filter_strength=" + frm.temporal_filter_strength.value;
            params += "&diagonal_smoothing_filter=" + frm.diagonal_smoothing_filter.value;
            params += "&galaxie_mode=" + frm.galaxie_mode.value;
            params += "&enable_scene_detection=" + frm.enable_scene_detection.value;
            params += "&buffer_constraint=" + frm.buffer_constraint.value;
<?php if (ENABLE_PYRAMID_B == 1) { ?>
            params += "&pyramid_b=" + frm.pyramid_b.value;
<?php } ?>
            params += "&audio_sync_delta0=" + frm.audio_sync_delta0.value;
            params += "&audio_sync_delta1=" + frm.audio_sync_delta1.value;
            params += "&audio_sync_delta2=" + frm.audio_sync_delta2.value;
            params += "&audio_ac3_dialnorm0=" + frm.audio_ac3_dialnorm0.value;
            params += "&audio_ac3_dialnorm1=" + frm.audio_ac3_dialnorm1.value;
            params += "&audio_ac3_dialnorm2=" + frm.audio_ac3_dialnorm2.value;
            params += "&audio_channels0=" + frm.audio_channels0.value;
            params += "&audio_channels1=" + frm.audio_channels1.value;
            params += "&audio_channels2=" + frm.audio_channels2.value;
            params += "&ethernet_interface=" + frm.ethernet_interface.value;
            params += "&image_overlay_file=" + frm.image_overlay_file.value;

            params += "&output_color_range=" + frm.output_color_range.value;
            params += "&output_color_primaries=" + frm.output_color_primaries.value;
            params += "&output_color_trc=" + frm.output_color_trc.value;
            params += "&output_color_space=" + frm.output_color_space.value;

            var overlay_width = 0;
            var overlay_height = 0;
            if (frm.image_overlay_file.value && frm.image_overlay_file.value.length)
            {
                var image_overlay_res = frm.image_overlay_file.value.split(".");
                image_overlay_res = image_overlay_res[image_overlay_res.length-2].split("x");
                overlay_width = image_overlay_res[0];
                overlay_height = image_overlay_res[1];
            }
            params += "&image_overlay_width=" + overlay_width;
            params += "&image_overlay_height=" + overlay_height;
            params += "&image_overlay_position=" + frm.image_overlay_position.value;
            params += "&image_overlay_margin_x=" + frm.image_overlay_margin_x.value;
            params += "&image_overlay_margin_y=" + frm.image_overlay_margin_y.value;
            params += "&image_overlay_alpha=" + frm.image_overlay_alpha.value;

            params += "&enable_sdi_repeat=" + (frm.enable_sdi_repeat.checked ? "1" : "0");
            params += "&sdi_frame_timeout=" + frm.sdi_frame_timeout.value;
            params += "&sdi_cc_data_rate=" + frm.sdi_cc_data_rate.value;
            params += "&enable_genlock=" + frm.enable_genlock.value;
            params += "&bottom_field_first=" + frm.bottom_field_first.value;

            <?php if ($enable_atsc_input) { ?>
            params += "&dvbapi_tuner_name=" + frm.input_atsc_tuner.options[frm.input_atsc_tuner.selectedIndex].text;
            params += "&dvbapi_frontend_path=" + frm.input_atsc_tuner.value;
            params += "&dvbapi_tuning_info=" + frm.input_atsc_channel.value;
            <?php } ?>

            params += "&apple_hls_input_url=" + (frm.apple_hls_input_url ? frm.apple_hls_input_url.value : "");
            params += "&apple_hls_input_num_prebuffer_segs=" + (frm.apple_hls_input_num_prebuffer_segs ? frm.apple_hls_input_num_prebuffer_segs.value : "1");

            params += "&rtmp_input_url=" + (frm.rtmp_input_url ? frm.rtmp_input_url.value : "");
            params += "&rtmp_input_stream_name=" + (frm.rtmp_input_stream_name ? frm.rtmp_input_stream_name.value : "");

            // SCRAMBLING OPTIONS
            <?php if (ENABLE_SCRAMBLING) { ?>
                params += "&scrambling_keymode=" + frm.scrambling_keymode.value;
                params += "&scrambling_sourceAddress=" + frm.scrambling_sourceAddress.value;
                params += "&scrambling_sourceBasePort=" + frm.scrambling_sourceBasePort.value;
                params += "&scrambling_targetAddress=" + frm.scrambling_targetAddress.value;
                params += "&scrambling_targetBasePort=" + frm.scrambling_targetBasePort.value;
                params += "&scrambling_ecmgHost=" + frm.scrambling_ecmgHost.value;
                params += "&scrambling_ecmgPort=" + frm.scrambling_ecmgPort.value;
                params += "&scrambling_ecmgBackupHost=" + frm.scrambling_ecmgBackupHost.value;
                params += "&scrambling_ecmgBackupPort=" + frm.scrambling_ecmgBackupPort.value;
                params += "&scrambling_protocolVersion=" + frm.scrambling_protocolVersion.value;
                params += "&scrambling_ecmId=" + frm.scrambling_ecmId.value;
                params += "&scrambling_streamId=" + frm.scrambling_streamId.value;
                params += "&scrambling_channelId=" + frm.scrambling_channelId.value;
                params += "&scrambling_superCasId=" + frm.scrambling_superCasId.value;
                params += "&scrambling_rekeyInterval=" + frm.scrambling_rekeyInterval.value;
                params += "&scrambling_stkmSendInterval=" + frm.scrambling_stkmSendInterval.value;
                params += "&scrambling_stkmPort=" + frm.scrambling_stkmPort.value;
                params += "&scrambling_fixedKeyMaterial=" + frm.scrambling_fixedKeyMaterial.value;
                params += "&scrambling_authKey=" + frm.scrambling_authKey.value;
                params += "&scrambling_useAuthentication=" + frm.scrambling_useAuthentication.checked;
                params += "&scrambling_scrambleRTCP=" + frm.scrambling_scrambleRTCP.checked;
                params += "&scrambling_logLevel=" + frm.scrambling_logLevel.value;
            <?php } ?>

            params += "&verimatrix_enable=" + frm.verimatrix_enable.value;
            params += "&verimatrix_encryptor_url=" + encodeURIComponent(frm.verimatrix_encryptor_url.value);
            params += "&verimatrix_client_url=" + encodeURIComponent(frm.verimatrix_client_url.value);
            params += "&verimatrix_max_segments=" + frm.verimatrix_max_segments.value;
            params += "&verimatrix_resource_id=" + frm.verimatrix_resource_id.value;
            params += "&verimatrix_asset_type=" + frm.verimatrix_asset_type.value;
            params += "&verimatrix_iv_mode=" + frm.verimatrix_iv_mode.value;

            <?php
            if (ENABLE_NIELSEN) {
            ?>
                params += "&nielsen_watermark_decoding_enable=" + frm.nielsen_watermark_decoding_enable.value;
                params += "&nielsen_distributor_id=" + encodeURIComponent(frm.nielsen_distributor_id.value);
                params += "&nielsen_breakout_code=" + frm.nielsen_breakout_code.value;
            <?php } ?>

            params += "&buydrm_enable1=" + frm.buydrm_enable1.value;
            params += "&buydrm_userkey1=" + encodeURIComponent(frm.buydrm_userkey1.value);
            params += "&buydrm_keyid1=" + encodeURIComponent(frm.buydrm_keyid1.value);
            params += "&buydrm_contentid1=" + encodeURIComponent(frm.buydrm_contentid1.value);
            params += "&buydrm_mediaid1=" + encodeURIComponent(frm.buydrm_mediaid1.value);
            params += "&buydrm_enable2=" + frm.buydrm_enable2.value;
            params += "&buydrm_userkey2=" + encodeURIComponent(frm.buydrm_userkey2.value);
            params += "&buydrm_keyid2=" + encodeURIComponent(frm.buydrm_keyid2.value);
            params += "&buydrm_contentid2=" + encodeURIComponent(frm.buydrm_contentid2.value);
            params += "&buydrm_mediaid2=" + encodeURIComponent(frm.buydrm_mediaid2.value);

            if (mpts_discover_cache && mpts_discover_cache.programs && mpts_discover_cache.programs.length > 0) {
                params += "&mpts_discover_cache=" + encodeURIComponent(JSON.stringify(mpts_discover_cache));
            }

// DEBUG OPTIONS BEGIN
            params += "&input_type=" + frm.input_type.value;

            var source_file_name = frm.yuv_file_name.value;
            <?php if (ENABLE_SOURCE_FILE_FTP) { ?>
            if (source_file_name.substring(0,1) != "/")
                source_file_name = "<?= SOURCE_FILE_PATH ?>" + source_file_name;
            <?php } ?>
            params += "&yuv_file_name=" + source_file_name;

            var mp4_file_name = frm.mp4file_input_name.value;
            <?php if (ENABLE_SOURCE_FILE_FTP) { ?>
            if (mp4_file_name.substring(0,1) != "/")
                mp4_file_name = "<?= SOURCE_FILE_PATH ?>" + mp4_file_name;
            <?php } ?>
            params += "&mp4file_input_name=" + mp4_file_name;

            params += "&mp4file_loop=" + frm.mp4file_loop.value;
            params += "&tsfile_loop=" + frm.tsfile_loop.value;

            params += "&yuv_frame_rate=" + frm.yuv_frame_rate.value;
            params += "&yuv_input_buffer_size=" + frm.yuv_input_buffer_size.value;
            params += "&h264_encoder_quality=" + frm.h264_encoder_quality.value;
            params += "&noise_filtering=" + frm.noise_filtering.value;
            params += "&delay=" + frm.delay.value;
            params += "&buffer_delay=" + frm.buffer_delay.value;
            if (frm.save_input_ts_file.checked == true) {
                params += "&save_input_ts_file=1";
            } else {
                params += "&save_input_ts_file=0";
            }
            if (frm.save_output_ts_file.checked == true) {
                params += "&save_output_ts_file=1";
            } else {
                params += "&save_output_ts_file=0";
            }
            params += "&simulated_interlaced_mode=" + frm.simulated_interlaced_mode.value;
// DEBUG OPTIONS END

            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open('POST', '<?php echo $SELF; ?>', false);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.send(params);

            if (xmlhttp.responseText == "OK") {
                alert("Configuration saved.");
                save_state();
            }
            else if (xmlhttp.responseText == "BADCONFIG") {
                alert("Configuration saved (***).");
                save_state();
            } else {
                alert("Error saving configuration.");
            }
        }
    }

    function save_state()
    {
        if (window.XMLHttpRequest)
        {
            var frm = document.configuration;
            var select_obj = document.getElementById("current_file");
            var xmlhttp = new XMLHttpRequest();
            var current_time = new Date();

            xmlhttp.open('GET', '<?php echo $SELF; ?>?action=save_state&config_filename='+select_obj.value+'&ts='+current_time.getTime(), false);
            xmlhttp.send();
        }
    }

    function update_form(settings, filenameOverride) {
        var frm = document.configuration;
        frm.reset();

        var i, j;
        var val;

        $(".scrambleDynamicOption").hide();
        $(".scrambleFixedTekOption").hide();
        $(".scrambleGeneralOption").hide();

        var input_interface = "IP";
        var output_encoder = "MPEG2";
        var yuv_file_name = "";
        var mp4_file_name = "";
        var atsc_tuner = null;
        var atsc_channel = null;
        mpts_discover_cache = null;
        var input_subtitle_pid = -1;
        var input_audio_pid0 = -1;
        var input_audio_pid1 = -1;
        var input_audio_pid2 = -1;
        var minimum_audio_pid = -1;
        var old_style = 0;
        var has_config_version = false;
        var config_version = "N/A";
        slate_enable_clicked();

        for (i = 0; i < settings.length; i++) {
            args = settings[i].split("=");
            key = args[0];

            if (!key || !key.length) {
                continue;
            }

            val = args[1];

            // Reconstruct values that have = in them
            for (var j = 2; j < args.length; ++j) {
                val += "=" + args[j];
            }

            val = decodeURIComponent(val);
            if(val == "source_ip_address")
            alert("Key is "+key+" & val is "+val);
            if (key == "config_filename") {
                if (filenameOverride != undefined) {
                    frm.current_file.value = filenameOverride;
                    save_state();
                } else {
                    frm.current_file.value = val;
                }
            } else if (key == "config_version") {
                has_config_version = true;
                config_version = val;
            } else if (key == "output_resolution") {
                if (val == "USER") {
                    $("#row_output_override").show();
                } else {
                    $("#row_output_override").hide();
                }

                var preset = frm.input_resolution.value;
                if (preset == "HD1080" || preset == "HD720") {
                    setup_output_resolution(true);
                } else {
                    setup_output_resolution(false);
                }

                safe_set_select_val(frm.output_resolution, val, "SAME");
            } else if (key == "enable_gpu") {
                frm.enable_gpu.checked = false;
                if (val == 1) {
                    frm.enable_gpu.click();
                }
            } else if (key == "output_framerate") {
                frm.output_framerate.value = val;

                output_framerate_changed(frm.output_framerate);
            } else if (key == "output_resizing") {
                if (val == 2) {
                    frm.enable_crop.checked = true;
                } else {
                    frm.enable_crop.checked = false;
                }
            } else if (key == "biss_mode") {
                    frm.biss_mode.value = val;
                    frm.biss_mode.onchange();
            } else if (key == "output_encoder") {
                output_encoder = val;
            } else if (key == "input_interface") {
                <?php if (ENABLE_SOURCE_FILE_FTP) { ?>
                // If source file list is empty but TSFILE was selected, reset input interface to default
                if (source_file_list_count() == 0 && val == "TSFILE") {
                    window.alert("Warning: Input interface was set to TSFILE but no files are available. Resetting to default interface.");
                    val = "IP";
                }
                <?php } ?>

                <?php
                /*
                Attempt to make some effort to recover from configs that were created with a build with
                features that are now disabled.
                */
                ?>
                <?php if (!$enable_atsc_input) { ?>
                if (val == "ATSC" || val == "DVB-API")
                    val = "IP";
                <?php } ?>

                input_interface = val;
                set_active_input_interface(val);
            } else if (key == "output_interface") {
                set_active_output_interface(val);

                if (val == "RTMP" ||
                    val == "APPLE" ||
                    val == "APPLEVOD" ||
                    val == "SILVERLIGHT" ||
                    val == "DASH" ||
                    val == "RTP" ||
                    val == "ATSC" ||
                    val == "MULTITS") {
                    var row;

                    output_audio_clicked0_aac(frm.output_audio_format);
                    stream_audio_populate();
                } else {
                    var row;

                    output_audio_clicked0_normal(frm.output_audio_format);
                }
            } else if (key == "output_audio_format") {
                frm.output_audio_format.value = val;

                if (is_audio_passthrough(val)) {
                    var row;
                    var obj;
                    row = document.getElementById("audio_bitrate_row0");
                    row.style["color"] = "#888888";
                    row.hidden = false;
                    row = document.getElementById("audio_volume_row0");
                    row.style["color"] = "#888888";

                    frm.output_audio_bitrate0.disabled = true;
                    frm.output_audio_volume0.disabled = true;

                    frm.output_audio_volume0.style["color"] = "#888888";

                    row = document.getElementById("audio_bitrate_row1");
                    row.style["color"] = "#888888";
                    row.hidden = false;
                    row = document.getElementById("audio_volume_row1");
                    row.style["color"] = "#888888";

                    //frm.output_audio_bitrate1.disabled = true;
                    frm.output_audio_volume1.disabled = true;

                    frm.output_audio_volume1.style["color"] = "#888888";

                    row = document.getElementById("audio_bitrate_row2");
                    row.style["color"] = "#888888";
                    row.hidden = false;
                    row = document.getElementById("audio_volume_row2");
                    row.style["color"] = "#888888";

                    //frm.output_audio_bitrate2.disabled = true;
                    frm.output_audio_volume2.disabled = true;

                    frm.output_audio_volume2.style["color"] = "#888888";
                } else {
                    var row;
                    var obj;
                    row = document.getElementById("audio_bitrate_row0");
                    row.style["color"] = "black";
                    row.hidden = false;
                    row = document.getElementById("audio_volume_row0");
                    row.style["color"] = "black";

                    frm.output_audio_bitrate0.disabled = false;
                    frm.output_audio_volume0.disabled = false;

                    frm.output_audio_volume0.style["color"] = "black";

                    row = document.getElementById("audio_bitrate_row1");
                    row.style["color"] = "black";
                    row.hidden = false;
                    row = document.getElementById("audio_volume_row1");
                    row.style["color"] = "black";

                    //frm.output_audio_bitrate1.disabled = false;
                    frm.output_audio_volume1.disabled = false;

                    frm.output_audio_volume1.style["color"] = "black";

                    row = document.getElementById("audio_bitrate_row2");
                    row.style["color"] = "black";
                    row.hidden = false;
                    row = document.getElementById("audio_volume_row2");
                    row.style["color"] = "black";

                    //frm.output_audio_bitrate2.disabled = false;
                    frm.output_audio_volume2.disabled = false;

                    frm.output_audio_volume2.style["color"] = "black";
                }
                /*row = document.getElementById("audio_sync_delta_row0");
                row.hidden = true;

                row = document.getElementById("audio_sync_delta_row1");
                row.hidden = true;

                row = document.getElementById("audio_sync_delta_row2");
                row.hidden = true;*/

                if (val == "RTMP" || val == "APPLE" || val == "APPLEVOD" || val == "SILVERLIGHT" || val == "DASH" ||
                    val == "RTP" || val == "ATSC" || val == "MULTITS") {
                    output_audio_clicked0_aac(frm.output_audio_format);
                } else {
                    output_audio_clicked0_normal(frm.output_audio_format);
                }

                output_audio_clicked1(frm.output_audio_format);
                output_audio_clicked2(frm.output_audio_format);
                update_audio_controls();
            } else if (key == "output_audio_bitrate1") {
                //JNB
                if (val != "0") {
                    //var row
                    //row = document.getElementById("audio_bitrate_row1");
                    //row.style["color"] = "#888888";
                    //row.hidden = false;
                    //row = document.getElementById("audio_volume_row1");
                    //row.style["color"] = "#888888";
                    console.log("set output_audio_bitrate1 value");
                    $("#output_audio_bitrate1").val(val);
                    console.log("done set output_audio_bitrate1 value");
                }

            } else if (key == "output_audio_bitrate2") {
                if (val != "0") {
                    console.log("set output_audio_bitrate2 value");
                    $("#output_audio_bitrate2").val(val);
                    console.log("done set output_audio_bitrate2 value");
                }
            } else if (key == "enable_raw_output") {
                frm.enable_raw_output.checked = "1" == val;
            } else if (key == "output_type") {
                frm.output_type.value = val;
                ip_output_type_selected(frm.output_type);
            } else if (key == "enable_igmp_input") {
                frm.enable_igmp_input.checked = "1" == val;
            } else if (key == "enable_raw_input") {
                frm.enable_raw_input.checked = "1" == val;
            } else if (key == "enable_rtcp") {
                if (val == "true") {
                    frm.enable_rtcp.checked = true;
                } else {
                    frm.enable_rtcp.checked = false
                }
            } else if (key == "slate_enable") {
                if (val == "1") {
                    frm.slate_enable.checked = true;
                } else {
                    frm.slate_enable.checked = false;
                }
                slate_enable_clicked();
            } else if (key == "slate_filename") {
                slateRefreshFiles(val);
            } else if (key == "slate_entry_time") {
                frm.slate_entry_time.value = val;
            } else if (key == "slate_duration_time") {
                frm.slate_duration_time.value = val;
            } else if (key == "slate_exit_time") {
                frm.slate_exit_time.value = val;
            } else if (key == "slate_silence") {
                if (val == "1") {
                    frm.slate_silence.checked = true;
                } else {
                    frm.slate_silence.checked = false;
                }
            } else if (key == "audio_only") {
                if (val == "1") {
                    frm.audio_only.checked = true;
                } else {
                    frm.audio_only.checked = false;
                }

                audio_only_clicked();

            } else if (key == "sdi_card_num") {
                frm.sdi_card_num.value = val;
            } else if (key == "sdi_card_input_num") {
                frm.sdi_card_input_num.value = val;
            } else if (key == "multi_output_file_mode") {
                for (j = 0; j < frm.multi_output_file_mode.length; j++)
                {
                    frm.multi_output_file_mode[j].checked = false;
                    if (frm.multi_output_file_mode[j].value == val)
                    {
                        frm.multi_output_file_mode[j].checked = true;
                        multi_output_file_mode_selected(parseInt(val));
                    }
                }
            } else if (key == "multi_output_file_max_duration") {
                frm.multi_output_file_max_duration.value = parseInt(val) / 60;
            } else if (key == "stream_group_active1") {
                if (frm.stream_group_checkbox1 == undefined) {
                    continue;
                }

                if (val == "true") {
                    frm.stream_group_checkbox1.checked = true;
                } else {
                    frm.stream_group_checkbox1.checked = false;
                }

                group_checkbox_clicked(frm.stream_group_checkbox1, 1);
            } else if (key == "stream_group_active2") {
                if (frm.stream_group_checkbox2 == undefined) {
                    continue;
                }

                if (val == "true") {
                    frm.stream_group_checkbox2.checked = true;
                } else {
                    frm.stream_group_checkbox2.checked = false;
                }

                group_checkbox_clicked(frm.stream_group_checkbox2, 2);
            } else if (key == "stream_group_profile1") {
                frm.stream_group_select1.value = val;

                <?php if(CONFIG_MODE != 1) { ?>
                if (frm.stream_group_select1.value == 0) {
                    stream_group1_ipod();
                } else {
                    stream_group1_normal();
                }
                <?php } else { ?>
                stream_group_atsc(1);
                frm.stream_group_select1.value = val;
                <?php } ?>

            } else if (key == "stream_group_profile2") {
                if (frm.stream_group_select2 == undefined) {
                    continue;
                }

                frm.stream_group_select2.value = val;

                <?php if(CONFIG_MODE != 1) { ?>
                if (frm.stream_group_select2.value == 0) {
                    stream_group2_ipod();
                } else {
                    stream_group2_normal();
                }
                <?php } else { ?>
                stream_group_atsc(2);
                frm.stream_group_select2.value = val;
                <?php } ?>
            } else if (key == "ethernet_interface") {
                frm.ethernet_interface.value = val;
                // Check for bad values to reset to 0 if necessary
                if (frm.ethernet_interface.value != val) {
                    frm.ethernet_interface.selectedIndex = 0;
                }
            } else if (key == "image_overlay_file") {
                imageOverlayRefreshFiles(val);
            } else if (key == "enable_sdi_repeat") {
                frm.enable_sdi_repeat.checked = "1" == val;
                $("#enable_sdi_repeat").change();
            }
            <?php if ($enable_atsc_input) { ?>
            else if (key == "dvbapi_frontend_path") {
                atsc_tuner = val;
            } else if (key == "dvbapi_tuning_info") {
                atsc_channel = val;
            }
            <?php } ?>
            // SCRAMBLING OPTIONS
            else if (key == "scrambling_keymode") {
                frm.scrambling_keymode.value = val;
                scramblingKeyModeChanged();
            } else if (key == "scrambling_useAuthentication") {
                frm.scrambling_useAuthentication.checked = val;
            } else if (key == "verimatrix_enable") {
                frm.verimatrix_enable.value = val;
                verimatrixEnableChanged();
            } else if (key == "nielsen_watermark_decoding_enable") {
                frm.nielsen_watermark_decoding_enable.value = val;
                nielsenEnableChanged();
            } else if (key == "buydrm_enable1") {
                frm.buydrm_enable1.value = val;
                buydrmEnableChanged();
            } else if (key == "buydrm_enable2") {
                frm.buydrm_enable2.value = val;
                buydrmEnableChanged();
            } else if (key == "master_variant_config-output_settings-num_video_profiles") {
                addRows('videos',val,true);
            } else if (key == "master_variant_config-output_settings-num_audio_profiles") {
                addRows('audios',val,true);
                //After adding rows set the Discover results
                if ((input_interface == "IP" || input_interface == "DVB-API") && mpts_discover_cache && mpts_discover_cache.source.type!="sdi"){
                    mpts_discover_set_results(mpts_discover_cache, false);
                } else {
                    mpts_discover_enable_results(false);
                }
            } else if (key == "master_variant_config-output_settings-num_output_streams") {
                addRows('outputs',val,true);
                $(".out_audio_profile").val(-1);
            } else if ( key.startsWith("master_variant_config-video_profile"))
            {
                var matches = key.match(/master_variant_config-video_profile(\d+)/g);
                matches = key.match(/\d+/);
                matches = parseInt(matches)+1;

                var arr = ["width", "height", "codec", "framerate", "profile", "rate_ctl", "mux_target", "vbr_max_bitrate","encoder_profile"];
                arr.forEach(function(element){if(key.endsWith(element)){$(".vid_"+element).eq(matches).val(val);}});
            } else if ( key.startsWith("master_variant_config-audio_profile"))
            {
                console.log("process audio_profile");
                var matches = key.match(/master_variant_config-audio_profile(\d+)/g);
                matches = key.match(/\d+/);
                matches = parseInt(matches)+1;

                var arr = ["source_stream","codec","bitrate","channels","dialnorm","volume"];

                console.log("key=" + key + "     val=" + val);
                console.log("matches=" + matches);

                arr.forEach(function(element){
                    if (key.endsWith(element)){
                        $(".aud_"+element).eq(matches).val(val);
                    }
                });
                $(".aud_codec").change();

                // for debug, iterate over all the aud_source objects and print their value
                $(".aud_source_stream").each(function(i) {
                    //saved_aud_source_stream.push($(".aud_source_stream").eq(i).val());
                    console.log(".aud_source_stream" + i + ": value = " +  $(this).val());
                });
                console.log("done");
//throw Error();

            } else if ( key.startsWith("master_variant_config-output_abr_stream"))
            {
                var matches = key.match(/\d+/g);
                var id = parseInt(matches[0])+1;

                var arr = ["multi_ts_address","multi_ts_port"];
                arr.forEach(function(element){if(key.endsWith(element)){$(".out_"+element).eq(id).val(val);}});
                arr = ["enabled"];
                arr.forEach(function(element){if(key.endsWith(element)){if(val){$(".out_"+element).eq(id).attr("checked","checked");}}});

                arr = ["video_profile","audio_profile"];
                arr.forEach(function(element){
                if(key.search("-"+element)!=-1)
                {
                    var num= matches[1];
                    if(val){
                        if(element == "audio_profile"){
                                $(".out_"+element).eq(id).children("option[value='" + (num) + "']").attr("selected", 'selected');
                                $(".out_"+element).eq(id).children("option[value='" + -1 + "']").attr("selected", '');
                        }else{
                            $(".out_"+element).eq(id).val(num);
                        }
                    }
                }
        });
        }
// DEBUG OPTIONS BEGIN
            else if (key == "yuv_file_name") {
                // Defer setting this until full config is loaded
                yuv_file_name = val;
            } else if (key == "mp4file_input_name") {
                // Defer setting this until full config is loaded
                mp4_file_name = val;
            }
            <?php if (ENABLE_DVB_SUBTITLES == 1) { ?>
            else if (key == "input_subtitle_mode") {
                if (val < 0 || val > 3) {
                    val = 0;
                }
                $("#input_subtitle_mode" + val).click();
            } else if (key == "input_subtitle_pid") {
                input_subtitle_pid = val;
            }
            <?php } ?>

            else if (key == "input_audio_pid0") {
                input_audio_pid0 = val;
                if (input_audio_pid0 >= 4) {
                    old_style = 1;
                    if (minimum_audio_pid == -1 )
                        minimum_audio_pid = input_audio_pid0;
                    else if (minimum_audio_pid > input_audio_pid0)
                        minimum_audio_pid = input_audio_pid0;
                }

            } else if (key == "input_audio_pid1") {
                input_audio_pid1 = val;
                if (input_audio_pid1 >= 4) {
                    old_style = 1;
                    if (minimum_audio_pid == -1 )
                        minimum_audio_pid = input_audio_pid1;
                    else if (minimum_audio_pid > input_audio_pid1)
                        minimum_audio_pid = input_audio_pid1;
                }

            } else if (key == "input_audio_pid2") {
                input_audio_pid2 = val;
                if (input_audio_pid2 >= 4) {
                    old_style = 1;
                    if (minimum_audio_pid == -1 )
                        minimum_audio_pid = input_audio_pid2;
                    else if (minimum_audio_pid > input_audio_pid2)
                        minimum_audio_pid = input_audio_pid1;
                }

                if (old_style == 1) {
                    if (input_audio_pid0 >= 4)
                        input_audio_pid0 = input_audio_pid0 - minimum_audio_pid;
                    else if (input_audio_pid0 == 0)
                        input_audio_pid0 = -1;

                    if (input_audio_pid1 >= 4)
                        input_audio_pid1 = input_audio_pid1 - minimum_audio_pid;
                    else if (input_audio_pid1 == 0)
                        input_audio_pid1 = -1;

                    if (input_audio_pid2 >= 4)
                        input_audio_pid2 = input_audio_pid2 - minimum_audio_pid;
                    else if (input_audio_pid2 == 0)
                        input_audio_pid2 = -1;
                }
                frm.input_audio_pid0.value = input_audio_pid0;
                frm.input_audio_pid1.value = input_audio_pid1;
                frm.input_audio_pid2.value = input_audio_pid2;


            } else if (key == "mpts_discover_cache") {
                mpts_discover_cache = val;
                if (mpts_discover_cache && mpts_discover_cache.length > 0) {
                    mpts_discover_cache = JSON.parse(mpts_discover_cache);
                if (!mpts_discover_cache || !mpts_discover_cache.programs || mpts_discover_cache.programs.length == 0) {
                    mpts_discover_cache = null;
                }

                if ((input_interface == "IP" || input_interface == "DVB-API") && mpts_discover_cache && mpts_discover_cache.source.type!="sdi"){
                    mpts_discover_set_results(mpts_discover_cache, false);
                } else {
                    mpts_discover_enable_results(false);
                }
            }
            } else {
                var elem = $("#" + key);

                if (elem && elem.length > 0) {
                    if (key.match(/stream_active\d+/)) {
                        elem.attr("checked", val == "true");
                    } else if (key.match(/stream_width\d+/)) {
                        elem.val(val);
                    } else if (key.match(/stream_height\d+/)) {
                        elem.val(val);
                    } else if (key.match(/stream_bitrate\d+/)) {
                        elem.val(val);
                    } else if (key.match(/stream_codec\d+/)) {
                        elem.val(val);
                    } else if (key.match(/stream_framerate\d+/)) {
                        elem.val(val);
                    } else if (key.match(/stream_profile\d+/)) {
                                elem.val(val);
                         } else if (key.match(/stream_audio_bitrate\d+/)) {
                        elem.val(val);
                    } else if (key.match(/stream_audio_channels\d+/)) {
                                elem.val(val);
                                stream_audio_populate();
                    } else if (key.match(/stream_audio_only\d+/)) {
                        elem.attr("checked", val == "true");
                    } else if (key.match(/stream_enable_image_overlay\d+/)) {
                        elem.attr("checked", val == "true");
                   } else if (key.match(/stream_vbr\d+/)) {
                        elem.val(val == "true" ? "1" : "0");
                    } else if (key.match(/stream_max_bitrate\d+/)) {
                        elem.val(val);
                    } else if (key.match(/rtp_address\d+/)) {
                        elem.val(val);
                    } else if (key.match(/rtp_port\d+/)) {
                        elem.val(val);
                    } else if (key.match(/multi_ts_address\d+/)) {
                        elem.val(val);
                    } else if (key.match(/multi_ts_port\d+/)) {
                        elem.val(val);
                    } else if (key.match(/rtmp_stream_name\d+/)) {
                        elem.val(val);
                    } else if (key.match(/multi_output_file_active\d+/)) {
                        elem.attr("checked", val == "true");
                    } else if (key == "scte35_passthru") {
                        $("#scte35_passthru").val(val).change();
                        $("#mv_scte35_passthru").val(val).change();
                    } else {
                        if (elem.is(":checkbox")) {
                            if (val == "1" || val == "true") {
                                elem.attr("checked", true);
                            } else {
                                elem.attr("checked", false);
                            }
                        } else {
                            elem.val(val).change();
                        }
                    }
                }else {
                    if (key.match(/stream_overlay_file\d+/)) {
                        idx = key[key.length-1];
                        $("#image_overlay_params"+idx).val($("#image_overlay_params"+idx).val()+"&"+key+"="+val);
                    } else if (key.match(/stream_overlay_position\d+/)) {
                        idx = key[key.length-1];
                        $("#image_overlay_params"+idx).val($("#image_overlay_params"+idx).val()+"&"+key+"="+val);
                    } else if (key.match(/stream_overlay_margin_x\d+/)) {
                        idx = key[key.length-1];
                        $("#image_overlay_params"+idx).val($("#image_overlay_params"+idx).val()+"&"+key+"="+val);
                   } else if (key.match(/stream_overlay_margin_y\d+/)) {
                        idx = key[key.length-1];
                        $("#image_overlay_params"+idx).val($("#image_overlay_params"+idx).val()+"&"+key+"="+val);
                  } else if (key.match(/stream_overlay_width\d+/)) {
                        idx = key[key.length-1];
                        $("#image_overlay_params"+idx).val($("#image_overlay_params"+idx).val()+"&"+key+"="+val);
                  } else if (key.match(/stream_overlay_height\d+/)) {
                        idx = key[key.length-1];
                        $("#image_overlay_params"+idx).val($("#image_overlay_params"+idx).val()+"&"+key+"="+val);
                  } else if (key.match(/stream_overlay_alpha\d+/)) {
                        idx = key[key.length-1];
                        $("#image_overlay_params"+idx).val($("#image_overlay_params"+idx).val()+"&"+key+"="+val);
                   }
                }
            }
// DEBUG OPTIONS END
        }
        if(!has_config_version || config_version == "N/A")
        {
                alert("Please re-save this config before using. Format is out of date.");
        }

        <?php if (ENABLE_DVB_SUBTITLES == 1) { ?>
        // We have to wait until the discover cache is processed to set this
        frm.input_subtitle_pid.value = input_subtitle_pid;

        if ($("#input_subtitle_pid").find("option").length <= 1) {
            $("#input_subtitle_mode1").attr("disabled", "disabled");
            $("#input_subtitle_mode1").parent().css("color", "gray");
        } else {
            $("#input_subtitle_mode1").removeAttr("disabled");
            $("#input_subtitle_mode1").parent().css("color", "black");
        }
        <?php } ?>

        frm.input_audio_pid0.value = input_audio_pid0;
        if ($("#input_audio_pid0").find("option").length <= 1) {
            $("#input_audio_pid0").attr("disabled","disabled");
        } else {
            $("#input_audio_pid0").removeAttr("disabled");
        }

        frm.input_audio_pid1.value = input_audio_pid1;
        if ($("#input_audio_pid1").find("option").length <= 1) {
            $("#input_audio_pid1").attr("disabled","disabled");
        } else {
            $("#input_audio_pid1").removeAttr("disabled");
        }

        frm.input_audio_pid2.value = input_audio_pid2;
        if ($("#input_audio_pid2").find("option").length <= 1) {
            $("#input_audio_pid2").attr("disabled","disabled");
        } else {
            $("#input_audio_pid2").removeAttr("disabled");
        }

        <?php if ($enable_atsc_input) { ?>
        if (atsc_tuner != null) {
            $("#input_atsc_tuner").val(atsc_tuner);
        }
        input_atsc_tuner_changed(atsc_channel);
        <?php } ?>

        // Update input file name as appropriate
        <?php if (ENABLE_SOURCE_FILE_FTP) { ?>
        var source_file_path = "<?= SOURCE_FILE_PATH ?>";
        if (yuv_file_name.substring(0,source_file_path.length) == source_file_path)
            yuv_file_name = yuv_file_name.substring(source_file_path.length);
        if (mp4_file_name.substring(0,source_file_path.length) == source_file_path)
            mp4_file_name = mp4_file_name.substring(source_file_path.length);
        <?php } ?>

        frm.yuv_file_name.value = yuv_file_name;
        source_file_list_set(yuv_file_name);

        frm.mp4file_input_name.value = mp4_file_name;
        mp4file_list_set(mp4_file_name);

        var preset;
        preset = frm.input_resolution.value;
        if (preset == "USER" && input_interface != "HD-SDI") {
            $("#input_row_1").show();
        } else {
            $("#input_row_1").hide();
        }
        sync_hd_sdi_input_mode(false);
        sync_hdmi_input_mode(false);

        var output_audio_bitrate2 = frm.output_audio_bitrate2.value;

        refresh_output_interface();

        frm.output_audio_bitrate2.value = output_audio_bitrate2;
        $("#output_audio_bitrate2").change();

        select_output_encoder(output_encoder);

        var max_streams = MAX_STREAM_GROUPS * MAX_VIDEO_STREAMS;
        for (i = 0; i < max_streams; i++)
        {
            var name;
            var obj;
            var width, height;

            //obj.value = frm.output_audio_bitrate0.value / 1000;

            name = "stream_width" + i;
            var width_obj = document.getElementById(name);
            width = width_obj.value;

            name = "stream_height" + i;
            var height_obj = document.getElementById(name);
            height = height_obj.value;

            //alert("width: " + width + " height: "+ height);
            if (width == 1280 && height == 720)
                index = 0;
            else if (width == 960 && height == 360)
                index = 1;
            else if (width == 640 && height == 480)
                index = 2;
            else if (width == 480 && height == 320)
                index = 3;
            else if (width == 320 && height == 240)
                index = 4;
            else if (width == 176 && height == 90)
                index = 5;
            else if (width == 848 && height == 480)
                index = 7;
            else if (width == 640 && height == 368)
                index = 8;
            else if (width == 416 && height == 240)
                index = 9;
            else if (width == 1920 && height == 1080)
                index = 10;
            else
                index = 6;

            name = "stream_preset" + i;
            obj = document.getElementById(name);

            // Make sure option element really exists before selecting
            var optionElem = $(obj).find("option[value='" + index + "']");
            if (optionElem.length == 0) {
                index = 6;
            }

            obj.value = index;

            if (index == 6)
            {
                width_obj.disabled == false;
                height_obj.disabled == false;
                width_obj.style["color"] = "black";
                height_obj.style["color"] = "black";
            }
            else
            {
                width_obj.disabled == true;
                height_obj.disabled == true;
                width_obj.style["color"] = "#888888";
                height_obj.style["color"] = "#888888";
            }
        }

        var output_encoder = frm.output_encoder.value;

        <?php if (ENABLE_PYRAMID_B == 1) { ?>
        if (is_multirate_output()) {
            var row = document.getElementById("h264_pyramid_row");
            row.style["display"] = "";
        } else {
            var row = document.getElementById("h264_pyramid_row");
            row.style["display"] = "none";
        }
        <?php } ?>

        <?php if(CONFIG_MODE != 1) { ?>
        if (!is_multirate_output() && (output_encoder == "H264" || output_encoder == "LOWLATENCY") || output_encoder == "H264FF" )
        {
            var row = document.getElementById("h264_profile_row");
            row.style["display"] = "";
            row = document.getElementById("h264_constraint_row");
            row.style["display"] = "";
        }
        else
        {
            var row = document.getElementById("h264_profile_row");
            row.style["display"] = "none";
            row = document.getElementById("h264_constraint_row");
            row.style["display"] = "none";
        }
        <?php } ?>

        audio_only_clicked();

        group_checkbox_clicked(frm.stream_group_checkbox1, 1);
        // Check if there are two groups or just one
        <?php
        if(MAX_STREAM_GROUPS > 1)
        {
        ?>
        group_checkbox_clicked(frm.stream_group_checkbox2, 2);
        <?php
        }
        ?>

        // Now the form is updated with the necessary values, but sometimes, a specific configuration needs some specific
        // values
         <?php
        // If we are in ATSC mode, the tab MPEG2TS streaming should be hidden, and strangely, the easiest way
        // to do it, is to call this function with this output aas parameter
        if(CONFIG_MODE == 1)
        {
        ?>
            output_interface_selected("ATSC");

            // Output video format is fixed to progressive
            $("#output_format").val("0");

            // Enable group 1/disable 2
            $("#stream_group_checkbox1").attr("checked", true);
            $("#stream_group_checkbox1").attr("disabled", "disabled");
            group_checkbox_clicked(frm.stream_group_checkbox1, 1);

            $("#stream_active0").attr("checked", true);
            $("#stream_active0").attr("disabled", "disabled");

            $("#stream_group_checkbox2").attr("checked", false);

            // Hide the optios for the tabs that must not be seen with this configuration
            $("#rtmp-options").css("display","none");
            $("#apple-options").css("display","none");
            $("#silverlight-options").css("display","none");
        <?php
        }
        ?>
        if((get_active_output_interface()=="HDSDI"))
           refresh_output_interface();
        if($("output_encoder").val()=="H264LD")
           video_encoder_changed($("#output_encoder")[0]);
        $("input[name=input_interface]:radio").change();
        if(!$(".ui-state-active").is(":visible")) //Set tab to first tab if last tab no longer exists (for example output mode changed)
            select_option_from_active(0); //Todo: Show next closest visible
    }
    function select_option_from_active(index)
    {
      //var index = 0;//$('.ui-state-active').index() - 1;
      switch(index){
       case 0:
            select_option0();
            break;
       case 1:
            select_option1();
            break;
       case 2:
            select_option2();
            break;
      case 3:
            select_option3();
            break;
      case 4:
            select_option4();
            break;
      case 5:
            select_option5();
            break;
      case 6:
            select_option6();
            break;
      }
    }
    function refresh_output_interface()
    {
        set_active_output_interface(get_active_output_interface());
    }

    function sync_hd_sdi_input_mode(force_correct) {
        var frm = document.configuration;

        var preset;
        var width;
        var height;
        var format = frm.input_format.value;
        var framerate = frm.input_framerate.value;
        var enable_psf = frm.enable_psf.value;

        preset = frm.input_resolution.value;
        if (preset == "4K")
        {
            width = 4096;
            height = 2160;
        }
        else if (preset == "UltraHD")
        {
            width = 3840;
            height = 2160;
        }
        else if (preset == "HD1080")
        {
            width = 1920;
            height = 1080;
        }
        else if (preset == "HD720")
        {
            width = 1280;
            height = 720;
        }
        else if (preset == "PAL")
        {
            width = 704;
            height = 576;
        }
        else if (preset == "PAL720")
        {
            width = 720;
            height = 576;
        }
        else if (preset == "NTSC")
        {
            width = 704;
            height = 480;
        }
        else if (preset == "NTSC720")
        {
            width = 720;
            height = 480;
        }
        else
        {
            width = frm.input_width.value;
            height = frm.input_height.value;
        }

        var mode = -1;
        var offset = 0;
        if(width == 4096 && height == 2160)
        {
            switch (framerate*100)
            {
                case 2398:
                    offset = 0;
                    break;
                case 2400:
                    offset = 1;
                    break;
                case 2500:
                    offset = 2;
                    break;
                case 2997:
                    offset = 3;
                    break;
                case 3000:
                    offset = 4;
                    break;
                case 5000:
                    offset = 5;
                    break;
                case 5994:
                    offset = 6;
                    break;
                case 6000:
                    offset = 7;
                    break;
            }
            mode = 30 + offset;
        }
        else if (width == 3840 && height == 2160)
        {
            switch (framerate*100)
            {
                case 2398:
                    offset = 0;
                    break;
                case 2400:
                    offset = 1;
                    break;
                case 2500:
                    offset = 2;
                    break;
                case 2997:
                    offset = 3;
                    break;
                case 3000:
                    offset = 4;
                    break;
                case 5000:
                    offset = 5;
                    break;
                case 5994:
                    offset = 6;
                    break;
                case 6000:
                    offset = 7;
                    break;
            }
            mode = 22 + offset;
        }
        else if (width == 1920 && height == 1080)
        {
            // Only a subset of input parameters are supported in HD-SDI mode
            // so correct for unsupported options
            if (force_correct) {
                if (framerate == 50)
                {
                    framerate = 25;
                    frm.input_framerate.value = framerate;
                }
                else if (framerate == 59.94)
                {
                    framerate = 29.97;
                    frm.input_framerate.value = framerate;
                }
                else if (framerate == 60)
                {
                    framerate = 30;
                    frm.input_framerate.value = framerate;
                }
            }

            if (format == 0)
            {
                if (framerate == 23.98)
                {
                    if (enable_psf == 0) {
                        mode = 3;
                    } else {
                        mode = 14;
                    }
                }
                else if (framerate == 24)
                {
                    if (enable_psf == 0) {
                        mode = 4;
                    } else {
                        mode = 15;
                    }
                }
                else if (framerate == 25)
                {
                    if (enable_psf == 0) {
                        mode = 5;
                    } else {
                        mode = 16;
                    }
                }
                else if (framerate == 29.97)
                {
                    if (enable_psf == 0) {
                        mode = 6;
                    } else {
                        mode = 17;
                    }
                }
                else if (framerate == 30)
                {
                    if (enable_psf == 0) {
                        mode = 7;
                    } else {
                        mode = 18;
                    }
                }
            }
            else if (format == 1)
            {
                if (force_correct) {
                    if (framerate == 23.98)
                    {
                        framerate = 30;
                        frm.input_framerate.value = framerate;
                    }
                    else if (framerate == 24)
                    {
                        framerate = 30;
                        frm.input_framerate.value = framerate;
                    }
                }

                if (framerate == 25)
                    mode = 8;
                else if (framerate == 29.97)
                    mode = 9;
                else if (framerate == 30)
                    mode = 10;
            }
        }
        else if (width == 1280 && height == 720)
        {
            if (force_correct) {
                if (framerate == 23.98)
                {
                    framerate = 60;
                    frm.input_framerate.value = framerate;
                }
                else if (framerate == 24)
                {
                    framerate = 60;
                    frm.input_framerate.value = framerate;
                }
                else if (framerate == 25)
                {
                    framerate = 50;
                    frm.input_framerate.value = framerate;
                }
                else if (framerate == 29.97)
                {
                    framerate = 59.94;
                    frm.input_framerate.value = framerate;
                }
                else if (framerate == 30)
                {
                    framerate = 60;
                    frm.input_framerate.value = framerate;
                }
            }

            if (framerate == 50)
            {
                if (enable_psf == 0) {
                    mode = 11;
                } else {
                    mode = 19;
                }
            }
            else if (framerate == 59.94)
            {
                if (enable_psf == 0) {
                    mode = 12;
                } else {
                    mode = 20;
                }
            }
            else if (framerate == 60)
            {
                if (enable_psf == 0) {
                    mode = 13;
                } else {
                    mode = 21;
                }
            }
        }
        else if (width == 720 && height == 576)
        {
            mode = 2;
        }
        else if (width == 720 && height == 480)
        {
            if (force_correct) {
                if (framerate != 23.98 && framerate != 29.97) {
                    framerate = 29.97;
                    frm.input_framerate.value = framerate;
                }
            }

            if (framerate == 23.98)
                mode = 1;
            else if (framerate == 29.97)
                mode = 0;
        }
        else if (force_correct) {
            // Found an unknown combination of options so default to something reasonable
            mode = 0;
        }

        frm.sdi_input_mode.value = mode;

        $("#rtmp_naming").change();
    }

    function sync_hdmi_input_mode(force_correct) {
        var frm = document.configuration;

        var preset;
        var width;
        var height;
        var format = frm.input_format.value;
        var framerate = frm.input_framerate.value;

        preset = frm.input_resolution.value;
        if (preset == "HD1080")
        {
            width = 1920;
            height = 1080;
        }
        else if (preset == "HD720")
        {
            width = 1280;
            height = 720;
        }
        else if (preset == "PAL")
        {
            width = 720;
            height = 576;
        }
        else if (preset == "PAL720")
        {
            width = 720;
            height = 576;
        }
        else if (preset == "NTSC")
        {
            width = 720;
            height = 480;
        }
        else if (preset == "NTSC720")
        {
            width = 720;
            height = 480;
        }
        else
        {
            width = frm.input_width.value;
            height = frm.input_height.value;
        }

        var mode = -1;
        if (width == 1920 && height == 1080) {
            // Only a subset of input parameters are supported in HDMI mode
            // so correct for unsupported options
            if (force_correct) {
                if (framerate == 50) {
                    framerate = 25;
                    frm.input_framerate.value = framerate;
                } else if (framerate == 59.94){
                    framerate = 29.97;
                    frm.input_framerate.value = framerate;
                } else if (framerate == 60) {
                    framerate = 30;
                    frm.input_framerate.value = framerate;
                }
            }

            if (format == 0) {
                if (framerate == 23.98) {
                    mode = 5;
                } else if (framerate == 24) {
                    mode = 6;
                } else if (framerate == 25) {
                    mode = 7;
                } else if (framerate == 29.97) {
                    mode = 8;
                } else if (framerate == 30) {
                    mode = 9;
                } else {
                    mode = 9;
                }
            } else if (format == 1) {
                if (force_correct) {
                    if (framerate != 25 && framerate != 29.97 && framerate != 30) {
                        framerate = 30;
                        frm.input_framerate.value = framerate;
                    }
                }
                if (framerate == 25) {
                    mode = 10;
                } else if (framerate == 29.97) {
                    mode = 11;
                } else if (framerate == 30) {
                    mode = 12;
                } else {
                    mode = 12;
                }
            }
        }
        else if (width == 1280 && height == 720)
        {
            if (force_correct) {
                if (framerate == 23.98) {
                    framerate = 60;
                    frm.input_framerate.value = framerate;
                } else if (framerate == 24) {
                    framerate = 60;
                    frm.input_framerate.value = framerate;
                } else if (framerate == 25) {
                    framerate = 50;
                    frm.input_framerate.value = framerate;
                } else if (framerate == 29.97) {
                    framerate = 59.94;
                    frm.input_framerate.value = framerate;
                } else if (framerate == 30) {
                    framerate = 60;
                    frm.input_framerate.value = framerate;
                } else if (framerate != 50 && framerate != 59.94 && framerate != 60) {
                    framerate = 60;
                    frm.input_framerate.value = framerate;
                }
            }

            if (framerate == 50) {
                mode = 13;
            } else if (framerate == 59.94) {
                mode = 14;
            } else if (framerate == 60) {
                mode = 15;
            } else {
                mode = 15;
            }
        }
        else if (width == 720 && height == 576)
        {
            if (format == 0) {
                if (force_correct && framerate != 50) {
                    framerate = 50;
                    frm.input_framerate.value = framerate;
                }
                mode = 4;
            } else {
                if (force_correct && framerate != 25) {
                    framerate = 25;
                    frm.input_framerate.value = framerate;
                }
                mode = 2;
            }
        }
        else if (width == 720 && height == 480)
        {
            if (format == 0) {
                if (force_correct && framerate != 23.98 && framerate != 59.94) {
                    framerate = 59.94;
                    frm.input_framerate.value = framerate;
                }
                if (framerate == 23.98) {
                    mode = 1;
                } else {
                    mode = 3;
                }
            } else {
                if (force_correct) {
                    if (framerate != 29.97) {
                        framerate = 29.97;
                        frm.input_framerate.value = framerate;
                    }
                }
                mode = 0;
            }
        } else if (force_correct) {
            // Found an unknown combination of options so default to something reasonable
            mode = 0;
        }

        frm.hdmi_input_mode.value = mode;
    }

    function file_selected(select_obj)
    {
        var frm = document.configuration;
        if (window.XMLHttpRequest)
        {
            var xmlhttp = new XMLHttpRequest();
            var current_time = new Date();
            xmlhttp.open('GET', '<?php echo $SELF; ?>?action=get_config&config_filename='+select_obj.value+'&ts='+current_time.getTime(), false);
            xmlhttp.send();
            results = xmlhttp.responseText

            if (results.toString().includes("ParserError")) {
                alert("Error: File could not be parsed");
            } else {
                results = results.split(";");
                update_form(results, select_obj.value);
            }
        }
    }

    function ip_output_type_selected(select_obj)
    {
        var frm = document.configuration;
    }

    function frame_type_selected(frame_type)
    {
        if (frame_type == 'progressive')
        {
            var frm = document.configuration;
            frm.encode_format[0].checked = true;
            frm.encode_format[1].disabled = true;
        }
        else
        {
            var frm = document.configuration;
            frm.encode_format[1].disabled = false;
        }
    }

    function video_preset_selected(select_obj, stream_num)
    {
        var width_id = "stream_width"+stream_num;
        var height_id = "stream_height"+stream_num;
        var width_obj = document.getElementById(width_id);
        var height_obj = document.getElementById(height_id);

        width_obj.disabled = true;
        height_obj.disabled = true;
        width_obj.style["color"] = "#888888";
        height_obj.style["color"] = "#888888";

        switch (select_obj.value)
        {
            case "0":
                width = 1280;
                height = 720;
                break;
            case "1":
                width = 960;
                height = 360;
                break;
            case "2":
                width = 640;
                height = 480;
                break;
            case "3":
                width = 480;
                height = 320;
                break;
            case "4":
                width = 320;
                height = 240;
                break;
            case "5":
                width = 176;
                height = 90;
                break;
            case "7":
                width = 848;
                height = 480;
                break;
            case "8":
                width = 640;
                height = 368;
                break;
            case "9":
                width = 416;
                height = 240;
                break;
            case "10":
                width = 1920;
                height = 1080;
                break;
            case "11":
                width = 3840;
                height = 2160;
                break;
            case "6":
            default:
                width_obj.disabled = false;
                height_obj.disabled = false;
                width_obj.style["color"] = "black";
                height_obj.style["color"] = "black";
                break;

        }

        width_obj.value = width;
        height_obj.value = height;

        updateFrameRates();
    }

    function output_audio_clicked_disable(enable1)
    {
        var frm = document.configuration;
        var obj;
        var row;

        row = document.getElementById("audio_bitrate_row0");
        row.style["color"] = "black";
        row = document.getElementById("audio_volume_row0");
        row.style["color"] = "black";

        frm.output_audio_bitrate0.disabled = false;
        frm.output_audio_volume0.disabled = false;
        frm.output_audio_volume0.style["color"] = "black";

        if (enable1 == 1) {
            enable_output_audio_channel(1, true);
        } else {
            enable_output_audio_channel(1, false);
        }

        enable_output_audio_channel(2, false);

        update_audio_controls();
    }

    function stream_group_atsc(groupIndex)
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;
        var st;

        for (st = 0; st < <?php echo MAX_VIDEO_STREAMS ?>; st++)
        {
            id = "stream_preset" + st;
            obj = document.getElementById(id);
            selected_val = obj.value;

            for (i = obj.options.length-1; i>=0; i--)
            {
                obj.remove(i);
            }

            obj.options[0] = new Option("848x480",'7', false, false);
            obj.options[1] = new Option("640x368",'8', false, false);
            obj.options[2] = new Option("416x240",'9', false, false);
            obj.options[3] = new Option("Custom...",'6', false, false);
            obj.value = selected_val;
        }
    }

    function stream_group1_ipod()
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;
        var st;

        for (st = 0; st < <?php echo MAX_VIDEO_STREAMS ?>; st++)
        {
            id = "stream_preset" + st;
            obj = document.getElementById(id);
            selected_val = obj.value;

            for (i = obj.options.length-1; i>=0; i--)
            {
                obj.remove(i);
            }

            obj.options[0] = new Option("3840x2160",'11', false, false);
            obj.options[1] = new Option("1920x1080",'10', false, false);
            obj.options[2] = new Option("1280x720",'0', false, false);
            obj.options[3] = new Option("640x480",'2', false, false);
            obj.options[4] = new Option("480x320",'3', false, false);
            obj.options[5] = new Option("320x240",'4', false, false);
            obj.options[6] = new Option("176x90",'5', false, false);
            obj.options[7] = new Option("Custom...",'6', false, false);
            obj.value = selected_val;
        }
    }

    function stream_group2_ipod()
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;
        var st;

        for (st = MAX_VIDEO_STREAMS; st < 2*MAX_VIDEO_STREAMS; st++)
        {
            id = "stream_preset" + st;
            obj = document.getElementById(id);
            selected_val = obj.value;

            for (i = obj.options.length-1; i>=0; i--)
            {
                obj.remove(i);
            }

            obj.options[0] = new Option("1920x1080",'10', false, false);
            obj.options[1] = new Option("1280x720",'0', false, false);
            obj.options[2] = new Option("640x480",'2', false, false);
            obj.options[3] = new Option("480x320",'3', false, false);
            obj.options[4] = new Option("320x240",'4', false, false);
            obj.options[5] = new Option("176x90",'5', false, false);
            obj.options[6] = new Option("Custom...",'6', false, false);
            obj.value = selected_val;
        }
    }

    function stream_group1_normal()
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;
        var st;

        for (st = 0; st < MAX_VIDEO_STREAMS; st++)
        {
            id = "stream_preset" + st;
            obj = document.getElementById(id);
            if(obj == null)
                continue;

            selected_val = obj.value;

            for (i = obj.options.length-1; i>=0; i--)
            {
                obj.remove(i);
            }

            if (st == 0)
            {
                obj.options[0] = new Option("3840x2160",'11', false, false);
                obj.options[0] = new Option("1920x1080",'10', false, false);
                obj.options[1] = new Option("1280x720",'0', false, false);
                obj.options[2] = new Option("960x360",'1', false, false);
                obj.options[3] = new Option("640x480",'2', false, false);
                obj.options[4] = new Option("480x320",'3', false, false);
                obj.options[5] = new Option("320x240",'4', false, false);
                obj.options[6] = new Option("176x90",'5', false, false);
                obj.options[7] = new Option("Custom...",'6', false, false);
            }
            else
            {
                obj.options[0] = new Option("3840x2160",'11', false, false);
                obj.options[0] = new Option("1920x1080",'10', false, false);
                obj.options[1] = new Option("1280x720",'0', false, false);
                obj.options[2] = new Option("960x360",'1', false, false);
                obj.options[3] = new Option("640x480",'2', false, false);
                obj.options[4] = new Option("480x320",'3', false, false);
                obj.options[5] = new Option("320x240",'4', false, false);
                obj.options[6] = new Option("176x90",'5', false, false);
                obj.options[7] = new Option("Custom...",'6', false, false);
            }

            obj.value = selected_val;
        }
    }

    function stream_group2_normal()
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;
        var st;

        for (st = MAX_VIDEO_STREAMS; st < 2*MAX_VIDEO_STREAMS; st++)
        {
            id = "stream_preset" + st;
            obj = document.getElementById(id);
            if(obj == null)
                continue;
            selected_val = obj.value;

            for (i = obj.options.length-1; i>=0; i--)
            {
                obj.remove(i);
            }

            obj.options[0] = new Option("1920x1080",'10', false, false);
            obj.options[1] = new Option("1280x720",'0', false, false);
            obj.options[2] = new Option("960x360",'1', false, false);
            obj.options[3] = new Option("640x480",'2', false, false);
            obj.options[4] = new Option("480x320",'3', false, false);
            obj.options[5] = new Option("320x240",'4', false, false);
            obj.options[6] = new Option("176x90",'5', false, false);
            obj.options[7] = new Option("Custom...",'6', false, false);

            obj.value = selected_val;
        }
    }

    function output_audio_clicked0_aac(selector)
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;

        id = "output_audio_bitrate0";
        obj = document.getElementById(id);
        selected_val = obj.value;

        for (i = obj.options.length-1; i>=0; i--)
        {
            obj.remove(i);
        }

        obj.options[0] = new Option("24 kbps MPEG4 HE-AAC",'24000', false, false);
        obj.options[1] = new Option("32 kbps MPEG4 HE-AAC",'32000', false, false);
        obj.options[2] = new Option("40 kbps MPEG4 HE-AAC",'40000', false, false);

        <?php if(CONFIG_MODE != 1) { ?>
        obj.options[3] = new Option("64  kbps MPEG4 HE-AAC",'64000', false, false);
        obj.options[4] = new Option("80  kbps MPEG4 HE-AAC",'80000', false, false);
        obj.options[5] = new Option("96  kbps MPEG4 AAC-LC",'96000', false, false);
        obj.options[6] = new Option("128 kbps MPEG4 AAC-LC",'128000', false, false);
        obj.options[7] = new Option("160 kbps MPEG4 AAC-LC",'160000', false, false);
        obj.options[8] = new Option("192 kbps MPEG4 AAC-LC",'192000', false, false);
        obj.options[9] = new Option("256 kbps MPEG4 AAC-LC",'256000', false, false);
        obj.options[10] = new Option("384 kbps MPEG4 AAC-LC",'384000', false, false);
        <?php } ?>
        obj.value = selected_val;
    }
    function stream_audio_populate()
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;

        id = ".stream_audio_select,.aud_bitrate";
        //id = ".aud_bitrate";
        objects = $(id).get();
        objects.forEach(function(obj){
            var disabledOption = 0;
            selected_val = obj.value;
            var offset = 0;
            var index = obj.name.substr(-1);
            if(!$(obj).hasClass("aud_bitrate")){
                    if(obj.name.myStartsWith("stream_audio_bitrate2"))
                    {
                        if ($("#stream_audio_channels2_"+index).val() == 6)
                                offset = 5;
                        disabledOption = 1;
                    }
                    else if ($("#stream_audio_channels"+index).val() == 6)
                    {
                        offset = 5;
                    }
                }
            else {
              if($(obj).closest("td").prev().children(".aud_codec")[0].value == "AC3"){
                $(obj).closest("td").next().next().children(".aud_dialnorm").show();
                add_ac3_bitrates(obj,false);
                // Verify that old value still exists before re-selecting it
                var old_val_exists = 0 != $(obj).find('option[value="' + selected_val + '"]').length;
                if (old_val_exists)
                    obj.value = selected_val;
                else if (selected_val != null && selected_val!="")
                {
                    var chan = parseInt(index)+1;
                    if(!isNaN(chan))
                        alert("Audio bitrate is too low for 5.1 (stream "+chan+"). Please select a higher bitrate or return to stereo");
                }
                return;
              }
              else
                $(obj).closest("td").next().next().children(".aud_dialnorm").hide();

            }
            for (i = obj.options.length-1; i>=0; i--)
            {
                obj.remove(i);
            }
        if(disabledOption)
            obj.options[0] = new Option("Disabled",'0', false, false);
                obj.options[disabledOption+0] = new Option("24 kbps MPEG4 HE-AAC",'24000', false, false);
                obj.options[disabledOption+1] = new Option("32 kbps MPEG4 HE-AAC",'32000', false, false);
                obj.options[disabledOption+2] = new Option("40 kbps MPEG4 HE-AAC",'40000', false, false);
                obj.options[disabledOption+3] = new Option("64 kbps MPEG4 HE-AAC",'64000', false, false);
                obj.options[disabledOption+4] = new Option("80 kbps MPEG4 HE-AAC",'80000', false, false);
                obj.options[disabledOption+5-offset] = new Option("96  kbps MPEG4 AAC-LC",'96000', false, false);
                obj.options[disabledOption+6-offset] = new Option("128 kbps MPEG4 AAC-LC",'128000', false, false);
                obj.options[disabledOption+7-offset] = new Option("160 kbps MPEG4 AAC-LC",'160000', false, false);
                obj.options[disabledOption+8-offset] = new Option("192 kbps MPEG4 AAC-LC",'192000', false, false);
                obj.options[disabledOption+9-offset] = new Option("256 kbps MPEG4 AAC-LC",'256000', false, false);
                obj.options[disabledOption+10-offset] = new Option("384 kbps MPEG4 AAC-LC",'384000', false, false);

        // Verify that old value still exists before re-selecting it
        var old_val_exists = 0 != $(obj).find('option[value="' + selected_val + '"]').length;
        if (old_val_exists)
            obj.value = selected_val;
        else if (selected_val != null && selected_val!="")
        {
            var chan = parseInt(index)+1;
            alert("Audio bitrate is too low for 5.1 (stream "+chan+"). Please select a higher bitrate or return to stereo");
        }
        });
    }

    function add_ac3_bitrates(obj, includeDisabled)
    {
        if(obj.options){
        for (i = obj.options.length-1; i>=0; i--)
        {
            obj.remove(i);
        }
        }
        var iStart = 0;
        if (includeDisabled)
        {
            obj.options[0] = new Option("Disable",'0', false, true);
            iStart = 1;
        }

        obj.options[iStart+0] = new Option("128 kbps",'128000', false, false);
        obj.options[iStart+1] = new Option("192 kbps",'192000', false, false);
        obj.options[iStart+2] = new Option("256 kbps",'256000', false, false);
        obj.options[iStart+3] = new Option("384 kbps",'384000', false, false);
        obj.options[iStart+4] = new Option("448 kbps",'448000', false, false);
        obj.options[iStart+5] = new Option("512 kbps",'512000', false, false);
        obj.options[iStart+6] = new Option("576 kbps",'576000', false, false);
        obj.options[iStart+7] = new Option("640 kbps",'640000', false, false);
    }

    function output_audio_clicked0_ac3(selector)
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;

        id = "output_audio_bitrate0";
        obj = document.getElementById(id);
        selected_val = obj.value;
        add_ac3_bitrates(obj, false);
        obj.value = selected_val;
    }


   function output_audio_clicked0_normal(selector)
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;

        id = "output_audio_bitrate0";
        obj = document.getElementById(id);
        selected_val = obj.value;

        for (i = obj.options.length-1; i>=0; i--)
        {
            obj.remove(i);
        }

        if (is_audio_passthrough(selector.value))
        {
            obj.options[0] = new Option("Enable",'64000', false, true);
        }
        else
        {
            if (selector.value == "aac") {
                obj.options[0] = new Option("24 kbps MPEG4 HE-AAC",'24000', false, false);
                obj.options[1] = new Option("32 kbps MPEG4 HE-AAC",'32000', false, false);
                obj.options[2] = new Option("40 kbps MPEG4 HE-AAC",'40000', false, false);

                <?php if(CONFIG_MODE != 1) { ?>
                obj.options[3] = new Option("64 kbps MPEG4 HE-AAC",'64000', false, false);
                obj.options[4] = new Option("80 kbps MPEG4 HE-AAC",'80000', false, false);
                obj.options[5] = new Option("96 kbps MPEG4 HE-AAC",'96000', false, false);
                obj.options[6] = new Option("128 kbps MPEG2 AAC-LC",'128000', false, false);
                obj.options[7] = new Option("192 kbps MPEG2 AAC-LC",'192000', false, false);
                <?php } ?>
            }
            else if (selector.value == "ac3") {
                add_ac3_bitrates(obj, false);
            } else {
                obj.options[0] = new Option("64 kbps",'64000', false, false);
                obj.options[1] = new Option("96 kbps",'96000', false, false);
                obj.options[2] = new Option("128 kbps",'128000', false, false);
                obj.options[3] = new Option("192 kbps",'192000', false, false);
            }
        }

        // Verify that old value still exists before re-selecting it
        var old_val_exists = 0 != $(obj).find('option[value="' + selected_val + '"]').length;
        if (old_val_exists)
            obj.value = selected_val;
    }

    function output_audio_clicked1(selector)
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;

        id = "output_audio_bitrate1";
        obj = document.getElementById(id);
        selected_val = obj.value;

        for (i = obj.options.length-1; i>=0; i--)
        {
            obj.remove(i);
        }

        if (is_audio_passthrough(selector.value)||get_active_output_interface()=="MULTITS")
        {
            obj.options[0] = new Option("Disable",'0', false, true);
            obj.options[1] = new Option("Enable",'64000', false, false);
        }
        else
        {
            obj.options[0] = new Option("Disable",'0', false, true);
            if (selector.value == "aac") {
                obj.options[1] = new Option("24 kbps MPEG4 HE-AAC",'24000', false, false);
                obj.options[2] = new Option("32 kbps MPEG4 HE-AAC",'32000', false, false);
                obj.options[3] = new Option("40 kbps MPEG4 HE-AAC",'40000', false, false);

                <?php if(CONFIG_MODE != 1) { ?>
                obj.options[4] = new Option("64 kbps MPEG4 HE-AAC",'64000', false, false);
                obj.options[5] = new Option("80 kbps MPEG4 HE-AAC",'80000', false, false);
                obj.options[6] = new Option("96 kbps MPEG2 AAC-LC",'96000', false, false);
                obj.options[7] = new Option("128 kbps MPEG2 AAC-LC",'128000', false, false);
                obj.options[8] = new Option("192 kbps MPEG2 AAC-LC",'192000', false, false);
                obj.options[9] = new Option("256 kbps MPEG2 AAC-LC",'256000', false, false);
                <?php } ?>
            } else if (selector.value == "ac3") {
                add_ac3_bitrates(obj, true);
            } else {
                obj.options[1] = new Option("64 kbps",'64000', false, false);
                obj.options[2] = new Option("96 kbps",'96000', false, false);
                obj.options[3] = new Option("128 kbps",'128000', false, false);
                obj.options[4] = new Option("192 kbps",'192000', false, false);
            }
        }
        // Verify that old value still exists before re-selecting it
        var old_val_exists = 0 != $(obj).find('option[value="' + selected_val + '"]').length;
        if (old_val_exists)
           obj.value = selected_val;
        $("#output_audio_bitrate1").change();
    }

    function output_audio_clicked2(selector)
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;

        id = "output_audio_bitrate2";
        obj = document.getElementById(id);
        selected_val = obj.value;

        for (i = obj.options.length-1; i>=0; i--)
        {
            obj.remove(i);
        }
        if (is_audio_passthrough(selector.value) || get_active_output_interface()=="MULTITS")
        {
            obj.options[0] = new Option("Disable",'0', false, true);
            obj.options[1] = new Option("Enable",'64000', false, false);
            obj.value = 0;
        } else if (selector.value == "ac3") {
            add_ac3_bitrates(obj, true);
        }
        else
        {
            obj.options[0] = new Option("Disable",'0', false, true);
            if (selector.value == "aac") {
                obj.options[1] = new Option("24 kbps MPEG4 HE-AAC v2",'24000', false, false);
                obj.options[2] = new Option("32 kbps MPEG4 HE-AAC v2",'32000', false, false);
                obj.options[3] = new Option("40 kbps MPEG4 HE-AAC v2",'40000', false, false);

                <?php if(CONFIG_MODE != 1) { ?>
                obj.options[4] = new Option("64 kbps MPEG2 AAC-LC",'64000', false, false);
                obj.options[5] = new Option("96 kbps MPEG2 AAC-LC",'96000', false, false);
                obj.options[6] = new Option("128 kbps MPEG2 AAC-LC",'128000', false, false);
                obj.options[7] = new Option("192 kbps MPEG2 AAC-LC",'192000', false, false);
                <?php } ?>
            } else {
                obj.options[1] = new Option("64 kbps",'64000', false, false);
                obj.options[2] = new Option("96 kbps",'96000', false, false);
                obj.options[3] = new Option("128 kbps",'128000', false, false);
                obj.options[4] = new Option("192 kbps",'192000', false, false);
            }
        }
        // Verify that old value still exists before re-selecting it
        var old_val_exists = 0 != $(obj).find('option[value="' + selected_val + '"]').length;
        if (old_val_exists)
            obj.value = selected_val;

        $("#output_audio_bitrate2").change();
    }

    function group_checkbox_clicked(checkbox, index)
    {
        //alert($('input[name=output_interface]:radio').length);
        if(!checkbox)
            return;

        var stream_index;
        var first_index;
        var last_index;

        //$("#stream_group_streams"+index).toggleClass("force_hide", !checkbox.checked);

        enable_row(".stream_group"+index+"_row", checkbox.checked);

        first_index = (index - 1) * MAX_VIDEO_STREAMS;
        last_index = first_index + (MAX_VIDEO_STREAMS - 1);

        for (stream_index = first_index; stream_index <= last_index; stream_index++)
        {
            set_stream_controls(stream_index, !checkbox.checked);
        }

        // DBA: 11/6/2012: Added Full back for all modes with warning on Save.
        // Remove the "Full" framerate option for RTMP/Apple output streams
        // if the input is Progressive, 60 fps
        if (checkbox.checked)
        {
            var frm = document.configuration;
            var id;
            var obj;
            var i;
            var selected_val;

            for (stream_index = first_index; stream_index <= last_index; stream_index++)
            {
                id = "stream_framerate" + stream_index;
                obj = document.getElementById(id);
                selected_val = obj.value;

                if (selected_val == "") {
                    selected_val = "0";
                }

                for (i = obj.options.length-1; i>=0; i--)
                {
                    obj.remove(i);
                }

                if(<?php echo CONFIG_MODE ?> == 1)
                {
                    obj.options[0] = new Option("Full", '0', false, false);
                }
                else
                {
                    obj.options[0] = new Option("Full (same as input)", '0', false, false);
                    obj.options[1] = new Option("1/2", '1', false, false);
                    obj.options[2] = new Option("1/4", '2', false, false);
                    obj.options[3] = new Option("2", '3', false, false);

                    <?php if (0 == strcasecmp(VENDOR, "CSIX")) { ?>
                    if (stream_index == 0) {
                        obj.options[4] = new Option("1 FPS", '101', false, false);
                    }
                    <?php } ?>
                    updateFrameRates();
                }

                obj.value = selected_val;
                // Check for bad values to reset to default if necessary
                if (obj.value != selected_val) {
                    obj.value = "0";
                }

            }
        }
    }

    function set_stream_controls(stream_idx, group_disabled)
    {
        var frm = document.configuration;
        var id;
        var obj;
        var custom_preset = false;
        var image_overlay_available = $("#image_overlay_params"+stream_idx).val().length;

        var row = $("#stream_row"+stream_idx);
        var stream_enabled = false;

        // Only enable a stream if the group is enabled and the previous
        // stream within in the group has also been enabled
        if (!group_disabled) {
            var first_stream_in_group = false;
            var is_curr_stream_active = $("#stream_active" + stream_idx).is(":checked");
            var is_prev_stream_active = false;

            if (stream_idx == 0 || (stream_idx % MAX_VIDEO_STREAMS) == 0) {
                first_stream_in_group = true;
            }

            if (first_stream_in_group) {
                stream_enabled = true;
            } else if (stream_idx > 0) {
                is_prev_stream_active = $("#stream_active" + (stream_idx - 1)).is(":checked");
            }

            if (is_curr_stream_active || is_prev_stream_active) {
                stream_enabled = true;
            }
        }

        id = "stream_active" + stream_idx;
        obj = document.getElementById(id);
        obj.disabled = !stream_enabled;

        $("#stream_active_label"+stream_idx).css("color", group_disabled ? "#888888" : "black");

        id = "stream_audio_only" + stream_idx;
        var audio_only = document.getElementById(id);
        id = "stream_enable_image_overlay" + stream_idx;
        var enable_image_overlay = document.getElementById(id);
        id = "stream_vbr" + stream_idx;
        var stream_vbr = document.getElementById(id);

        // If we are in ATSC mode, we only have the video output ATSC, no more, and here it is trying to access
        // to the value of another output format, that in this case, it does not exist
        if (get_active_output_interface() == "ATSC")
        {
            if (audio_only)
                audio_only.checked = false;
            if (enable_image_overlay)
                enable_image_overlay.checked = false;
            if (stream_vbr)
                stream_vbr.value = "0";
        }

        var is_audio_only = false;
        if (audio_only) {
            audio_only.disabled = !stream_enabled;
            is_audio_only = audio_only.checked;
        }

        var video_enabled = stream_enabled && !is_audio_only;
        var is_stream_vbr = false;
        if (stream_vbr) {
            stream_vbr.disabled = !video_enabled;
            is_stream_vbr = parseInt(stream_vbr.value) == 1;
        }

        if (enable_image_overlay) {
            enable_image_overlay.disabled = !video_enabled;
        }

        id = "stream_preset" + stream_idx;
        obj = document.getElementById(id);
        obj.disabled = !video_enabled;
        if (obj.value == 6)
        {
            custom_preset = true;
        }

        id = "stream_width" + stream_idx;
        obj = document.getElementById(id);
        obj.disabled = !video_enabled;
        if (!video_enabled)
        {
            obj.style["color"] = "#888888";
        }
        else
        {
            if (custom_preset)
            {
                obj.style["color"] = "black";
            }
        }

        id = "stream_height" + stream_idx;
        obj = document.getElementById(id);
        obj.disabled = !video_enabled;
        if (!video_enabled)
        {
            obj.style["color"] = "#888888";
        }
        else
        {
            if (custom_preset)
            {
                obj.style["color"] = "black";
            }
        }
        id = "stream_codec" + stream_idx;
        obj = document.getElementById(id);
        obj.disabled = !video_enabled;

        id = "stream_framerate" + stream_idx;
        obj = document.getElementById(id);
        obj.disabled = !video_enabled;

        id = "stream_audio_channels" + stream_idx;
        obj = document.getElementById(id);
        obj.disabled = !stream_enabled;

        id = "stream_audio_channels2_" + stream_idx;
        obj = document.getElementById(id);
        obj.disabled = !stream_enabled;

        id = "stream_audio_bitrate" + stream_idx;
        obj = document.getElementById(id);
        obj.hidden = false;
        obj.disabled = !stream_enabled;

        id = "stream_audio_bitrate2_" + stream_idx;
        obj = document.getElementById(id);
        obj.hidden = false;
        obj.disabled = !stream_enabled;

        if (is_multirate_output())
        {
            id = "stream_profile" + stream_idx;
            obj = document.getElementById(id);
            obj.disabled = !video_enabled;

            id = "stream_group_select1";
            obj = document.getElementById(id);
            obj.hidden = true;

            if (MAX_STREAM_GROUPS == 2)
            {
                id = "stream_group_select2";
                obj = document.getElementById(id);
                obj.hidden = true;
            }
        }
        else
        {
            id = "stream_profile" + stream_idx;
            obj = document.getElementById(id);
            obj.disabled = true;

            id = "stream_group_select1";
            obj = document.getElementById(id);
            obj.hidden = false;

            if (MAX_STREAM_GROUPS == 2)
            {
                id = "stream_group_select2";
                obj = document.getElementById(id);
                obj.hidden = false;
            }
        }

        id = "stream_bitrate" + stream_idx;
        obj = document.getElementById(id);
        obj.disabled = !video_enabled;
        if (!video_enabled)
        {
            obj.style["color"] = "#888888";
        }
        else
        {
            obj.style["color"] = "black";
        }

        id = "stream_max_bitrate" + stream_idx;
        obj = document.getElementById(id);
        obj.disabled = !(is_stream_vbr&&video_enabled);
        if (!(is_stream_vbr&&video_enabled))
        {
            obj.style["color"] = "#888888";
        }
        else
        {
            obj.style["color"] = "black";
        }
    }

    function rtcp_checkbox_clicked()
    {
        if (checkbox.checked)
        {
        }
    }
    function slate_enable_clicked()
    {
<?php if(ENABLE_SLATE == 1) { ?>
        $("#slate_source_heading").show();
        var enabled = $("#slate_enable").is(":checked");
        if (enabled)
            $(".slate_input_row").show();
        else
            $(".slate_input_row").hide();
<?php } else { ?>
        $("#slate_source_heading").hide();
        $(".slate_input_row").hide();
<?php } ?>

    }

    function audio_only_clicked()
    {
        var frm = document.configuration;
        var audioOnly = $("#audio_only").is(":checked");

        // Order is important here. Interface must be selected before individual controls are hidden/disabled
        // to avoid interface selection overriding audio_only values.
        if (audioOnly)
        {
            // Currently, only IP output is allowed
            set_active_output_interface("IP");
        }

        $(".video_setting_row").toggleClass("force_hide", audioOnly);

        //$(".video_setting_row").toggleClass("force_hide", audioOnly);

        // Disable non-supported output interfaces
        $(".disable_on_audio_only input").each(function() {
            this.disabled = audioOnly;
        });
        $(".disable_on_audio_only label").each(function() {
            this.style["color"] = audioOnly ? "#888888" : "#000000";
        });

        // Show a warning message regarding disabled output interfaces
        $("#audio_only_output_warning").toggle(audioOnly);
    }

    function audio_format_selected(selector)
    {
        var frm = document.configuration;
        var row;
        var obj;

        output_audio_clicked0_normal(selector);
        output_audio_clicked1(selector);
        output_audio_clicked2(selector);
        stream_audio_populate();

        if (is_audio_passthrough(selector.value))
        {
            row = document.getElementById("audio_bitrate_row0");
            row.style["color"] = "#888888";
            row.hidden = false;

            row = document.getElementById("audio_volume_row0");
            row.style["color"] = "#888888";

            frm.output_audio_bitrate0.disabled = true;
            frm.output_audio_volume0.disabled = true;
            frm.output_audio_volume0.style["color"] = "#888888";
        }
        else
        {
            row = document.getElementById("audio_bitrate_row0");
            row.style["color"] = "black";
            row.hidden = false;
            row = document.getElementById("audio_volume_row0");
            row.style["color"] = "black";

            frm.output_audio_bitrate0.disabled = false;
            frm.output_audio_volume0.disabled = false;
            frm.output_audio_volume0.style["color"] = "black";
        }

        var input_interface = get_active_input_interface();
        var isHdSdiInput = "HD-SDI" == input_interface;
        var isHdmiInput = "HDMI" == input_interface;
        enable_output_audio_channel(1, !isHdmiInput);
        enable_output_audio_channel(2, !isHdSdiInput && !isHdmiInput);

        update_audio_controls();
    }

    function setup_output_resolution(input_is_hd)
    {
        var frm = document.configuration;
        var id;
        var obj;
        var i;
        var selected_val;
        var st;

        id = "output_resolution";
        obj = document.getElementById(id);
        if (obj.selectedIndex >= 0) {
            selected_val = obj.value;
            if (selected_val == "")
            {
                selected_val = frm.output_resolution.value;
            }
        } else {
            selected_val = "SAME";
        }

        var select = $(obj);
        select.children('option').remove();

        var options = [
                ["Same as input",'SAME']
            ];

        if (ENABLE_HD_OUTPUT || ENABLE_4K_OUTPUT)
        {
            if(ENABLE_4K_OUTPUT)
            {
                $.merge(options, [
                     ["4K (4096x2160)",'4K'],
                    ["UltraHD (3840x2160)",'UltraHD']
                ]);
            }
            $.merge(options, [
                ["HD (1920x1080)",'HD1080'],
                ["HD (1280x720)",'HD720'],
                ["PAL (704x576)",'PAL'],
                ["PAL (720x576)",'PAL720']
            ]);
            if (input_is_hd) {
                $.merge(options, [
                    ["NTSC (704x480) CenterCrop",'CENTER'],
                    ["NTSC (704x480) Scale",'NTSC'],
                    ["NTSC (704x480) Letterbox",'LETTERBOX'],
                    ["NTSC (720x480)",'NTSC720'],
                ]);
            } else {
                $.merge(options, [
                    ["NTSC (704x480)",'NTSC'],
                    ["NTSC (720x480)",'NTSC720'],
                ]);
            }
        }
        else
        {
            $.merge(options, [
                ["PAL (704x576)",'PAL'],
                ["PAL (720x576)",'PAL720']
            ]);

            if (input_is_hd) {
                $.merge(options, [
                    ["NTSC (704x480) CenterCrop",'CENTER'],
                    ["NTSC (704x480) Scale",'NTSC'],
                    ["NTSC (704x480) Letterbox",'LETTERBOX'],
                ]);
            } else {
                $.merge(options, [
                    ["NTSC (704x480)",'NTSC'],
                ]);
            }
        }

        $.merge(options, [
            ["VGA (640x480)",'VGA'],
            ["Mediaroom PIP (192x192)",'PIP192'],
            ["Mediaroom PIP (128x96)",'PIP128'],
            ["User Override",'USER'],
        ]);

        $.each(options, function(i, opt) {
            select.append($('<option></option>').val(opt[1]).text(opt[0]));
        });

        safe_set_select_val(obj, selected_val, "SAME");
    }

    // Set select object's value to new_val if option exists. Otherwise, use default.
    function safe_set_select_val(select_obj, new_val, default_val)
    {
        if (!select_obj.options.length) {
            return;
        }

        select_obj.value = new_val;
        if (select_obj.value != new_val || select_obj.selectedIndex == -1) {
            // If default isn't explicitly passed, use the first option
            if (!default_val) {
                default_val = select_obj.options[0].value;
            }
            select_obj.value = default_val;
        }

        $(select_obj).change();
    }

    function hide_capture_element()
    {
        var frm = document.configuration;
        var row;

        addnew_menu();

        row = document.getElementById("index3z");
        row.style["display"] = "none";
    }

    function show_capture_element()
    {
        var frm = document.configuration;
        var row;

        addnew_menu();

        row = document.getElementById("index3z");
        row.style["display"] = "";
    }

    function hide_mobile_element()
    {
        var frm = document.configuration;
        var row;

        addnew_menu();

        row = document.getElementById("index4z");
        row.style.display = 'none';
        row = document.getElementById("index2z");
        row.style.display = '';
    }

    function show_mobile_element()
    {
        var frm = document.configuration;
        var row;

        addnew_menu();

        row = document.getElementById("index4z");
        row.style.display = '';
        row = document.getElementById("index2z");
        row.style.display = 'none';
    }

    function select_option0()
    {
        var newli = document.getElementById("index0z");
        var newdiv = document.getElementById("input-options");
        var activeTabClasses = "ui-tabs-selected ui-state-active";
        $(".option-tab").removeClass(activeTabClasses);
        $(".option-tab-content").css("display", "none");
        $(newli).addClass(activeTabClasses);
        $(newdiv).css("display", "block");
    }

   // function select_option0a()
   // {
   //     var newli = document.getElementById("index0a");
   //     var newdiv = document.getElementById("splitter-options");
   //     var oldli;
   //     var olddiv;

   //     newli.setAttribute("class","ui-state-default ui-corner-top ui-tabs-selected ui-state-active");
   //     oldli = document.getElementById("index0z");
   //     oldli.setAttribute("class","ui-state-default ui-corner-top");
   //     oldli = document.getElementById("index1z");
   //     oldli.setAttribute("class","ui-state-default ui-corner-top");
   //     oldli = document.getElementById("index2z");
   //     oldli.setAttribute("class","ui-state-default ui-corner-top");
   //     oldli = document.getElementById("index3z");
   //     oldli.setAttribute("class","ui-state-default ui-corner-top");
   //     oldli = document.getElementById("index4z");
   //     oldli.setAttribute("class","ui-state-default ui-corner-top");

   //     newdiv.style.display = '';
   //     olddiv = document.getElementById("output-options");
   //     olddiv.style.display = 'none';
   //     olddiv = document.getElementById("streaming-options");
   //     olddiv.style.display = 'none';
   //     olddiv = document.getElementById("capture-options");
   //     olddiv.style.display = 'none';
   //     olddiv = document.getElementById("apple-streaming-options");
   //     olddiv.style.display = 'none';
   //     olddiv = document.getElementById("input-options");
   //     olddiv.style.display = 'none';
   // }

    function select_option1()
    {
        var newli = document.getElementById("index1z");
        var newdiv = document.getElementById("output-options");
        var activeTabClasses = "ui-tabs-selected ui-state-active";
        $(".option-tab").removeClass(activeTabClasses);
        $(".option-tab-content").css("display", "none");
        $(newli).addClass(activeTabClasses);
        $(newdiv).css("display", "block");
    }

    function select_option2()
    {
        var newli = document.getElementById("index2z");
        var newdiv = document.getElementById("streaming-options");
        var activeTabClasses = "ui-tabs-selected ui-state-active";
        $(".option-tab").removeClass(activeTabClasses);
        $(".option-tab-content").css("display", "none");
        $(newli).addClass(activeTabClasses);
        $(newdiv).css("display", "block");
    }

    function select_option3()
    {
        var newli = document.getElementById("index3z");
        var newdiv = document.getElementById("capture-options");
        var activeTabClasses = "ui-tabs-selected ui-state-active";
        $(".option-tab").removeClass(activeTabClasses);
        $(".option-tab-content").css("display", "none");
        $(newli).addClass(activeTabClasses);
        $(newdiv).css("display", "block");
    }

    function select_option4()
    {
        var newli = document.getElementById("index4z");
        var newdiv = document.getElementById("apple-streaming-options");
        var activeTabClasses = "ui-tabs-selected ui-state-active";
        $(".option-tab").removeClass(activeTabClasses);
        $(".option-tab-content").css("display", "none");
        $(newli).addClass(activeTabClasses);
        $(newdiv).css("display", "block");

        var name;
        var obj;
        var bitrate;

        var frm = document.configuration;
        group_checkbox_clicked(frm.stream_group_checkbox1, 1);
        <?php
        // In the ATSC M/H mode, we don't have groups of streams
        if(MAX_STREAM_GROUPS > 1)
        {
        ?>
        group_checkbox_clicked(frm.stream_group_checkbox2, 2);
        <?php
        }
        ?>

        stream_audio_populate();
    }

    function select_option5()
    {
        var newli = document.getElementById("index5z");
        var newdiv = document.getElementById("scrambling-options");
        var activeTabClasses = "ui-tabs-selected ui-state-active";
        $(".option-tab").removeClass(activeTabClasses);
        $(".option-tab-content").css("display", "none");
        $(newli).addClass(activeTabClasses);
        $(newdiv).css("display", "block");
    }

    function selectVerimatrixTab()
    {
        var newli = document.getElementById("verimatrixTab");
        var newdiv = document.getElementById("verimatrix-options");
        var activeTabClasses = "ui-tabs-selected ui-state-active";
        $(".option-tab").removeClass(activeTabClasses);
        $(".option-tab-content").css("display", "none");
        $(newli).addClass(activeTabClasses);
        $(newdiv).css("display", "block");
    }

    function selectBuydrmTab()
    {
        var newli = document.getElementById("buydrmTab");
        var newdiv = document.getElementById("buydrm-options");
        var activeTabClasses = "ui-tabs-selected ui-state-active";
        $(".option-tab").removeClass(activeTabClasses);
        $(".option-tab-content").css("display", "none");
        $(newli).addClass(activeTabClasses);
        $(newdiv).css("display", "block");
    }

    function selectNielsenTab()
    {
        var newli = document.getElementById("nielsenTab");
        var newdiv = document.getElementById("nielsen-options");
        var activeTabClasses = "ui-tabs-selected ui-state-active";
        $(".option-tab").removeClass(activeTabClasses);
        $(".option-tab-content").css("display", "none");
        $(newli).addClass(activeTabClasses);
        $(newdiv).css("display", "block");
    }

    function addnew_menu()
    {
        var anchor = document.getElementById("options_row_0");
        var newli;
        var newa;
        var checkli;

        checkli = document.getElementById("index0z");
        if (checkli == null)
        {
            newli = document.createElement("li");
            newa = document.createElement("a");
            newli.setAttribute("id","index0z");
            newli.setAttribute("onclick","select_option0(); return false;");
            newli.setAttribute("class","ui-state-default ui-corner-top option-tab");
            newa.setAttribute("href","#input-options");
            newa.appendChild(document.createTextNode("Input"));
            newli.appendChild(newa);
            anchor.appendChild(newli);

            //newli = document.createElement("li");
            //newa = document.createElement("a");
            //newli.setAttribute("id","index0a");
            //newli.setAttribute("onclick","select_option0a()");
            //newli.setAttribute("class","ui-state-default ui-corner-top");
            //newa.setAttribute("href","#splitter-options");
            //newa.appendChild(document.createTextNode("Splitter"));
            //newli.appendChild(newa);
            //anchor.appendChild(newli);

            newli = document.createElement("li");
            newa = document.createElement("a");
            newli.setAttribute("id","index1z");
            newli.setAttribute("onclick","select_option1(); return false;");
            newli.setAttribute("class","ui-state-default ui-corner-top option-tab");
            newa.setAttribute("href","#output-options");
            newa.appendChild(document.createTextNode("Output"));
            newli.appendChild(newa);
            anchor.appendChild(newli);

            newli = document.createElement("li");
            newa = document.createElement("a");
            newli.setAttribute("id","index2z");
            newli.setAttribute("onclick","select_option2(); return false;");
            newli.setAttribute("class","ui-state-default ui-corner-top option-tab");
            newa.setAttribute("href","#streaming-options");
            newa.appendChild(document.createTextNode("MPEG2TS Streaming"));
            newli.appendChild(newa);
            anchor.appendChild(newli);

            newli = document.createElement("li");
            newa = document.createElement("a");
            newli.setAttribute("id","index3z");
            newli.setAttribute("onclick","select_option3(); return false;");
            newli.setAttribute("class","ui-state-default ui-corner-top option-tab");
            newa.setAttribute("href","#capture-options");
            newa.appendChild(document.createTextNode("Composite Input"));
            newli.appendChild(newa);
            anchor.appendChild(newli);
           //newli.style.display = 'none';

            newli = document.createElement("li");
            newa = document.createElement("a");
            newli.setAttribute("id","index4z");
            newli.setAttribute("onclick","select_option4(); return false;");
            newli.setAttribute("class","ui-state-default ui-corner-top option-tab");
            newa.setAttribute("href","#apple-streaming-options");
            <?php
            $streamingTabName = "";
            if(CONFIG_MODE == 0)
            {
                $streamingTabName = "Multirate Streaming";
            }
            /*else if(CONFIG_MODE == 1)
            {
                $streamingTabName = "ATSC M/H Streaming";
            }*/
            ?>
            newa.appendChild(document.createTextNode("<?php echo $streamingTabName ?>"));
            newli.appendChild(newa);
            anchor.appendChild(newli);

            <?php
            if (ENABLE_SCRAMBLING) {
            ?>
            newli = document.createElement("li");
            newa = document.createElement("a");
            newli.setAttribute("id","index5z");
            newli.setAttribute("onclick","select_option5(); return false;");
            newli.setAttribute("class","ui-state-default ui-corner-top option-tab");
            newa.setAttribute("href","#scrambling-options");
            newa.appendChild(document.createTextNode("Scrambling"));
            newli.appendChild(newa);
            anchor.appendChild(newli);
            <?php
            }
            ?>

            <?php
            if (ENABLE_VERIMATRIX) {
            ?>
            newli = document.createElement("li");
            newa = document.createElement("a");
            newli.setAttribute("id","verimatrixTab");
            newli.setAttribute("onclick","selectVerimatrixTab(); return false;");
            newli.setAttribute("class","ui-state-default ui-corner-top option-tab");
            newa.setAttribute("href","#verimatrix-options");
            newa.appendChild(document.createTextNode("Verimatrix"));
            newli.appendChild(newa);
            anchor.appendChild(newli);
            <?php
            }
            ?>

            <?php
            if (ENABLE_BUYDRM) {
            ?>
            newli = document.createElement("li");
            newa = document.createElement("a");
            newli.setAttribute("id","buydrmTab");
            newli.setAttribute("onclick","selectBuydrmTab(); return false;");
            newli.setAttribute("class","ui-state-default ui-corner-top option-tab");
            newa.setAttribute("href","#buydrm-options");
            newa.appendChild(document.createTextNode("BuyDRM"));
            newli.appendChild(newa);
            anchor.appendChild(newli);
            <?php
            }
            ?>

            <?php
            if (ENABLE_NIELSEN) {
            ?>
            newli = document.createElement("li");
            newa = document.createElement("a");
            newli.setAttribute("id","nielsenTab");
            newli.setAttribute("onclick","selectNielsenTab(); return false;");
            newli.setAttribute("class","ui-state-default ui-corner-top option-tab");
            newa.setAttribute("href","#nielsen-options");
            newa.appendChild(document.createTextNode("Nielsen"));
            newli.appendChild(newa);
            anchor.appendChild(newli);
            <?php
            }
            ?>
            select_option0();
        }
    }

    function hide_all_controls() {
        $(".apple_hls_input_row").hide();
        $(".capture_input_row").hide();
        $(".dvbasi_input_row").hide();
        $(".hdmi_setting_row").hide();
        $(".hd_sdi_setting_row").hide();
        $(".input_atsc_row").hide();
        $(".ip_input_row").hide();
        $(".ip_input_row_2").hide();
        $(".rtmp_input_row").hide();
        $(".rtp_input_row").hide();
        $(".mp4file_input_row").hide();
        $(".mpts_input_row").hide();
        $(".tsfile_input_row").hide();
    }

   function enable_sdi_controls(enable)
    {
        var row;
        var frm = document.configuration;

        $("#input_row_1").hide();
        $("#enable_afd_row").show();
        $("#fec_on_input_row").hide();

        if (enable == 1)
        {
            hide_all_controls();
            $(".hd_sdi_setting_row").show();
            $(".mpts_discover_row").show();
            $(".baseband_setting_row").show();
            mpts_discover_enable_results(false);

            row = document.getElementById("hd_sdi_row");
            row.style["color"] = "#888888";
            frm.sdi_input_mode.disabled = true;
            frm.sdi_input_mode.style["color"] = "#888888";

            row = document.getElementById("input_row_0");
            row.style["color"] = "#888888";
            frm.input_resolution.disabled = true;
            frm.input_resolution.style["color"] = "#888888";

            row = document.getElementById("input_row_2");
            row.style["color"] = "#888888";
            frm.input_format.disabled = true;
            frm.input_format.style["color"] = "#888888";

            row = document.getElementById("input_row_3");
            row.style["color"] = "#888888";
            frm.input_framerate.disabled = true;
            frm.input_framerate.style["color"] = "#888888";
            $("#bottom_field_first_row").hide();
        }
    }

   function enable_hdmi_controls(enable)
    {
        var row;
        var frm = document.configuration;

        $("#input_row_1").hide();
        $("#enable_afd_row").show();
        $("#fec_on_input_row").hide();

        if (enable == 1)
        {
            hide_all_controls();
            $(".hdmi_setting_row").show();
            mpts_discover_enable_results(false);

            row = document.getElementById("input_row_0");
            row.style["color"] = "#888888";
            frm.input_resolution.disabled = true;
            frm.input_resolution.style["color"] = "#888888";

            row = document.getElementById("input_row_2");
            row.style["color"] = "#888888";
            frm.input_format.disabled = true;
            frm.input_format.style["color"] = "#888888";

            row = document.getElementById("input_row_3");
            row.style["color"] = "#888888";
            frm.input_framerate.disabled = true;
            frm.input_framerate.style["color"] = "#888888";
        }
    }

    function enable_mpeg2ts_controls(enable)
    {
        var frm = document.configuration;
        var row;

        $("#enable_afd_row").show();

        if (enable == 2)
        {
            $("#fec_on_input_row").hide();

            hide_all_controls();
            $(".mpts_input_row").show();
            $(".tsfile_input_row").show();
            mpts_discover_enable_results(false);

            row = document.getElementById("input_row_0");
            row.style["color"] = "black";
            frm.input_resolution.disabled = false;
            frm.input_resolution.style["color"] = "black";

            row = document.getElementById("input_row_2");
            row.style["color"] = "black";
            frm.input_format.disabled = false;
            frm.input_format.style["color"] = "black";

            row = document.getElementById("input_row_3");
            row.style["color"] = "black";
            frm.input_framerate.disabled = false;
            frm.input_framerate.style["color"] = "black";
        }

        if (enable == 1)
        {
<?php if(!$is_novelrx){ ?>
            $("#fec_on_input_row").show();
<?php } ?>
            hide_all_controls();
            $(".mpts_input_row").show();
            $(".ip_input_row").show();
            $("#enable_source_input_2").change();

            if (mpts_discover_cache && mpts_discover_cache.programs && mpts_discover_cache.programs.length > 0) {
                mpts_discover_set_results(mpts_discover_cache, false);
            } else {
                mpts_discover_enable_results(false);
            }

            row = document.getElementById("input_row_0");
            row.style["color"] = "black";
            frm.input_resolution.disabled = false;
            frm.input_resolution.style["color"] = "black";

            row = document.getElementById("input_row_2");
            row.style["color"] = "black";
            frm.input_format.disabled = false;
            frm.input_format.style["color"] = "black";

            row = document.getElementById("input_row_3");
            row.style["color"] = "black";
            frm.input_framerate.disabled = false;
            frm.input_framerate.style["color"] = "black";
        }
    }

    function enable_mp4file_controls()
    {
        var frm = document.configuration;
        var row;

        $("#enable_afd_row").show();
        $("#fec_on_input_row").hide();

        hide_all_controls();
        $(".mp4file_input_row").show();
        mpts_discover_enable_results(false);

        row = document.getElementById("input_row_0");
        row.style["color"] = "black";
        frm.input_resolution.disabled = false;
        frm.input_resolution.style["color"] = "black";

        row = document.getElementById("input_row_2");
        row.style["color"] = "black";
        frm.input_format.disabled = false;
        frm.input_format.style["color"] = "black";

        row = document.getElementById("input_row_3");
        row.style["color"] = "black";
        frm.input_framerate.disabled = false;
        frm.input_framerate.style["color"] = "black";
    }

    function enable_rtp_controls(enable)
    {
        var frm = document.configuration;
        var row;

        $("#input_row_1").hide();
        $("#enable_afd_row").show();
        $("#fec_on_input_row").hide();

        if (enable == 1)
        {
            hide_all_controls();
            $(".rtp_input_row").show();
            mpts_discover_enable_results(false);

            row = document.getElementById("input_row_0");
            row.style["color"] = "#888888";
            frm.input_resolution.disabled = true;
            frm.input_resolution.style["color"] = "#888888";

            row = document.getElementById("input_row_2");
            row.style["color"] = "black";
            frm.input_format.disabled = false;
            frm.input_format.style["color"] = "black";

            row = document.getElementById("input_row_3");
            row.style["color"] = "black";
            frm.input_framerate.disabled = false;
            frm.input_framerate.style["color"] = "black";
        }
    }

    function enable_capture_controls(enable) {
        var frm = document.configuration;
        var row;

        $("#input_row_1").hide();
        $("#enable_afd_row").hide();
        $("#fec_on_input_row").hide();

        if (enable == 1)
        {
            hide_all_controls();
            $(".capture_input_row").show();
            $(".baseband_setting_row").show();
            mpts_discover_enable_results(false);

            row = document.getElementById("input_row_0");
            row.style["color"] = "#888888";
            frm.input_resolution.disabled = true;
            frm.input_resolution.style["color"] = "#888888";

            row = document.getElementById("input_row_2");
            row.style["color"] = "#888888";
            frm.input_format.disabled = true;
            frm.input_format.style["color"] = "#888888";

            row = document.getElementById("input_row_3");
            row.style["color"] = "#888888";
            frm.input_framerate.disabled = true;
            frm.input_framerate.style["color"] = "#888888";

            frm.input_resolution.value = "NTSC";
            frm.input_format.value = 1;
            frm.input_framerate.value = 29.97;
        }
    }

    function enable_dvbasi_controls(enable)
    {
        var frm = document.configuration;
        var row;

        $("#enable_afd_row").show();
        $("#fec_on_input_row").hide();

        if (enable == 1)
        {
            hide_all_controls();
            $(".mpts_input_row").show();
            $(".dvbasi_input_row").show();
            mpts_discover_enable_results(false);

            row = document.getElementById("input_row_0");
            row.style["color"] = "black";
            frm.input_resolution.disabled = false;
            frm.input_resolution.style["color"] = "black";

            row = document.getElementById("input_row_2");
            row.style["color"] = "black";
            frm.input_format.disabled = false;
            frm.input_format.style["color"] = "black";

            row = document.getElementById("input_row_3");
            row.style["color"] = "black";
            frm.input_framerate.disabled = false;
            frm.input_framerate.style["color"] = "black";
        }
    }


    function enable_dvbapi_controls(enable)
    {
        var frm = document.configuration;
        var row;

        $("#enable_afd_row").show();
        $("#fec_on_input_row").hide();

        if (enable == 1)
        {
            hide_all_controls();
            $(".input_atsc_row").show();
            $(".mpts_discover_row").show();

            if (mpts_discover_cache && mpts_discover_cache.programs && mpts_discover_cache.programs.length > 0) {
                mpts_discover_set_results(mpts_discover_cache, false);
            } else {
                mpts_discover_enable_results(false);
            }


            row = document.getElementById("input_row_0");
            row.style["color"] = "black";
            frm.input_resolution.disabled = false;
            frm.input_resolution.style["color"] = "black";

            row = document.getElementById("input_row_2");
            row.style["color"] = "black";
            frm.input_format.disabled = false;
            frm.input_format.style["color"] = "black";

            row = document.getElementById("input_row_3");
            row.style["color"] = "black";
            frm.input_framerate.disabled = false;
            frm.input_framerate.style["color"] = "black";
        }
    }

    function enable_apple_hls_input_controls(enable)
    {
        var frm = document.configuration;
        var row;

        $("#enable_afd_row").show();
        $("#fec_on_input_row").hide();

        if (enable == 1)
        {
            hide_all_controls();
            $(".apple_hls_input_row").show();
            mpts_discover_enable_results(false);

            row = document.getElementById("input_row_0");
            row.style["color"] = "black";
            frm.input_resolution.disabled = false;
            frm.input_resolution.style["color"] = "black";

            row = document.getElementById("input_row_2");
            row.style["color"] = "black";
            frm.input_format.disabled = false;
            frm.input_format.style["color"] = "black";

            row = document.getElementById("input_row_3");
            row.style["color"] = "black";
            frm.input_framerate.disabled = false;
            frm.input_framerate.style["color"] = "black";
        }
    }

    function enable_rtmp_input_controls(enable)
    {
        var frm = document.configuration;
        var row;

        $("#enable_afd_row").show();
        $("#fec_on_input_row").hide();

        if (enable == 1)
        {
            hide_all_controls();
            $(".rtmp_input_row").show();
            mpts_discover_enable_results(false);

            row = document.getElementById("input_row_0");
            row.style["color"] = "black";
            frm.input_resolution.disabled = false;
            frm.input_resolution.style["color"] = "black";

            row = document.getElementById("input_row_2");
            row.style["color"] = "black";
            frm.input_format.disabled = false;
            frm.input_format.style["color"] = "black";

            row = document.getElementById("input_row_3");
            row.style["color"] = "black";
            frm.input_framerate.disabled = false;
            frm.input_framerate.style["color"] = "black";
        }
    }

    function input_interface_selected(source)
    {
        var frm = document.configuration;
        var row;
        var checkUserOverride = false;
        var enableHdSdiOutput = false;
        var audioOnlySupported = false;
        $("#input_format").change();
        if (source == "IP")
        {
            enable_mpeg2ts_controls(1);
            checkUserOverride = true;
            audioOnlySupported = true;
            enableHdSdiOutput = true;
        }
        else if (source == "RTP")
        {
            enable_rtp_controls(1);
        }
        else if (source == "CAPTURE")
        {
            enable_capture_controls(1);
            checkUserOverride = true;
        }
        else if (source == "DVBASI")
        {
            enable_dvbasi_controls(1);
            checkUserOverride = true;
        }
        else if (source == "TSFILE")
        {
            enable_mpeg2ts_controls(2);
            checkUserOverride = true;
        }
        else if (source == "MP4FILE")
        {
            enable_mp4file_controls(1);
            checkUserOverride = true;
        }
        else if (source == "HD-SDI")
        {
            enable_sdi_controls(1);
            sync_hd_sdi_input_mode(true);
        }
        else if (source == "HDMI")
        {
            enable_hdmi_controls(1);
            sync_hdmi_input_mode(true);
        }
        else if (source == "DVB-API")
        {
            enable_dvbapi_controls(1);
            checkUserOverride = true;
        }
        else if (source == "APPLE")
        {
            enable_apple_hls_input_controls(1);
            checkUserOverride = true;
            enableHdSdiOutput = true;
        }
        else if (source == "RTMP")
        {
            enable_rtmp_input_controls(1);
            checkUserOverride = true;
        }
        if (source == "CAPTURE")
        {
            // set input_resolution_preset to ntsc
            show_capture_element();
        }
        else
        {
            hide_capture_element();
        }

        if (checkUserOverride) {
            // If we are not in RTP or SDI mode and the Input resolution preset selecte was User override,
            // the Input resolution override boxes must be displayed
            if ($("#input_resolution").val() == "USER") {
                $("#input_row_1").show();
            }
        }

        enable_option("audio_only_row", frm.audio_only, audioOnlySupported);
        if (!audioOnlySupported)
        {
            if (frm.audio_only.checked)
            {
                frm.audio_only.checked = false;
                audio_only_clicked();
            }
        }

        if(enableHdSdiOutput && !frm.audio_only.checked)
        {
            // HD-SDI Output must be enabled because SDI input has been selected
            $("input[name=output_interface][value=HDSDI]").attr('disabled',false).parent().css('color', "#000000");
        }
        else
        {
            $("input[name=output_interface][value=HDSDI]").attr('disabled',true).parent().css('color', "#888888");
        }

        update_audio_controls();
        var input_interface = get_active_input_interface();
        var output_interface = get_active_output_interface();

        if(input_interface=="HD-SDI")
        {
           $("#audio_pid_row0").hide();
           $("#low_video_frame_rate_mode").hide();
           $("#diagonal_smoothing_filter_mode").hide();
           $("#temporal_filter_strength_mode").hide();
           // $("#scene_detection_mode").hide();
               if (mpts_discover_cache && mpts_discover_cache.source.type=="sdi"){
                mpts_discover_set_results_deltacast(mpts_discover_cache, false);
           } else {
                mpts_discover_enable_results(false);
           }
        }
        else if (output_interface == "HDSDI") {
           $("#audio_pid_row0").show();
           $("#low_video_frame_rate_mode").hide();
           $("#diagonal_smoothing_filter_mode").hide();
           $("#temporal_filter_strength_mode").hide();
           $("#scene_detection_mode").hide();
           frm.output_format.disabled = false;
           if ((input_interface == "IP" || input_interface == "DVB-API") && mpts_discover_cache && mpts_discover_cache.source.type!="sdi"){
                mpts_discover_set_results(mpts_discover_cache, false);
           } else {
                mpts_discover_enable_results(false);
           }
        }
        else
        {
           $("#audio_pid_row0").show();
           $("#low_video_frame_rate_mode").show();
           $("#diagonal_smoothing_filter_mode").show();
           $("#temporal_filter_strength_mode").show();
           $("#scene_detection_mode").show();
           if ((input_interface == "IP" || input_interface == "DVB-API") && mpts_discover_cache && mpts_discover_cache.source.type!="sdi"){
                mpts_discover_set_results(mpts_discover_cache, false);
           } else {
                mpts_discover_enable_results(false);
           }

        }
   }

    function select_output_encoder(value) {
        var elem = $("#output_encoder");
        var selectedVal = null;
        elem.children("option").each(
            function(i, option) {
                if (!selectedVal) {
                    selectedVal = option.value;
                }
                var selected = option.value == value;
                if (selected) {
                    selectedVal = option.value;
                    return false;
                }
        });

        elem[0].value = selectedVal;
        video_encoder_changed(elem[0]);
    }

    function update_output_encoder() {
        var elem = $("#output_encoder");
        var curCodec = elem.val();
        var selectedVal = null;

        var input_interface = get_active_input_interface();
        var output_interface = get_active_output_interface();
        var isMultiOut = is_multirate_output(output_interface);

        var codecs = <?php echo json_encode(array_values($build->getVideoEncoders())); ?>;

        elem.children('option').remove();
        $.each(codecs, function(i, codec) {
            var enabled = codec.enabled;
            if (enabled) {
                if (codec.input_interfaces) {
                    if (-1 == $.inArray(input_interface, codec.input_interfaces)) {
                        enabled = false;
                    }
                }
                if (enabled && codec.output_interfaces) {
                    if (-1 == $.inArray(output_interface, codec.output_interfaces)) {
                        enabled = false;
                    }
                }
                if(codec.value=="H264FF" && get_active_output_interface()!="IP")
                    enabled = false;
                if(codec.value=="H264SOCIO" && isMultiOut)
                    enabled = false;
                if(codec.value=="HEVCSOCIO" && isMultiOut)
                    enabled = false;
            }
            if (enabled) {
                if (!selectedVal) {
                    selectedVal = codec.value;
                }
                var selected = codec.value == curCodec;
                if (selected) {
                    selectedVal = codec.value;
                }
                elem.append("<option value='"+codec.value+"'>"+codec.name+"</option>");
            }
        });

<?php
        for ($idx = 0; $idx < MAX_VIDEO_STREAMS; $idx++)
        {
?>
            selectedVal = $("#stream_codec<?=$idx?>")[0].value;
            $("#stream_codec<?=$idx?>")[0].innerHTML = elem[0].innerHTML;
            $("#stream_codec<?=$idx?>")[0].value = selectedVal;
<?php
        }
?>

        elem[0].value = selectedVal;
        elem.change();
    }

    function enable_option(option_row_name, option_ctrl, enable)
    {
        var row = document.getElementById(option_row_name);
        row.style["color"] = enable ? "black" : "#888888";
        option_ctrl.disabled = !enable;
        option_ctrl.style["color"] = enable ? "black" : "#888888";
    }

    function enable_row(option_row_selector, enable)
    {
        var rows = $(option_row_selector);
        rows.css("color", enable ? "black" : "#888888");
        rows.find("input,select,button").each(function(i,ctrl) {
            ctrl.disabled = !enable;
            ctrl.style["color"] = enable ? "black" : "#888888";
        });
    }

    function output_interface_selected(source)
    {
        var frm = document.configuration;
        var row;

        var input_interface = get_active_input_interface();
        var isSdiInput = "HD-SDI" == input_interface;

        update_output_encoder();

        <?php if (ENABLE_VERIMATRIX) { ?>
        $("#verimatrixTab").toggle(source == "APPLE" || source == "APPLEVOD");
        <?php } ?>

        <?php if (ENABLE_NIELSEN) { ?>
        $("#nielsenTab").toggle(source == "APPLE" || source == "APPLEVOD");
        <?php } ?>

        <?php if (ENABLE_BUYDRM) { ?>
        $("#buydrmTab").toggle(source == "SILVERLIGHT");
        <?php } ?>

        if (source == "RTMP" || source == "APPLE" || source == "APPLEVOD" || source == "SILVERLIGHT" || source == "DASH" ||
            source == "RTP" || source == "ATSC" || source == "MULTITS") {
            output_audio_clicked0_aac(frm.output_audio_format);
        } else {
            output_audio_clicked0_normal(frm.output_audio_format);
        }

        output_audio_clicked1(frm.output_audio_format);
        output_audio_clicked2(frm.output_audio_format);
        update_audio_controls();

        <?php if (ENABLE_PYRAMID_B == 1) { ?>
        if (is_multirate_output()) {
            var row = document.getElementById("h264_pyramid_row");
            row.style["display"] = "";
        } else {
            var row = document.getElementById("h264_pyramid_row");
            row.style["display"] = "none";
        }
        <?php } ?>

        if(source!="MULTITS")
        {
            $(".tab_overlay_settings").show();
            $(".overlay_set_link").hide();
        }
        else
        {
            $(".tab_overlay_settings").hide();
            $(".overlay_set_link").show();
        }

        if (source == "RTMP" || source == "APPLE" || source == "APPLEVOD" || source == "SILVERLIGHT" || source == "DASH" || source == "RTP" || source == "ATSC" || source == "MULTITS")
        {

            $("#remote-http-options-div").toggleClass("force_hide", !(source == "APPLE" || source == "APPLEVOD" || source == "DASH" || source == "RTP" || source == "ATSC"));
            $("#multi-output-options-div").toggleClass("force_hide", source != "MULTITS");
           $("#rtmp_options_tab,#apple_options_tab,#silverlight_options_tab,#rtp_options_tab,#multits_options_tab").hide();
            if (source == "RTMP") {
                $("#rtmp_options_tab").show().find("a").click();
            } else if (source == "APPLE" || source == "APPLEVOD") {
                $("#apple_options_tab").show().find("a").click();
            } else if (source == "SILVERLIGHT" || source == "DASH") {
                $("#silverlight_options_tab").show().find("a").click();
                if(source == "SILVERLIGHT")
                        $(".silverlight-only").show();
                else
                        $(".silverlight-only").hide();
            } else if (source == "RTP" || source == "ATSC") {
                $("#rtp_options_tab").show().find("a").click();
            } else if (source == "MULTITS") {
                $("#multits_options_tab").show().find("a").click();
            }

            if (source == "MULTITS") {
                $("#segment-file-archival-div").hide();
            } else {
                $("#segment-file-archival-div").show();
            }
            var stream_index;
            var first_index;
            var last_index;
            var index = 1;
            var checkbox = frm.stream_group_checkbox1;
            var id;
            var obj;

            first_index = (index - 1) * MAX_VIDEO_STREAMS;
            last_index = first_index + (MAX_VIDEO_STREAMS - 1);

            for (stream_index = first_index; stream_index <= last_index; stream_index++)
            {
               set_stream_controls(stream_index, !checkbox.checked);
            }

            if (MAX_STREAM_GROUPS == 2)
            {
                checkbox = frm.stream_group_checkbox2;
                index = 2;
                first_index = (index - 1) * MAX_VIDEO_STREAMS;
                last_index = first_index + (MAX_VIDEO_STREAMS - 1);

                for (stream_index = first_index; stream_index <= last_index; stream_index++)
                {
                    set_stream_controls(stream_index, !checkbox.checked);
                }
            }

            $("#output_video_format_row").hide();

            row = document.getElementById("i_p_frame_distance_row");
            row.style["color"] = "black";
            row = document.getElementById("gop_length_row");
            row.style["color"] = "black";
            row = document.getElementById("output_video_encoder_row");
            row.style["color"] = "black";
            row = document.getElementById("output_audio_format_row");
            row.style["color"] = "#888888";
            $("#output_audio_format_row").hide();
            row = document.getElementById("h264_profile_row");
            row.style["color"] = "#888888";

            $(".stream_audio2").hide();
            if (source == "RTMP" || source == "DASH" || source == "APPLE" || source == "APPLEVOD" || source == "MULTITS" || source == "ATSC") {
                row = document.getElementById("audio_channels_row0");
                    row.hidden = true;
                row = document.getElementById("audio_channels_row1");
                    row.hidden = true;
                row = document.getElementById("audio_bitrate_row0");
                    row.hidden = true;
        } else {
                row = document.getElementById("audio_channels_row0");
                    row.hidden = false;
            row = document.getElementById("audio_channels_row1");
                    row.hidden = false;
                row = document.getElementById("audio_bitrate_row0");
                    row.hidden = false;
        }

            <?php if (ENABLE_OUTPUT_VIDEO_BITRATE) { ?>
            enable_option("output_video_bitrate_row", frm.output_video_bitrate, true);
            <?php } ?>
            enable_option("output_mux_rate_row", frm.output_mux_rate, true);
            enable_option("output_ip_address_row", frm.output_ip_address, true);
            <?php if (ENABLE_IPV6) { ?>
            enable_option("output_ip_address_ipv6_row", frm.output_ip_address_ipv6, true);
            <?php } ?>
            enable_option("multicast_ttl_row", frm.multicast_ttl, true);
            enable_option("ip_output_type_row", frm.output_type, true);
            enable_option("enable_cc_row", frm.enable_cc, true);
            enable_option("enable_afd_row", frm.enable_afd, true);

            /*
            var enable_output_port = source == "RTP" || source == "ATSC" || source == "MULTITS";
            enable_option("preferred_output_row", frm.ethernet_interface, enable_output_port);
            */


            //frm.output_encoder.value = "H264";
            frm.output_audio_format.value = "aac";

            frm.enable_raw_output.disabled = true;
            frm.GOP_length_seconds.disabled = false;
            frm.I_P_frame_distance.disabled = false;
            frm.output_encoder.disabled = false;
            frm.output_audio_format.disabled = true;
            frm.output_format.disabled = true;

            frm.h264_profile.disabled = true;
            $("#h264_profile_row").hide();
            $("#h264_constraint_row").hide();

            ip_output_type_selected(frm.output_type);

            if (source == "MULTITS") {
                output_audio_clicked_disable(1);
            } else {
                output_audio_clicked_disable(0);
            }
            output_audio_clicked0_aac(frm.output_audio_format);

            show_mobile_element();

            // Disable multi ts archival options for all but MULTITS mode
            var isMultiTs = source == "MULTITS";
            $('#multi-output-options-div').toggleClass("force_hide", !isMultiTs);
        }
        else if (source == "HDSDI")
        {
            select_output_encoder("MPEG2");

            frm.output_audio_format.value = "passthrough";

            output_audio_clicked_disable(0);
            audio_format_selected(frm.output_audio_format);

            row = document.getElementById("i_p_frame_distance_row");
            row.style["color"] = "#888888";
            row = document.getElementById("gop_length_row");
            row.style["color"] = "#888888";
            row = document.getElementById("output_video_encoder_row");
            row.style["color"] = "#888888";
            row = document.getElementById("output_video_encoder_row");
            row.style["color"] = "#888888";
            //row = document.getElementById("output_audio_format_row");
            //row.style["color"] = "#888888";
            $("#output_audio_format_row").hide();
            row = document.getElementById("h264_profile_row");
            row.style["color"] = "#888888";

            if($("#input_audio_pid0").find("option").length > 1){
                enable_output_audio_channel(1, true);
            }else{
                enable_output_audio_channel(1, false);
            }
            enable_output_audio_channel(2, false);

            <?php if (ENABLE_OUTPUT_VIDEO_BITRATE) { ?>
            enable_option("output_video_bitrate_row", frm.output_video_bitrate, false);
            <?php } ?>
            enable_option("output_mux_rate_row", frm.output_mux_rate, false);
            enable_option("output_ip_address_row", frm.output_ip_address, false);
            <?php if (ENABLE_IPV6) { ?>
            enable_option("output_ip_address_ipv6_row", frm.output_ip_address_ipv6, true);
            <?php } ?>
            enable_option("multicast_ttl_row", frm.multicast_ttl, false);
            enable_option("output_port_row", frm.output_port, false);
            enable_option("ip_output_type_row", frm.output_type, false);
            enable_option("enable_cc_row", frm.enable_cc, true);
            enable_option("scte35_passthru_row", frm.scte35_passthru, true);
            enable_option("enable_afd_row", frm.enable_afd, true);


            frm.enable_raw_output.disabled = true;
            frm.GOP_length_seconds.disabled = true;
            frm.I_P_frame_distance.disabled = true;
            frm.output_encoder.disabled = false;
            frm.output_audio_format.disabled = true;
            frm.output_format.disabled = true;

            frm.h264_profile.disabled = true;
            $("#h264_profile_row").hide();
            $("#h264_constraint_row").hide();

            video_encoder_changed(frm.output_encoder.value);

            hide_mobile_element();
        }
        else
        {
            $("#output_video_format_row").show();

            row = document.getElementById("i_p_frame_distance_row");
            row.style["color"] = "black";
            row = document.getElementById("gop_length_row");
            row.style["color"] = "black";
            row = document.getElementById("output_video_encoder_row");
            row.style["color"] = "black";
            row = document.getElementById("output_audio_format_row");
            row.style["color"] = "black";
            $("#output_audio_format_row").show();
            row = document.getElementById("h264_profile_row");
            row.style["color"] = "black";

            enable_output_audio_channel(1, true);
            enable_output_audio_channel(2, !isSdiInput);

            <?php if (ENABLE_OUTPUT_VIDEO_BITRATE) { ?>
            enable_option("output_video_bitrate_row", frm.output_video_bitrate, true);
            <?php } ?>
            enable_option("output_mux_rate_row", frm.output_mux_rate, true);

            var isFileOut  = false;
            if (source == "TSFILE")
              isFileOut = true;

            enable_option("output_ip_address_row", frm.output_ip_address, !isFileOut);
            <?php if (ENABLE_IPV6) { ?>
            enable_option("output_ip_address_ipv6_row", frm.output_ip_address_ipv6, !isFileOut);
            <?php } ?>
            enable_option("multicast_ttl_row", frm.multicast_ttl, !isFileOut);
            enable_option("output_port_row", frm.output_port, !isFileOut);
            enable_option("ip_output_type_row", frm.output_type, !isFileOut);
            enable_option("enable_cc_row", frm.enable_cc, !isFileOut);
            enable_option("enable_afd_row", frm.enable_afd, !isFileOut);

            enable_option("scte35_passthru_row", frm.scte35_passthru, !isFileOut);



            frm.enable_raw_output.disabled = isFileOut;
            frm.GOP_length_seconds.disabled = false;
            frm.I_P_frame_distance.disabled = false;
            frm.output_encoder.disabled = false;
            frm.output_audio_format.disabled = false;
            frm.output_format.disabled = false;

            frm.h264_profile.disabled = false;
            if (!frm.audio_only.checked) {
                $("#h264_profile_row").show();
                $("#h264_constraint_row").show();
            }
            ip_output_type_selected(frm.output_type);

            audio_format_selected(frm.output_audio_format);

            hide_mobile_element();
        }

        if(is_multirate_output())
        {
           $("#output_video_encoder_row").hide();
        }
        else
        {
           $("#output_video_encoder_row").show();
        }

        if ( source == "HDSDI")
            {
                $("#h264_constraint_row").hide();
                $("#output_encoder").val("H264");
                $("#output_resolution").val("SAME");
                $("#output_framerate").val(0);
                $(".hideforhdsdi").hide();
                $("#output_video_encoder_row").hide();
                $("#output_resolution option[value!='SAME']").attr("disabled","disabled");
                $("#output_framerate option[value!=0]").attr("disabled","disabled");
                // allow end user to force a different output type if needed (hevc hack for now)
                //$("#output_format").val(2);
                //$("#output_format option[value!=2]").attr("disabled","disabled");
        } else {
                $("#h264_constraint_row").show();
                $("#output_encoder").attr("disabled","");
                $(".hideforhdsdi").show();
                $("#output_video_encoder_row").show();
                $("#output_resolution option").attr("disabled","");
                $("#output_format option").attr("disabled","");
                $("#output_framerate option").attr("disabled","");
        }
    }

    function group_preset_selected(mode_selector, index)
    {
        <?php if(CONFIG_MODE != 1) { ?>

        var mode = mode_selector.value;

        if (index == 1)
        {
            var stream_select_id = "stream_group_select1";
            var stream_select_obj = document.getElementById(stream_select_id);
            if (mode == "0")
            {
                stream_group1_ipod();
            }
            else
            {
                stream_group1_normal();
            }
        }
        else if (index == 2)
        {
            if (MAX_STREAM_GROUPS == 2)
            {
                var stream_select_id = "stream_group_select2";
                var stream_select_obj = document.getElementById(stream_select_id);
                if (mode == "0")
                {
                    stream_group2_ipod();
                }
                else
                {
                    stream_group2_normal();
                }
            }
        }
        <?php } else { ?>
        stream_group_atsc(index);
        <?php } ?>
    }

    function output_framerate_changed(mode_selector)
    {
        <?php if (CONFIG_MODE != 1) { ?>
        var frm = document.configuration;
        var mode = mode_selector.value;

        if (mode == "2")   // pal-to-ntsc
        {
            frm.input_framerate.value = "25";
        }
        else  if (mode == "10")   // ntsc-to-pal
        {
            frm.input_framerate.value = "29.97";
        }
        else
        {
        }
        <?php } ?>
    }

    function output_resolution_changed(mode_selector)
    {
        var mode = mode_selector.value;
        var frm = document.configuration;

        if (mode == "USER")
        {
            var row;

            row = document.getElementById("row_output_override");
            row.style["display"] = "";
        }
        else
        {
            var row;

            row = document.getElementById("row_output_override");
            row.style["display"] = "none";
        }

        var is_pip = mode == "PIP192" || mode == "PIP128";
        if (is_pip) {
            $("#output_format").val("0").change();
        }

        enable_option("output_video_format_row", frm.output_format, !is_pip);
    }

    function video_encoder_changed(mode_selector) {
        var mode = mode_selector.value;
        if (!is_multirate_output() && (mode == "H264" || mode == "LOWLATENCY" || mode == "H264LD" || mode == "H264FF")) {
            $("#h264_profile_row").show();
            $("#h264_constraint_row").show();
            if(mode == "H264FF")
            {
                if($('#h264_profile').val()==66)
                {
                    alert("Baseline is not valid for H.264 FF, defaulting H.264 profile to 'Main'");
                    $('#h264_profile').val('77');
                }
                $('#h264_profile').children('option[value="66"]').attr('disabled','disabled');

                if($('#output_format').val()==0)
                {
                    alert("Progressive output is not valid for H.264 FF, defaulting Output Video Format to 'Same as Input'");
                    $('#output_format').val('2');
                }
                $('#output_format').children('option[value="0"]').attr('disabled','disabled');
            }
            else
            {
                $('#h264_profile').children('option[value="66"]').attr('disabled','');
                $('#output_format').children('option[value="0"]').attr('disabled','');
            }
            if(mode == "H264" && $("#h264_profile")==66)
            {
                $('#I_P_frame_distance').val(1);
                if($('#I_P_frame_distance').val()!="1")
                    alert("For H264 mode in baseline mode, I/P frame distance must be 1. Setting has been updated.");
                $('#I_P_frame_distance').attr('readonly','readonly');
            }
            else
                $('#I_P_frame_distance').attr('readonly','');
        } else {
              $("#h264_profile_row").hide();
              $("#h264_constraint_row").hide();
              $('#h264_profile').children('option[value="66"]').attr('disabled','');
              $('#output_format').children('option[value="0"]').attr('disabled','');
        }

        <?php if (ENABLE_PYRAMID_B == 1) { ?>
        if (is_multirate_output()) {
            var row = document.getElementById("h264_pyramid_row");
            row.style["display"] = "";
        } else {
            var row = document.getElementById("h264_pyramid_row");
            row.style["display"] = "none";
        }
        <?php } ?>

        if(mode == "H264LD")
        {
            $("#output_resolution").val("SAME");
            $("#output_format").val(2);
            $("#output_framerate").val(0);
            $("#I_P_frame_distance").val(1);
            $("#output_audio_format").val("ac3");
            $("#nonprimaryaudio").hide();
            $("#output_format option[value!=2]").attr("disabled","true");
            $("#output_framerate option[value!=0]").attr("disabled","true");
            $("#output_resolution option[value!='SAME']").attr("disabled","true");
            $("#output_audio_format option[value!='ac3']").attr("disabled","true");
            $("#I_P_frame_distance").attr("readonly","true");
        }
        else {
            $("#nonprimaryaudio").show();
            $("#output_format option").attr("disabled","");
            $("#output_framerate option").attr("disabled","");
            $("#output_resolution option").attr("disabled","");
            $("#output_audio_format option").attr("disabled","");
            $("#I_P_frame_distance").attr("readonly","");
        }
        // May 14, 2025
        setTimeout(() => {
            ["nonprimaryaudio", "audio_pid_row1", "audio_heading_row1"].forEach(x => {
                $("#"+x).removeClass('force_hide').show()
            })
            $("#audio_volume_row0").hide();
        }, 1000)

        if(mode == "HEVCSOCIO" || mode == "H264SOCIO") {
            $("#cpb_delay_row").show();
        } else {
            $("#cpb_delay_row").hide();
        }

        ip_output_type_selected($("#ip_output_type"));
        if(mode == "HEVC") {
            $(".vid_encoder_profile").val(1);
            $(".vid_encoder_profile").attr("readonly",true);
        } else {
            $(".vid_encoder_profile").removeAttr("readonly");
        }
    }

    function h264_profile_changed(mode_selector) {
        if(mode_selector.value==66)
        {
            if($('#I_P_frame_distance').val()!="1")
                alert("For H264 mode in baseline mode, IP Frame Distance must be 1. Setting has been updated.");
            $('#I_P_frame_distance').val(1);
            $('#I_P_frame_distance').attr('readonly','readonly');
        }
        else
            $('#I_P_frame_distance').attr('readonly','');
    }

    function source_file_list_count()
    {
        var options = $("#source_file_list option");
        var count = options.length;
        options.each(function(i,opt) {
            // Filter out placeholder for user-defined path
            if (opt.value == "") {
                count -= 1;
                return false;
            }
        });
        return count;
    }

    function source_file_list_set(file)
    {
    <?php if (ENABLE_SOURCE_FILE_FTP) { ?>
        var list = $("#source_file_list");

        var found = false;
        $("#source_file_list option").each(function(i,opt) {
            if (opt.value == "")
            {
                // If we made it here, the file is not in the list.
                opt.selected = true;
                return false;
            }
            else if (file == opt.value)
            {
                found = true;
                opt.selected = true;
                return false;
            }
        });

        if (!found) {
            // Allow for user-defined paths starting from root
            if (file.indexOf("/") != 0) {
                // Only alert user to input file weirdness if TSFILE input is selected
                var input_interface = get_active_input_interface();
                if (input_interface == "TSFILE") {
                    window.alert("The input file specified in this config does not exist.\n\nFile: "+file+
                                 "\n\nReverting to default.");
                }
            }
        }

        source_file_list_changed($("#source_file_list")[0]);

    <?php } else { ?>
        $("#yuv_file_name").val(file);
    <?php } ?>
    }

    function source_file_list_changed(mode_selector)
    {
        <?php if (ENABLE_SOURCE_FILE_FTP) { ?>
        var mode = mode_selector.value;
        if (mode == "")
        {
            $("#source_file_row").removeClass("force_hide");
        }
        else
        {
            $("#source_file_row").addClass("force_hide");
            $("#yuv_file_name").val(mode);
        }
        <?php } ?>
    }


    function mp4file_list_count()
    {
        var options = $("#mp4file_list option");
        var count = options.length;
        options.each(function(i,opt) {
            // Filter out placeholder for user-defined path
            if (opt.value == "") {
                count -= 1;
                return false;
            }
        });
        return count;
    }

    function mp4file_list_set(file)
    {
    <?php if (ENABLE_SOURCE_FILE_FTP) { ?>
        var list = $("#mp4file_list");

        var found = false;
        $("#mp4file_list option").each(function(i,opt) {
            if (opt.value == "")
            {
                // If we made it here, the file is not in the list.
                opt.selected = true;
                return false;
            }
            else if (file == opt.value)
            {
                found = true;
                opt.selected = true;
                return false;
            }
        });

        if (!found) {
            // Allow for user-defined paths starting from root
            if (file.indexOf("/") != 0) {
                // Only alert user to input file weirdness if TSFILE input is selected
                var input_interface = get_active_input_interface();
                if (input_interface == "MP4FILE") {
                    window.alert("The input file specified in this config does not exist.\n\nFile: "+file+
                                 "\n\nReverting to default.");
                }
            }
        }

        mp4file_list_changed($("#mp4file_list")[0]);

    <?php } else { ?>
        $("#mp4file_input_name").val(file);
    <?php } ?>
    }

    function mp4file_list_changed(mode_selector)
    {
        <?php if (ENABLE_SOURCE_FILE_FTP) { ?>
        var mode = mode_selector.value;
        if (mode == "")
        {
            $("#mp4file_list").removeClass("force_hide");
        }
        else
        {
            $("#mp4file_input_row").addClass("force_hide");
            $("#mp4file_input_name").val(mode);
        }
        <?php } ?>
    }

    function input_resolution_changed(mode_selector)
    {
        var mode = mode_selector.value;

        if (mode == "UltraHD" || mode == "4K" || mode == "HD1080" || mode == "HD720") {
           setup_output_resolution(true);
        } else {
           setup_output_resolution(false);
        }

        if (mode == "USER") {
            $("#input_row_1").show();
        } else {
            $("#input_row_1").hide();
        }
        updateFrameRates();
    }

    function updateFrameRates()
    {
        var first_index = 0;
        var last_index = first_index + (MAX_VIDEO_STREAMS - 1);
        var stream_index = 0;
        if($("#input_resolution").val()=="HD1080" && $("#input_format").val()==1)//1080i
        {
           for (stream_index = first_index; stream_index <= last_index; stream_index++){

                if($("#stream_preset"+stream_index).val()==0){
                  $("#stream_framerate"+stream_index+" option[value*='3']").attr("disabled",false);
               }else {
                  $("#stream_framerate"+stream_index+" option[value*='3']").attr("disabled",true);
               if($("#stream_framerate"+stream_index).val()==3)
                    $("#stream_framerate"+stream_index).val(0);
                }
            }
        }
        else
        {
           for (stream_index = first_index; stream_index <= last_index; stream_index++)
           {
               $("#stream_framerate"+stream_index+" option[value*='3']").attr("disabled",true);
               if($("#stream_framerate"+stream_index).val()==3)
                    $("#stream_framerate"+stream_index).val(0);
           }
        }
    }


/*
    function input_secondary_interface_enable_changed()
    {
        var enable = this.val;
        console.log("enable = " + enable);
        $(".output_ethernet_interface_2").toggleClass("force_hide", !enabled);

        if (enable == "1") {
            $("#preferred_output_row_2").show();
            <?php if (ENABLE_IPV6) { ?>
            $("#output_ip_address_ipv6_2").show();
            <?php } ?>
            $("#output_ip_address_row_2").show();
            $("#output_port_row_2").show();
            $("#multicast_ttl_row_2").show();
        } else {
            $("#preferred_output_row_2").hide();
            <?php if (ENABLE_IPV6) { ?>
            $("#output_ip_address_ipv6_2").show();
            <?php } ?>
            $("#output_ip_address_row_2").hide();
            $("#output_port_row_2").hide();
            $("#multicast_ttl_row_2").hide();
        }
    }
*/
    function sdi_input_mode_changed(mode_selector)
    {
        var mode = mode_selector.value;
        var width, height;
        var format;
        var framerate;
        var enable_psf;
        var is_sd = false;

        switch (mode)
        {
        case "0":
            width = 720;
            height = 480;
            format = 1;
            framerate = 29.97;
            enable_psf = 0;
            is_sd = true;
            break;
        case "1":
            width = 720;
            height = 480;
            format = 1;
            framerate = 23.98;
            enable_psf = 0;
            is_sd = true;
            break;
        case "2":
            width = 720;
            height = 576;
            format = 1;
            framerate = 25;
            enable_psf = 0;
            is_sd = true;
            break;
        case "3":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 23.98;
            enable_psf = 0;
            break;
        case "4":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 24;
            enable_psf = 0;
            break;
        case "5":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 25;
            enable_psf = 0;
            break;
        case "6":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 29.97;
            enable_psf = 0;
            break;
        case "7":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 30;
            enable_psf = 0;
            break;
        case "8":
            width = 1920;
            height = 1080;
            format = 1;
            framerate = 25;
            enable_psf = 0;
            break;
        case "9":
            width = 1920;
            height = 1080;
            format = 1;
            framerate = 29.97;
            enable_psf = 0;
            break;
        case "10":
            width = 1920;
            height = 1080;
            format = 1;
            framerate = 30;
            enable_psf = 0;
            break;
        case "11":
            width = 1280;
            height = 720;
            format = 0;
            framerate = 50;
            enable_psf = 0;
            break;
        case "12":
            width = 1280;
            height = 720;
            format = 0;
            framerate = 59.94;
            enable_psf = 0;
            break;
        case "13":
            width = 1280;
            height = 720;
            format = 0;
            framerate = 60;
            enable_psf = 0;
            break;
        case "14":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 23.98;
            enable_psf = 1;
            break;
        case "15":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 24;
            enable_psf = 1;
            break;
        case "16":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 25;
            enable_psf = 1;
            break;
        case "17":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 29.97;
            enable_psf = 1;
            break;
        case "18":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 30;
            enable_psf = 1;
            break;
        case "19":
            width = 1280;
            height = 720;
            format = 0;
            framerate = 50;
            enable_psf = 1;
            break;
        case "20":
            width = 1280;
            height = 720;
            format = 0;
            framerate = 59.94;
            enable_psf = 1;
            break;
        case "21":
            width = 1280;
            height = 720;
            format = 0;
            framerate = 60;
            enable_psf = 1;
            break;
        case "22":
            width = 3840;
            height = 2160;
            format = 0;
            framerate = 23.98;
            enable_psf = 0;
            break;
        case "23":
            width = 3840;
            height = 2160;
            format = 0;
            framerate = 24;
            enable_psf = 0;
            break;
        case "24":
            width = 3840;
            height = 2160;
            format = 0;
            framerate = 25;
            enable_psf = 0;
            break;
        case "25":
            width = 3840;
            height = 2160;
            format = 0;
            framerate = 29.97;
            enable_psf = 0;
            break;
        case "26":
            width = 3840;
            height = 2160;
            format = 0;
            framerate = 30;
            enable_psf = 0;
            break;
        case "27":
            width = 3840;
            height = 2160;
            format = 0;
            framerate = 50;
            enable_psf = 0;
            break;
        case "28":
            width = 3840;
            height = 2160;
            format = 0;
            framerate = 59.94;
            enable_psf = 0;
            break;
        case "29":
            width = 3840;
            height = 2160;
            format = 0;
            framerate = 60;
            enable_psf = 0;
            break;
        case "30":
            width = 4096;
            height = 2160;
            format = 0;
            framerate = 23.98;
            enable_psf = 0;
            break;
        case "31":
            width = 4096;
            height = 2160;
            format = 0;
            framerate = 24;
            enable_psf = 0;
            break;
        case "32":
            width = 4096;
            height = 2160;
            format = 0;
            framerate = 25;
            enable_psf = 0;
            break;
        case "33":
            width = 4096;
            height = 2160;
            format = 0;
            framerate = 29.97;
            enable_psf = 0;
            break;
        case "34":
            width = 4096;
            height = 2160;
            format = 0;
            framerate = 30;
            enable_psf = 0;
            break;
        case "35":
            width = 4096;
            height = 2160;
            format = 0;
            framerate = 50;
            enable_psf = 0;
            break;
        case "36":
            width = 4096;
            height = 2160;
            format = 0;
            framerate = 59.94;
            enable_psf = 0;
            break;
        case "37":
            width = 4096;
            height = 2160;
            format = 0;
            framerate = 60;
            enable_psf = 0;
            break;
        }

        var frm = document.configuration;

        if (width == 3840 && height == 2160)
        {
            frm.input_resolution.value = "UltraHD";
        }
        else if (width == 4096 && height == 2160)
        {
            frm.input_resolution.value = "4K";
        }
        else if (width == 1920 && height == 1080)
        {
            frm.input_resolution.value = "HD1080";
        }
        else if (width == 1280 && height == 720)
        {
            frm.input_resolution.value = "HD720";
        }
        else
        {
            frm.input_resolution.value = "USER";
            frm.input_width.value = width;
            frm.input_height.value = height;
        }

        setup_output_resolution(true);

        frm.input_format.value = format;
        frm.input_framerate.value = framerate;
        frm.enable_psf.value = enable_psf;

        var enable_field_order = (format == 1 || framerate == 23.98 || framerate == 24) && mode < 22;
        $("#bottom_field_first_row").toggleClass("force_hide", !enable_field_order);
        enable_option("bottom_field_first_row", frm.bottom_field_first, enable_field_order);

        $(".sd_sdi_setting_row").toggleClass("force_hide", !is_sd);
    }

    function hdmi_input_mode_changed(mode_selector)
    {
        var mode = mode_selector.value;
        var width, height;
        var format;
        var framerate;

        switch (mode)
        {
        case "0":
            width = 720;
            height = 480;
            format = 1;
            framerate = 29.97;
            break;
        case "1":
            width = 720;
            height = 480;
            format = 0;
            framerate = 23.98;
            break;
        case "2":
            width = 720;
            height = 576;
            format = 1;
            framerate = 25;
            break;
        case "3":
            width = 720;
            height = 480;
            format = 0;
            framerate = 59.94;
            break;
        case "4":
            width = 720;
            height = 576;
            format = 0;
            framerate = 50;
            break;

        case "5":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 23.98;
            break;
        case "6":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 24;
            break;
        case "7":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 25;
            break;
        case "8":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 29.97;
            break;
        case "9":
            width = 1920;
            height = 1080;
            format = 0;
            framerate = 30;
            break;

        case "10":
            width = 1920;
            height = 1080;
            format = 1;
            framerate = 25;
            break;
        case "11":
            width = 1920;
            height = 1080;
            format = 1;
            framerate = 29.97;
            break;
        case "12":
            width = 1920;
            height = 1080;
            format = 1;
            framerate = 30;
            break;

        case "13":
            width = 1280;
            height = 720;
            format = 0;
            framerate = 50;
            break;
        case "14":
            width = 1280;
            height = 720;
            format = 0;
            framerate = 59.94;
            break;
        case "15":
            width = 1280;
            height = 720;
            format = 0;
            framerate = 60;
            break;
        }

        var frm = document.configuration;

        if (width == 1920 && height == 1080)
        {
            frm.input_resolution.value = "HD1080"
        }
        else if (width == 1280 && height == 720)
        {
            frm.input_resolution.value = "HD720";
        }
        else if (width == 720 && height == 480)
        {
            frm.input_resolution.value = "NTSC720";
        }
        else if (width == 720 && height == 576)
        {
            frm.input_resolution.value = "PAL720";
        }
        else
        {
            frm.input_resolution.value = "USER";
            frm.input_width.value = width;
            frm.input_height.value = height;
        }

        setup_output_resolution(true);

        frm.input_format.value = format;
        frm.input_framerate.value = framerate;
        frm.enable_psf.value = 0;
    }

    function show_help()
    {
        window.open("index_help.html");
    }

    function scramblingKeyModeChanged()
    {
        var selected = $("#scrambling_keymode").val();
        $(".scrambleModeOption").hide();
        if ("DYNAMIC" == selected)
            $(".scrambleDynamicOption").show();
        else if ("FIXEDTEK" == selected)
            $(".scrambleFixedTekOption").show();

        $(".scrambleGeneralOption").toggle("NONE" != selected);
    }

    function verimatrixEnableChanged()
    {
        var selected = $("#verimatrix_enable").val();
        $(".verimatrixOption").toggle("0" != selected);
    }

    function nielsenEnableChanged()
    {
        var selected = $("#nielsen_watermark_decoding_enable").val();
        $(".nielsenOption").toggle("0" != selected);
    }

    function buydrmEnableChanged()
    {
        var selected1 = $("#buydrm_enable1").val();
        $(".buydrmOption1").toggle("0" != selected1);
        var selected2 = $("#buydrm_enable2").val();
        $(".buydrmOption2").toggle("0" != selected2);
    }

    function multi_output_file_mode_selected(mode) {
        var frm = document.configuration;
        switch (mode)
        {
            case 0: // NONE
                enable_option("multi_output_file_max_duration_row", frm.multi_output_file_max_duration, false);
                enable_option("multi_output_file_max_size_row", frm.multi_output_file_max_size, false);
                enable_option("multi_output_file_format_row", frm.multi_output_file_format, false);
                enable_option("multi_output_file_format_row", frm.multi_output_file_format, false);
                break;
            case 1: // DURATION
                enable_option("multi_output_file_max_duration_row", frm.multi_output_file_max_duration, true);
                enable_option("multi_output_file_max_size_row", frm.multi_output_file_max_size, false);
                enable_option("multi_output_file_format_row", frm.multi_output_file_format, true);
                break;
            case 2: // SIZE
                enable_option("multi_output_file_max_duration_row", frm.multi_output_file_max_duration, false);
                enable_option("multi_output_file_max_size_row", frm.multi_output_file_max_size, true);
                enable_option("multi_output_file_format_row", frm.multi_output_file_format, true);
                break;
            case 3: // UNLIMITED
                enable_option("multi_output_file_max_duration_row", frm.multi_output_file_max_duration, false);
                enable_option("multi_output_file_max_size_row", frm.multi_output_file_max_size, false);
                enable_option("multi_output_file_format_row", frm.multi_output_file_format, true);
                break;
        }

        var enabled = mode != 0;
        $("#multi_output_file_active_row").toggleClass("force_hide", !enabled);
    }

        function streamImageOverlayFileUpload()
        {
                $.ajaxFileUpload
                (
                        {
                                url:'json/image_overlay.php',
                                secureuri:false,
                                fileElementId:'stream_image_overlay_upload_box',
                                dataType: 'json',
                                data:{ t: (new Date()).getTime() },
                                success: function (data, status)
                                {
                    if(data.error && data.error.length > 0)
                    {
                        alert("Error: " + data.error);
                    }else
                    {
                        var fname = data.data.name.split("/");
                        fname = fname[fname.length - 1];
                        alert("Image successfully uploaded and converted to " + fname);
                        imageOverlayRefreshFiles(data.data.name);
                    }
                                },
                                error: function (data, status, e)
                                {
                                        alert(e);
                                }
                        }
                )

                return false;
    }

    function imageOverlayFileUpload()
        {
                $.ajaxFileUpload
                (
                        {
                                url:'json/image_overlay.php',
                                secureuri:false,
                                fileElementId:'image_overlay_upload_box',
                                dataType: 'json',
                                data:{ t: (new Date()).getTime() },
                                success: function (data, status)
                                {
                    if(data.error && data.error.length > 0)
                    {
                        alert("Error: " + data.error);
                    }else
                    {
                        var fname = data.data.name.split("/");
                        fname = fname[fname.length - 1];
                        alert("Image successfully uploaded and converted to " + fname);
                        imageOverlayRefreshFiles(data.data.name);
                    }
                },
                error: function (data, status, e)
                {
                    alert(e);
                }
            }
        )

        return false;
    }
    function slateFileUpload()
    {
        $.ajaxFileUpload
        (
            {
                url:'json/slate.php',
                secureuri:false,
                fileElementId:'slate_upload_box',
                dataType: 'json',
                data:{ t: (new Date()).getTime() },
                success: function (data, status)
                {
                    if(data.error && data.error.length > 0)
                    {
                        alert("Error: " + data.error);
                    }else
                    {
                        var fname = data.data.name.split("/var/www/slates/");
                        fname = fname[fname.length - 1];
                        fname=fname.toLowerCase();
                        var posOfDot= fname.indexOf('.jpeg');
                        if(posOfDot==0)
                        {
                            alert("Invaild file name");
                            return false;
                        }
                        posOfDot= fname.indexOf('.png');
                        if(posOfDot==0)
                        {
                            alert("Invaild file name");
                            return false;
                        }
                        posOfDot= fname.indexOf('.jpg');
                        if(posOfDot==0)
                        {
                            alert("Invaild file name");
                            return false;
                        }

                        alert("Slate successfully uploaded and converted to " + fname);
                        slateRefreshFiles(data.data.name);
                    }
                },
                error: function (data, status, e)
                {
                    alert(e);
                }
            }
        )

        return false;
    }

    function slateRefreshFiles(selectedFile)
    {
        $.ajax({
            async: true,
            url: "json/slate.php",
            data: { action: "list", t: (new Date()).getTime() },
            dataType: "json",
            success: function (data) {
                if (data && data.data && data.data.images) {
                    var select = $('.slate_filename');
                    select.children('option').remove();
                    select.append($('<option></option>').val("").html("None"));
                    $.each(data.data.images, function(index, option) {
                        var display_name = option.split("/");
                        display_name = display_name[display_name.length-1];
                        select.append($('<option></option>').val(option).html(display_name));
                    });
                    select.children("option[selected]").removeAttr("selected");
                    select.children("option[value='"+(selectedFile?selectedFile:"")+"']").attr("selected", "selected");
                    slate_changed();
                }
            }
        });
    }
    function imageOverlayRefreshFiles(selectedFile)
    {
        $.ajax({
            async: false,
            url: "json/image_overlay.php",
            data: { action: "list", t: (new Date()).getTime() },
            dataType: "json",
            success: function (data) {
                if (data && data.data && data.data.images) {
                    var select = $('.image_overlay_file');
                    select.children('option').remove();
                    select.append($('<option></option>').val("").html("None"));
                    $.each(data.data.images, function(index, option) {
                        var display_name = option.split("/");
                        display_name = display_name[display_name.length-1];
                        select.append($('<option></option>').val(option).html(display_name));
                    });
                    select.children("option[selected]").removeAttr("selected");
                    select.children("option[value='"+(selectedFile?selectedFile:"")+"']").attr("selected", "selected");
                    image_overlay_file_changed();
                    stream_image_overlay_file_changed();
                }
            }
        });
    }

    function get_config_list(selectedFile = "<?php echo $selected_filename;?>")
    {
         $.ajax({
             async: false,
             url: "json/config.php",
             data: { action: "list_configs", t: (new Date()).getTime() },
             dataType: "json",
             success: function (data) {
                 if (data && data.data && data.data.configs) {
                     var select = $('#current_file');
                     select.children('option').remove();
                     select.append($('<option></option>').val("").html("None"));
                     $.each(data.data.configs, function(index, option) {
                         var display_name = option;
                         select.append($('<option></option>').val(option).html(display_name));
                     });
                     select.children("option[selected]").removeAttr("selected");
                     select.children("option[value='"+(selectedFile?selectedFile:"")+"']").attr("selected", "selected");
                 }
             }
         });
     }

    function streamImageOverlayFileDelete()
    {
        var select = $('#stream_image_overlay_file');
        var selectedFile = select.val();

        if (selectedFile && selectedFile.length > 0)
        {
            select.children("option[selected]").removeAttr("selected").remove();
            stream_image_overlay_file_changed();

            $.getJSON(
                "json/image_overlay.php?callback=?",
                {
                    action: "delete",
                    file: selectedFile,
                    t: (new Date()).getTime()
                });
        }
        return false;

    }
    function imageOverlayFileDelete()
    {
        var select = $('#image_overlay_file');
        var selectedFile = select.val();

        if (selectedFile && selectedFile.length > 0)
        {
            select.children("option[selected]").removeAttr("selected").remove();
            image_overlay_file_changed();

            $.getJSON(
                "json/image_overlay.php?callback=?",
                {
                    action: "delete",
                    file: selectedFile,
                    t: (new Date()).getTime()
                });
        }
        return false;
    }

    function slateFileDelete()
    {
        var select = $('#slate_filename');
        var selectedFile = select.val();

        if (selectedFile && selectedFile.length > 0)
        {
            select.children("option[selected]").removeAttr("selected").remove();
            slate_changed();

            $.getJSON(
                "json/slate.php?callback=?",
                {
                    action: "delete",
                    file: selectedFile,
                    t: (new Date()).getTime()
                });
        }
        return false;
    }

    function input_atsc_tuner_changed(channelVal)
    {
        var tuner_elem = $("#input_atsc_tuner")[0];
        var baseTunerIndex = 2*Math.floor(tuner_elem.selectedIndex/2);
        $("#input_atsc_scan_url").attr("href", "tuner.php#tuner"+baseTunerIndex);

        $.getJSON("tuner.php",
        {
                action: "GetChannels",
                dt: new Date().getTime(),
                tuner: baseTunerIndex
        },
        function GetData(data)
        {
            if(data.status == "OK")
            {
                var channelElem = $("#input_atsc_channel");
                channelElem.children().remove();

                if (!data.channels) {
                    $("<option value=''>No channels available. Please scan.</option>").appendTo(channelElem);
                    channelElem.attr("disabled", "disabled");
                    channelElem.css("color", "#888888");
                } else {
                    channelElem.removeAttr("disabled");
                    channelElem.css("color", "#000000");

                    $.each(data.channels, function(freq, channelsByFreq) {
                        var group = $("<optgroup label='"+freq+" Hz'></optgroup>").appendTo(channelElem);
                        $.each(channelsByFreq, function(i, channel) {
                            $("<option value='"+channel.tuningInfo+"' data-freq='"+freq+"'>"+channel.name+" ("+channel.programNumber+")</option>").appendTo(group);
                        });
                    });
               }

               if (channelVal) {
                    $("#input_atsc_channel").val(channelVal);
               }
               input_atsc_channel_changed();
            }
        });
    }

    function input_atsc_channel_changed()
    {
    }

    function subtitle_mode_selected(index) {
        if (index == 0) {
            $("#input_subtitle_pid").attr("disabled", "disabled");
            $("#input_subtitle_order").attr("disabled", "disabled");
        } else if (index == 1) {
            $("#input_subtitle_order").attr("disabled", "disabled");
            $("#input_subtitle_pid").removeAttr("disabled");
        } else if (index == 2) {
            $("#input_subtitle_order").removeAttr("disabled");
            $("#input_subtitle_pid").attr("disabled", "disabled");
        } else if (index == 3) {
            $("#input_subtitle_order").removeAttr("disabled");
            $("#input_subtitle_pid").removeAttr("disabled");
        }



    }
    </script>
</body>
</html>
