var Mp3Player = function(cid, fid, src) {
  this.$container = $("#"+cid);
  this.flashId = fid;
  this.src = src;

  this.flashObject = null;

  this.$play = $(".play", this.$container);
  this.$stop = $(".stop", this.$container);

  this.$time = $(".time", this.$container);
  this.timeIsSet = (this.$time.html() != "");

  this.$lineContainer = $(".line-container", this.$container)
  this.$line = $("ins", this.$lineContainer);
  this.lineWidth = this.$lineContainer.width();
  // TODO: sound control

  var that = this;
  this.listener = new Object();
  this.listener.onInit = function() { this.position = 0; }
  this.listener.onUpdate = function() {
    var isPlaying = (this.isPlaying == "true");
    if (isPlaying) that.$play.addClass("pause")
    else that.$play.removeClass("pause");
    that.$line.width(that.lineWidth*this.position/this.duration);
    if (!that.timeIsSet) that.setTime(Math.round(this.duration/1000));
  }

  return this.setup();
}
Mp3Player.prototype = {
  setup: function() {
    var self = this;
    this.$play.click(function() { self.togglePlay(); });
    this.$lineContainer.click(function(event) { self.setPosition(event); });
    return this;
  },
  getFlashObject: function() {
    if (!this.flashObject) this.flashObject = $("#"+this.flashId).get(0);
    return this.flashObject;
  },
  setTime: function(length) {
    var mm = Math.floor(length/60);
    var ss = length%60;
    if (/^\d$/.test(ss)) ss = "0"+ss;
    this.$time.html(mm+":"+ss);
    return this;
  },
  isPlaying: function() {
    return (this.listener.isPlaying == "true");
  },
  togglePlay: function() {
    if (this.isPlaying()) this.pause()
    else this.play();
    return this;
  },
  play: function() {
    if (this.listener.position == 0) this.getFlashObject().SetVariable("method:setUrl", this.src);
    this.getFlashObject().SetVariable("method:play", "");
    this.getFlashObject().SetVariable("enabled", "true");
    return this;
  },
  pause: function() {
    this.getFlashObject().SetVariable("method:pause", "");
    return this;
  },
  stop: function() {
    this.getFlashObject().SetVariable("method:stop", "");
    return this;
  },
  setPosition: function(event) {
    event = event || window.event;
    var mouseX = mousePos(event).x - Math.round(this.$lineContainer.offset().left);
    if (mouseX < 0) mouseX = 0;
    if (mouseX > this.lineWidth) mouseX = this.lineWidth;
    var relMouseX = mouseX/this.lineWidth;
    var position = this.listener.duration*relMouseX;
    this._setValue("Position", position);
    return this;
  },
  _setValue: function(name, value) {
    this.getFlashObject().SetVariable("method:set"+name, value);
    return this;
  }
}

