_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.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)
	pObj.mCsData:SetVal("Used", true);
	pObj.mPdata.mBar:RemoveSlot(pObj.mId);
	pObj.mAlpha:AncSetupChange(255.0, 0.0, PhKeyVanishAfterUse, IcAutoNumChgr.IC_ANCM_LINEAR);
	pObj:DisablePolys();
	IcPlaySample("PH_SFX_OBJ_USED");
end


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

	if pObj.mCsData:GetBool("MovingToSlot") then
		if not pObj:SmIsMoving() then
			pObj.mDiscovered = false;
			pObj.mZ	= pObj.mCsData:GetInt("PrevZ");
			pObj:StopParticleEmission(false);
			pObj.mCsData:SetVal("MovingToSlot", false);
			IcPlaySample("PH_SFX_OBJ_IN_INV");
		end
	end

	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, pActorObj, pPolyNum, pX, pY)

	if pName == "" then

		assert(pObj.mCurImg == 0);
		local aActivatorFlag = pObj.mCsData:GetString("ActivatorFlag1");
		if not pObj.mPdata.mCsData:GetBool(aActivatorFlag) then
         cm.ShowInfo(pObj, "Using the scroll now would just waste it", 180);
         return true;
      end

		pObj.mState     = pObj.mState + 1;
		local aFlagName = pObj.mCsData:GetString("SetLevelFlag");
		pObj.mPdata.mCsData:SetVal(aFlagName, true);
		_G[pObj.mScriptTag].OnUse(pObj);
		return true;

	else
		cm.ObjDoesNotWork(pObj);
		return false;
	end

	return false;

end


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

	if pObj.mIsDone then
		return;
	end
	pG:PushState();

	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);

	pG:PopState();

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;

