cDoorClosed = 0;
cDoorClosing = 1;
cDoorOpening = 2;
cDoorOpened = 3;

function Door()
{
	this.state = cDoorClosed;
	this.stateTime = 0;
	this.openPos = 0;		// 0: fully closed  1: fully opened
}

Door.prototype.think = function()
{
	this.stateTime += frameTime;

	switch(this.state)
	{
	case cDoorClosed:
		break;
		
	case cDoorClosing:
		this.openPos = 1 - this.stateTime;
		if (this.stateTime >= 1)
		{
			this.openPos = 0;
			this.state = cDoorClosed;
			this.stateTime = 0;
		}
		break;
	
	case cDoorOpening:
		this.openPos = this.stateTime;
		if (this.stateTime >= 1)
		{
			this.openPos = 1;
			this.state = cDoorOpened;
			this.stateTime = 0;
		}
		break;

	case cDoorOpened:
		if (this.stateTime >= 5)
			this.close();
		break;
	}
}

Door.prototype.open = function()
{
	if (this.state != cDoorClosed)
		return;
	this.state = cDoorOpening;
	this.stateTime = 0;
}

Door.prototype.close = function()
{
	if (this.state != cDoorOpened)
		return;
	this.state = cDoorClosing;
	this.stateTime = 0;
}

Door.prototype.toggle = function()
{
	switch(this.state)
	{
	case cDoorClosed:
		this.open();
		break;
		
	case cDoorClosing:
	case cDoorOpening:
		this.state = (this.state == cDoorClosing) ? cDoorOpening : cDoorClosing;
		this.stateTime = 1 - this.stateTime;
		break;
	
	case cDoorOpened:
		this.close();
		break;
	}
}

Door.prototype.walkable = function()
{
	return this.state == cDoorOpened;
}



cSecretDoorIdle = 0;
cSecretDoorMoving = 1;

function SecretDoor(wallId, pos)
{
	this.wallId = wallId;
	this.pushPos = 0;
	this.movesLeft = 0;
	this.levelPos = pos;
	this.dPos = 0;
	this.state = cSecretDoorIdle;
	this.pushable = true;
}

SecretDoor.prototype.think = function()
{
	if (this.state == cSecretDoorIdle)
		return;
		
	this.pushPos += frameTime * 0.25;
	if (this.pushPos < 1)
		return;
		
	var levelPos = this.levelPos;
	var dPos = this.dPos;
	level[levelPos] = 0;
	delete doors[levelPos];

	levelPos += dPos;
	this.levelPos = levelPos;
	var newPos = levelPos + dPos;
	if (!this.movesLeft || level[newPos] > 0)
	{
		this.state = cSecretDoorIdle;
		this.pushPos = 0;
		level[levelPos] = this.wallId;
		if (!this.pushable)
			delete doors[levelPos];		
		return;
	}
	
	this.pushPos--;
	this.movesLeft--;
	level[newPos] = -1;
	if (doors[newPos] && doors[newPos] instanceof SecretDoor)
		this.pushable = true;
	doors[newPos] = this;
}

SecretDoor.prototype.toggle = function()
{
	if (this.state == cSecretDoorMoving)
		return;
		
	var levelPos = this.levelPos;
	var dPos = levelPos - (Math.floor(playerX) + Math.floor(playerY) * cLevelSize);
	
	if (level[levelPos + dPos])
		return;

	this.state = cSecretDoorMoving;
	this.pushPos = 0;
	this.dPos = dPos;
	this.movesLeft = 2;
	this.pushable = false;
	
	level[levelPos] = -1;
	level[levelPos + dPos] = -1;
	doors[levelPos + dPos] = this;
}

SecretDoor.prototype.walkable = function()
{
	return false;
}