/*
 * PathFinder
 * 
 * Find paths for the MotionManager
 */

/**
 * Constructor
 */
function PathFinder(motionManager, mapPaths, mapTeleporters)
{
	this.motionManager = motionManager;
	this.mapPaths = mapPaths;
	this.mapTeleporters = mapTeleporters;
	
	//Create an array which will be used to save a path
	this.computedPath = new Array(mapPaths.length);
	this.lastComputedPathTilePosition = {"x":-1, "y":-1};
	for(var i = 0; i < mapPaths.length; i++) this.computedPath[i] = new Array(mapPaths[0].length);
}

/**
 * Get the last computed path.
 *
 * @return array which contains the directions (i.e.: array[gridPosition.x][gridPosition.y]=this.motionManager.KEY_xxx)
 */
PathFinder.prototype.getComputedPath = function()
{
	return this.computedPath;
}

/**
 * Get the last computed path tile position.
 *
 * @return last computed path tile position
 */
PathFinder.prototype.getLastComputedPathTilePosition = function()
{
	return this.lastComputedPathTilePosition;
}

/**
 * Clear the array used to save the computed path.
 */
PathFinder.prototype.clearComputedPath = function()
{
	for(var row = 0; row < this.computedPath.length; row++)
	{
		for(var column = 0; column < this.computedPath[row].length; column++)
			this.computedPath[row][column] = 0;
	}
}

/**
 * Get the position of the exit teleporter.
 *
 * @param teleporterEntrancePosition position of the teleporter entrance
 */
PathFinder.prototype.getExitTeleporterLocation = function(teleporterEntrancePosition)
{
	var teleporterExitPosition = {"x":0, "y":0};
	var teleporterID = this.mapTeleporters[teleporterEntrancePosition.y][teleporterEntrancePosition.x];
	
	for(var row in this.mapTeleporters)
	{
		for(var column in this.mapTeleporters[row])
		{
			if(this.mapTeleporters[row][column] == teleporterID &&
			   !(teleporterEntrancePosition.y == row && teleporterEntrancePosition.x == column))
			{
				teleporterExitPosition.x = Number(column);
				teleporterExitPosition.y = Number(row);
				return teleporterExitPosition;
			}
		}
	}
	
	return teleporterExitPosition;
}

/**
 * Simple inherance.
 * @see http://www.sitepoint.com/blogs/2006/01/17/javascript-inheritance/
 */
function copyPrototype(descendant, parent)
{ 
	var sConstructor = parent.toString(); 
	var aMatch = sConstructor.match( /\s*function (.*)\(/ ); 
	if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; } 
	for (var m in parent.prototype)
	{ 
		descendant.prototype[m] = parent.prototype[m]; 
	} 
};

