﻿Bullet.bullets = new Array();

function Bullet(xPos, yPos, type) 
{
if(type == "ship")
{
    //trace("bullet -- ship");
   // trace("__" + xPos + " " + yPos);
}
    this.xPos = xPos;
    this.yPos = yPos;
    this.type = type.toLowerCase();
    this.holder = $("gameHolder"); // hacky!
    this.height = Settings.BULLET_HEIGHT;
    this.width = Settings.BULLET_WIDTH;
    this.offset = (type == "ship") ? 0 : -1;
    this.rate = (type == "ship") ? Settings.SHIP_SHOT_RATE : Settings.ENEMY_SHOT_RATE;
    this.rate *= (type == "ship") ? -1 : 1;
    
    EventCenter.addListener(this, Events.ENTER_FRAME, "onEnterFrame");
    EventCenter.addListener(this, Events.SHOT_HIT, "shotHit");
    
    this.makeBullet();
}

Bullet.prototype.makeBullet = function()
{
    var blt = this.bullet = document.createElement('div');
    blt.id = Bullet.bullets.length + "_bullet_";
    with(blt.style)
    {
         background = Settings.SHOT_IMAGE || "#123456";
         height = this.height + "px";
         width = this.width + "px";
         position = "absolute";
         left = this.xPos - this.width / 2 + "px";
         top = this.yPos+ this.offset * this.height + "px";
    }
    
    this.holder.appendChild(blt);
    Bullet.bullets.push(this);
}
Bullet.prototype.onEnterFrame = function()
{
    var blt = this.bullet;
    var yPos = parseInt(blt.style.top);
    yPos += this.rate;
    if(this.type == "ship")
    {
        if(yPos < Boundary.yMin)
        {
            this.die();
        }
    }
    else
    {
        if(yPos > Boundary.yMax - this.height)
        {
            this.die()
        }
    }
    
    blt.style.top = yPos + "px";
    EventCenter.broadcast(Events.SHOT_MOVES, {shot:this, x:parseInt(blt.style.left), y:yPos, type:this.type});
}

Bullet.prototype.shotHit = function(evt)
{
    if (evt.data == this)
    {
        this.die();
    }
}

Bullet.prototype.die = function()
{   
    if(this.bullet)
    {
        EventCenter.removeListener(this, Events.ENTER_FRAME, "onEnterFrame");
        EventCenter.removeListener(this, Events.SHOT_HIT, "shotHit");
        
        this.holder.removeChild($(this.bullet.id));
        delete Bullet.bullets[parseInt(this.bullet.id)]
        
        for(var i in this)
        {
            delete this[i];
        }
    }
}
