function AISMN_RepairBuilding::OnEnter(%this, %cmpAI)
{
   //Is the target a building? If not, we'll set a flag denoting it isn't.
	%tar = GetParameterTarget(%cmpAI);
   %cmpBldg = slgQueryInterface(%tar, $CID_BUILDING); 
   if(!isObject(%cmpBldg))
   {
      SetStateVariable(%cmpAI,0,1);
      return;
   }
   
   %object  = GetThisObject(%cmpAI);
   %cmpChar = slgQueryInterface(%object, $CID_CHARACTER);
   %resource = GameResourceStack.getResource();
   %datablock = %cmpBldg.getDatablock();
   if (isObject(%resource) == false)
   {
      %component.stopRepair();
      error("No resources were found-- cannot repair building.");
      SetStateVariable(%cmpAI,0,1);
      return;
   }
   
   %gold = %resource.getGold();
   %wood = %resource.getWood();
   
   %maxHealth = %tar.getMaxHealth();
   %healthGain = %maxHealth - %tar.health;
   if (%healthGain > %datablock.repairAmount)
   {
      %healthGain = %datablock.repairAmount;
   }
   %percentage = %healthGain / %datablock.repairAmount;
   %goldCost = mCeil(%datablock.repairGold * %percentage);
   %woodCost = mCeil(%datablock.repairWood * %percentage);

   // can no longer repair a building because health is full
   // or there are not enough resources to repair the building
   if (%gold.getCount() < %goldCost || %wood.getCount() < %woodCost)
   {
      %client = ClientGroup.getObject(0);
      commandToClient(%client, 'SendHudMessage', "Not enough resources to repair " @ %tar.name @ ".");
      SetStateVariable(%cmpAI,0,1);
      return;
   }
   
   %cmpBldg.startRepair(%cmpChar);
   
   // Play repair animation
   %object.playThread( 0, "repair");
   
   // Face the object
   FaceObject(%cmpAI, %tar);
   
   // We no longer want to ignore commands...keep this commented
   //%cmpAI.ignoreCommands(true);
   
   // Update mount
   %object.mountImage("hammer",2);
}

function AISMN_RepairBuilding::OnExit(%this, %cmpAI)
{
   // Stop any repairs from happening
   %tar = GetParameterTarget(%cmpAI);
   %cmpBldg = slgQueryInterface(%tar, $CID_BUILDING);
   if(isObject(%cmpBldg)) {
      %cmpBldg.stopRepair();
   }
   
   // Play root animation
   GetThisObject(%cmpAI).playThread( 0, "root");
   
   // We no longer want to ignore commands...keep this commented
   //%cmpAI.ignoreCommands(false);
   
   // Reset character outfit
   RestoreCharacterOutfit(%cmpAI);
}

function AISMN_RepairBuilding::Update(%this, %cmpAI)
{
   //If it wasn't a building, exit.
   if(GetStateVariable(%cmpAI,0) >= 1)
   {
      ReturnValue(%cmpAI,0);
      return;
   }
   
   //If we've reached the PRODUCTION state of the building, exit.
	%tar = GetParameterTarget(%cmpAI);
	%cmpBldg = slgQueryInterface(%tar, $CID_BUILDING); 
	if(!%cmpBldg)
   {
      ReturnValue(%cmpAI,0);
      return;
   }
   else if(!%cmpBldg.underRepair())
   {
      ReturnValue(%cmpAI,1);
      return;
   }
	
   ReturnValue(%cmpAI,-1);
}
