void LocationEditor::AdvanceModeBuilding()
{
	BuildingEditWindow *ew = (BuildingEditWindow *)EclGetWindow("editor_buildingid");
	if (ew && EclMouseInWindow(ew))	return;
	
	Camera *cam = g_app->m_camera;

	// Find the ID of the building the user is clicking on
	int newSelectionId = -1;
	if ( g_inputManager->controlEvent( ControlTileSelect ) )
	{
		Vector3 rayStart, rayDir;
		cam->GetClickRay( g_target->X(), g_target->Y(), &rayStart, &rayDir );
		newSelectionId = DoesRayHitBuilding(rayStart, rayDir);
	}

	if (m_selectionId == -1)
	{
		// If there isn't currently any selection, then check for a new one
		if (newSelectionId != -1)
		{
			m_selectionId = newSelectionId;
			BuildingsCreateWindow *cw = (BuildingsCreateWindow*)EclGetWindow("editor_buildings");
			AppDebugAssert(!ew);
			AppDebugAssert(cw);
			BuildingEditWindow *bew = new BuildingEditWindow("editor_buildingid");
			bew->m_w = cw->m_w;
			bew->m_h = 140;
			bew->m_x = cw->m_x;
			EclRegisterWindow(bew);
			bew->m_y = cw->m_y - bew->m_h - 10;
			m_waitingForRelease = true;

            Location *location = g_app->m_location;
		    Building *building = location->GetBuilding(m_selectionId);            
            if( building->m_type == Building::TypeTree )
            {
                TreeWindow *tw = new TreeWindow( "editor_treeditor" );
                tw->m_w = cw->m_w;
                tw->m_h = 230;
                tw->m_y = bew->m_y - tw->m_h - 10;
                tw->m_x = bew->m_x;
                EclRegisterWindow( tw );
            }
		}
	}
	else 
	{
		Location *location = g_app->m_location;
		Building *building = location->GetBuilding(m_selectionId);
	
		
		if ( g_inputManager->controlEvent( ControlTileSelect ) )                  // If left mouse is clicked then consider creating a new link
		{
			if (newSelectionId == -1)
			{
				EclRemoveWindow("editor_buildingid");
				m_selectionId = -1;
			}
			else if (m_tool == ToolLink)
			{
				building->SetBuildingLink(newSelectionId);
				m_tool = ToolNone;
			}
		}		
		else if ( g_inputManager->controlEvent( ControlTileDrag ) && newSelectionId == -1 )  // Otherwise consider rotation and movement
		{
			switch (m_tool)
			{
				case ToolMove:
				{
					Vector3 mousePos = g_app->m_userInput->GetMousePos3d();
					building->m_pos = mousePos;
					break;
				}
				case ToolRotate:
				{
					Vector3 front = building->m_front;
					front.RotateAroundY((float)g_target->dX() * 0.01);
					building->m_front = front;
					break;
				}
			}
		}
	}
}