/*********************************
 SquareAttack - audioManager.js
 Copyright: Marcis Berzins (berzins.marcis@gmail.com), 2013
 Inspiration: http://stackoverflow.com/q/5313646
              http://stackoverflow.com/a/14022366
 This program is licensed under the terms of the GNU General Public License: http://www.gnu.org/licenses/gpl-3.0.txt
 *********************************/

function AudioManager() {
  this.SOUNDS = {
    MENU_CLICK: 'audio/menu_click.ogg',
    MOVE: 'audio/move.ogg',
    BOIL: 'audio/boil.ogg',
    PULL: 'audio/pull.ogg',
    COLLIDE: 'audio/collide.ogg',
    HIT: 'audio/hit.ogg',
    DIE: 'audio/die.ogg'
  };
  this.loadState = { count: Object.keys(this.SOUNDS).length, loaded: 0, ready: false };
  this.playing = {};
  this.init();
}

AudioManager.prototype.init = function() {
  for (var p in this.SOUNDS) {
    var a = new Audio(this.SOUNDS[p]);
    var that = this;
    a.addEventListener('canplaythrough', function loaded() {
      this.removeEventListener('canplaythrough', loaded);
      that.loadState.loaded++;
      if (that.loadState.loaded >= that.loadState.count) { that.loadState.ready = true; }
    }, false);
    this[p] = a;
  }
};

AudioManager.prototype.playSound = function(s) {
  var a = this.SOUNDS[s] + Math.random() + '';
  this.playing[a] = this[s].cloneNode(true);
  var that = this;
  this.playing[a].addEventListener('ended', function() { delete that.playing[a]; }, false);
  this.playing[a].play();
};