_G[gTable] = {};

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


-- Called on Init
_G[gTable].OnInit = function(pObj)
	pObj.mState = 0;
end


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

end


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

   -- See if the lock has accomplished its purpose
   if pObj.mState == 1 then

      if cm.GetGlobalBoolIndirect(pObj, "SetFlag1") then
         pObj:StartFadeRects(PhFadeAnotherTimeMedium);
    		pObj.mState      = pObj.mState   + 1;
   		pObj.mCurCell    = pObj.mCurCell + 1;
   	   pObj.mDiscovered = false;
         pObj:SetActive(0, 0, false);
         pObj:StopParticleEmission(false);
         IcPlaySample("PH_SFX_CHESTUNLOCKED");
      end

	elseif pObj.mState == 2 then

      if not pObj.mAlpha:AncIsChanging() then
         pObj:StartFadeRects(PhFadeAnotherTimeMedium);
    		pObj.mState      = pObj.mState   + 1;
   		pObj.mCurCell    = pObj.mCurCell + 1;
   		IcPlaySample("PH_SFX_SOMETHINGHEAVYFALLS");
      end

   end

end


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

	pObj.mDiscovered = true;

	if pName == "" then

      -- The lock is jammed
      if pObj.mState == 0 then
         cm.GetShowInfo(pObj, "InfoStr1", "InfoTime1");
         IcPlaySample("PH_SFX_DOES_NOT_WORK");
         return true;

      -- The lock is well oiled now
      elseif pObj.mState == 1 then
         local aPuzzleFlag = pObj.mCsData:GetString("SetFlag1");
         local aPuzzSol    = pObj.mCsData:GetInt("PuzzleSolution");
         local aNumSlot    = pObj.mCsData:GetInt("NumSlots");
         AddNumberLockWidget(pObj.mPdata, aPuzzleFlag, aNumSlot, aPuzzSol);
         IcPlaySample("PH_SFX_CLOSER_LOOK");
         return true;
      end
      return true;

	elseif pName == pObj.mCsData:GetString("KeyObject") then

      -- Oiling the jammed lock
      if pObj.mState == 0 then
   		pObj.mState = pObj.mState + 1;
   		pObj:StopParticleEmission(false);
   		_G[pActorObj.mScriptTag].OnUse(pActorObj, pObj);
         cm.GetShowInfo(pObj, "InfoStr2", "InfoTime2");
   		return true;

      -- The lock is already oiled
		else
         cm.GetShowInfo(pObj, "InfoStr3", "InfoTime3");
         return false;
		end

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



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

	local aRpos = pObj.mSmPos;
	local aImg  = IcImageWrap(pObj.mSmallImage);
	assert(aImg);
	local aRect = aImg:GetCelRect(pObj.mCurCell);
	pG:DrawImage(aImg:GetImage(), aRpos.x, aRpos.y, aRect);

end


