var KalturaUploader;

var KALTURA_ENTRY_READY = 'kaltura_entry_ready',
    KALTURA_ENTRY_CLEARED = 'kaltura_entry_cleared',
    KALTURA_ENTRY_ADDED = 'kaltura_entry_added',
    KALTURA_FILE_SELECTED = 'kaltura_file_selected',
    KALTURA_FILE_BROWSE = 'kaltura_file_browse',
    KALTURA_ENTRY_SUBMITTING = 'kaltura_entry_submitting';
    
RECORDER_PRESENT = false;

var KalturaUploaderDelegate = {
    readyHandler: function () {
        KalturaUploader = document.getElementById('uploader'); // Do it the DOM way.
        KalturaUploader.setMediaType('video'); // Defaults to 'image'
        
        // console.log('Kaltura Uploader Ready.');
    },
    
    selectHandler: function (arguments) {
        // console.log('Kaltura Uploader: File(s) Selected');
        
        filename = KalturaUploader.getFiles()[0].title
        $('#upload .filename').html(filename);
        $('#upload').removeClass('choose')
        $('#upload').addClass('selected');
        $('#uploader').css({
            height: '1px'
        });
        $('#upload .confirm').show();
        $('#upload .confirm a.continue').bind('click', function () {
            $('#upload .confirm').hide();
            KalturaUploader.upload();
            return false;
        });
        
        $('#upload .confirm a.cancel').bind('click', function () {
            $('#upload .confirm').hide();
            $('#upload').removeClass('selected');
            $('#upload .filename').html('');
            
            $(document).trigger(KALTURA_ENTRY_CLEARED);
            
            create_kaltura_uploader();
            return false;
        });
    },
    
    singleUploadCompleteHandler: function () {
        // console.log('Kaltura Uploader: File upload complete.');
    },
    
    allUploadsCompleteHandler: function () {
        // console.log('Kaltura Uploader: All file(s) complete.');
        var progress = ['<b>100%</b><br />Upload Successful!'].join(' ');
        $('#upload .progress').html(progress);
        $(document).trigger(KALTURA_ENTRY_READY);
    },
    
    entriesAddedHandler: function (entries) {
        // console.log('Kaltura Uploader: ', entries.length, ' Entries Added');
        var entry = entries[0];
        if (typeof entry !== 'undefined' && entry.entryId.length) {
            $(document).trigger(KALTURA_ENTRY_ADDED, [entry.entryId]);
        }
    },
    
    progressHandler: function (transfer) {
        var total = transfer[1],
            sent = transfer[0],
            file = transfer[2];
        var percentage = parseInt((sent / total) * 100);
        var progress = ['<b>', percentage, '%', '</b><br />Uploading...'].join('');
        $('#upload .progress').html(progress);
    },
    
    uiConfErrorHandler: function () {
        // console.log('Kaltura Uploader: UI Configration Error.');
    }
};

function submit_entry () {
    $(document).trigger(KALTURA_ENTRY_SUBMITTING);
    KalturaUploader.addEntries();
};

function upload_file_selected () {
    return typeof KalturaUploader !== 'undefined' ? KalturaUploader.getFiles().length > 0 : false;
};

function toggle_browse_enabled () {
    // console.log('Kaltura Uploader: Preventing Upload');
    $('#upload .prevent').css('top', '100px');
    $('#upload .prevent').bind('click', function (event) {
        interrupt = confirm_interrupt_recorder()
        if (interrupt) {
            create_kaltura_uploader();
        };
    });
}

function confirm_interrupt_upload () {
    interrupt = false;
    if (upload_file_selected()) {
        interrupt = confirm('Are you sure you want to record a video instead of uploading a file?');
        if (interrupt) {
            // console.log('KalturaRecorder: Interrupting file upload.');
            create_kaltura_uploader();
        } else {
            // console.log('KalturaRecorder: Interrupting recorder launch.');
            recorder.PREVENT_LAUNCH = true;
        }
    }
    return interrupt;
}

function confirm_interrupt_recorder () {
    interrupt = confirm('Choosing a file now will close the video recorder.');
    if (interrupt) {
        // console.log('KalturaRecorder: Interrupting recorder.');
        RECORDER_PRESENT.unload();
    }
    return interrupt;
}

function create_kaltura_uploader () {
    var params = {
        allowScriptAccess: 'always',
    	allowNetworking: 'all'
    }, flashvars = {
        conversionProfile: 5,
        uiConfId: '11500',
        maxUploads: 1,
        subPId: '3116000',
        host: 'http://www.kaltura.com',
        jsDelegate: 'KalturaUploaderDelegate',
        kshowid: -1,
        entryId: -2,
        partnerId: '31160',
        Permissions: 1
    }, attributes = {
        wmode: 'transparent'
    }, id = 'uploader';
    
    if (typeof KalturaUploader !== 'undefined') {
        // console.log('Kaltura Uploader: Unloading');
        var container = $('#upload');
        container.attr('class', '');
        $('.confirm, .progress', container).hide();
        swfobject.removeSWF(id);
        $(['<div id="', id, '"></div>'].join('')).prependTo(container);
        KalturaUploader = undefined;
    }

    $.extend(flashvars, KalturaClient.session);

    swfobject.embedSWF('http://www.kaltura.com/kupload/ui_conf_id/11500', id, 320, 240, '9.0.0', null, flashvars, params, {wmode:'transparent'});
    
    $('#upload .prevent').css('top', '-1000px');
    
    $('#'+id).bind('click', function (event) {
        // console.log('Kaltura Uploader: Browsing Files.');
        $(document).trigger(KALTURA_FILE_BROWSE, KalturaUploader);
    });
    
    try {
        $(document).bind(KALTURA_RECORD_INIT, function (event, recorder) {
            // console.log('Kaltura Uploader: Recorder Present: **Initializing**: ', recorder);
            confirm_interrupt_upload();
            RECORDER_PRESENT = recorder;
            toggle_browse_enabled();
        });
    } catch (e) {
        // Set IS_UPLOADER_PRESENT = false;
    };
};

$(document).bind(KALTURA_SESSION_START, function (event, args) {
    if (swfobject.hasFlashPlayerVersion('9.0.0')) {
        create_kaltura_uploader();

        // Combine into event and handle click elsewhere
        $('#id-submit').bind('click', function () {
            // console.log('Kaltura Uploader: Submit Clicked.');
            if (upload_file_selected()) {
                submit_entry();
            }
        });
    } else {
        $('#upload').addClass('incompatible');
    }
});