//===========================================================================//
//
//  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/
//
//===========================================================================//

//top.window.encodeDone = false


function getQueryVariable(variable){
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++){
		var pair = vars[i].split("=");
		if (pair[0] == variable){
			return pair[1];
		}
	}
} 

magicDirectory = getQueryVariable("clientID");


//if (magicFile==null){
var magicFile;
//}
encodeDone = false;
magicDone = false;
getFile = function(){
	return ("Hello Eric");
}



/**
*
* 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;

// this var is used to keep track of upload failures
var upload_attempts = 0;

/**
* jquery's version of window/document onload()
*/
// jquery's onload
$(document).ready(function() {
    if (flixpub_record == false && flixpub_transcode == false) {
        alert("At least one of flixpub_record or flixpub_transcode "
            + "must be set to true in flixpub_conf.js");
        return;
    }
    
    // debug enabled?
    if (fp_debug) {
        $("#debug_div").removeClass("hidden");
    }
    
    // Mac plug-in?
    if (isMacSafari) {
        // no broadcasting support in Mac Publisher, disable UI elements
        flixpub_record_fms_ui = false;
        flixpub_transcode_fms_ui = false;
    }

    // set plug-in dimensions
    $('#div_plugin_holder').css("width", on2pub_plugin_width);
    $('#div_plugin_holder').css("height", on2pub_plugin_height);
    // set slider width
    $('#markholder, #select, #slider_track').attr("width", on2pub_slider_width);

    // tweak the slider nub styles to make it fit
    if ($.browser.msie) {
        $('#div_slider_nub')
        .css("width", "8px")
        .css("height", "12px");
    } else if ($.browser.mozilla || isMac) {
        $('#div_slider_nub')
        .css("width", "6px")
        .css("height", "10px")
        .css("margin-top", "2px");
        $('#status_r').css("margin-right", "0");
    }

    // 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,'  // the plug-in div
    + '#slider_track,'       // the slider track div
    + '#div_slider_nub,'     // the slider nub div
    + 'input:button'         // all buttons
        ).removeClass("hidden");

    // init carpe slider
    setupSliders();
    // add styles to input elements
    add_button_styles();
    add_radio_styles();

    if (flixpub_record_fms_ui || flixpub_transcode_fms_ui) {
        // FMS UI enabled...
        if (flixpub_fms_auth_mode == kFmsAuthModeAkamai 
            || flixpub_fms_auth_mode == kFmsAuthModeAkamai) 
        {
            var cur = $('#div_fms_settings').html();
            // add username and password fields
            $('#div_fms_settings').html(
                'Username: <input type="text" id="ti_fms_username" class="ti" /><br />\n'
                + 'Password: <input type="password" id="ti_fms_password" class="ti" /><br />\n'
                + cur);
        }
    }

    // hide all controls
    hide_all_controls();

    // 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_v" + on2pub.Version;
    debug_str(dbg_str);

    // set start image
    fp_set_bg_img(flixpub_startup_bg_image);

    // set button styles
    // set event handlers (clicks mostly, some others)
    // input playback buttons
    $('#btn_mark_i').click(
        function() {
        swap_buttons(this, '#btn_clear_i');
        return btn_mark_i_click(); });
    $('#btn_clear_i').click(
        function() {
        swap_buttons(this, '#btn_mark_i');
        return btn_clear_i_click(); });
    $('#btn_resume_i').click(
        function() {
        swap_buttons(this, '#btn_pause_i');
        return btn_resume_i_click(); });
    $('#btn_pause_i').click(
        function() {
        swap_buttons(this, '#btn_resume_i');
        return btn_pause_i_click(); });
    $('#btn_mark_o').click(
        function() {
        swap_buttons(this, '#btn_clear_o');
        return btn_mark_o_click(); });
    $('#btn_clear_o').click(
        function() {
        swap_buttons(this, '#btn_mark_o');
        return btn_clear_o_click(); });
    // output playback buttons
    $('#btn_pause_o').click(
        function() {
        swap_buttons(this, '#btn_resume_o');
        return btn_pause_o_click(); });
    $('#btn_resume_o').click(
        function() {
        swap_buttons(this, '#btn_pause_o');
        return btn_resume_o_click(); });
    // capture buttons
    $('#btn_create').click(
        function () {
        $(this).hide(0);
        $('#btn_load').hide(0);
        return btn_create_click(); }).addClass("wide");

    if (flixpub_record == true) {
        $('#btn_create').show(0);
    }

    $('#btn_preview').click(
        function() {
        swap_buttons(this, '#btn_stop_preview');
        return btn_preview_click(); }).addClass("wide");
    $('#btn_stop_preview').click(
        function() {
        swap_buttons(this, '#btn_preview');
        return btn_stop_preview_click(); }).addClass("wide");
    $('#btn_aset').click(
        function() {
        return btn_aset_click(); }).addClass("wide");
    $('#btn_vset').click(
        function() {
        return btn_vset_click(); }).addClass("wide");
		
	if (isMacSafari == false) {
	    $('#cb_audio_preview_enable').attr("checked", 
	                                       on2pub.AudioCapturePreviewEnable)
	                                 .attr("disabled", "");
	    $('#cb_audio_preview_enable').click(
	        function() {
	            return cb_audio_preview_enable_click();
	        });
	} else {
		$('#cb_audio_preview_enable').attr("checked", false)
	                                 .attr("disabled", "disabled");
	}
        
    $('#btn_show_fms').click(
        function() {
        swap_buttons(this, '#btn_hide_fms');
        return btn_show_fms_click(); }).addClass("wide");
    $('#btn_hide_fms').click(
        function() {
        swap_buttons(this, '#btn_show_fms');
        return btn_hide_fms_click(); }).addClass("wide");
    $('#btn_capture').click(
        function() {
        swap_buttons(this, '#btn_stop_capture');
        return btn_capture_click(); }).addClass("wide");
    $('#btn_stop_capture').click(
        function() {
        swap_buttons(this, '#btn_capture');
        return btn_stop_capture_click(); }).addClass("wide");

    // transcode buttons
    $('#btn_load').click(
        function() {
        return btn_load_click(); }).addClass("wide");

    if (flixpub_transcode == true) {
        $('#btn_load').show(0);
    }

    $('#btn_encode').click(
        function() {
        swap_buttons(this, '#btn_stop_encode');
        return btn_encode_click(); }).addClass("wide");
    $('#btn_stop_encode').click(
        function() {
        swap_buttons(this, '#btn_encode');
        return btn_stop_encode_click(); }).addClass("wide");
    // upload buttons
    $('#btn_upload').click(
        function() {
        swap_buttons(this, '#btn_stop_upload');
        return btn_upload_click(); }).addClass("wide");
    $('#btn_stop_upload').click(
        function() {
        swap_buttons(this, '#btn_upload');
        return btn_stop_upload_click(); }).addClass("wide");
    // play input/output
    $('#btn_playinput').click(
        function() {
        swap_buttons(this, '#btn_playoutput');
        return btn_playinput_click(); }).addClass("wide");
    $('#btn_playoutput').click(
        function() {
        swap_buttons(this, '#btn_playinput');
        return btn_playoutput_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(); });
    // setup show/hide encode settings buttons
    $('#btn_show_es_capture').click(
        function() {
        swap_buttons(this, '#btn_hide_es_capture');
        return show_encode_settings(true, true); }).addClass("wide");
    $('#btn_hide_es_capture').click(
        function() {
        swap_buttons(this, '#btn_show_es_capture');
        return show_encode_settings(false, true); }).addClass("wide");
    $('#btn_show_es_encode').click(
        function() {
        swap_buttons(this, '#btn_hide_es_encode');
        return show_encode_settings(true, false); }).addClass("wide");
    $('#btn_hide_es_encode').click(
        function() {
        swap_buttons(this, '#btn_show_es_encode');
        return show_encode_settings(false, false); }).addClass("wide");
    // FMS settings controls
    // FMS enable checkbox click
    $('#cb_fms_enable').click(
        function() {
        return cb_fms_enable_click(); }).attr("checked", false);
    // FMS settings buttons
    $('#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(); });
    // Encoding settings controls
    // radios
    // key frame modes
    $('#ra_akf').click(
        function () {
            radio_set($(this), '#ra_fkf');
            //ra_akf_click($(this).attr("checked"));
        });
    $('#ra_fkf').click(
        function () {
            radio_set($(this), '#ra_akf');
            //ra_fkf_click($(this).attr("checked"));
        });
    // quality level/speed mode
    $('#ra_q_rt').click(
        function () {
            radio_set($(this), '#ra_q_g, #ra_q_b');
            //ra_qrt_click($(this).attr("checked"));
        });
    $('#ra_q_g').click(
        function () {
            radio_set($(this), '#ra_q_rt, #ra_q_b');
            //ra_qg_click($(this).attr("checked"));
        });
    $('#ra_q_b').click(
        function () {
            radio_set($(this), '#ra_q_rt, #ra_q_g');
            //ra_qb_click($(this).attr("checked"));
        });
    // audio format
    $('#ra_mp3').click(
        function () {
            radio_set($(this), '#ra_nm');
            //ra_akf_click($(this).attr("checked"));
        });
    $('#ra_nm').click(
        function () {
            radio_set($(this), '#ra_mp3');
            //ra_akf_click($(this).attr("checked"));
        });
    // buttons
    $('#btn_apply_enc_set').click(
        function() {
        $(this).hide(0);
        return btn_apply_enc_settings_click(); });
    $('#btn_clear_enc_set').click(
        function() {
        return btn_clear_enc_settings_click(); });


    if (flixpub_record_enc_ui == true || flixpub_transcode_enc_ui == true) {
        // select all text inputs in div_enc_controls
        //  first those in the video div
        $('#div_enc_controls_video').children().filter('.ti')
        //  add the bitrate text input from the audio div
        .add('#ti_bitrate_a')
        // filter keystrokes
        .keydown(
            function (e) {
                var ev_res = false;
                var code = e.keyCode;
                if (fp_filter_nonnumeric(e)) {
                    ev_res = true;
                }
                else if (($(this).attr('id') == 'ti_fps') &&
                        (code == 110 || code == 190))
                {
                    // above allows frame rate field to receive the '.' character
                    if ($(this).attr('value').indexOf(".") == -1)
                        ev_res = true;	// this allows only 1 dot
                }
                if (ev_res) {
                    // a change was made, show the 'Set' button
                    show_button('#btn_apply_enc_set');
                }
                return ev_res;
            }
        )
        // show 'Set' button when changes occur
        .add('input:radio')	// hook the radio buttons up too
        .change(
            function (e) {
                show_button('#btn_apply_enc_set');
                return true;
            }
        );
        // show 'Set' button when the check boxes are interacted with
        var cb_handler = function () {
                            show_button('#btn_apply_enc_set');
                            return true;
                        };
        $('#cb_mar,#cb_vbr')
        .mouseup(cb_handler)
        .mousedown(cb_handler)
        .change(cb_handler);
    }

});

function hide_all_controls() {
    // hide all buttons
    $('input:button').hide(0);
    // hide the selects div
    $('#div_device_select').addClass('hidden');
    // hide the slider
    $('#div_slider').addClass('hidden');
    // hide the status bar
    $('#status_container').addClass('hidden');
    // hide the info pane
    $('#div_file_info').addClass('hidden');
    // hide FMS settings pane
    $('#div_fms_controls').addClass('hidden');
    // hide encode settings pane
    $('#div_enc_controls').addClass('hidden');
}

//////////////////////////
// click event handlers //
//////////////////////////
// capture ui button clicks
function btn_create_click() {
    // set default capture settings
    set_encoder_settings(true, true);
    // show the capture instructions image
    fp_set_bg_img(flixpub_record_bg_image);
    // load the capture devices into the selects
    load_capture_devices();
    // show the selects
    $('#div_device_select').removeClass('hidden');
    // show the preview button
    show_button('#btn_preview');
    // hide the settings buttons
    $('#btn_aset').hide(0);
    $('#btn_vset').hide(0);
    // hide the stop preview button
    $('#btn_stop_preview').hide(0);
    // show the capture button
    show_button('#btn_capture');

    if (flixpub_record_fms_ui == true) {
        // show the show live settings button
        show_button('#btn_show_fms');
    }

    if (flixpub_record_enc_ui == true) {
        // show encode settings button
        show_button('#btn_show_es_capture');
    }
}

function btn_load_click() {
	
    if (fp_show_file_chooser(on2pub)){
        filesDropped();
		
	}
}

// fms pane clicks
function btn_show_fms_click() {
    $('#div_fms_controls').removeClass("hidden");
    
    if ($('#cb_fms_enable').attr("checked")) {
        // show set/clear buttons when shown if enable is checked
        show_button('#btn_set_fms_settings,#btn_clear_fms_settings');
    } else {
        $('#btn_set_fms_settings').hide(0);
        $('#btn_clear_fms_settings').hide(0);
    }
}
function btn_hide_fms_click() {
    $('#div_fms_controls').addClass("hidden");
}
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"))
    {
        if (flixpub_fms_auth_mode ==  kFmsAuthModeAkamai 
            || flixpub_fms_auth_mode == kFmsAuthModeLimelight)
        {
            fp_set_fms_uid(on2pub, 
                $('#ti_fms_username').attr("value"), 
                $('#ti_fms_password').attr("value"));
        }

        fp_set_fms_settings(on2pub,
            $('#cb_fms_enable').attr("checked"), 
            $('#ti_fms_server').attr("value"),
            $('#ti_fms_path').attr("value"),
            $('#ti_fms_name').attr("value"),
            $('#cb_fms_ignore_errors_enable').attr("checked"));
    } else {
        show_button('#btn_set_fms_settings');
    }
}
function cb_fms_enable_click() {
    if ($('#cb_fms_enable').attr("checked")) {
        $('#div_fms_settings').removeClass('hidden');
        show_button('#btn_set_fms_settings');
        show_button('#btn_clear_fms_settings');
        // disable vbr mode in the encode settings pane
        $('#cb_vbr').attr("checked", false).attr("disabled", "disabled");
    } else {
        $('#div_fms_settings').addClass('hidden');
        $('#btn_set_fms_settings').hide(0);
        $('#btn_clear_fms_settings').hide(0);
        // enable vbr mode in the encode settings pane
        $('#cb_vbr').attr("disabled", "");
        on2pub.FmsEnable = 0;
    }
}
// encode settings pane clicks
function show_encode_settings(b_show, b_capture) {

    if (b_show == true) {
        if (b_capture == true && flixpub_record_enc_ui == false)
            return;
        else if (b_capture == false && flixpub_transcode_enc_ui == false)
            return;
    }

    if (b_capture) {
        // set real time quality, disable quality radios:
        radio_set('#ra_q_rt', '#ra_q_g, #ra_q_b');
        $('#ra_q_rt, #ra_q_g, #ra_q_b').attr("disabled","disabled");
    } else {
        // enable quality radios
        $('#ra_q_rt, #ra_q_g, #ra_q_b').attr("disabled","");
    }

    if (on2pub.FmsEnable || $('#cb_fms_enable').attr("checked") == true) {
        // no VBR if FMS streaming is enabled,
        // uncheck VBR, disable VBR checkbox:
        $('#cb_vbr').attr("checked", false).attr("disabled", "disabled");
    } else {
        // allow user to set vbr mode
        $('#cb_vbr').attr("disabled", "");
    }

    if (b_show) {
        $('#div_enc_controls').removeClass("hidden");
        show_button('#btn_clear_enc_set, #btn_apply_enc_set');
    } else
        $('#div_enc_controls').addClass("hidden");

    if (isMacSafari) {
        // disable UI elements that control settings unavailable
        // in the Mac Publisher API
        $('#cb_vbr').attr("disabled","disabled");
        $('#cb_mar').attr("disabled","disabled");
        $('#ra_akf').attr("disabled","disabled");
        $('#ra_fkf').attr("disabled","disabled");
        $('#ra_q_rt').attr("disabled","disabled");
        $('#ra_q_g').attr("disabled","disabled");
        $('#ra_q_b').attr("disabled","disabled");
        $('#ti_kff').attr("disabled","disabled");
        // audio format
        $('#ra_mp3').attr("disabled","disabled");
        $('#ra_nm').attr("disabled","disabled");
    }
}
function btn_apply_enc_settings_click() {
    try {
        set_encoder_settings(false, is_capture());
    } catch (e) {
        set_encoder_settings(true, is_capture());
    }
}
function btn_clear_enc_settings_click() {
    set_encoder_settings(true, is_capture());
}
// capture mode clicks
function btn_capture_click() {
    fp_stop();
    set_audio_capture_device();
    set_video_capture_device();

    try {
        set_encoder_settings(false, true);
    } catch (e) {
        set_encoder_settings(true, true);
    }

    fp_start_capture();
    show_capture_ui();

    if (!isMacSafari)
        handle_encode();
}

function btn_stop_capture_click() {
    if (fp_fms_enabled(on2pub))
        $.blockUI(flixpub_block_ui_markup);

    fp_stop_capture();

    if (isMacSafari) {
        // Mac Publisher cannot capture in real time,
        // load the capture file as an input file:
        
        // change, this should be moved to captureCompleted
    	try {
            on2pub.addFile(on2pub.InputFileName);
        } catch (e) {
            failed = true;
        }
    	filesDropped();
    }
}

function btn_preview_click() {
    fp_stop();
    set_audio_capture_device();
    set_video_capture_device();
    
    if (isMacSafari == false) {
        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');
	if (isMacSafari == false) {
        $('#cb_audio_preview_enable').attr("checked", on2pub.AudioCapturePreviewEnable)
                                     .attr("disabled", "disabled");
	}
}

function btn_stop_preview_click() {
    // show the capture instructions image
    fp_set_bg_img(flixpub_record_bg_image);
    $('#btn_aset').hide(0);
    $('#btn_vset').hide(0);
    
    if (isMacSafari == false) {
        $('#cb_audio_preview_enable').attr("disabled", "")
                                     .attr("checked", on2pub.AudioCapturePreviewEnable);
    }
    fp_stop_preview();
}

function btn_aset_click() {
    fp_show_audio_settings();
}

function btn_vset_click() {
    fp_show_video_settings();
}

function cb_audio_preview_enable_click() {
    if (isMacSafari == false) {
        on2pub.AudioCapturePreviewEnable = 
            Boolean($('#cb_audio_preview_enable').attr("checked"));
    }
}

function btn_pause_c_click() {
    on2pub.pause();
}

function btn_resume_c_click() {
    on2pub.resume();
}

// transcode mode clicks
function btn_encode_click() {
    show_transcode_ui();
    try {
        set_encoder_settings(false);
    } catch (e) {
        set_encoder_settings(true);
    }
    fp_start_transcode();
    
    if(isMacSafari) {
        // Mac Publisher cannot show video during encode
        // show a background image:
        fp_set_bg_img(flixpub_encode_bg_image);
    }

    handle_encode();
}

function btn_stop_encode_click() {
    if (fp_fms_enabled(on2pub))
        $.blockUI(flixpub_block_ui_markup);

    fp_stop_transcode();
}

function btn_pause_e_click() {
    on2pub.pause();
}

function btn_resume_e_click() {
    on2pub.resume();
}

// input playback ui button clicks
function btn_mark_i_click() {
    if (!on2pub.InputFileCanSeek) {
        swap_buttons('#btn_clear_i', '#btn_mark_i')
        return;
    }
    var s = on2pub.PlayPosition;
    on2pub.EncodeTimeStart = s;

    set_slider_selections(false, on2pub.InputFileDuration,
        s, on2pub.EncodeTimeEnd);
}

function btn_clear_i_click() {
    var s = 0;
    on2pub.EncodeTimeStart = s;
    set_slider_selections(false, on2pub.InputFileDuration,
        s, on2pub.EncodeTimeEnd);
}

function btn_pause_i_click() {
    on2pub.pause();
}
function btn_resume_i_click() {
    on2pub.resume();
}
function btn_mark_o_click() {
    if (!on2pub.InputFileCanSeek) {
        swap_buttons('#btn_clear_o', '#btn_mark_o')
        return;
    }
    var d = on2pub.InputFileDuration;
    var e = on2pub.PlayPosition;
    on2pub.EncodeTimeEnd = e;
    set_slider_selections(false, d, on2pub.EncodeTimeStart, e);
}
function btn_clear_o_click() {
    var d = on2pub.InputFileDuration;
    on2pub.EncodeTimeEnd = d;
    set_slider_selections(false, d, on2pub.EncodeTimeStart, d);
}

// output playback ui button clicks
function btn_pause_o_click() {
    on2pub.pause();
}
function btn_resume_o_click() {
    on2pub.resume();
}
function btn_playinput_click() {
    // can't play output on the Mac, no point in switching back
    // to input playback mode as the user has no way of looking
    // over the output file
    if (isMacSafari) {
        return;
    }

    var dur = on2pub.InputFileDuration;
    show_input_file_ui();
    set_slider_selections(false, dur, on2pub.EncodeTimeStart,
        on2pub.EncodeTimeEnd);
    fp_play_file(true);

    var set_position = false;

    if (on2pub.EncodeTimeStart != 0) {
        swap_buttons('#btn_mark_i', '#btn_clear_i');
        set_position = true;
    }
    if (on2pub.EncodeTimeEnd < on2pub.InputFileDuration)
        swap_buttons('#btn_mark_o', '#btn_clear_o');

    if (set_position) {
        fp_set_play_position(on2pub, on2pub.EncodeTimeStart);
        on2pub.pause();
        on2pub.resume();
    }

    show_button('#btn_playoutput');
	
	
		
    set_file_info("Input File Name", "Video Stream Info",
            "Audio Stream Info", on2pub.InputFileName, on2pub.InputFileWidth,
            on2pub.InputFileHeight, on2pub.InputFileFrameRate.toPrecision(5),
            on2pub.InputFileAudioSampleSize, on2pub.InputFileAudioChannels,
            on2pub.InputFileAudioSampleRate);

    handle_playback();
}
function btn_playoutput_click() {
    if(isMacSafari) {
        // can't play FLV files in the Mac Publisher
        return;
    }

    set_slider_selections(true);
    fp_play_file(false);
    show_output_file_ui();
    handle_playback();
}

var uploading = false;
function btn_upload_click() {
    uploading = true;
    upload_attempts = 0;
    var ret = fp_start_upload();
    fp_set_bg_img(flixpub_upload_bg_image);
    show_upload_ui();
    handle_upload();
}
function btn_stop_upload_click() {
    uploading = false;
    fp_stop();
    fp_set_bg_img(flixpub_startup_bg_image);
}

// hide the input file playback controls, or show them in their
// default form
function show_input_file_ui() {
    // save visibility state of output playback button
    var bpo_visible = ($('#btn_playoutput').css("display") !== "none");
    // save visibility state of encode settings panel
    var es_visible = ($('#div_enc_controls').css("display") !== "none");

    // hide everything
    hide_all_controls();

    // set slider duration
    set_slider_duration(on2pub.InputFileDuration);

    // show slider and status
    $('#div_slider').removeClass('hidden');
    $('#status_container').removeClass('hidden');

    // on input playback start, mark in/out and pause visible
    show_button('#btn_pause_i');

    if (on2pub.InputFileCanSeek) {
        // only show the mark in/out buttons when they can be used
        show_button('#btn_mark_i');
        show_button('#btn_mark_o');
    }

    // show file info
    $('#div_file_info').removeClass('hidden');

    // show encode button
    show_button('#btn_encode');

    if (!isMacSafari && bpo_visible) {
        // show the play output button if it was visible;
        // this allows the user to quickly switch between input
        // and output file playback
        show_button('#btn_playoutput');
    }

    if (flixpub_transcode_enc_ui == true) {
        if (es_visible) {
            // keep the encoder settings panel open if it was visible
            show_encode_settings(true, false);
            show_button('#btn_hide_es_encode');
        } else {
            // show encode settings button
            show_button('#btn_show_es_encode');
        }
    }

    if (flixpub_transcode_fms_ui == true) {
        show_button('#btn_show_fms');
    }
}

// hide the input file playback controls, or show them in their
// default form
function show_output_file_ui() {
    // hide everything
    hide_all_controls();

    if(!isMacSafari) {
        // set slider duration
        set_slider_duration(on2pub.OutputFileDuration);

        // show slider, status, and pause button
        $('#div_slider').removeClass('hidden');
        $('#status_container').removeClass('hidden');
        show_button('#btn_pause_o');
    }

    var fname = on2pub.OutputFileName;
    if (fname.indexOf("recording") != -1 && String(on2pub.InputFileName).length == 0) {
        show_button('#btn_capture');
    } else if (!isMacSafari) {
    
        // Can't play output on the Mac, no point in providing means to 
        // go back and replay the input file (since user can't watch output)
    
        // show play input button
        show_button('#btn_playinput');
    }

    set_file_info("Output File Name", "Video Stream Info",
        "Audio Stream Info", on2pub.OutputFileName, on2pub.OutputFileWidth,
        on2pub.OutputFileHeight, on2pub.OutputFileFrameRate.toPrecision(5),
        16, 1, 22050);

    // show encode info
    $('#div_file_info').removeClass('hidden');
    // show upload button
    show_button('#btn_upload');
}

function show_capture_ui() {
    if (isMacSafari) {
        // show a bg image when preview is hidden for performance reasons
        fp_set_bg_img(flixpub_capture_bg_image);
    }
    
    // hide everything
    hide_all_controls();

    //show_button('#btn_pause_c');

    // show slider and status
    $('#div_slider').removeClass('hidden');
    $('#status_container').removeClass('hidden');

    set_capture_info("Output File Name", "Video Device",
        "Audio Device", on2pub.OutputFileName, on2pub.AudioCaptureDevice,
        on2pub.VideoCaptureDevice);

    // show info
    $('#div_file_info').removeClass('hidden');

    // show stop capture button
    show_button('#btn_stop_capture');
}

function show_transcode_ui() {
    // hide everything
    hide_all_controls();

    //show_button('#btn_pause_e');

    // show slider and status
    $('#div_slider').removeClass('hidden');
    $('#status_container').removeClass('hidden');

    // show input file info
    $('#div_file_info').removeClass('hidden');

    set_slider_selections(true);

    // show stop encode button
    show_button('#btn_stop_encode');
}

function show_upload_ui() {
    // hide everything
    hide_all_controls();

    // show slider and status
    $('#div_slider').removeClass('hidden');
    $('#status_container').removeClass('hidden');

    set_slider_duration(on2pub.UploadFileSize);
    set_slider_selections(true);
}

// set file and video info
function set_file_info(h_str1, h_str2, h_str3, fname, w, h, fps, ss, chan, sr) {
    $('#h_fi1').html(h_str1);
    $('#h_fi2').html(h_str2);
    $('#h_fi3').html(h_str3);

    $('#file_str').html(fname);

    if (w > 0) {
        $('#video_str').html(w + 'x' + h + ' px' + ' ' + fps + ' fps');
    } else {
    $('#video_str').html("Video not detected, or unplayable format.");
    }

    if (chan > 0) {
    
        if (isMacSafari) {
            $('#audio_str').html("Mac plug-in cannot detect audio properties");
        } else {
            $('#audio_str').html(ss + "-bit "
                + (chan > 1 ? (chan > 2 ? "multi/surround, ": "stereo, ") : "mono, ")
                + sr + " Hz");
			
        }
           
    } else {
        $('#audio_str').html("Audio not detected, or unplayable format.");
    }
}

// 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() {
    debug_str("clicked: received event");
}
function doubleClicked() {
    debug_str("doubleClicked: received event");
}
function rightClicked() {
}
function captureCompleted() {
    debug_str("captureCompleted: received event");
    if (fp_fms_enabled(on2pub))
        $.unblockUI();
		
    if(fp_play_file(false)) {
        show_output_file_ui();
        handle_playback();
    }
}
function fileEncoded() {
    debug_str("fileEncoded: received event");
	btn_upload_click();
	thisMovie("controls").fileEncoded2();
	
    if (!isMacSafari)
    {
        if (fp_fms_enabled(on2pub))
            $.unblockUI();

        if(fp_play_file(false)) {
            show_output_file_ui();
            handle_playback();
			encodeDone = true;
        }
    } else {
        show_output_file_ui();
        fp_set_bg_img(flixpub_encode_complete_bg_image);
    }
}

var warning_tid;

function filesDropped() {
	
    debug_str("filesDropped: received event");
	
    if (flixpub_transcode == false) return;

    hide_all_controls();
    fp_stop();

    fp_set_bg_img(flixpub_validate_bg_image);

    var input_file_result = fp_load_input_file();
	//alert("result = "+input_file_result+" FE_SUCCESS = "+FE_SUCCESS);
	
	
    if (input_file_result != FE_SUCCESS) {
		
        fp_show_error(on2pub, input_file_result);
        return;
    }
	
	/////////////////////////////////////////////////////////////////////////////
	//RESET ENCODED STATE
	encodeDone = false
	/////////////////////////////////////////////////////////////////////////////
	
	/////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////
	///SET UP THE CORRECT PATH FOR OUTPUT
	
	outArr = new Array();
	
	outArr = on2pub.InputFileName.split("\\")
	
	var inputDir=""
	
	///REBUILD WITHOUT THE FILENAME
	for (i=0;i<outArr.length-1; i++) {
		inputDir = inputDir + outArr[i]+"\\"
	}
	
	fileStr = outArr[outArr.length-1]
	fileStrArr = fileStr.split(".")
	
	theTimer = new Date();
	uid = theTimer.getTime();
	
	//on2pub.OutputFileName = inputDir + "magic_" +fileStrArr[0]+"_"+uid+".flv"
	on2pub.OutputFileName = inputDir + magicFile +".flv";
	//on2pub.FtpDestinationFile = magicFile +".flv";
	upload_file_name =magicFile +".flv";
	
	theOutputFileName = on2pub.OutputFileName
	//alert("Output is "+theOutputFileName+" Input is "+on2pub.InputFileName);
	
	if(magicFile == ""){
		alert("There has been a problem, please select the file again.");
	}
	
	/////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////
	
    // input file ok, setup for playback and transcode
    on2pub.EncodeTimeStart = 0;
    var end_time = on2pub.InputFileDuration;
    on2pub.EncodeTimeEnd = end_time;
	
    // setup the slider
    //set_slider_duration(end_time);
    //set_slider_selections(true);

    // start playback
    fp_play_file(true);
	
    //show_input_file_ui();
	
    if (isMacSafari) {
    	set_file_info("Input File Name", "Video Stream Info",
            "Audio Stream Info", on2pub.InputFileName, on2pub.InputFileWidth,
            on2pub.InputFileHeight, on2pub.InputFileFrameRate.toPrecision(5),
            16, 1,
            22050);
    } else {
    	set_file_info("Input File Name", "Video Stream Info",
            "Audio Stream Info", on2pub.InputFileName, on2pub.InputFileWidth,
            on2pub.InputFileHeight, on2pub.InputFileFrameRate.toPrecision(5),
            on2pub.InputFileAudioSampleSize, on2pub.InputFileAudioChannels,
            on2pub.InputFileAudioSampleRate);
    }
	
	//alert("duration = "+on2pub.InputFileDuration);
	thisMovie("uploadSettings").showFileName(on2pub.InputFileName);
	thisMovie("uploadSettings").showFileHeight(on2pub.InputFileWidth+" x "+on2pub.InputFileHeight+"  "+on2pub.InputFileFrameRate.toPrecision(4)+" fps");
	thisMovie("uploadSettings").showFileDur(on2pub.InputFileDuration);
	thisMovie("controls").showFileDur2(on2pub.InputFileDuration);
	
	/*if (on2pub.InputFileAudioChannels<1){
	
	channelStr = "No Audio"
	
	}
	
	if (on2pub.InputFileAudioChannels==1){
	
	channelStr = "Mono"
	
	}
	
	if (on2pub.InputFileAudioChannels==2){
	
	channelStr = "Stereo"
	
	}
	
	
	if (on2pub.InputFileAudioChannels>2){
	
	channelStr = "Multi Channel"
	
	}
	
	if (on2pub.InputFileAudioSampleSize!=0){
	
	AudioData = on2pub.InputFileAudioSampleSize+" Bit, "+channelStr+", "+on2pub.InputFileAudioSampleRate+"Hz"
	
	}
	
	else {AudioData = "No Audio Detected"}
	
	
	thisMovie("uploadSettings").showFileAudio(AudioData);*/
	
	
	
    // set default encoder settings
    set_encoder_settings(true, false);

    // handle playback status
    // (handle_playback() sets a timer and immediately returns)
    handle_playback();

	thisMovie("controls").filesDropped2();
	thisMovie("uploadSettings").filesDropped2();
		
    // set a timer so we can return and allow the user as much time as is
    // needed to read file warnings, if any
    warning_tid = setTimeout(
        function () {
            var show_duration_warning = false;
            if (on2pub.MaximumDuration > 0 && on2pub.InputFileDuration > on2pub.MaximumDuration)
                show_duration_warning = true;
            var show_seek_warning = false;
            if (!on2pub.InputFileCanSeek)
                show_seek_warning = true;
            show_file_warnings(show_duration_warning, show_seek_warning); },
        timeout_delay);
	
		
	
}
function filePlayed() {
    debug_str("filePlayed: received event");
    if (uploading) return;

    fp_stop();
    var play_input = fp_input_file_selected(on2pub);
    
	if (fp_play_file(play_input)) 
	{
        if (play_input) 
	    {
            show_input_file_ui();
            swap_buttons('#btn_pause_i', '#btn_resume_i');
        }
	    else 
	    {
            show_output_file_ui();
            swap_buttons('#btn_pause_o', '#btn_resume_o');
        }
    }
    on2pub.pause();
}
function filePaused() {
    $('#btn_pause_i').hide();
    show_button('#btn_resume_i');
}

//===========================================================================//
function uploadStart() {
    debug_str("uploadStart: received event");
	//magicDone = "starting upload";
}

//===========================================================================//
function uploadComplete() {
    debug_str("uploadComplete: received event");
    uploading = false;
	magicDone = true;
	//alert("magic is done");
	
    var failed = false;

    if (upload_mode >= kUploadModeHttpFormPost) {
        var http_resp = on2pub.getHttpResponse();
        
        debug_str('uploadComplete: http_resp=[<br>' + http_resp + '<br>]');
        
        if (upload_http_success_200 == true) {
            if (http_resp.indexOf("200") == -1) {
                failed = true;
            }
        }
        else if (http_resp.indexOf(upload_http_success_message) == -1) {
            failed = true; 
        }
    } 
    
    if (failed) {
        upload_attempts++;

        if (upload_attempts < upload_max_attempts) {
            on2pub.publishFile();
            return;
        } else {
            fp_show_error(on2pub, FE_TRANSFER_FAILED);
        }
    }
    
    if (failed == false) {
		
        if (upload_reload_on_success == true){
            javascript:location.reload(true);
			
		}else if (upload_next_page_success.length) {
			
            var query_str = "placeholder";
            
            try {
                query_str = get_upload_redirect_query_string(on2pub);
            } catch (e) {};
        
            if (query_str.length > 0 && query_str.charAt(0) === "?")
                document.location = upload_next_page_success + query_str;
            else                
                document.location = upload_next_page_success;
        }
    }
    
	
	
    if (upload_next_page_error.length)
        document.location = upload_next_page_error;
}
//===========================================================================//
function uploadFailed()
{
    debug_str("uploadFailed: received event");
    upload_attempts++;

    if (upload_attempts < upload_max_attempts) {
        on2pub.publishFile();
        return;
    }

    uploading = false;
    fp_show_error(on2pub, FE_TRANSFER_FAILED);

    if (upload_next_page_error.length)
        document.location = upload_next_page_error;
}

//===========================================================================//
function update_slider(current_time, duration) {
    if (duration <= 0) {
        carpeLeft('div_slider_nub', 0);
        return;
    }

    // calculate the position value
    var pos = on2pub_slider_width * current_time / duration;

    // set the slider position
    carpeLeft('div_slider_nub', pos);
}


//===========================================================================//
function change_slider_pos()
{
    var playing = is_playing();
    var infile_can_seek = on2pub.InputFileCanSeek;
    var infile_selected = fp_input_file_selected(on2pub);

    if (playing) {
    	if (isMacSafari)
    	    if (!infile_can_seek)
                return;
    	else if (infile_selected && !infile_can_seek)
            return;

        on2pub.pause();

        var carpesl = document.getElementById('slider1');

        try {
            fp_set_play_position(on2pub, carpesl.value);
        } catch (e) {};

        if (infile_selected) 
        {
            $('#btn_pause_i').hide(0);
            show_button('#btn_resume_i');
        } 
        else 
        {
            $('#btn_pause_o').hide(0);
            show_button('#btn_resume_o');
        }
    }
}

// set status strings
function set_status_strings(left, middle, right) {
    $('#status_l').html(left);
    $('#status_m').html(middle);
    $('#status_r').html(right);
}

function set_marked_str() {
    var marked_str = "";

	if (fp_input_file_selected(on2pub)) {
        var marked_ms = on2pub.EncodeTimeEnd-on2pub.EncodeTimeStart;

        if (marked_ms >= 1000 && marked_ms < on2pub.InputFileDuration)
            marked_str = "Marked: " + fp_time_to_str(marked_ms);
        else
            marked_str = "";
    }
	
    set_status_strings($('#status_l').html(), marked_str,
        $('#status_r').html());
}
/******************************************************************************
******************************************************************************/
function update_encode_status(current_time, duration) {
    // update the slider
    update_slider(current_time, duration);
	
	///////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////
	thisMovie("controls").showPos(on2pub.EncodedDuration+on2pub.EncodeTimeStart);
	///////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////
	
    var progressstr = fp_time_to_str(current_time);

    if (is_capturing() == false) {
        progressstr += '/' + fp_time_to_str(duration);
    }

    var state_string = is_capturing() ? 'Recording' : 'Transcoding';

    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 update_playback_status(current_time, duration) {
    // update the slider
    update_slider(current_time, duration);
	
	if (encodeDone!=true){
		thisMovie("controls").showPos(on2pub.PlayPosition);
	}
	else{
		thisMovie("controls").showPos(on2pub.PlayPosition+on2pub.EncodeTimeStart);
	}
	
    // create status string
    var statusstr = fp_state_to_str(on2pub);
    var infile_selected = fp_input_file_selected(on2pub);

    statusstr += infile_selected ? " (input)" : " (output)";

    // create progress string
    var progressstr = fp_time_to_str(current_time) + '/' + fp_time_to_str(duration);

    // set progress and status strings while maintaining previous 'status_m' string
    set_status_strings(statusstr, $('#status_m').html(), progressstr);

    set_marked_str();
}

/******************************************************************************
******************************************************************************/
function update_upload_status(bytes_uploaded, total_size) {
	
	////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////
	//show progress STREAM CITY SPECIFIC
	if(document.layers){	   //NN4+
    	document.layers["hideMe"].visibility = "hide";
		document.layers["progress"].visibility = "show";
    }else if(document.getElementById){	  //gecko(NN6) + IE 5+
    	var obj = document.getElementById("hideMe");
        var obj2 = document.getElementById("progress");
        obj2.style.visibility = "visible";
		obj.style.visibility = "visible";
    }else if(document.all){	// IE 4
    	document.all["hideMe"].style.visibility = "visible";
        document.all["progress"].style.visibility = "visible";
    }
	
	
    // update the slider
    update_slider(bytes_uploaded, total_size);
	
	//magicDone = bytes_uploaded;
	
    showit = function(){
		thisMovie("uploadBar").showProgress(on2pub.UploadedBytes/on2pub.UploadFileSize*500);
	}

	var interval = setInterval(showit,100)

	// create status string
    var status_str = fp_state_to_str(on2pub);

    // create progress string
    var progress_str = String(parseInt(bytes_uploaded / 1024))
        + "kB / "
        + String(parseInt(total_size /1024))
        + "kB";

    // set progress and status strings while maintaining previous 'tt_middle' string
    // tt_middle is the tt element in which the marked duration is displayed
    set_status_strings(status_str, '', progress_str);
}


/******************************************************************************
// 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;
        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;
        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;
        }
    }
}

// conditionally shows duration and InputFileCannotSeek warnings
function show_file_warnings(w_duration, w_cannot_seek) {
    clearTimeout(warning_tid);
    if (w_duration) {
        alert("Your file is longer than " + fp_time_to_minutes(on2pub.MaximumDuration)
            + " minutes, please select a subsection by moving the slider below the "
            + "image, and marking a section to encode.");
    }
    if (w_cannot_seek) {
        alert("The media file you are viewing does not allow seeking.\n"
            + " This prevents:\n"
            + "  - scrubbing/seeking through the media\n"
            + "  - selection of a subsection for transcode\n");
    }
}

function debug_str(str) {
    var cur = $('#debug_div').html();
    $('#debug_div').html(cur + '<br>' + str);
}

// set encoder settings in plug-ins and settings pane
function set_encoder_settings(b_default, b_capture) {
    if (b_default) {
        try {		
            // default the plug-in settings (to those specified in flixpub_conf.js)
            fp_set_video_settings(on2pub, b_capture, -1, -1, -1, -1, -1, -1, -1, -1, flixpub_flv_codec);
            fp_set_audio_settings(on2pub, -1, -1);
        } catch (e) {};

        // now populate the settings pane with the output settings from the plug-in
        $('#ti_bitrate_v').attr("value", on2pub.VideoBitrate);
        $('#ti_width').attr("value", on2pub.OutputFileWidth);
        $('#ti_height').attr("value", on2pub.OutputFileHeight);
        $('#cb_mar').attr("checked", true);
	
        if(!isMacSafari) {
            $('#ti_fps').attr("value", on2pub.OutputFileFrameRate);
            $('#cb_vbr').attr("checked",
                on2pub.VideoBitrateControlMode == kBitrateModeVBR);
            $('#ra_akf').attr("checked",
                on2pub.VideoKeyFrameMode == kKeyframeModeAuto);
            $('#ra_fkf').attr("checked",
                on2pub.VideoKeyFrameMode == kKeyframeModeConstFrequency);
            $('#ti_kff').attr("value", on2pub.VideoKeyFrameFrequency);
            $('#ra_q_rt').attr("checked",
                on2pub.VideoCompressMode == kCompressModeRealTime);
            $('#ra_q_g').attr("checked",
                on2pub.VideoCompressMode == kCompressModeGood);
            $('#ra_q_b').attr("checked",
                on2pub.VideoCompressMode == kCompressModeBest);
            $('#ra_nm').attr("checked",
                on2pub.AudioCodecID == kAudioCodecNellyMoser);
            $('#ra_mp3').attr("checked",
                on2pub.AudioCodecID == kAudioCodecMp3);
        }

        $('#ti_bitrate_a').attr("value", on2pub.AudioBitrate);
        show_button('#btn_apply_enc_set');
    } else {
        // video first
        var mar = $('#cb_mar').attr("checked");
        var w = parseInt($('#ti_width').attr("value"));
        var h = parseInt($('#ti_height').attr("value"));

        var dimensions = fp_get_video_dimensions(on2pub, b_capture, mar, 
            on2pub.InputFileWidth, on2pub.InputFileHeight, w, h);
            
        w = dimensions[0];
        h = dimensions[1];
        
        $('#ti_width').attr("value", w);
        $('#ti_height').attr("value", h);
        
        delete dimensions;
        
        var cm;

        if ($('#ra_q_rt').attr("checked") == true)
            cm = kCompressModeRealTime;
        else if ($('#ra_q_g').attr("checked") == true)
            cm = kCompressModeGood;
        else if ($('#ra_q_b').attr("checked") == true)
            cm = kCompressModeBest;
        
        fp_set_video_settings(on2pub, b_capture, 
            $('#ti_bitrate_v').attr("value"), w, h,
            $('#ti_fps').attr("value"), 
            $('#cb_vbr').attr("checked") == true ? kBitrateModeVBR : kBitrateModeCBR,
            $('#ra_akf').attr("checked") == true ? kKeyframeModeAuto : kKeyframeModeConstFrequency,
            $('#ti_kff').attr("value"),
            cm,
			flixpub_flv_codec);    

        // now audio 
        fp_set_audio_settings(on2pub, 
            $('#ra_mp3').attr("checked") == true ? kAudioCodecMp3 : kAudioCodecNellyMoser,
            $('#ti_bitrate_a').attr("value"));
    }
}
function is_capture() {
    // determine whether we're capturing or transcoding	
    // by using the visibility state of the hide encoder
    // settings button
    var b_capture;
    try {
        b_capture = $('#btn_hide_es_capture')
            .css("display") != "none" ? true : false;
    } catch (e) {
        b_capture = false;
    }
    return b_capture;
}
function fmsConnectionDown() {
	debug_str("fms connection down.");
}
function fmsConnectionUp() {
	debug_str("fms connection up.");
}

//STREAMCITY INTERFACE SPECIFICS

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}

// SCRUB FUNCTIONS

function jumpTo(thepos){

if (encodeDone == true){

on2pub.PlayPosition = thepos+200

}

else {

on2pub.PlayPosition = thepos

}


}

function inToOut(intime,outtime){

if (intime<0){intime = 0}
on2pub.EncodeTimeStart = intime
on2pub.EncodeTimeEnd = outtime
//alert (intime+" , "+outtime)
}


function changeRatio(which){

	if (which==16){
	
	on2pub.OutputFileWidth = 420
	on2pub.OutputFileHeight = 236
	}
	
	if (which==4){
	on2pub.OutputFileWidth = 315
	on2pub.OutputFileHeight = 236
	}
}
function setSize(width, height){

	on2pub.OutputFileWidth = width;
	on2pub.OutputFileHeight = height;
	
	on2pub.VideoBitrate = width*1.1
	
}

function audioState(value){
	
	if(value == 0){
		
		//on2pub.AudioCaptureMute = 1;
		//on2pub.AudioCaptureVolume = 0;
		//alert("muting audio");
	}else{
		
		//on2pub.AudioCaptureMute = 0;
		//on2pub.AudioCaptureVolume = 50;
		//alert("UNmuting audio");
	}
	
}

lookForName = function(){

	if (magicDirectory!=null&&magicFile!=null){
	clearInterval(hoping)
	//alert(magicDirectory)
	//alert(magicFile)
	
	upload_path_ftp = "Uploads/Assets/"+magicDirectory.toString()+"/"
	
	//alert(upload_path_ftp)
	
	}

}


var hoping=setInterval (lookForName,100)
