////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//////
////// Area Management
//////
var arrayAreas 				= new Array;
var currentViewingArea 		= null;
var DISTANCETOSELECTAREA	= .6;
var areAreasLoaded			= false;

function Area( id, geox,geoy,name)
{
	this.AddGroupInArea = AddGroupInArea;

	this.m_id 	= id;	
	this.m_geox = geox;
	this.m_geoy = geoy;
	this.m_name	= name;
	
	this.m_aGroups = new Array;
	
	arrayAreas[ id ] = this;
}

function AddGroupInArea( group )
{
	for ( i = 0 ; i<this.m_aGroups.length;i++)
		if ( group.m_id == this.m_aGroups[i].m_id )
			return;	// already inserted
	this.m_aGroups[ this.m_aGroups.length ] = group;
}

function onAreasLoaded( jsonArray )
{
	html="";
	if ( jsonArray != null )
	{
		//
		var oObjects = eval(jsonArray);
		//
		if ( !HasErrorProperty( oObjects) )
		{
			//
			for ( var oId in oObjects)
			{
				var oObject = oObjects[oId];				
				new Area( oObject.m_id, oObject.m_geoy, oObject.m_geox, oObject.m_name );				
			}
		}	
	}
	areAreasLoaded = true;	
}

function LoadAllAreas()
{
	DAO( DAOAPI_GETALLAREAS, "onAreasLoaded", null);  
}

function findAreaById( id )
{
	if ( arrayAreas != null )	
	for ( var oId in arrayAreas)
	{
		var oArea = arrayAreas[oId];
		if ( oArea.m_id == id )
			return oArea;
	}
	return null;
}

function executeForEachArea( callback )
{
	if ( arrayAreas != null )	
	for ( var oId in arrayAreas)
	{
		var oArea = arrayAreas[oId];
		callback( oArea );
	}
}

//
// Search if there is a known area next to the center of the map
//
function lookupViewingArea( x, y )
{
	if ( arrayAreas != null )	
	for ( var oId in arrayAreas)
	{
		var oArea = arrayAreas[oId];
		if ( oArea != null )
		{
			distanceToArea = 
				( x - oArea.m_geox )*( x - oArea.m_geox ) +
				( y - oArea.m_geoy )*( y - oArea.m_geoy );
			//alert( distanceToArea +" to " + oArea.m_name );
			if ( distanceToArea < DISTANCETOSELECTAREA )
			{
				if ( currentViewingArea != oArea )
				{
					currentViewingArea  = oArea;
				}
				return distanceToArea;
			}
		}
	}
	if ( currentViewingArea != null )
	{
		currentViewingArea = null;
	} 
	return 0;
}


