/*
 * Requries: swfobject.js
 * 
 * Handles interfacing with the flash JW FLV Media player
 * Provides functionality for loading, playing, pausing, stoping of tracks in the player.
 */

$j.mediaPlayers = {}
var MediaPlayer = function() {
    return this.init.apply(this, arguments);
};
MediaPlayer.prototype = {
    swf_id: 'player1',
    container: 'media-player',
    loaded: false,  // set to true when the swf player is loaded

    init: function(swf_file, options) {
        var self = this;
        self.options = $j.extend(self, options);

        // Add the swf object for the media player
        var so = new SWFObject(swf_file, self.swf_id, '400', '20', '8');
        so.addParam('allowscriptaccess','always');
        so.addParam('allowfullscreen','true');
        so.addVariable('height','20');
        so.addVariable('width','400');
        so.addVariable('displaywidth','20');
        so.addVariable('usefullscreen','false');
        so.addVariable('backcolor','0xFFFFFF');
        so.addVariable('frontcolor','0x888888');
        so.addVariable('lightcolor','0xbbbbbb');
        so.addVariable('screencolor','0xC7CBCE');
        so.addVariable('showeq','true');
        so.addVariable('searchbar','false');
        so.addVariable('enablejs','true');
        so.addVariable('thumbsinplaylist','false');
        so.addVariable('javascriptid', self.swf_id);
        so.write(self.container);

        self.swf = $j('#' + self.swf_id)[0];
        $j.mediaPlayers[self.swf_id] =  self;
    },

    loadTrack: function(obj) {
        var self = this;
        if (!self.swf.loadFile) {
            window.setTimeout(function(){self.loadTrack(obj);}, 500);
            return;
        }
        self.swf.loadFile(obj);
    },
    
    playpause: function() {
        var self = this;
        self._sendEvent('playpause');
    },

    stop: function() {
        var self = this;
        self._sendEvent('stop');
    },

    // Receive updates from the swf object.
    _getUpdate: function(type, pr1, pr2) {
        var self = this;
        if (type == 'item') {
            if (!self.loaded) {
                self.loaded = true;
                $j(window).trigger('playerLoaded', [{id: self.swf.id}]);
            }
        }
    },

    _sendEvent: function(event) {
        var self = this;
        if (self.loaded) {
            self.swf.sendEvent(event);
        }
        else {
            $j(window).one('playerLoaded', function() {
                window.setTimeout(function(){ self.swf.sendEvent(event) }, 500);
            });
        }
    }
};  
// Return player object based on swf object
function getPlayer(swf_id) {
    return $j.mediaPlayers[swf_id];
}
// Handle update callback from the media player swf obj
function getUpdate(type,pr1,pr2,pid) {
    var player = getPlayer(pid);
    if (player) {
        player._getUpdate(type, pr1, pr2);
    }
}

