/*

(C)2008-2009 B-Lex IT

Soundmanager problems:
- volume setting in .createSound() and default options are ignored

*/

if (typeof blexplaybackslaves == 'undefined')
  blexplaybackslaves = [];

blexplaybackslaves.push({ name:      'blex MP3 slave'
                        , mimetypes: [ 'audio/mpeg' /* rfc3003 */
                                     ]
                        , classref:  blexMP3slave
                        , initialize: function(baseurl)
                                      {
                                        if (typeof soundManager != 'undefined' && soundManager)
                                          return;

                                        soundManager = new SoundManager(null, null, baseurl);
                                        soundManager.beginInit();
                                      }
                        }
                       );

blexMP3slave_usecount = 0;

function blexMP3slave()
{
  //blexMP3slave.prototype.usecount++;
  blexMP3slave_usecount++

  // blexMP3slave uses the global SoundManager object, so each blexMP3slave needs to use unique names
  // so we prepend each soundid with tempid
  this.tempid = blexMP3slave_usecount;

  // FIXME: this will fail in case multiple players are trying to
  //        start playback of audio before soundmanager is initialized
  var self=this;

  // _didInit = an attempt was made to initialize
  // .enabled = succesfull initialization
  if (!soundManager._didInit)
  {
    // soundManager's onload will fire if Flash reported it's ready for action
    // Flash -> s._externalInterfaceOK() -> s.init() -> s.initComplete() -> s.initUserOnload()
    soundManager.onload = function()
                          {
                            if (self.onload)
                              self.onload();
                          }
  }
}

blexMP3slave.prototype.name = 'Soundmanager2';

blexMP3slave.prototype.isabletoplay = function blexMP3slave_isabletoplay()
{
  var soundmanagerAvailable = (typeof soundManager != 'undefined');

  if (!soundmanagerAvailable)
    toddConsoleLog('Cannot play audio without soundManager.');

  return soundmanagerAvailable;
}

blexMP3slave.prototype.isready = function blexMP3slave_isready()
{
  return soundManager.enabled;
}

// stop/flush media but stay on standby for future use
blexMP3slave.prototype.flush = function(mediaid)
{
  soundManager.stop(this.mediaid);
  soundManager.destroySound(this.mediaid);
}

blexMP3slave.prototype.deactivate = function blexMP3slave_deactivate()
{
}

blexMP3slave.prototype.activate = function blexMP3slave_activate()
{
  toddConsoleLog('blexMP3slave activated');
}

// our services won't be required anymore
blexMP3slave.prototype.DeInit = function blexMP3slave_DeInit()
{
  // flush loaded media
  this.flush();

  // FIXME: is there more to cleanup?
}

blexMP3slave.prototype.SetSize = function blexMP3slave_SetSize()
{
}

blexMP3slave.prototype.loadmedia = function blexMP3slave_loadmedia(media)
{
  // prefix mediaid with tempid so it is unique
  // (soundManager uses a global list of soundid's which is used for all blexMP3slave's)
  this.mediaid = this.tempid+"_"+media.rowkey;
  toddConsoleLog('Loading media, giving it SM2 id: "'+this.mediaid+'"');

  var _player = this.playerinstance;
  var _self   = this;
  this.forcevolumehackdone = false;

  var options = {
      id:       this.mediaid
    , url:      media.url
    , autoLoad: _player.autoload
    , autoPlay: _player.autoplay

  //, volume:   this.muted ? 0 : this.volume

    , onload:       function()
                    {
                      toddConsoleLog("Mediaitem %s has finished loading.\n"
                                     +"Duration = %i", this.sID, this.duration);

                      _player.duration    = this.duration;

                      _self.isplaying = false;
                      _self.ispaused  = true; // FIXME: paused != loading
                      _self.onstatechange();

                      if (_player.onmetadata)
                        _player.onmetadata();
                    }

    , whileloading: function()
                    {
                      //console.log('sound '+this.sID+': '+this.bytesLoaded+' of '+this.bytesTotal+' bytes loaded.');
                      if (_player.whileloading)
                        _player.whileloading(this.bytesLoaded, this.bytesTotal);
                    }

    , whileplaying: function()
                    {
                      // SM2 ignores the volume in .defaultOptions and .createSound()
                      // and trying to use setVolume too early will cause setVolume not to work anymore!?
                      if (!_self.forcevolumehackdone)
                      {
                        soundManager.setVolume(_self.mediaid, _player.muted ? 0 : _player.volume);
                        _self.forcevolumehackdone = true;
                      }

                      // SM2 won't call onplay when a loaded audio autoplays
                      if (!_self.isplaying)
                      {
                        _self.isplaying = true;
                        _self.ispaused  = false;
                        _self.onstatechange();
                      }

                      _player.position = this.position;

                      _player.updatetime();

                      if (_player.cbinstance)
                        _player.cbinstance.updateposition(this.position);
                    }

    , onplay:       function()
                    {
                      _self.isplaying = true;
                      _self.ispaused  = false;
                      _self.onstatechange();
                    }

    , onpause:      function()
                    {
                      _self.isplaying = false;
                      _self.ispaused  = true;
                      _self.onstatechange();
                    }

    , onstop:       function()
                    {
                      _self.isplaying = false;
                      _self.ispaused  = false;
                      _self.onstatechange();
                    }

    , onfinish:     function()
                    {
                      _self.isplaying = false;
                      _self.ispaused  = false;
                      _self.onstatechange();
                      _player.onendofmedia();
                    }
  };

  soundManager.createSound(options);
}

blexMP3slave.prototype.onstatechange = function blexMP3slave_onstatechange()
{
  //toddConsoleLog('FLVslave internal isplaying '+this.isplaying);
  //console.log('FLVslave internal isplaying '+this.isplaying);
  this.playerinstance.isplaying = this.isplaying;
  this.playerinstance.ispaused = this.ispaused;

  if (this.playerinstance.onstatechange) // .event.
    this.playerinstance.onstatechange();
}


blexMP3slave.prototype.play = function blexMP3slave_play()
{
  soundManager.play(this.mediaid);
}

blexMP3slave.prototype.stop = function blexMP3slave_stop()
{
  soundManager.stop(this.mediaid);
}

blexMP3slave.prototype.pause = function blexMP3slave_pause(pausestate)
{
  if (pausestate)
    soundManager.pause(this.mediaid);
  else
    soundManager.resume(this.mediaid);
}

blexMP3slave.prototype.setPosition = function blexMP3slave_setPosition(milliseconds)
{
  soundManager.setPosition(this.mediaid, milliseconds);
}

blexMP3slave.prototype.setplaystate = function blexMP3slave_pause(play)
{
  if (play)
    soundManager.play(this.mediaid);
  else
    soundManager.pause(this.mediaid);
}

blexMP3slave.prototype.setVolume = function blexMP3slave_setVolume(volume)
{
  soundManager.setVolume(this.mediaid, volume);
}

blexMP3slave.prototype.setMute = function blexMP3slave_setMute(mute)
{
//  console.log('MP3 mutestate: %i (volume is %i)', mute, this.playerinstance.volume);

  // we don't use soundManager's mute/unmute, because it might be bugged(fixme: recheck)
  // internally soundManager also does mute by setting the volume
  if (mute)
    soundManager.setVolume(this.mediaid, 0);
  else
    soundManager.setVolume(this.mediaid, this.playerinstance.volume);
}

blexMP3slave.prototype.setAutoPlay = function blexMP3slave_setAutoPlay(autoplay)
{
}

if (typeof toddCurrentLoads != 'undefined')
  toddCurrentLoads["blexmediaplayer/playerslave_soundmanager.js"]=true;