_G[gTable] = {};

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


-- Called on Init
_G[gTable].OnInit = function(pObj)
	pObj.mState = 0;
	pObj.mCsData:SetVal("AppearStart",  	1);
	pObj.mCsData:SetVal("AppearEnd",    	2);
	pObj.mCsData:SetVal("DisappearStart",	3);
	pObj.mCsData:SetVal("DisappearEnd",		4);
end

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

end


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

   local aState = 0 + pObj.mState;

	if aState == 0 then
      if cm.GetGlobalBoolIndirect(pObj, "OnePuzzleSolved") then
         pObj.mState = aState + 1;
   		pObj.mAlpha:AncSetupChange(0.0, 255.0, PhMaterializeTimeLong,
            IcAutoNumChgr.IC_ANCM_LINEAR);

			if pObj.mCsData:IfExistsString("ObjSfxId") then
			   local aStr = pObj.mCsData:GetString("ObjSfxId");
			   IcPlaySample(aStr);
			else
			   IcPlaySample("PH_SFX_OBJ_USED");
			end

      end

	elseif aState == 1 then
		if not pObj.mAlpha:AncIsChanging() then
         pObj.mState = aState + 1;
         pObj:SetActive(0, 0, true);
		end

	elseif aState == 3 then
		if not pObj.mAlpha:AncIsChanging() then
         pObj.mState  = 0;
         if pObj.mCsData:GetInt("MaxPuzzles") == pObj.mCsData:GetInt("aPuzzleNum") then
            pObj.mState  = aState + 1;
            pObj.mIsDone = true;
         end
		end
	end

end


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

	if pName == "" then

		if pObj.mState == 2 then

	      local aPuzzleNum = pObj.mCsData:GetInt("aPuzzleNum");
	      local aStr = string.format("SpawnObject%d", aPuzzleNum);
	      if not cm.SpawnObject(pObj, 0, pObj.mSmPos, aStr) then
	         return true;
	      end

         cm.SetGlobalValIndirect(pObj, "OnePuzzleSolved", false);
	      pObj.mCsData:SetVal("aPuzzleNum", aPuzzleNum + 1);

			pObj.mState = 1 + pObj.mState;
			pObj.mAlpha:AncSetupChange(255.0, 0.0, PhSpawnerVanishAfterUse,
	         IcAutoNumChgr.IC_ANCM_LINEAR);

			pObj:SetActive(0, pPolyNum, false);
			IcPlaySample("PH_SFX_OBJ_PICKUP");
		end
		return true;

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

	return false;

end


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

   local aState = pObj.mState;
   if aState < 1 then
      return;
   end

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

	if (aState == 3 or aState == 1) then
		pG:SetColorizeImages(true);
		pG:SetColor(Color(255, 255, 255, pObj.mAlpha:AncGetVal()));
	end
	pG:DrawImage(aImg:GetImage(), aRpos.x, aRpos.y, aRect);

end




