-- Author      : MrExillion
-- Create Date : 3/17/2021 8:33:42 PM

iStableMaster = iStableMaster or {}

   
-- Future plans for the Hook!
do
--[[
Library is being planned, options to accomplish these are being explored.
As Libraries cannot include XML templates, a frame Factory is being considered.
If the packager, can somehow be customized to transpile XML properties into a table, then a frame factory can be used.
The issue is that we cannot load XML templates within a library that is embedded, and a frame Factory cannot define templates as the xmlutility doesn't provide such methods.
After looking into intrinsics etc. the most likely option is to perhaps do clobbering for XML virtuals if the virtuals aren't named, they might be inheritable as templates as long as they can be identified from an unique attributes or dictionary-like references, if this is valid: ]]

-- CreateFrame("Frame",instanceName,parent, dictionaryLookup ["NameOfTemplateAliasPairs"][1] and dictionaryLookup["NameOfTemplateAliasPairs"][2]) where index 2 are the mixins.

--[[ Then a frame factory can be an alternative to the Templates.

	The idea is to have a public interface like this:

	function lib:PushNewTab(arg1,arg2,...)
		local arg3, arg4, arg5, arg6, callback = ...;
		-- mandatory argument: frameParent, textLabel - optional arguments: frameOrTableToControl, mixinsToAppend, hijackExistingTab_tab, function to run as callback.
		-- perhaps an overload with self might be beneficial if possible to make.
				local tabSystem, stackTail = lib:GetOrCreateTabSystem(arg1);
				local mixin = {};
					
					if(type(arg4) == "string") then 
						mixin = _G[arg4] or nil;
					elseif(type(arg4) == "table")
						if(type(arg4[1] == "table") then
							for _,t in ipairs(arg4) do
								for i=1, #t, 1 do
									mixin[#mixin] = t[i];
								end				
							end
						else
							assert(); -- throw error in this case.
						end
					
					end
					if(not arg6) then
						arg6:Hide();
						mixin[#mixin] = lib:Hijack(arg6); -- from within this we can parse all behaviours of different known tablibraries on demand. This should check if the frame is already registered as hijacked. And should also be accompanied by a public scoped function where a lib:ReleaseHostageTab(hijackedframes[index]) and a lib:ReleaseHostageTab(hijackedframes,[tbl or [indexStart, [indexEnd) basicc idea is to securely hijack tabs that are otherwise incompatible with eachother. while copying all their onclick behaviour, and then suppressing and hiding the frame, unregistering events etc from it to incapacitate it.
					end
					mixin[#mixin] = lib:SecurelyAddTabDefaultBehaviours(callback); -- restrict this function to library core itself to avoid addons to inappropriately hook the function. Use a callback instead.
			  local f  = CreateFrame("Frame",arg1:GetName()..Tab..(stackTail+1),arg1, mixin and lib:GetTemplate("LuaTabs-1.0_Tab"));
					f:SetID(stackTail+1);
					f:AutoArrangeTabs();
					f:OnLoad();
					f:Skin();
					f:Refresh();
					
					callback(f:GetName());
					
					return f;
					
	end

		The concept above is simple, we make a library to handle multiple tables of mixins that can be appended, callback for hijacking other libraries tabs on demand, as well as provide an environment that can do this safely. To costomize the frame and subframes we simply need to modify the template, which should be done with caution, this can evolve in multiple ways from here.


]]
end -- regionend


if( not IsAddOnLoaded("Blizzard_Collections")) then
	--LoadAddOn("Blizzard_Collections");	
	--l_CollectionsJournalTab7 = CreateFrame("Button","CollectionsJournalTab7",CollectionsJournal, "CollectionsJournalTab");
	--l_CollectionsJournalTab7:SetPoint("LEFT",CollectionsJournalTab5,"RIGHT",120,0);
	--l_CollectionsJournalTab7:SetText("CollectionJournalTab7");
	--l_CollectionsJournalTab7:SetSize(180,40);
	--l_CollectionsJournalTab7:Show();  
	STABLE_COLLECTIONS_TAB_ID = 6;
	--- THIS was an attempt to make ElvUI Skin the tab, but it didn't work!

end
--hooksecurefunc(C_STABLES_COLLECTION,"OnLoad",function() 
--					if(LoadAddOn("Blizzard_Collections") == true)then
				
				--end 
			--	end);



local tabisHooked = false;
local originalNumTabs = 5;
local secureTabs = {};
function iStableMaster:HookTab()
		if(UnitClass("player") ~= "Hunter") then
			if(not iStableMasterAccountOptions.EnableAddOnForAllClasses) then
				return;
			end
		end

	if(tabisHooked) then
		return;
	else

		C_STABLES_COLLECTION = {}
		D_STABLES_COLLECTION = {} 

		secureTabs = iStableMaster:FindSecureTabs2_0().tabs[CollectionsJournal] or {};

		tabToBeNum = CollectionsJournal.numTabs + 1 + #secureTabs;	
		
		--if(#secureTabs > 0) then		
		--STABLE_COLLECTIONS_TAB_ID = tabToBeNum + #secureTabs; 
		--else
		
		STABLE_COLLECTIONS_TAB_ID = tabToBeNum;
		--end
--- SNIPPET FOR INFORMATION OF SECURETABS2.0

--[[ Main API ]]--
--
-- function Lib:Add(panel, frame, label)
--	local secureTabs = self.tabs[panel] or {}
--	local id = #secureTabs
--	local anchor = id > 0 and 'SecureTab' .. (id-1) or 'Tab' .. panel.numTabs
--		end

--- SNIPPET END
		

		originalNumTabs = CollectionsJournal.numTabs;
		iStableMasterDB["Dynamics"]["D_STABLES_COLLECTION"]["TabId"] = tabToBeNum;
		C_STABLES_COLLECTION["Title"] = iStableMasterDB["Constants"]["C_STABLES_COLLECTION"]["Title"];
		C_STABLES_COLLECTION["Tab"] = iStableMasterDB["Constants"]["C_STABLES_COLLECTION"]["Tab"];
		D_STABLES_COLLECTION["TabId"] = iStableMasterDB["Dynamics"]["D_STABLES_COLLECTION"]["TabId"];
		STABLE_COLLECTIONS_TAB_ID = D_STABLES_COLLECTION["TabId"];
		CollectionsJournalKids = { CollectionsJournal:GetChildren() };
		iStableMaster:HookTabUpdateToOGTabs();
		TabHookFrame_OnLoad(CollectionsJournaliStableMasterTab);
		

		if(#secureTabs > 0) then 
		--hooksecurefunc(LibStub('SecureTabs-2.0'),"Update",function()
		--	if(_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:GetPoint(1) ~= {"LEFT",secureTabs[#secureTabs],"RIGHT",3, 0}) then
		--	_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:ClearAllPoints();
		--	_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetPoint("LEFT",secureTabs[#secureTabs],"RIGHT",3, 0);
		--	--secureTabs[#secureTabs]:HookScript("OnClick",function()
		--	--	StablesCollection_Hide();
		--	--	end);
		--	end	
		--end);

		for i = 1,#iStableMaster:FindSecureTabs2_0().tabs[CollectionsJournal],1 do
			local tab = secureTabs[i];
			local str = string.gsub(tab:GetName(),"CollectionsJournalSecureTab","");
			--print(str);
			local appendID = tonumber(str) + originalNumTabs + 1;
			tab:SetID(tonumber(appendID));
			tab:HookScript("OnClick",function(tab) 
				--print(tonumber(tab:GetID()));
				_G["CollectionsJournalTab"..tab:GetID()] = tab;
				iStableMaster:FindSecureTabs2_0():Select(tab)
				CollectionsJournal_SetTab(CollectionsJournal,tonumber(tab:GetID()));
				SetCVar("petJournalTab", tonumber(tab:GetID()));
				tab.frame:Show();
				--local name = tab:GetName();
				--_G[name..'LeftHighlight']:SetShown(false)
				--_G[name..'MiddleHighlight']:SetShown(false)
				--_G[name..'RightHighlight']:SetShown(false)
				

				--local panel = CollectionsJournal;

				
				--LibStub('SecureTabs-2.0'):Override_Update(panel, tab:GetID())

				--local selection = panel.selectedTab == appendID;
				--local cover = iStableMaster:FindSecureTabs2_0().covers[panel]
--				local Mtab = _G[panel:GetName() .. 'Tab'.. panel.selectedTab]
--				local name = Mtab:GetName()
--				local left = Mtab.LeftActive or _G[name..'LeftDisabled']
--				local middle = Mtab.MiddleActive or _G[name..'MiddleDisabled']
--				local right = Mtab.RightActive or _G[name..'RightDisabled']

--				cover:SetShown(not selection)
--				Mtab:SetShown(selection)
--				left:SetShown(selection)
--				middle:SetShown(selection)
--				right:SetShown(selection)

-- 				if not selection then
--					cover:SetParent(Mtab)
--					cover:SetAllPoints(Mtab)
--					cover:SetText(Mtab:GetText())
--					PanelTemplates_TabResize(cover, 0, nil, 36, panel.maxTabWidth or 88)
--				end



				--_G[name.."Text"]:SetShown(false);
				--iStableMaster:FindSecureTabs2_0().covers[CollectionsJournal][i]:SetText(tab:GetText())

			end);
			CollectionsJournal.Tabs[#CollectionsJournal.Tabs] = CollectionsJournaliStableMasterTab;
		_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID] = CollectionsJournaliStableMasterTab;
		_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:ClearAllPoints();
		_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetPoint("LEFT",CollectionsJournal.Tabs[#CollectionsJournal.Tabs-1],"RIGHT",3, 0);
			--tab:SetScript("OnSelect",function() end);
		iStableMaster:TabHookingCallsAtFirstShow()


		
		end
		else
						CollectionsJournal_SetTab(CollectionsJournal,tonumber(GetCVar("petJournalTab")) or 1);

		end
		hooksecurefunc(iStableMaster,"TabHookingCallsAtFirstShow",function(self) 
			--self:Print("HELLO WORLD");
					_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID] = CollectionsJournaliStableMasterTab;
					_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:ClearAllPoints();
					_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetPoint("LEFT",CollectionsJournal.Tabs[#CollectionsJournal.Tabs-1],"RIGHT",3, 0);
					HookCollectionsJournal_UpdateSelectedTab(CollectionsJournaliStableMasterTab);
					iStableMaster:SkinTabs();

			end);
		
		tabisHooked = true;
		iStableMaster:SkinTabs();

	end
end


function iStableMaster:TabHookingCallsAtFirstShow()


-- CallBackFor First show




end

function iStableMaster:SkinTabs() 
--- SKIN THE TAB
	-- iStableMaster:Print(iStableMaster.ElvUIPlugin.IsPresent);
		if(iStableMaster.ElvUIPlugin.IsPresent) then 
			--iStableMaster.ElvUIPlugin.SkinModule:AddCallbackForAddon('iStableMaster')
			
			for i = 1, #CollectionsJournal.Tabs, 1 do 
				iStableMaster.ElvUIPlugin.SkinModule:HandleTab(CollectionsJournal.Tabs[i]);
				if(i > 1) then -- prevent the entire tabs section from moving top left, could have also set i == 2
					CollectionsJournal.Tabs[i]:ClearAllPoints();
					CollectionsJournal.Tabs[i]:Point('TOPLEFT', CollectionsJournal.Tabs[i-1], 'TOPRIGHT', -5, 0);
				end

--				local tab = _G.CollectionsJournalTab1
--	local index, lastTab = 1, tab
--	while tab do
--		S:HandleTab(tab)

--		tab:ClearAllPoints()

--		if index == 1 then
--			tab:Point('TOPLEFT', _G.CollectionsJournal, 'BOTTOMLEFT', -3, 0)
--		else
--			tab:Point('TOPLEFT', lastTab, 'TOPRIGHT', -5, 0)
--			lastTab = tab
--		end

--		index = index + 1
--		tab = _G['CollectionsJournalTab'..index]
--	end

			end
		end


end




--local tabToBeNum = 1;
--for _, child in ipairs(CollectionsJournalKids) do
--	if(child:GetName() == child:GetParent():GetName()..child:GetID()) then
--	tabToBeNum = tabToBeNum + 1;

--	end


--end			
				
function iStableMaster:HookTabUpdateToOGTabs()

		if(UnitClass("player") ~= "Hunter") then
			if(not iStableMasterAccountOptions.EnableAddOnForAllClasses) then
			 return;
			end
		end


	for _, child in ipairs(CollectionsJournalKids) do
		local parentFrame = child:GetParent();
		local parentName = parentFrame:GetName();
		local matchingChildName = parentName.."Tab"..child:GetID();
		local matchingChildNameSecTabs = parentName.."SecureTab";
		--child:GetName().gsub(parentName.."SecureTab","");
		local shiftTabAnchor = 0;
		
		if(child:GetName() ~= nil) then 
		
		local str = string.gsub(child:GetName(),""..parentName.."SecureTab","");
		

		if(child:GetName() == matchingChildName) then
		
			--hooksecurefunc("CollectionsJournal_UpdateSelectedTab",function(child)HookCollectionsJournal_UpdateSelectedTab(child)end);
			child:HookScript("OnClick",function(child)HookCollectionsJournal_UpdateSelectedTab(child)end);

		elseif(string.find(child:GetName(),matchingChildNameSecTabs) ~= nil) then
			local id = 6 + tonumber(str);	

			child:HookScript("OnClick",function(child)HookCollectionsJournal_UpdateSelectedTab(CollectionsJournaliStableMasterTab)
			--SetCVar("petJournalTab", id);
			--CollectionsJournal_SetTab(child, id); This should be how it it should work but it secure tabs are naughty!
			StablesCollection_Hide();
					--iStableMaster:FindSecureTabs2_0():Select(child)
					iStableMaster:FindSecureTabs2_0():Uncover(CollectionsJournal);
					iStableMaster:FindSecureTabs2_0():Update(CollectionsJournal,child);

			
			if(CollectionsJournal.selectedTab == STABLE_COLLECTIONS_TAB_ID) then
			--CollectionsJournalCoverTab:Hide();
			end
			shiftTabAnchor = shiftTabAnchor+1;


			end);
			


		end
		end		
		if(shiftTabAnchor ~= 0) then 
			--if(_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:GetPoint(1) ~= {"LEFT",CollectionsJournalSecureTab..shiftTabAnchor,"RIGHT",3, 0}) then
				_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:ClearAllPoints();
				_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetPoint("LEFT",CollectionsJournalSecureTab..shiftTabAnchor,"RIGHT",3, 0);
			--end
		end
	end	
	--if(#iStableMaster:FindSecureTabs2_0() > 0) then 
	--	for _, child in ipairs(iStableMaster:FindSecureTabs2_0().tabs[CollectionsJournal]) do
	
	--		child:HookScript("OnClick",function()
	--		StablesCollection_Hide();
	--		end)
	--	end
	--end


end






--[[
function GenerateAnotherTab()
				STABLE_COLLECTIONS_TAB_ID = (CollectionsJournal.numTabs + 1);
				PanelTemplates_SetNumTabs(CollectionsJournal,STABLE_COLLECTIONS_TAB_ID);
				local newTab = CreateFrame("Button", "CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID, _G["CollectionsJournal"], "CollectionsJournalStablesTab",STABLE_COLLECTIONS_TAB_ID);
				--local newTab = _G["CollectionsJournalTabTemporary"];
				--local point, relativeTo, relativePoint, ofsX, ofsY = _G[newTab:GetName()]:GetPoint(1);
				_G[newTab:GetName()]:ClearAllPoints();
				_G[newTab:GetName()]:SetPoint("LEFT", "CollectionsJournalTab"..(CollectionsJournal.numTabs-1), "RIGHT", -16, 0);
				--_G[newTab:GetName()]:SetAllPoints();
				_G[newTab:GetName()]:SetText(STABLES_COLLECTION);

				--_G[newTab:GetName()]:SetID(STABLE_COLLECTIONS_TAB_ID);


				function NewOnClick(CollectionsJournal,self,STABLE_COLLECTIONS_TAB_ID)
				local STABLE_COLLECTIONS_TAB_ID = STABLE_COLLECTIONS_TAB_ID;

				StablesCollectionsJournal_SetTab(CollectionsJournal,self:GetID(),STABLE_COLLECTIONS_TAB_ID);
				PlaySound(SOUNDKIT.UI_TOYBOX_TABS);

				end



end
]]
local aliasRefLib = LibStub('SecureTabs-2.0');
--aliasRefLib:Update = aliasRefLib:Update();
function aliasRefLib:Update(panel, selection)
 
	local secureTabs = self.tabs[panel]
	if not secureTabs then
		return
	end

	for i, tab in ipairs(secureTabs) do
		local selected = tab == selection
		if selected then
			PanelTemplates_SelectTab(tab)
		else
			PanelTemplates_DeselectTab(tab)
		end

		local frame = tab.frame
		if frame then
			frame:SetShown(selected)

			if selected then
				frame:SetParent(panel)
				frame:EnableMouse(true)
				frame:SetAllPoints(true)
				frame:SetFrameLevel(panel:GetFrameLevel() + 20)

				if frame.CloseButton then
					frame.CloseButton:SetScript('OnClick', function()
						local original = frame:GetParent() and frame:GetParent().CloseButton
						if original then
							ExecuteFrameScript(original, 'OnClick') -- make sure any additional behaviour is replicated
						end

						HideUIPanel(frame) -- safest hiding method
					end)
				end
			end
		end
	end

	if panel.selectedTab then
		--print(selection:GetName().." , "..string.find(selection:GetName(),"CollectionsJournalSecureTab"));
		if(selection ~= nil) then 
			if( string.find(selection:GetName() or " ","CollectionsJournalSecureTab") ) then return end
		end
		local cover = self.covers[panel]
		local tab = _G[panel:GetName() .. 'Tab'.. panel.selectedTab]

		local name = tab:GetName()
		local left = tab.LeftActive or _G[name..'LeftDisabled']
		local middle = tab.MiddleActive or _G[name..'MiddleDisabled']
		local right = tab.RightActive or _G[name..'RightDisabled']

		cover:SetShown(selection)
		left:SetShown(not selection)
		middle:SetShown(not selection)
		right:SetShown(not selection)

 		if selection then
			cover:SetParent(tab)
			cover:SetAllPoints(tab)
			cover:SetText(tab:GetText())
			PanelTemplates_TabResize(cover, 0, nil, 36, panel.maxTabWidth or 88)
		end
	end
end





function TabHookFrame_OnLoad(tab)
	_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID] = tab;

	
	_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:RegisterEvent("CVAR_UPDATE");

	_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetID(STABLE_COLLECTIONS_TAB_ID);
	--CollectionsJournal:SetTitle(COLLECTIONS);
	--CollectionsJournal:SetPortraitToAsset("Interface\\Icons\\MountJournalPortrait");
	_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetText(C_STABLES_COLLECTION["Tab"]);
	PanelTemplates_SetNumTabs(CollectionsJournal,STABLE_COLLECTIONS_TAB_ID);
	_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetParent(CollectionsJournal);
	--CollectionsJournalTab6:SetAllPoints();
	


	
		--print(tonumber(GetCVar("petJournalTab")));
		hooksecurefunc(iStableMaster,"TabHookingCallsAtFirstShow", function()



		_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID] = tab;
		_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:RegisterEvent("CVAR_UPDATE");
		_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetID(STABLE_COLLECTIONS_TAB_ID);
		_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:ClearAllPoints();

		iStableMaster:HookTabUpdateToOGTabs()
		if(#iStableMaster:FindSecureTabs2_0().tabs > 0) then
		_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetPoint("LEFT",secureTabs[#secureTabs],"RIGHT",3, 0);
		else
		_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetPoint("LEFT",CollectionsJournalTab5,"RIGHT",3, 0);


		end
			for i = 1,#iStableMaster:FindSecureTabs2_0().tabs[CollectionsJournal],1 do
			local t = secureTabs[i];
			local str = string.gsub(t:GetName(),"CollectionsJournalSecureTab","");
			--print(str);
			

			local appendID = tonumber(str) + originalNumTabs + 1;
			t:SetID(tonumber(appendID));
			--print(tonumber(tab:GetID()));
			_G["CollectionsJournalTab"..t:GetID()] = t;
			
			--local ref = _G["CollectionsJournalTab"..t:GetID()];
			--function ref:GetName() 
			--return "CollectionsJournalTab"..t:GetID();
			
			--end;
			
				--if(tonumber(GetCVar("petJournalTab")) == t:GetID()) then 
				--	iStableMaster:FindSecureTabs2_0():Select(t)
				--	t.frame:Show();
				--end
			end
			


		if (tonumber(GetCVar("petJournalTab")) ~= tabToBeNum) then	
			local tabToCheck = CollectionsJournal.Tabs[tonumber(GetCVar("petJournalTab"))];
				if(string.find(tabToCheck:GetName(),"CollectionsJournalSecureTab")) then 
					--print("TEST");
					
					--iStableMaster:FindSecureTabs2_0().covers[CollectionsJournal]:Uncover(CollectionsJournal);
					iStableMaster:FindSecureTabs2_0():Select(tabToCheck)
					iStableMaster:FindSecureTabs2_0():Uncover(CollectionsJournal);
					--iStableMaster:FindSecureTabs2_0():Update(CollectionsJournal,_G["CollectionsJournalTab"..tonumber(GetCVar("petJournalTab"))]);
					CollectionsJournal_SetTab(CollectionsJournal, tonumber(GetCVar("petJournalTab")) or 1);
					iStableMaster:FindSecureTabs2_0():Update(CollectionsJournal,_G["CollectionsJournalTab"..tonumber(GetCVar("petJournalTab"))]);
					
				else
					CollectionsJournal_SetTab(CollectionsJournal, tonumber(GetCVar("petJournalTab")) or 1);
					iStableMaster:FindSecureTabs2_0():Update(CollectionsJournal,_G["CollectionsJournalTab"..tonumber(GetCVar("petJournalTab"))]);
					CollectionsJournal_SetTab(CollectionsJournal, tonumber(GetCVar("petJournalTab")) or 1);


				end
		
				
				
		elseif(tonumber(GetCVar("petJournalTab")) == tabToBeNum) then
		--PanelTemplates_SetNumTabs(CollectionsJournal,6);
		
		--iStableMaster:FindSecureTabs2_0():Select(_G["CollectionsJournalTab"..tonumber(GetCVar("petJournalTab"))])
		
		CollectionsJournal_SetTab(CollectionsJournal,tonumber(GetCVar("petJournalTab")));
		--iStableMaster:FindSecureTabs2_0():Update(CollectionsJournal,_G["CollectionsJournalTab"..tonumber(GetCVar("petJournalTab"))]);
		--iStableMaster:FindSecureTabs2_0():Select(_G["CollectionsJournalTab"..tonumber(GetCVar("petJournalTab"))])
		iStableMaster:FindSecureTabs2_0():Uncover(CollectionsJournal);

		--StablesCollectionsJournal_SetTab(CollectionsJournal, tonumber(GetCVar("petJournalTab")));
		--StablesCollection_Show(); -- not needed i think commented to reduce calls
		
		
		end
	
		

	local secureTabs = iStableMaster:FindSecureTabs2_0().tabs[CollectionsJournal] or {};


		if(#secureTabs > 0 ) then  
			if(_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:GetPoint(1) ~= {"LEFT",secureTabs[#secureTabs],"RIGHT",3, 0}) then
			_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:ClearAllPoints();
			_G["CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID]:SetPoint("LEFT",secureTabs[#secureTabs],"RIGHT",3, 0);

			end
		
			
		end
		
		end);
	--/run _G["CollectionsJournalTab"..7]:ClearAllPoints(); _G["CollectionsJournalTab"..7]:SetPoint("LEFT",iStableMaster:FindSecureTabs2_0().tabs[CollectionsJournal][#iStableMaster:FindSecureTabs2_0().tabs[CollectionsJournal]-1],"RIGHT",3,0);
		--StablesCollection_Hide();
	
	





	--_G["CollectionsJournalTab6"]:SetName("CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID);


	--		hooksecurefunc(CollectionsJournalTab,"OnClick", StablesCollection_Show());


	--[[
	if (not IsAddOnLoaded("Blizzard_Collections")) then



	LoadAddOn("Blizzard_Collections");


	end


	STABLE_COLLECTIONS_TAB_ID = (CollectionsJournal.numTabs + 1);
	PanelTemplates_SetNumTabs(CollectionsJournal,STABLE_COLLECTIONS_TAB_ID);
	local newTab = CreateFrame("Button", "CollectionsJournalTab"..STABLE_COLLECTIONS_TAB_ID, _G["CollectionsJournal"], "CollectionsJournalStablesTab",STABLE_COLLECTIONS_TAB_ID);
	--local newTab = _G["CollectionsJournalTabTemporary"];
	--local point, relativeTo, relativePoint, ofsX, ofsY = _G[newTab:GetName()]:GetPoint(1);
	_G[newTab:GetName()]:ClearAllPoints();
	_G[newTab:GetName()]:SetPoint("LEFT", "CollectionsJournalTab"..(CollectionsJournal.numTabs-1), "RIGHT", -16, 0);
	--_G[newTab:GetName()]:SetAllPoints();
	_G[newTab:GetName()]:SetText(STABLES_COLLECTION);

	--_G[newTab:GetName()]:SetID(STABLE_COLLECTIONS_TAB_ID);


	function NewOnClick(CollectionsJournal,self,STABLE_COLLECTIONS_TAB_ID)
	local STABLE_COLLECTIONS_TAB_ID = STABLE_COLLECTIONS_TAB_ID;

	StablesCollectionsJournal_SetTab(CollectionsJournal,self:GetID(),STABLE_COLLECTIONS_TAB_ID);
	PlaySound(SOUNDKIT.UI_TOYBOX_TABS);

	end



	--_G[newTab:GetName()]:SetScript("OnClick", function(self,STABLE_COLLECTIONS_TAB_ID)NewOnClick(self,STABLE_COLLECTIONS_TAB_ID) end);



	function InitFirstTab()
	]]

	--CollectionsJournalTab6:SetText(STABLES_COLLECTION["Tab"]);

	--CollectionsJournal_SetTab(self, tab)
	--_G[newTab:GetName()]:SetName("CollectionsJournalTab".._G[newTab:GetName()]:GetID());


	--[[
	for i=1,CollectionsJournal.numTabs,1 do

	if(i ~= STABLE_COLLECTIONS_TAB_ID) then

	_G["CollectionsJournalTab"..i]:SetScript("OnClick", function(self,STABLE_COLLECTIONS_TAB_ID)

	if(PanelTemplates_GetSelectedTab(CollectionsJournal):GetID() == STABLE_COLLECTIONS_TAB_ID) then
	NewOnClick(self,STABLE_COLLECTIONS_TAB_ID)
	else
	require(PanelTemplates_GetSelectedTab(CollectionsJournal):GetScript("OnClick"))

	end
	end);
	end
	end
	]]

	--[[
	for i=1,5,1 do
	_G["CollectionsJournalTab"..i]:SetScript("OnClick", function(self,...)
	StablesCollectionsJournal_SetTab(CollectionsJournal,self:GetID(),STABLE_COLLECTIONS_TAB_ID)
	PlaySound(SOUNDKIT.UI_TOYBOX_TABS)

	end);
	end
	]]
	--end

	--GenerateAnotherTab();


end



--local Override_Update = iStableMaster:FindSecureTabs2_0();

--function Override_Update:Override_Update(panel, selection)
--	local secureTabs = self.tabs[panel]
--	if not secureTabs then
--		return
--	end

--	for i, tab in ipairs(secureTabs) do
--		local selected = tab ~= selection
--		if not selected then
--			PanelTemplates_SelectTab(tab)
--		else
--			PanelTemplates_DeselectTab(tab)
--		end

--		local frame = tab.frame
--		if frame then
--			frame:SetShown(selected)

--			if selected then
--				frame:SetParent(panel)
--				frame:EnableMouse(true)
--				frame:SetAllPoints(true)
--				frame:SetFrameLevel(panel:GetFrameLevel() + 20)

--				if frame.CloseButton then
--					frame.CloseButton:SetScript('OnClick', function()
--						local original = frame:GetParent() and frame:GetParent().CloseButton
--						if original then
--							ExecuteFrameScript(original, 'OnClick') -- make sure any additional behaviour is replicated
--						end

--						HideUIPanel(frame) -- safest hiding method
--					end)
--				end
--			end
--		end
--	end

--	if panel.selectedTab then
--		local cover = self.covers[panel]
--		local tab = _G[panel:GetName() .. 'Tab'.. panel.selectedTab]

--		local name = tab:GetName()
--		local left = tab.LeftActive or _G[name..'LeftDisabled']
--		local middle = tab.MiddleActive or _G[name..'MiddleDisabled']
--		local right = tab.RightActive or _G[name..'RightDisabled']

--		cover:SetShown(selection)
--		left:SetShown(not selection)
--		middle:SetShown(not selection)
--		right:SetShown(not selection)

-- 		if selection then
--			cover:SetParent(tab)
--			cover:SetAllPoints(tab)
--			cover:SetText(tab:GetText())
--			PanelTemplates_TabResize(cover, 0, nil, 36, panel.maxTabWidth or 88)
--		end
--	end
--end



function TabHookFrame_OnEvent(self, event, ...)
	local arg1, arg2 = ...;

	if(event == "CVAR_UPDATE") then
		if(arg1 ~= "petJournalTab") then return; 
		else
			if(arg2 ~= STABLE_COLLECTIONS_TAB_ID) then
				--StablesCollection_Hide();


			end

		end



	end


end


function HookCollectionsJournal_UpdateSelectedTab(self) 


	


	local selected = CollectionsJournal_GetTab(self);

	--if (not CollectionsJournal_ValidateTab(selected)) then
	--	PanelTemplates_SetTab(self, 1);
	--	selected = 1;
	--end
	
	--MountJournal:SetShown(selected == 1);
	--PetJournal:SetShown(selected == 2);
	--ToyBox:SetShown(selected == 3);
	--HeirloomsJournal:SetShown(selected == 4);
	---- don't touch the wardrobe frame if it's used by the transmogrifier
	--if ( WardrobeCollectionFrame:GetParent() == self or not WardrobeCollectionFrame:GetParent():IsShown() ) then
	--	if ( selected == 5 ) then
	--		HideUIPanel(WardrobeFrame);
	--		WardrobeCollectionFrame_SetContainer(self);
	--	else
	--		WardrobeCollectionFrame:Hide();
	--	end
	--end


	--if ( selected == 1 ) then
	--	CollectionsJournalTitleText:SetText(MOUNTS);
	--elseif (selected == 2 ) then
	--	CollectionsJournalTitleText:SetText(PET_JOURNAL);
	--elseif (selected == 3 ) then
	--	CollectionsJournalTitleText:SetText(TOY_BOX);
	--elseif (selected == 4 ) then
	--	CollectionsJournalTitleText:SetText(HEIRLOOMS);
	--elseif (selected == 5 ) then
	--	CollectionsJournalTitleText:SetText(WARDROBE);
	--end
	if(selected == STABLE_COLLECTIONS_TAB_ID) then 
		StablesCollection_Show();
	else
		StablesCollection_Hide();
		--if(CollectionsJournalCoverTab ~= nil) then 
		--CollectionsJournalCoverTab:Hide();
		--end
	end
	--if(#iStableMaster:FindSecureTabs2_0().tabs > 0) then 
	--	hooksecurefunc(iStableMaster:FindSecureTabs2_0(),"Select",function()
	--	StablesCollection_Hide();
	--	end)
	--end

	--HelpTip:HideAll(self);
	--if ShouldShowHeirloomTabHelpTip() then
	--	local helpTipInfo = {
	--		text = HEIRLOOMS_JOURNAL_TUTORIAL_TAB,
	--		buttonStyle = HelpTip.ButtonStyle.Close,
	--		cvarBitfield = "closedInfoFrames",
	--		bitfieldFlag = LE_FRAME_TUTORIAL_HEIRLOOM_JOURNAL_TAB,
	--		targetPoint = HelpTip.Point.TopEdgeCenter,
	--		offsetY = -7,
	--	};
	--	HelpTip:Show(self, helpTipInfo, CollectionsJournalTab4);
	--elseif ShouldShowWardrobeTabHelpTip() then
	--	local helpTipInfo = {
	--		text = TRANSMOG_JOURNAL_TAB_TUTORIAL,
	--		buttonStyle = HelpTip.ButtonStyle.Close,
	--		cvarBitfield = "closedInfoFrames",
	--		bitfieldFlag = LE_FRAME_TUTORIAL_TRANSMOG_JOURNAL_TAB,
	--		targetPoint = HelpTip.Point.TopEdgeCenter,
	--		offsetY = -7,
	--	};
	--	HelpTip:Show(self, helpTipInfo, CollectionsJournalTab5);
	--end
end

		

--[[

function StablesRightColumn_OnLoad(self) 
-- why?
end

--stabletabid = _G["stabletabid"];
]]





function StablesCollectionsJournal_SetTab(self, tab)



	if (tab ~= STABLE_COLLECTIONS_TAB_ID and tab < (6 + #iStableMaster.FindSecureTabs2_0().tabs[CollectionsJournal])) then
		CollectionsJournal_SetTab(self, tab);

	elseif (tab == STABLE_COLLECTIONS_TAB_ID) then
		CollectionsJournal_SetTab(self, tab);
		CollectionsJournal_UpdateSelectedTab(self);
		HookCollectionsJournal_UpdateSelectedTab(self);
		SetCVar("petJournalTab", tab);


	end


end
local function CollectionsJournal_SetTab(self, tab)
	PanelTemplates_SetTab(self, tab);
	SetCVar("petJournalTab", tab);
	CollectionsJournal_UpdateSelectedTab(self);

end




--function StablesCollectionsJournal_SetTab(self, tab, stabletabid)

--	local stabletabid = stabletabid;

--	if (tab < stabletabid) then
--	CollectionsJournal_SetTab(self,tab);
	
--	elseif (tab == stabletabid) then
--	--PanelTemplates_SetTab(self, tab);
--	StablesCollection_UpdateSelectedTab(self,stabletabid);
--	SetCVar("petJournalTab", stabletabid);


--	end


--end

function CollectionsJournal_GetSelectedTab(self)
	return PanelTemplates_GetSelectedTab(self);
end

--[[
function StaticStablesCollection_UpdateSelectedTab(self)

if(CollectionsJournal_GetTab(self) == 6)
then
StablesCollection_UpdateSelectedTab(self,6)

else
Collection_UpdateSelectedTab(self)

end


end

]]
--[[
function StablesCollection_UpdateSelectedTab(self, stabletabid)
	
	local selected = CollectionsJournal_GetTab(self);

	if(selected == stabletabid) then 
	StablesCollection:SetShown(true);
	return;
	else
	StablesCollection:SetShown(false);

	end


	if (not CollectionsJournal_ValidateTab(selected)) then
		PanelTemplates_SetTab(self,1);
		selected = 1;
	end
	
	MountJournal:SetShown(selected == 1);
	PetJournal:SetShown(selected == 2);
	ToyBox:SetShown(selected == 3);
	HeirloomsJournal:SetShown(selected == 4);
	-- don't touch the wardrobe frame if it's used by the transmogrifier
	if ( WardrobeCollectionFrame:GetParent() == self or not WardrobeCollectionFrame:GetParent():IsShown() ) then
		if ( selected == 5 ) then
			HideUIPanel(WardrobeFrame);
			WardrobeCollectionFrame_SetContainer(self);
		else
			WardrobeCollectionFrame:Hide();
		end
	end
	
	
	
	--StablesCollection:SetShown(selected == stabletabid);


	if ( selected == 1 ) then
		CollectionsJournalTitleText:SetText(MOUNTS);
	elseif (selected == 2 ) then
		CollectionsJournalTitleText:SetText(PET_JOURNAL);
	elseif (selected == 3 ) then
		CollectionsJournalTitleText:SetText(TOY_BOX);
	elseif (selected == 4 ) then
		CollectionsJournalTitleText:SetText(HEIRLOOMS);
	elseif (selected == 5 ) then
		CollectionsJournalTitleText:SetText(WARDROBE);
	elseif (selected == stabletabid) then
		CollectionsJournalTitleText:SetText(t_STABLES_COLLECTION["Title"]);
	end

  if(selected ~= stabletabid) then
	HelpTip:HideAll(self);
	if ShouldShowHeirloomTabHelpTip() then
		local helpTipInfo = {
			text = HEIRLOOMS_JOURNAL_TUTORIAL_TAB,
			buttonStyle = HelpTip.ButtonStyle.Close,
			cvarBitfield = "closedInfoFrames",
			bitfieldFlag = LE_FRAME_TUTORIAL_HEIRLOOM_JOURNAL_TAB,
			targetPoint = HelpTip.Point.TopEdgeCenter,
			offsetY = -7,
		};
		HelpTip:Show(self, helpTipInfo, CollectionsJournalTab4);
	elseif ShouldShowWardrobeTabHelpTip() then
		local helpTipInfo = {
			text = TRANSMOG_JOURNAL_TAB_TUTORIAL,
			buttonStyle = HelpTip.ButtonStyle.Close,
			cvarBitfield = "closedInfoFrames",
			bitfieldFlag = LE_FRAME_TUTORIAL_TRANSMOG_JOURNAL_TAB,
			targetPoint = HelpTip.Point.TopEdgeCenter,
			offsetY = -7,
		};
		HelpTip:Show(self, helpTipInfo, CollectionsJournalTab5);
	end
  end
end

]]

--[[
local function ShouldShowHeirloomTabHelpTip()
	if GetCVarBitfield("closedInfoFrames", LE_FRAME_TUTORIAL_HEIRLOOM_JOURNAL_TAB) or Kiosk.IsEnabled() then
		return false;
	end

	if PetJournal_HelpPlate and HelpPlate_IsShowing(PetJournal_HelpPlate) then
		return false;
	end

	return C_Heirloom.ShouldShowHeirloomHelp();
end

local function ShouldShowWardrobeTabHelpTip()
	if GetCVarBitfield("closedInfoFrames", LE_FRAME_TUTORIAL_TRANSMOG_JOURNAL_TAB) or Kiosk.IsEnabled() then
		return false;
	end

	if PetJournal_HelpPlate and HelpPlate_IsShowing(PetJournal_HelpPlate) then
		return false;
	end

	return true;
end
]]



