function Sprite(image, x, y, width, height)
{
  this._init(image, x, y, width, height);
}

Sprite.prototype =
{
  _init : function(imageName, x, y, width, height)
  {
    this._image = new Image();
    this._image.src = imageName;
    this._x = x;
    this._y = y;
    this._width = width;
    this._height = height;
    this.jump = null;
    this._jump = null;
    this.atBounds = false;
  },

  draw : function(ctx)
  {
    ctx.drawImage(this._image, this._x, this._y, this._width, this._height);
  },

  updateJump : function(dy)
  {
    if (this.jump != null) {
      if (this._jump == null)
        this._jump = this.jump;
      dy += this._jump;
      this._jump += 0.1;
    }
    if (this._jump >= -this.jump) {
      this.jump = null;
      this._jump = null;
    }
    return dy;
  },

  move : function(dx, dy, yend)
  {
    this._x += dx;
    this._y += this.updateJump(dy);
    this.atBounds = (this._x <= 0) || (this._x + this._width >= yend);
  },

  jump : function()
  {
    this._jump = -7;
  }

};


function Monster(ctx)
{
  this._init(ctx);
};

Monster.prototype =
{
  _init : function(ctx)
  {
    if (ctx)
      this.ctx = ctx;
    if (this.interval) {
      clearInterval(this.interval);
      this.interval = null;
    }
    this.width = $("#canvas").width();
    this.height = $("#canvas").height();

    var spriteWidth = this.width/4;
    var spriteHeight = this.height/3;
    self = this;
    this.player = new Sprite("Player.png",
                             1, this.height - spriteHeight,
                             spriteWidth, spriteHeight);
    this.enemy = new Sprite("Enemy.png",
                            this.width - spriteWidth - 1, this.height - spriteHeight,
                            spriteWidth, spriteHeight);

    self.background = new Image();
    self.background.onload = function() {
      self.interval = setInterval(function(){self.update();}, 30);
    };
    self.background.src="Background.png";
  },

  draw : function()
  {
    this.ctx.drawImage(this.background, 0, 0, this.width, this.height);
    this.player.draw(this.ctx);
    this.enemy.draw(this.ctx);
  },

  onclick : function()
  {
    if (this.player.atBounds && this.enemy.atBounds)
      this._init()
    else
      this.player.jump = -7;
  },

  update : function()
  {
    if (!this.player.atBounds)
      this.player.move(1, 0, this.width);
    if (!this.enemy.atBounds)
      this.enemy.move(-1, 0, this.width);
      this.draw();
    if (this.player.atBounds && this.enemy.atBounds) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
};

