﻿Ship.targetX = 0;

function Ship(holder)
{
    this.holder = holder;
    this.holder.Ship = this;
    
    this.init();    
}

Ship.prototype.init = function()
{
    this.height = Settings.SHIP_HEIGHT;
    this.width = Settings.SHIP_WIDTH;
    this.moveRate = Settings.SHIP_MOVE_RATE;
    this.y = Settings.SHIP_YPOS;
    this.isAlive = true;
    this.buildShip();
    this.holder.onmousedown = this.makeBullet;    
}

Ship.prototype.buildShip = function()
{
    EventCenter.addListener(this, Events.ENTER_FRAME, "onEnterFrame");
    EventCenter.addListener(this, Events.SHOT_MOVES, "checkShotHit");
    var tmp = this.ship = document.createElement('div');
    tmp.id = "_ship_";
    this.xPos = (Boundary.xMax + Boundary.xMin) / 2;
    with(tmp.style)
    {
        height = this.height + "px";
        width = this.width + "px";
        background = Settings.SHIP_IMAGE || "#444444";
        position = "absolute";
        top = this.y + "px";
        left = this.xPos + "px";
        zIndex = 1;
    }
    this.holder.appendChild(tmp);
}

Ship.prototype.onEnterFrame = function()
{
    this.holder.onmousemove = function(evt)
	{
	   Ship.targetX = Math.floor(evt.clientX - Boundary.getOffset());
	}   
	
	this.xPos = parseInt(this.ship.style.left);	
		
	if(Ship.targetX < this.xPos)
	{
	    this.xPos -= Math.min(this.moveRate, Math.abs(Ship.targetX - this.xPos));
	    if(this.xPos <= Boundary.xMin)
	    {
	        this.xPos = Boundary.xMin;
	    }
	
	     this.ship.style.left = this.xPos + "px";
	    
	}
	else if(Ship.targetX > this.xPos)
	{
	    this.xPos += Math.min(this.moveRate, Math.abs(Ship.targetX - this.xPos));
	    if(this.xPos >=  Boundary.xMax - this.width)
	    {
	        this.xPos = Boundary.xMax - this.width;
	    }
	    
	    this.ship.style.left = this.xPos + "px";
	}
	else
	{
	    this.ship.style.left =  Ship.targetX + "px";
	}
}

Ship.prototype.makeBullet = function()
{
    var x = this.Ship.xPos + this.Ship.width / 2;
    var y = this.Ship.y;
    var type = "ship";
    new Bullet(x, y, type);
}

// need to set bounds on ship
Ship.prototype.checkShotHit = function(evt)
{
    var x = evt.data.x;
    var y = evt.data.y;
    
    if(y > this.y && y < this.y + this.height)
    {
        if(x > this.xPos && x < this.xPos + this.width)
        {
            EventCenter.broadcast(Events.SHOT_HIT, evt.data.shot);
            EventCenter.broadcast(Events.SHIP_HIT, null);
            this.die();
        }
    }
}

Ship.prototype.die = function()
{
    this.holder.removeChild(this.ship);
    EventCenter.removeListener(this, Events.ENTER_FRAME, "onEnterFrame");
    EventCenter.removeListener(this, Events.SHOT_MOVES, "checkShotHit");

    if(LevelManager.LIVES > 0)
    {
        this.buildShip();
    }
}
