var Mediaplayer = new Class({

    Implements: [Options],
    modules: {},

    initialize: function(name, vars, playlist) {

        params = {wmode: 'opaque', 'allowfullscreen': true};

        this.counter = 0;
        this.name  = name;
        this.playlist = playlist;
        this.vars = vars;
        swfobject.embedSWF(VIRTUAL_URL+"_module/mediaplayer/swf/mediaplayer.swf", this.name, vars['width'], vars['height'], "8.0.0", false, vars, params);
        this.bufferPlayer.delay(150, this);
    },

    preparePlaylist: function() {
        $(this.name).sendEvent('stop');

        if (this.playlist.length == 0) {
            this._playWhenAutostart();
            return;
        }

        for (var i=0; i < this.playlist.length; i++) {
            //FIXME: foreach loop.
            $(this.name).addItem({
                file : this.playlist[i]['file'],
                image : this.playlist[i]['image'],
                info: this.playlist[i]['info'],
                author: this.playlist[i]['author'],
                title : this.playlist[i]['title']
            });
        }

        // If dummy item is stored to fix the empty playlist bug in v3:
        if ($(this.name).getLength() > this.playlist.length) {
            $(this.name).removeItem(0);
            //$(this.name).sendEvent('playitem', 0);
            $(this.name).sendEvent('stop');
        }

        this._playWhenAutostart();
    },

    _playWhenAutostart: function() {
        if (this.vars.autostart == 'true') {
            $(this.name).sendEvent('playitem', 0);
        }
    },

    playTrack: function(url, title) {
        tracks = new Object();
        tracks[0] = {
            file:  url,
            title: title
        };
        $(this.name).sendEvent('stop');
        $(this.name).loadFile({file : url, title : title});
        $(this.name).sendEvent('next');
    },

    selectTrack: function() {
        Logger.trace('not yet implemented');
    },

    addTrack: function(url, name) {
        $(this.name).addItem({file : url, title : name});
    },

    bufferPlayer: function() {
        var bException = false;

        if (this.counter == 8) {
            $(this.name).setStyle('display', 'block');
            return;
        }

        try{
            $(this.name).sendEvent('playitem', 0);
        } catch (e) {
            bException = true;
            if (e.name == 'TypeError') {
                this.counter++;
            }

            this.bufferPlayer.bind(this).delay(200);
        } finally {
            if (bException == false) {
                this.preparePlaylist();
                if ($(this.name).style.display == "none") {
                    $(this.name).style.display = "block";
                }
            }
        }
    }

});