_G[gTable] = {};

local aTmpVal = gTable;
cm.SetupTable(_G[aTmpVal]);


-- Called on Init
_G[gTable].OnInit = function(pObj)

	pObj.mState		 = 0;
	pObj.mDiscovered = true;

	pObj.mCsData:SetVal("Used", false);
	pObj.mCsData:SetVal("NumUsed", 0);
	pObj.mAlpha:AncSetupChange(0, 255.0, PhMaterializeTime, IcAutoNumChgr.IC_ANCM_LINEAR);
	_G[aTmpVal].MoveToSlot(pObj, PhKeyToSlotTime, true);

end


-- Called after data being loaded from disk
_G[gTable].OnLoad = function(pObj)

end


-- Called on use
_G[gTable].OnUse = function(pObj, pActingObj)

   -- How many times was the key used?
   local aNumUses = pObj.mCsData:GetInt("NumUsed");
   aNumUses = aNumUses + 1;
	pObj.mCsData:SetVal("NumUsed", aNumUses);
	
	local aMaxUses = pObj.mCsData:GetInt("MaxUses");
	if aNumUses == aMaxUses - 1 then
	   IcPlaySample("PH_SFX_TUNINGFORKHIT");
	else
	   IcPlaySample("PH_SFX_ICEBREAKS");
	end


   -- Used enough times?
	if aNumUses == aMaxUses then
   	pObj.mCsData:SetVal("Used", true);
   	pObj.mPdata.mBar:RemoveSlot(pObj.mId);
   	pObj.mPdata:UnMouseObject();
   	pObj.mAlpha:AncSetupChange(255.0, 0.0, PhKeyVanishAfterUse,
       IcAutoNumChgr.IC_ANCM_LINEAR);
      pObj:DisablePolys();
	end

end


-- Called on a update
_G[gTable].OnUpdate = function(pObj)

   cm.MoveToSlotUpdate(pObj);

	if pObj.mCsData:GetBool("Used") then
		if not pObj.mAlpha:AncIsChanging() then
			pObj.mIsDone = true;
		end
	end

end


-- Called on a succesful click
_G[gTable].OnClick =  function(pObj, pName)

	if pObj.mCurImg == 0 then
		if pName == "" then
			pObj.mPdata:MouseTheObject(pObj);
			IcPlaySample("PH_SFX_OBJ_PICKUP");
			return true;
		end
		cm.ObjDoesNotWork(pObj);
		return false;
	end
	return false;

end



-- Called on draw
_G[gTable].OnDraw =  function(pObj, pG)

	local aImg  = IcImageWrap(pObj.mSmallImage);
	assert(aImg);
	local aRpos = pObj.mSmPos;
	local aRect = aImg:GetCelRect(pObj.mCurCell);

	if pObj.mCsData:GetBool("Used") or pObj.mCsData:GetBool("MovingToSlot") then
		pG:SetColorizeImages(true);
		pG:SetColor(Color(255, 255, 255, pObj.mAlpha:AncGetVal()));
	end
	pG:DrawImage(aImg:GetImage(), aRpos.x, aRpos.y, aRect);

end



-- Called on moused
_G[gTable].OnMoused =  function(pObj)

end


-- Called on Unmoused
_G[gTable].OnUnMoused =  function(pObj)
	if not pObj.mCsData:GetBool("Used") then
		_G[aTmpVal].MoveToSlot(pObj, PhKeyToSlotTime, false);
	end
end



-- Moves the key to a slot
_G[gTable].MoveToSlot = cm.MoveToSlot;

