var KALTURA_RECORD_START = 'kaltura_record_start',
    KALTURA_RECORD_END = 'kaltura_record_end',
    KALTURA_RECORD_SUCCESS = 'sdpiuha98adshf',
    KALTURA_ERROR = 'kaltura_error',
    KALTURA_RECORD_INIT = 'kaltura_record_init',
    KALTURA_RECORD_READY = 'AoihSOPIJDOJ9as9',
    KALTURA_PREVIEW_START = 'kaltura_preview_start',
    KALTURA_PREVIEW_END = 'kaltura_preview_end',
    KALTURA_CAMERA_DETECTED = 'kaltura_camera_detected',
    KALTURA_CONNECTING = 'kaltura_connecting',
    KALTURA_CONNECTED = 'kaltura_connected',
    KALTURA_ENTRY_READY = 'kaltura_entry_ready',
    KALTURA_ENTRY_CLEARED = 'kaltura_entry_cleared',
    KALTURA_ENTRY_ADDED = 'kaltura_entry_added',
    KALTURA_ENTRY_SUBMITTING = 'kaltura_entry_submitting';

var KalturaRecorder = {
    settings: {
        container: '#record',
        indicator: '#record .indicator',
        controls: {
            container: '#record .controls',
            record: '.record',
            playback: '.playback'
        },
        submit: '#id-submit',
        camera: 'camera',
        min_flash_version: '9.0.0',
        width: 320,
        height: 240,
        src: '/media/swf/krecord.swf',
        auto_preview: false
    },
    indicator: null, controls: null, help: null,
    status: null, runtime: null,
    container: null, session: null,
    camera: null,
    IS_UPLOADER_PRESENT: true,
    PREVENT_LAUNCH: false,
    
    initialize: function (session) {
        if (swfobject.hasFlashPlayerVersion('9.0.0') && this.store_session(session)) {
            this.container = $(this.settings.container);
            this.indicator = $(this.settings.indicator);
            this.controls = {
                container: $(this.settings.controls.container)
            };
            this.controls.record = $(this.settings.controls.record, this.controls.container);
            this.controls.playback = $(this.settings.controls.playback, this.controls.container);
            
            this.controls.container.hide();
            this.indicator.hide();
            
            this.help = $('.help', this.container);
            
            // // console.log(this.indicator);
            // // console.dir(this.controls);
            
            this.assign_events();
            this.set_status('initializing');
        } else {
            // console.log('Kaltura Recorder: Error.');
            this.container.addClass('incompatible');
        };
        
        this.PREVENT_LAUNCH = false;
    },
    
    get_runtime_minutes: function () {
        return this.runtime ? parseInt(this.get_runtime_seconds() / 60) : 0;
    },
    
    get_runtime_seconds: function () {
        return this.runtime ? parseInt(this.runtime / 1000) : 0;
    },
    
    get_runtime: function () {
        return this.runtime ? [this.get_runtime_minutes(), this.get_runtime_seconds()].join(':') : '0:00';
    },
    
    set_status: function (status) {
        switch (status) {
            case 'initializing':
            case 'idle':
            case 'recording':
            case 'recorded':
            case 'previewing':
            case 'uploading':
                this.status = status;
                // // console.log('Kaltura Recorder Status: ', status);
            default:
                break;
        };
        this.redraw_controls();
        this.redraw_indicator();
    },
    
    rerecord: function () {
        // // console.log('Kaltura Recorder: Re-recording');
        redo = window.confirm('You have already recorded your video. Your existing video will be overwritten if you continue.');
        if (redo) {
            this.runtime = null; // Clear out the recorded video.
            this.set_status('idle');
            
            $(document).trigger(KALTURA_ENTRY_CLEARED);
            
            // Start recording again.
            this.record();
        }
    },
    
    addentry: function () {
        var date = new Date(),
            name = ['wc', date.getTime()].join('_');
        this.camera.addEntry(name, '', '', '', '', -1, '', 'CC-0.1', '', '', '');
    },
    
    record: function () {
        switch (this.status) {
            case 'idle':
                // console.log('Kaltura Recorder: Starting Recording.');
                this.camera.startRecording();
                break;
            case 'recording':
                // console.log('Kaltura Recorder: Stopping Recording.');
                this.camera.stopRecording();
                break;
            default:
                // console.log('Kaltura Recorder: Not Recording: ', this.status);
                break;
        }
    },
    
    preview: function () {
        // console.log('Kaltura Recorder: Playing back preview.');
        this.set_status('previewing');
        this.camera.previewRecording();
    },
    
    redraw_indicator: function () {
        switch(this.status) {
            case 'recording':
                this.indicator.addClass('on');
                break;
            case 'idle':
            case 'recorded':
            case 'previewing':
            case 'uploading':
                this.indicator.show();
                this.indicator.removeClass('on');
            case 'initializing':
            default:
                break;
        }
    },
    
    redraw_controls: function () {
        if (this.status !== 'initializing') {
            this.controls.container.show();
        };
        
        this.help.html('');
        
        switch (this.status) {
            case 'idle':
                this.controls.playback.addClass('disabled');
                this.controls.record.removeClass('disabled');
                this.help.html('Click the red button to record');
                break;
            case 'recording':
                this.controls.record.addClass('stop');
                this.controls.playback.addClass('disabled');
                this.help.html('Recording...')
                break;
            case 'recorded':
                this.controls.record.removeClass('stop');
                this.controls.record.removeClass('disabled');
                this.controls.playback.removeClass('disabled');
                this.help.html('To preview your video, click the play button.')
                break;
            case 'uploading':
                this.controls.record.removeClass('stop');
                this.controls.playback.addClass('disabled');
                this.controls.record.addClass('disabled');
                break;
            case 'previewing':
                this.controls.record.removeClass('stop');
                this.controls.playback.addClass('disabled');
                this.controls.record.addClass('disabled');
                break;
            case 'initializing':
            default:
                break;
        };
    },
    
    assign_events: function () {
        var recorder = this;
        
        // console.log('Kaltura Recorder: Binding: ', this);
        
        recorder.container.bind('click', function () {
            // console.log('Kaltura Recorder: Engaged.');
            $(document).trigger(KALTURA_RECORD_INIT, KalturaRecorder);
            recorder.build();
        });
        
        recorder.controls.playback.bind('click', function () {
            // console.log('Kaltura Recorder: Playback Button Clicked.');
            
            switch (recorder.status) {
                case 'recorded':
                    // Playback (Preview)
                    recorder.preview();
                    break;
                case 'idle':
                case 'recording':
                case 'previewing':
                case 'uploading':
                case 'initializing':
                default:
                    // Do Nothing
                    break;
            };
        });
        
        recorder.controls.record.bind('click', function () {
            // console.log('Kaltura Recorder: Record Button Clicked.');
            
            switch (recorder.status) {
                case 'idle':
                case 'recording':
                    recorder.record();
                    break;
                case 'recorded':
                    recorder.rerecord();
                    break;
                case 'previewing':
                case 'uploading':
                case 'initializing':
                default:
                    break;
            };
        });
        
        // TODO: Move any conditional functionality from here to the set_status method.
        $(document).bind(KALTURA_RECORD_START, function () {
            recorder.set_status('recording');
        });
        
        $(document).bind(KALTURA_PREVIEW_END, function () {
            recorder.set_status('recorded');
        })
        
        $(document).bind(KALTURA_RECORD_READY, function () {
            // console.log('Kaltura Recorder: Ready.');
            recorder.container.removeClass('connected');
            recorder.container.addClass('ready');
            recorder.ready();
        });
        
        $(document).bind(KALTURA_RECORD_SUCCESS, function () {
            recorder.runtime = recorder.camera.getRecordedTime();
            // console.log('Kaltura Recorder: Record Success. Runtime: ', recorder.runtime);
            $(document).trigger(KALTURA_ENTRY_READY);
            recorder.set_status('recorded');
        });
        
        $(document).bind(KALTURA_CAMERA_DETECTED, function () {
            recorder.container.removeClass('detecting');
            recorder.container.addClass('connecting');
        });
        
        // Combine into event and handle click elsewhere
        $(recorder.settings.submit).bind('click', function () {
            // FIXME: Refactor double video check
            if (recorder.runtime) {
                // console.log('Kaltura Recorder: File is present: ', recorder.get_runtime());
                // console.log('Kaltura Recorder: Submit.');
                $(document).trigger(KALTURA_ENTRY_SUBMITTING);
                recorder.addentry();
            } else {
                // // console.log('Kaltura Recorder: File is not present: ', recorder.runtime);
            };
        });

        try {
            $(document).bind(KALTURA_FILE_BROWSE, function (event, uploader) {
                // // console.log('Kaltura Recorder: Uploader Present: **File being browsed** ', uploader);
                if (recorder.camera) {
                    interrupt = confirm('Are you sure you want to upload a file insead of recording a video?');
                    if (interrupt) {
                        // console.log('KalturaRecorder: Interrupting recorder.');
                        recorder.unload();
                    } else {
                        // console.log('KalturaRecorder: Interrupting file upload.');
                    }
                }
            });
        } catch (e) {
            recorder.IS_UPLOADER_PRESENT = false;
        };
    },
    
    unload: function () {
        // console.log('Kaltura Recorder: Unloading Recorder.');
        this.initialize(this.session);

        this.runtime = null;
        this.status = null;
        this.runtime = null;
        this.camera = null;
        
        this.container.removeClass('detecting connecting');

        swfobject.removeSWF(this.settings.camera);
        
        // Recreate Camera Container (It was just removed by removeSWF). 
        // Preserve stacking order with prependTo.
        $(['<div id="', this.settings.camera, '"></div>'].join('')).prependTo(this.container);
    },
    
    store_session: function (session) {
        if (typeof session !== 'undefined' && typeof session.ks !== 'undefined') {
            this.session = session;
            return true;
        } else {
            // Do Something. Session KS not defined. Can't continue.
        }
        return false;
    },
    
    build: function () {
        var recorder = KalturaRecorder;
        if (recorder.camera === null && !recorder.PREVENT_LAUNCH) {
            // console.log('Kaltura Recorder: Building. ', recorder.PREVENT_LAUNCH);
            
            recorder.container.addClass('detecting');
            
            var s = recorder.settings;
            var flashvars = {
                host: 'www.kaltura.com',
                cdnHost: 'cdn.kaltura.com',
                autoPreview: 'false',
                kshowid: '-1'
            }, params = {
                swliveconnect: 'true',
                allowScriptAccess: 'always',
                allowfullscreen: 'false'
            }, attributes = {
                wmode: 'transparent'
            };
            $.extend(flashvars, recorder.session);
            
            // // console.dir(s);
            // // console.dir(flashvars);
            // // console.dir(params);
            // // console.dir(attributes);
            
            swfobject.embedSWF(s.src, s.camera, s.width, s.height, s.min_flash_version, null, flashvars, params, attributes);
            
            recorder.camera = $('#'+s.camera); // Set before 'ready' gets called so that it can be hidden.
            
            recorder.container.unbind('click');
            recorder.container.css({
                'cursor': 'inherit'
            })
        } else {
            // console.log('Kaltura Recorder: Not Building: Camera: ', recorder.camera, ', PREVENT_LAUNCH: ', recorder.PREVENT_LAUNCH);
            // Don't do anything.
        };
        
        recorder.PREVENT_LAUNCH = false;
    },
    
    ready: function () {
        // this.show_camera();
        this.camera = document.getElementById(this.settings.camera);
        this.set_status('idle');
        this.set_quality(0, 0, 320, 240, 20);
    },
    
    set_quality: function (quality, bandwidth, width, height, fps) {
        this.camera.setQuality(quality, bandwidth, width, height, fps);
    }
};

$(document).bind(KALTURA_SESSION_START, function (event, args) {
    KalturaRecorder.initialize(args);
});

// Mqp Kaltura Events
function connected () {
    // console.log('Kaltura Recorder: Connected.');
    $(document).trigger(KALTURA_CONNECTED);
    $(document).trigger(KALTURA_RECORD_READY);
};

function recordStart () {
    // console.log('Kaltura Recorder: Started Recording.');
    $(document).trigger(KALTURA_RECORD_START);
};

function deviceDetected () {
    // console.log('Kaltura Recorder: Device Detected.');
    $(document).trigger(KALTURA_CAMERA_DETECTED);
    $(document).trigger(KALTURA_CONNECTING);
};

function flushComplete () {
    // console.log('Kaltura Recorder: Flush Complete.');
    $(document).trigger(KALTURA_RECORD_SUCCESS);
};

function previewEnd () {
    // console.log('Kaltura Recorder: Preview End');
    $(document).trigger(KALTURA_PREVIEW_END);
};

function addEntryFail (error) {
    // console.log('Kaltura Recorder: Add Entry Failed.');
    $(document).trigger(KALTURA_ERROR, ['add_entry_failed', error]);
};

function addEntryComplete (entry) {
    // console.log('Kaltura Recorder: Add Entry Complete');
    $(document).trigger(KALTURA_ENTRY_ADDED, [entry.entryId]);
};
