/**
@author bibby
The all seeing eye. An object that tracks elements and their locations
to detect and allow/prevent collisons.
**/

var Contact = {
	
	elements:{
		
	},
	
	register:function(elm,type)
	{
		if(!is(this.elements[type],'object'))
			this.elements[type]={};
		
		this.elements[type][elm.id]=elm;
		this.update(elm);
	},
	
	map:{},
	
	update:function(elm)
	{
		this.map[elm.id]=elm.area();
	},
	
	// object seeking permission to relocate
	mayMove:function(area,id,movedata)
	{
		// check map for other objects.
		var objects = this.getObjectsWithin(area, id);
		if(objects.length == 0)
			return true;
		
		var move = null; 
		objects.each(function()
		{
			var o = Contact.getObject(this);
			switch(o[1])
			{
				case 'Char':
					move = false;
					break;
				case 'Block':
					switch(o[0].moveable)
					{
						case true:
							if(is(move,'null'))
							move = o[0].move(movedata[0],movedata[1]);
						break;
						default:
							move=false;
							break;
					}
					break;
			}
		});
		return move;
	},
	
	/**
	@param array area [x1,y1,x2,y2]
	@param string object id of the seeker (to ignore for findging other objects)
	*/
	getObjectsWithin:function(area,seeker)
	{
		var ret=[];
		var corners,c;
		for(i in this.map)
		{
			if(i==seeker)
				continue;
			
			corners = this.corners(area);
			
			do
			{
				c = corners.current();
				if( this.map[i][0] <= c[0] && this.map[i][1] <= c[1] && this.map[i][2] >= c[0] && this.map[i][3] >= c[1])
				{
					ret.push(i);
					break;
				}
				
			}while(corners.next()!==false);
			
		}
		
		return ret;
	},
	
	
	getObject:function(id)
	{
		for(type in this.elements)
		{
			if(is(this.elements[type][id]))
				return [this.elements[type][id],type];
		}
	},
	
	//converts area into it's four XYs
	//[x1,y1,x2,y2]
	
	corners:function(area)
	{
		return [ 
			[area[0],area[1]], 
			[area[0],area[3]],
			[area[2],area[1]],
			[area[2],area[3]],
			];
	}
};

