////////////////
// MP3 Player //
////////////////
tr.player = function(){
  psid = 0;
  DEFAULT_VOLUME = 50;
  
  return {
    
    /**
    * 
    * @function ?
    */
    playStatic : function(){
      if (this.staticSound) this.staticSound.stop();
      this.staticSound = soundManager.createSound({
        id       : 'static' + psid++,
        url      : '/radio' + Math.ceil(Math.random()*3).toString() + '.mp3',
        volume   : 15,
        stream   : false,
        autoPlay : false,
        onload   : function(){
          this.setPosition(Math.ceil(Math.random()*10000));
        },
        onfinish : function(){
          this.play();
        }
      });
      this.staticSound.play();
    },
    
    /**
    * current volume
    **/
    getVolume : function(){
      return this.volume || DEFAULT_VOLUME;
    },
    
    /**
    * play the next track
    **/
    play : function(){
      var tweets = tr.data.unplayedTweets().clone();
      // go get more tweets when we get down to 5
      if (tweets.size() < 5) {
        tr.twitter.refresh();
      }
      tweets.size() > 0 ? this._play(tweets) : setTimeout(this.play.bind(this), 1000);
    },
    
    /**
    * really play the next track
    **/
    _play : function(tweets){
      // construct a new sound and play it 
      var _procede = function(tweet){
        var sound = soundManager.createSound({
          id       : 'sound_' + psid++,
          url      : tweet.url(),
          volume   : this.getVolume(),
          autoPlay : true,
          onload   : function(){
            if (this.loaded && this.duration > 0) {
              tr.player.staticSound.stop();
              return tweet.addToCrawler();
            }
            tweet.convert();
		        if (tr.data.unplayedTweets().size() < 3) {
              tr.log('running low on tweets...time to refresh');
		          tr.twitter.refresh();
            }
            setTimeout(tr.player._play.bind(tr.player, tweets), 0);
            return true;
          },
          onfinish : function(){
            tweet.played = true;
		        if (tr.data.unplayedTweets().size() < 3) {
              tr.log('running low on tweets...time to refresh');
		          tr.twitter.refresh();
            }
            tr.player.playStatic();
            setTimeout(tr.player._play.bind(tr.player, tweets), 2000);
          }
        });
        sound.play();
      }.bind(this);
      
      tweet = tweets.pop();
      tweet ? _procede(tweet) : setTimeout(this.play.bind(this), 1000);
    }
  };
}();