//===========================================================================//
//
//  File:  $Workfile: flixpub_advanced.js$
//         $Revision: 13$
//
//  Date:  $DateUTC: 2007-07-09 16:46:56Z$
//
//  Brief: Flix Publisher Reference Implementation Source Code
//
//  Info:  http://www.on2.com/cms-data/pdf/publisher3/
//
//===========================================================================//


/**
*
* slider width, in pixels (referenced in carpeslider.js)
*/
var on2pub_slider_width = 384;

// plugin dimensions, in pixels (referenced in flixpub_embed.js)
//  Note: if the width is changed, updates to v3.css and background images
//        will be required.  Changing the height does not require css update.  
var on2pub_plugin_width = 400;
var on2pub_plugin_height = 300;

/**
* jquery's version of window/document onload()
*/
// jquery's onload
$(document).ready(function() {
    // debug enabled?
    if (fp_debug) {
        $("#debug_div").removeClass("hidden");
    }

    // set plug-in dimensions
    $('#div_plugin_holder').css("width", on2pub_plugin_width);
    $('#div_plugin_holder').css("height", on2pub_plugin_height);

    // many controls have the hidden class assigned to them with the
    // intention being to avoid a big ugly mess of buttons on computers
    // where JS execution is disabled or blocked.
    // Remove the hidden style from the following elements:
    $('#div_plugin_holder, input:button').removeClass("hidden");

    // add styles to input elements
    add_button_styles();
    add_radio_styles();

    if (flixpub_fms_auth_mode == kFmsAuthModeAkamai 
        || flixpub_fms_auth_mode == kFmsAuthModeLimelight) 
    {
        var cur = $('#div_fms_settings').html();
        // add username and password fields
        $('#div_fms_settings').html(
            'Benutzername: <input type="text" id="ti_fms_username" class="ti" /><br />\n'
            + 'Passwort: <input type="password" id="ti_fms_password" class="ti" /><br />\n'
            + cur);
    }

    // hide all controls
    hide_all_controls();

    if (isMac) {
        alert("Broadcasting is not available in the Mac Publisher.");
        return;
    }
    
    // attempt plug-in load
    if (fp_init() == false) {
        // No plug-in,
        // - plug-in not installed, or
        // - update required
        // Bail, plug-in install/update is handled by flixpub_main.js
        // and flixpub_embed.js.  Upon install the page will automatically
        // refresh:
        return;
    }

    try {
        on2pub.MaximumDuration = flixpub_flv_max_duration;
    } catch (e) {};

    // show plug-in version
    var dbg_str = "flixpub_v3.1.5.2";// + on2pub.Version;
    debug_str(dbg_str);

    // set start image
    fp_set_bg_img(flixpub_startup_bg_image);

    
    // setup input elements:
    // preview start button
    $('#btn_preview').click(
        function() {
        swap_buttons(this, '#btn_stop_preview');
        return btn_preview_click(); }).addClass("wide");
    // preview stop button
    $('#btn_stop_preview').click(
        function() {
        swap_buttons(this, '#btn_preview');
        return btn_stop_preview_click(); }).addClass("wide");
    // audio settings button
    $('#btn_aset').click(
        function() {
        return btn_aset_click(); }).addClass("wide");
    // video settings button
    $('#btn_vset').click(
        function() {
        return btn_vset_click(); }).addClass("wide");
    $('#cb_audio_preview_enable').attr("checked", 
                                       on2pub.AudioCapturePreviewEnable)
                                 .attr("disabled", "");
    $('#cb_audio_preview_enable').click(
        function() {
            return cb_audio_preview_enable_click();
        });
        
    // stream start button
    $('#btn_stream_on').click(
        function() {
        swap_buttons(this, '#btn_stream_off');
        return btn_stream_on_click(); }).addClass("wide");
    // stream stop button
    $('#btn_stream_off').click(
        function() {
        swap_buttons(this, '#btn_stream_on');
        return btn_stream_off_click(); }).addClass("wide");

    // setup the capture device selects
    $('#sel_aud_dev').addClass("device_select").change(
        function() {
        return set_audio_capture_device(); });
    $('#sel_vid_dev').addClass("device_select").change(
        function() {
        return set_video_capture_device(); });
    
    // volume controls
    $('#btn_mute').click(
        function() {
        return btn_mute_click();
        });
    $('#btn_volume_down').click(
        function() {
        return btn_volume_down_click();
        });
    $('#btn_volume_up').click(
        function() {
        return btn_volume_up_click();
        });
        
    // FMS settings controls
    $('#btn_set_fms_settings').click(
        function() {
        $(this).hide(0);
        return btn_set_fms_settings_click(); });
    $('#btn_clear_fms_settings').click(
        function() {
        return btn_clear_fms_settings_click(); });
    // show latency settings checkbox
    $('#cb_fms_show_latency_ui').click(
        function () {
        return cb_fms_show_latency_click(); }).attr("checked", false);
    // write output file enable checkbox
    $('#cb_fms_write_output_file').click(
        function () {
        return cb_fms_write_output_file_click(); }).attr("checked", false);

    show_base_ui();
});


function cb_fms_show_latency_click() {
    if ($('#cb_fms_show_latency_ui').attr("checked")) {
        $('#la_max_capture_latency,#ti_max_capture_latency,'
            + '#la_audio_buffer_time,#ti_audio_buffer_time,'
            + '#la_fms_buffer_time,#ti_fms_buffer_time,'
            + '#tt_latency_tip').removeClass('hidden');
    } else {
        $('#la_max_capture_latency,#ti_max_capture_latency,'
            + '#la_audio_buffer_time,#ti_audio_buffer_time,'
            + '#la_fms_buffer_time,#ti_fms_buffer_time,'
            + '#tt_latency_tip').addClass('hidden');
    }
}

function cb_fms_write_output_file_click() {
    if ($('#cb_fms_write_output_file').attr("checked")) {
        
        // change, need to provide a way to change the output file name
        
        var failed = false;
        
        try {
            on2pub.OutputFileName = "";
        } catch (ex) {
            debug_str("cb_fms_write_output_file_click: OutputFileName threw ex="+ex);
            
            failed = true;
        }
    
        if (failed) {    
            $('#cb_fms_write_output_file').attr("checked", false);
            return;
        }
    
        $('#la_output_file_name,#ti_output_file_name').removeClass('hidden');
        $('#ti_output_file_name').attr("disabled", "disabled");
        $('#ti_output_file_name').attr("value", on2pub.OutputFileName);
    } else {
        $('#la_output_file_name,#ti_output_file_name').addClass('hidden');
    }
}


function hide_all_controls() {
    // hide all buttons
    $('input:button').hide(0);
    // hide the status bar
    $('#div_status_container').addClass('hidden');
}

//////////////////////////
// click event handlers //
//////////////////////////
// this function shows the base broadcast UI 
function show_base_ui() {
    // set default capture settings
    set_encoder_settings(true, true);
    // show the capture instructions image
    fp_set_bg_img(flixpub_broadcast_bg_image);
    // load the capture devices into the selects
    load_capture_devices();
    // show the selects
    $('#div_device_select').removeClass('hidden');

    
    // hide the settings buttons
    $('#btn_aset,#btn_vset').hide(0);
    
    // show the capture and preview buttons
    show_button('#btn_stream_on,#btn_preview');

    $('#div_fms_controls').removeClass("hidden");
    
    // and some extra code because IE's just the best platform
    show_button('#btn_set_fms_settings,#btn_clear_fms_settings');
}

function show_capture_ui() {
    // show status bar
    $('#div_status_container').removeClass('hidden');

    // block the device select div
    $('#div_device_select')
        .block('<tt>Stop your broadcast to change capture device settings.</tt>', 
            { font: '1.4em serif', border: '1px solid #000', opacity: '.60' });

    // block the settings div
    $('#div_fms_controls')
        .block('<tt>Stop your broadcast to change FMS settings.</tt>', 
            { font: '1.4em serif', border: '1px solid #000', opacity: '.60' });

    // show stop capture button and volume control buttons
    show_button('#btn_stream_off, #btn_mute, #btn_volume_down, #btn_volume_up');
}

function btn_clear_fms_settings_click () {
    $('.ti').attr("value", "");
    $('#cb_fms_ignore_errors_enable').attr("checked", 0);
    show_button('#btn_set_fms_settings');
}
function btn_set_fms_settings_click() {
    if ($('#ti_fms_server').attr("value")
        && $('#ti_fms_path').attr("value")
        && $('#ti_fms_name').attr("value"))
    {   
        try {
            var set_latency_values = $('#cb_fms_show_latency_ui').attr("checked") ? true : false;
            var write_output_file = $('#cb_fms_write_output_file').attr("checked");

            var fmsset = new fp.util.fms_settings(
                true,
                $('#ti_fms_server').attr("value"),
                $('#ti_fms_path').attr("value"),
                $('#ti_fms_name').attr("value"),
                false,
                write_output_file,
                flixpub_fms_auth_mode,
                $('#ti_fms_username').attr("value"), 
                $('#ti_fms_password').attr("value"),
                set_latency_values ? $('#ti_max_capture_latency').attr("value") : null,
                set_latency_values ? $('#ti_audio_buffer_time').attr("value") : null,
                set_latency_values ? $('#ti_fms_buffer_time').attr("value") : null
                );

            fp_set_fms_settings_obj(on2pub, fmsset);
            
            if (write_output_file) {
                var ofn = $('#ti_output_file_name').attr("value");
            
                if (ofn && ofn.length > 0) {
                    on2pub.OutputFileName = ofn;
                }
            }
        } catch(e) {
            debug_str("btn_set_fms_settings_click(): tried applying settings, caught e=" + e);
        }
    } else {
        show_button('#btn_set_fms_settings');
    }
}

// click event handler: start stream button
function btn_stream_on_click() {
    try {
        fp_stop();
        set_audio_capture_device();
        set_video_capture_device();
        try {
            set_encoder_settings();
        } catch (e) {
            debug_str("btn_stream_on_click: set_encoder_settings threw e=" + e);
        }
        fp_start_capture();
        show_capture_ui();
        handle_encode();
    }
    catch (e) {
       
    }
}
// click event handler: stop stream button
function btn_stream_off_click() {
    alert("Ihr Stream wird gestoppt. Warten Sie bis die beiden Buttons\n'Aktivieren' und 'Starten'\nsichtbar sind. Ein Augenblick bitte...");
    //$.blockUI(flixpub_block_ui_markup);
    fp_stop_capture();       
}
// click event handler: start preview button
function btn_preview_click() {
    fp_stop();
    set_audio_capture_device();
    set_video_capture_device();
    
	if (on2pub.AudioCapturePreviewEnable == true && 
	    on2pub.AudioCaptureDevice != "") 
	{
		on2pub.AudioCapturePreviewEnable = false;
		if (confirm('Are you wearing headphones?')) {
			on2pub.AudioCapturePreviewEnable = true;
		} else {
			$('#cb_audio_preview_enable').attr("checked", false);
		}
	} else {
		on2pub.AudioCapturePreviewEnable = false;
	}

    fp_start_preview();
    show_button('#btn_aset');
    show_button('#btn_vset');
    $('#cb_audio_preview_enable').attr("checked", on2pub.AudioCapturePreviewEnable)
                                 .attr("disabled", "disabled");
                                     
}
// click event handler: stop preview button
function btn_stop_preview_click() {
    $.blockUI(flixpub_block_ui_markup);
    // show the capture instructions image
    fp_set_bg_img(flixpub_broadcast_bg_image);
    $('#btn_aset').hide(0);
    $('#btn_vset').hide(0);
    $('#cb_audio_preview_enable').attr("disabled", "")
							  	 .attr("checked", on2pub.AudioCapturePreviewEnable);
    fp_stop_preview();
    $.unblockUI();
}
// click event handler: show audio settings
function btn_aset_click() {
    fp_show_audio_settings();
}
// click event handler: show video settings
function btn_vset_click() {
    fp_show_video_settings();
}

function cb_audio_preview_enable_click() {
     on2pub.AudioCapturePreviewEnable = 
        Boolean($('#cb_audio_preview_enable').attr("checked"));
}

function btn_mute_click() {
    on2pub.AudioCaptureMute = !Boolean(on2pub.AudioCaptureMute);
    debug_str("btn_mute_click: on2pub.AudioCaptureMute="+on2pub.AudioCaptureMute);
}

function btn_volume_down_click() {
    var vol = fp_volume.decrease(on2pub, 10);
    debug_str("btn_volume_down_click: vol="+vol);
}

function btn_volume_up_click() {
    var vol = fp_volume.increase(on2pub, 10);
    debug_str("btn_volume_up_click: vol="+vol);
    
    if (on2pub.AudioCaptureMute) {
        on2pub.AudioCaptureMute = 0;
        debug_str("btn_volume_up_click: on2pub.AudioCaptureMute=0");
    }
}

// set file and video info
function set_capture_info(h_str1, h_str2, h_str3, fname, adev, vdev) {
    $('#h_fi1').html(h_str1);
    $('#h_fi2').html(h_str2);
    $('#h_fi3').html(h_str3);
    $('#file_str').html(fname);
    $('#video_str').html(vdev);
    $('#audio_str').html(adev);
}

//==================================//
// publisher plug-in event handlers //
//==================================//
function clicked() {
}
function doubleClicked() {
}
function rightClicked() {
}
function captureCompleted() {
    $.unblockUI();
    $('#div_status_container').addClass('hidden');
    $('#btn_volume_down,#btn_volume_up,#btn_stream_off,#btn_mute').hide(0);
    $('#div_fms_controls,#div_device_select').unblock();
    show_base_ui();
    fp_set_bg_img(flixpub_startup_bg_image);
}
function fileEncoded() {
    $.unblockUI();
}
var warning_tid;
function filesDropped() {
    // no transcoding in the broadcast sample, just return
    return;
}
function filePlayed() {
    // no playback in the broadcast sample, just return
    return;
}
function filePaused() {
    // no playback in the broadcast sample, just return
    return;
}
function uploadComplete() {
    // no uploading in the broadcast sample, just return
    return;
}
//===========================================================================//
function uploadFailed()
{
    return;
}

// set status strings
function set_status_strings(left, middle, right) {
    $('#status_l').html(left);
    $('#status_m').html(middle);
    $('#status_r').html(right);
}

/******************************************************************************
******************************************************************************/
function update_encode_status(current_time, duration) {

    var progressstr = fp_time_to_str(current_time);

    if (is_capturing() == false) {
        progressstr += '/' + fp_time_to_str(duration);
    }

    var state_string = on2pub.FmsEnable ? 'Broadcasting' : 'Recording locally';

    if (is_paused()) {
        state_string += " (paused)";
    }

    var cur_s = current_time / 1000;
    var dur_s = duration / 1000;
    var dif_s = dur_s - cur_s;

    if (dif_s <= 1 && duration > 0) {
        $('#btn_stop_encode').hide(0);
        state_string = 'Completing Encode...';
    }

    set_status_strings(state_string, '', progressstr);
}

/******************************************************************************
// function load_capture_devices()
//  Populates the audio and video device SELECT's
******************************************************************************/
function load_capture_devices() {
    var aud_select = document.getElementById("sel_aud_dev");
    var vid_select = document.getElementById("sel_vid_dev");

    if (aud_select.length > 1 || vid_select.length > 1)
    {
        //alert("load_capture_devices: selects already populated, doing nothing");
        return;
    }

    // get the number of capture devices on the system
    var num_aud = on2pub.numAudioCaptureDevices();
    var num_vid = on2pub.numVideoCaptureDevices();

    // populate the audio device drop down list
    var i;
    for (i=1; i<=num_aud; i++)
    {
        var dev_name = on2pub.audioCaptureDeviceName(i);
        var selected = i == 1;
        
        var dev_type = on2pub.audioCaptureDeviceTypeByIndex(i);
        var dev_type_str;
        
        if (dev_type == dev_basic) 
            dev_type_str = "Basic";
        else if (dev_type == dev_ntsc_dv) 
            dev_type_str = "NTSC DV";
        else if (dev_type == dev_pal_dv) 
            dev_type_str = "PAL DV";

        debug_str("AUDIO DEVICE: name=" + dev_name + " type=(" + dev_type + ") " + dev_type_str);
        aud_select.options[i] = new Option(dev_name, dev_name, selected, selected);
    }

    // populate the video device drop down list
    for (i=1; i<=num_vid; i++)
    {
        var dev_name = on2pub.videoCaptureDeviceName(i);
        var selected = i == 1;
        
        var dev_type = on2pub.videoCaptureDeviceTypeByIndex(i);
        var dev_type_str;
        
        if (dev_type == dev_basic) 
            dev_type_str = "Basic";
        else if (dev_type == dev_ntsc_dv) 
            dev_type_str = "NTSC DV";
        else if (dev_type == dev_pal_dv) 
            dev_type_str = "PAL DV";

        debug_str("VIDEO DEVICE: name=" + dev_name + " type=(" + dev_type + ") " + dev_type_str);
        
        vid_select.options[i] = new Option(dev_name, dev_name, selected, selected);
    }
}
/******************************************************************************
// function set_audio_capture_device()
//  Sets audio capture device to the device currently selected in the audio
//  device select.
******************************************************************************/
function set_audio_capture_device() {
    var vid_select = document.getElementById("sel_vid_dev");
    var aud_select = document.getElementById("sel_aud_dev");
    var audio_capture_device = on2pub.AudioCaptureDevice;

    if (aud_select.selectedIndex == 0)
    {
        if (vid_select.selectedIndex != 0) {
            on2pub.AudioCaptureDevice = ""; 
        } else {
            try
            {
                aud_select.selectedIndex = 1;
            }
            catch(e){}
        }
    }
    else
    {
        var index = aud_select.selectedIndex;
        var audio_device_name
            = aud_select.options[index].text;

        //alert("index="+ index +
        //    "\naudio_capture_device=" + audio_capture_device +
        //    "\naudio_device_name=" + audio_device_name +
        //    "\naud_select.options[index].text=" + aud_select.options[index].text);

        if (audio_device_name != audio_capture_device)
        {
            //alert("changing audio device");
            audio_capture_device = audio_device_name;
            on2pub.AudioCaptureDevice = audio_capture_device;
        }
    }
}
/******************************************************************************
// function set_video_capture_device()
//  Sets video capture device to the device currently selected in the video
//  device select.
******************************************************************************/
function set_video_capture_device() {
    var vid_select = document.getElementById("sel_vid_dev");
    var aud_select = document.getElementById("sel_aud_dev");
    var video_capture_device = on2pub.VideoCaptureDevice;

    if (vid_select.selectedIndex == 0)
    {
        if (aud_select.selectedIndex != 0) {
            on2pub.VideoCaptureDevice = "";
        } else {
            try
            {
                vid_select.selectedIndex = 1;
            }
            catch(e){}
        }
    }
    else
    {
        var index = vid_select.selectedIndex;
        var video_device_name
            = vid_select.options[index].text;

        //alert("index="+ index +
        //    "\nvideo_capture_device=" + video_capture_device +
        //    "\nvideo_device_name=" + video_device_name +
        //    "\nvid_select.options[index].text=" + vid_select.options[index].text);

        if (video_device_name != video_capture_device)
        {
            //alert("changing video device");
            video_capture_device = video_device_name;
            on2pub.VideoCaptureDevice = video_capture_device;
        }
    }
}

function debug_str(str) {
    var cur = $('#debug_div').html();
    $('#debug_div').html(cur + '<br>' + str);
}

function set_encoder_settings() {    
    // default the plug-in settings (to those specified in flixpub_conf.js)
    
    try {
        fp_set_video_settings(on2pub, true, -1, -1, -1, -1, -1, -1, -1, -1);        
    } catch (e) {
        debug_str("set_encoder_settings: fp_set_video_settings threw e=" + e);
    };
    
    try {
        fp_set_audio_settings(on2pub, -1, -1);
    } catch (e) {
        debug_str("set_encoder_settings:fp_set_audio_settings threw e=" + e);
    };
    
}

function fmsConnectionDown() {
	debug_str("fms connection down.");
}
function fmsConnectionUp() {
	debug_str("fms connection up.");
}
