-- Author      : MrExillion
-- Create Date : 3/8/2021 12:48:19 AM
-- Last Structure Change: 19/12/2022 23:57:00
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------- BEGIN DOCUMENT ISH -------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


----------------------------------------------------
---				INITITALIZATION					 ---
----------------------------------------------------
iStableMaster = iStableMaster or {};

iStableMaster.debugEnabled = {
	switchstack_MoveEmptyAndOccupiedScrollSlots = false,
	all = false,
	presets_Swaps = false,
	unstableFunctionsOn = false,
}
iStableMaster.firstOpen = true;
iStableMaster.firstOpenCompact = true;
iStableMaster.SetPetSlotCompleted = false;
iStableMaster.currentlySelectedPet = nil;
local currentlyActiveHighlight = nil;
iStableMaster.currentHover = 0;
local backupAttempt = false;
iStableMaster.fistclick = false; -- for some reason this doesnt work anymore.
iStableMaster.LATEST_ADDED_BEASTSQUAD = "N/A";
local DebugMessageLimiter = 1;
iStableMaster.PetScrollFrameSeparator = {};
iStableMaster.ScrollFrameArrElem = {};
iStableMaster.FamilyFiltersElements = {};
iStableMaster.FilterScrollElementsArr = {};
iStableMaster.SpecializationFiltersElements = {};
iStableMaster.DietFiltersElements = {};
iStableMaster.FamilyAbilitiesFiltersElements = {};
iStableMaster.OtherFiltersElements = {};
----------------------------------------------------
---				INITITALIZATION	 END			 ---
----------------------------------------------------
----------------------------------------------------
---				General Functions    			 ---
----------------------------------------------------
--#Region General functions
-- WE USE THIS ONE PROBABLY IN SEVERAL PLACES
function iStableMaster:CountStabledPets()

	local NumPets = 0;

	for i = 6,205 do

		if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i].PetInfo.talent ~= "N/A") then 

			NumPets = NumPets + 1;


		end

	end


	return NumPets;
end

--THESE ARE CORE FUNCTIONS YOU CUNT DO NOT FUCKING TOUCH THEM! BEGIN:
function iStableMaster:StringKeyTableLength(table,namespace)
	local n = 0
	for k, v in pairs(table) do
		nsEnd = select(2,string.find(k,namespace))		
		if(string.find(k,namespace) ~=nil) then
			if(tonumber(string.sub(k,nsEnd+1,nsEnd+1)) ~= nil) then 
				n = n + 1
			end
		end
	end
	return n
end -- CORE FUNCTION DONT FUCK WITH IT
function iStableMaster:StringKeyTableLengthI(table)
	local n = 0
	for k, v in pairs(table) do
		n = n + 1		
	end
	return n
end -- CORE FUNCTION DONT FUCK WITH IT
-- END OF CORE FUNCTIONS
function iStableMaster:Truncate(num, digits)
	local mult = 10^(digits)
	return math.modf(num*mult)/mult
end-- iStableMaster:Truncate a number
function iStableMaster:FindValueFromKey(tableToLookin,valueIn) 
	for i=1,iStableMaster:StringKeyTableLengthI(tableToLookin) do
		if tableToLookin[i] == valueIn then
			return i;
		end
	end
end -- Reverse Look Up for tables
function iStableMaster:SpaceAdderForString(s)
	local alphabetUpperCase = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
	local out = string.sub(s,1,1);
	local temp = s;
	local found = 0;
	if (type(s) ~= "string") then
		return s;
	end
	for i = 2, #s do
		local tempreduced = string.sub(s,i,i);
		local a = 0;
		local b = 0;
		for j=1,#alphabetUpperCase do
			a, b = string.find(tempreduced,alphabetUpperCase[j]);
			if a ~=nil and b ~= nil then
				break;
			end
		end
		if a == nil or b == nil and i > #out then
			out = out..string.sub(s,i,i);
		elseif i >1 and i > #out-found then
			out = out.." "..string.sub(s,i,i);
			found = found +1;
		end
	end
	--print(out);
	return out;
end-- Splits Strings on namingConvention Returns "naming Convention"
--local function iStableMaster:SetContains(set, key)
--	return set[key] ~= nil
--end -- local function there is a global one that does the same in iStableMaster.lua should fix this duplication best possible -- result is that it is declared in the namespace in iStableMaster.lua
function iStableMaster:PrintPairs(table)
	for i=1,#table do
		print(i,table[i]);
	end
end-- TablePrinter returns K,V
--#EndRegion
----------------------------------------------------
---				General Functions END			 ---
----------------------------------------------------
----------------------------------------------------
---				DEVELEOPMENT TOOLS				 ---
----------------------------------------------------
function iStableMaster:DebugToggle(arg)
	iStableMaster.debugEnabled[arg] = not iStableMaster.debugEnabled[arg];
end
----------------------------------------------------
---				DEVELEOPMENT TOOLS	END			 ---
----------------------------------------------------

------------------------------------------------------------------------------------------------------- Look UP SECTION ----------------------------------------------------------------------------------------------------------


-------------------------------------------------------
--			DB LOOKUP FUNCTIONS HERE  			     --
-------------------------------------------------------
function iStableMaster:HowManyCallPets() 
	for i=1,6 do
		if(IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i])) then
		else
			return i-1;
		end
		if i == 5 then 
			return i;
		end
	end
end
-------------------------------------------------------
--			DB LOOKUP FUNCTIONS HERE END	         --
-------------------------------------------------------
-------------------------------------------------------
-- 					PetInfoLookUps					 --
-------------------------------------------------------
iStableMaster.RarePetNames = {"Lord Aj'qirai","Qroshekx","Xaarshej","Ssinkrix","Manax","Qu'rik","Qem","Ironeye the Invincible","Hissperak","Scale Belly","Deatheye",
	"Rockhide the Immovable","Hellgazer","Fangor","Osca the Bloodied","Ursol'lok","Mongress","Grizzled Ben","Grimrot","Big Samras",
	"Ol' Muddle","Mange","Hibernus the Sleeper","Bjarn","Sand Matriarch Ileus","Hadeon the Stonebreaker","Qho","Silithid Harvester","Henlare","Makhra the Ashtouched","Tahkwitz",
	"Garudeon","Quall","Olm the Wise","Aotona","Varah","Bonechewer","Fene-mal","Heress","Spiteflayer","Iceclaw","Shadowclaw","Duskstalker",
	"Tabbs","Pogeyan","Skarr","Kash","Feras","Duskcoat","Alash'anir","The Evalcharr","Somber Dawn","Aethon","Caverndark Terror","Needlespine",
	"Maison the Portabl","Iridescent Glimmershell","Sandclaw Stoneshell","Glimmerspine","Barnacle Jim","Karkin","Dunegorger Kraulok","King Krush",
	"Sunwing","Manas","Nemaeus","Whirlwing","Sorrow Wing","Pridewing Patriarch","Cloudtail","Biryuk","Blazeseeker","Plague","Trigore the Lasher",
	"Deviate Faerie Dragon","Rei Lun","Toxigore the Alpha","Banescale the Packfather","Siltstalker the Packmother","P4-N73R4","Sabertron",
	"Malfunctioning Beastbot","Optimo","Gib the Banana-Hoarder","Thicket","Dustwing","Sarltooth","Karapax","Soundless","Deepglider","Sorranos",
	"Acroniss","Deth'tilac","Bulvinkel","Lightning Paw","Magria","Ankha","Gondria","Loque'nahak","Karoma","Skoll","Arcturis","Ban'thalos",
	"Ghostcrawler","Chitali the Eldest","Anh-De the Loyal","Gorkek","Sigilback","Terrorpene","Rex Ashil","Glimmer","Hexapos","Sparkwing","Ionis",
	"Skyshadow","Anith","Yukiko","Chiaa","Vexis","Nighthowl","Snort","Stormhowl","Shiz'narasz the Consumer","Bombyx","Spirocula"
	-- Sabertron, Sandclaw Stoneshell and Grimrot exist in multiple looks figure out how do handle that. 
	-- Additionally what happens when a rare pet is renamed? can they be renamed?
	-- And What happens when a none rare pet is renamed to a rare's name?
	-- NOTE i copied from the wrong list, these are only "uncommon looks" other rares exist. that list would be 5 times as large! I should data scrape that with with a bit of code.
}; 
function iStableMaster:IsPetRare(index) 
	local l_iStableMaster = {}
	l_iStableMaster.RarePetNames = {"Lord Aj'qirai","Qroshekx","Xaarshej","Ssinkrix","Manax","Qu'rik","Qem","Ironeye the Invincible","Hissperak","Scale Belly","Deatheye",
		"Rockhide the Immovable","Hellgazer","Fangor","Osca the Bloodied","Ursol'lok","Mongress","Grizzled Ben","Grimrot","Big Samras",
		"Ol' Muddle","Mange","Hibernus the Sleeper","Bjarn","Sand Matriarch Ileus","Hadeon the Stonebreaker","Qho","Silithid Harvester","Henlare","Makhra the Ashtouched","Tahkwitz",
		"Garudeon","Quall","Olm the Wise","Aotona","Varah","Bonechewer","Fene-mal","Heress","Spiteflayer","Iceclaw","Shadowclaw","Duskstalker",
		"Tabbs","Pogeyan","Skarr","Kash","Feras","Duskcoat","Alash'anir","The Evalcharr","Somber Dawn","Aethon","Caverndark Terror","Needlespine",
		"Maison the Portabl","Iridescent Glimmershell","Sandclaw Stoneshell","Glimmerspine","Barnacle Jim","Karkin","Dunegorger Kraulok","King Krush",
		"Sunwing","Manas","Nemaeus","Whirlwing","Sorrow Wing","Pridewing Patriarch","Cloudtail","Biryuk","Blazeseeker","Plague","Trigore the Lasher",
		"Deviate Faerie Dragon","Rei Lun","Toxigore the Alpha","Banescale the Packfather","Siltstalker the Packmother","P4-N73R4","Sabertron",
		"Malfunctioning Beastbot","Optimo","Gib the Banana-Hoarder","Thicket","Dustwing","Sarltooth","Karapax","Soundless","Deepglider","Sorranos",
		"Acroniss","Deth'tilac","Bulvinkel","Lightning Paw","Magria","Ankha","Gondria","Loque'nahak","Karoma","Skoll","Arcturis","Ban'thalos",
		"Ghostcrawler","Chitali the Eldest","Anh-De the Loyal","Gorkek","Sigilback","Terrorpene","Rex Ashil","Glimmer","Hexapos","Sparkwing","Ionis",
		"Skyshadow","Anith","Yukiko","Chiaa","Vexis","Nighthowl","Snort","Stormhowl","Shiz'narasz the Consumer","Bombyx","Spirocula"}; 
	return tContains(l_iStableMaster.RarePetNames,select(2,GetStablePetInfo(index)));

end
iStableMaster.ExoticFamilies = {"Aqiri","Chimaera","Core Hound","Devilsaur","Spirit Beast","Worm","Shale Beast","Stone hound","Water Strider","Clefthoof","Carapid","Pterrordax"};
function iStableMaster:IsStabledPetExotic(index) --returns true if petInStable with index is exotic
	local l_iStableMaster ={}
	l_iStableMaster.ExoticFamilies = {"Aqiri","Chimaera","Core Hound","Devilsaur","Spirit Beast","Worm","Shale Beast","Stone Hound","Water Strider","Clefthoof","Carapid","Pterrordax"};
	return tContains(l_iStableMaster.ExoticFamilies,select(4,GetStablePetInfo(index)));
end
iStableMaster.ExpansionFamilyLookUp = {
	Classic={"Wolf","Gorilla","Cat","Bear","Raptor","Wind Serpent","Turtle","Spider","Bird of Prey","Serpent","Crab","Carrion Bird","Hyena","Scorpid","Bat","Crocolisk","Boar","Tallstrider"},
	TBC={"Ravager","Dragonhawk", "Warp Stalker", "Ray", "Sporebat"},
	WOTLK={"Spirit Beast","Core Hound","Devilsaur","Aqiri","Chimaera","Chimera","Wasp","Worm","Moth"},
	CATA={"Hound", "Shale Beast","Fox", "Beetle", "Monkey"},
	MOP={"Stone Hound", "Mechanical", "Rodent", "Basilisk", "Water Strider", "Gruffhorn", "Waterfowl"},
	WOD={"Clefthoof","Direhorn","Hydra","Riverbeast","Stag"},
	LEGION={"Scalehide","Feathermane","Oxen"},
	BFA={"Blood Beast","Toad","Carapid","Lizard","Pterrordax"},
	SL={"Camel","Courser","Mammoth"},
	DF={"Lesser Dragonkin"}
};
function iStableMaster:GetExpansionValue(family)
	if tContains(iStableMaster.ExpansionFamilyLookUp.Classic,family) then
		return 1;
	elseif tContains(iStableMaster.ExpansionFamilyLookUp.TBC,family) then
		return 2;
	elseif tContains(iStableMaster.ExpansionFamilyLookUp.WOTLK,family) then
		return 3;
	elseif tContains(iStableMaster.ExpansionFamilyLookUp.CATA,family) then
		return 4;
	elseif tContains(iStableMaster.ExpansionFamilyLookUp.MOP,family) then
		return 5;
	elseif tContains(iStableMaster.ExpansionFamilyLookUp.WOD,family) then
		return 6;
	elseif tContains(iStableMaster.ExpansionFamilyLookUp.LEGION,family) then
		return 7;
	elseif tContains(iStableMaster.ExpansionFamilyLookUp.BFA,family) then
		return 8;
	elseif tContains(iStableMaster.ExpansionFamilyLookUp.SL,family) then
		return 9;
	elseif tContains(iStableMaster.ExpansionFamilyLookUp.DF,family) then
		return 10;
	else
		assert(nil,family.." not found. Expected Return Value [1;10], Return Value: 11. Check if "..family.."Exists in: iStableMaster.ExpansionFamilyLookUp"..tostring(iStableMaster.ExpansionFamilyLookUp));
		return 11;
	end
end
iStableMaster.ExpansionName = {"Classic","The Burning Crusade","The Wrath of the Lich King","Cataclysm","Mists of Pandaria","Warloards of Draenor","Legion","Battle for Azeroth","Shadowlands","Dragonflight"};
function iStableMaster:IsExotic(family) --returns true family is exotic
	local l_iStableMaster = {}
	l_iStableMaster.ExoticFamilies = {"Aqiri","Chimaera","Core Hound","Devilsaur","Spirit Beast","Worm","Shale Beast","Stone Hound","Water Strider","Clefthoof","Carapid","Pterrordax"};
	return tContains(l_iStableMaster.ExoticFamilies,family);
end
----------------------------------------------------
---				PetInfoLookUps					 ---
----------------------------------------------------
----------------------------------------------------
--			 NEW TALENTS FUNCTIONS BEGIN	   	  --
----------------------------------------------------
-- Dragonflight Talentcheck
function iStableMaster:HasTalent(talentName) 
	lTalents = {};
	local lConfigID = C_ClassTalents.GetActiveConfigID();
	local lConfigInfo = C_Traits.GetConfigInfo(lConfigID);
	local lTreeIDs = lConfigInfo["treeIDs"];
	for i = 1, #lTreeIDs do
		for _, lNodeID in pairs(C_Traits.GetTreeNodes(lTreeIDs[i])) do
			local lNodeInfo = C_Traits.GetNodeInfo(lConfigID, lNodeID);
			local activeEntry = lNodeInfo.activeEntry;
			local activeRank = lNodeInfo.activeRank;
			if ( activeEntry and activeRank > 0 ) then
				local activeEntryID = activeEntry.entryID;
				local lEntryInfo = C_Traits.GetEntryInfo(lConfigID,activeEntryID);
				--if ( lEntryInfo ) then
				local lDefinitionID = lEntryInfo["definitionID"];
				--BA_Data["function LogTextLine"](string.format("def ID:%s",tostring(lDefinitionID)));
				local lDefinitionInfo = C_Traits.GetDefinitionInfo(lDefinitionID);
				--BA_Data["function LogTextLine"](string.format("def info:%s",tostring(lDefinitionInfo)));
				local spellID = lDefinitionInfo["spellID"];
				local spellName = GetSpellInfo(spellID);
				lTalents[spellName] = activeRank;
				--print(lTalents["Animal Companion"]);
			end
		end
	end
	if(iStableMaster:TalentExist(talentName)) then
		return (lTalents[talentName] >=1 )
	else
		return false;
	end
end
-- nillcheck for talents
function iStableMaster:TalentExist(spellName)
	return (lTalents[spellName] ~= nil);

end
----------------------------------------------------
--			 NEW TALENTS FUNCTIONS END		   	  --
----------------------------------------------------

------------------------------------------------------------------------------------------------------- AddOn Manifold Section -------------------------------------------------------------------------------------------------------

----------------------------------------------------
---		Blizzard Layout Handling Values			 ---
----------------------------------------------------

local tempPoint;
 --UIPanelWindows["PetStableFrame"] =				{ area = "left",			pushable = 7, allowOtherPanels = 1 };
--PetStableFrame:SetPoint("TOPLEFT",self:GetParent(),"TOPRIGHT",16,-200);
--UIPanelWindows["self:GetParent()"] =			{ area = "left",			pushable = 0, 	whileDead = 1, width = 733, allowOtherPanels = 1};

function iStableMaster:HookSetPetSlotToTrackCompletion()
iStableMaster.SetPetSlotCompleted = true;
end
function iStableMaster_hookOnDrag() 
	_G["PetStableFrame"]:HookScript("OnLeave", function() _G["PetStableFrame"].btnHover = nil; _G["PetStableFrame"].btnOrigin = nil; end);
	_G["PetStableFrame"].IsDragging = false;
	for i = 1,5 do 
		_G["PetStableActivePet"..i]:HookScript("OnDragStart", function()
			if(not _G["PetStableFrame"].IsDragging) then
				_G["PetStableFrame"].IsDragging = true;
				_G["PetStableFrame"].btnOrigin = _G["PetStableFrame"].btnHover;
			end
		end);
		_G["PetStableActivePet"..i]:HookScript("OnEnter", function()
			_G["PetStableFrame"].btnHover = PetStable_GetPetSlot(i,true); 	
		end);
	end
	for i = 1,10 do 
		_G["PetStableStabledPet"..i]:HookScript("OnEnter", function()
			_G["PetStableFrame"].btnHover = PetStable_GetPetSlot(i,false); 	
			--print(_G["PetStableFrame"].btnHover);
		end);
		_G["PetStableStabledPet"..i]:HookScript("OnDragStart", function() 

			if(not _G["PetStableFrame"].IsDragging) then
				_G["PetStableFrame"].IsDragging = true;
				_G["PetStableFrame"].btnOrigin = _G["PetStableFrame"].btnHover;

			end
		end);
	end
	hooksecurefunc("SetPetSlot", function()
		if(iStableMaster.debugEnabled.unstableFunctionsOn == false) then 
			return;
		end
		if(	_G["PetStableFrame"].btnHover ~= nil and _G["PetStableFrame"].IsDragging) then 
			if(_G["PetStableFrame"].btnOrigin ~= _G["PetStableFrame"].btnHover)then
				--print(_G["PetStableFrame"].btnOrigin,_G["PetStableFrame"].btnHover);
				iStableMaster:UpdateSquadCurrentSlots(_G["PetStableFrame"].btnOrigin,_G["PetStableFrame"].btnHover);
				_G["PetStableFrame"].IsDragging = false;
			end
		end
	end);
end -- Blizzard Hook to update if things change in Blizzard Standard UI while the AddOn Is Loaded
function iStableMaster:StablesOpen()
	local point, relativeTo, relativePoint, xOfs, yOfs = PetStableFrame:GetPoint(1);
	--print(xOfs);
	if(iStableMaster:Truncate(xOfs,3) == -500) then
		PetStableFrame:SetPoint("TOPLEFT",StablesCollection:GetParent():GetWidth()+50,-154);
	else
		PetStableFrame:SetPoint("TOPLEFT",-500,-204);
	end
end -- Blizzard Taint on PetStablesFrame Positioning befitting the AddOn
function iStableMaster:StablesToggleButtonTextUpdate() 
	local point, relativeTo, relativePoint, xOfs, yOfs = PetStableFrame:GetPoint(1);
	if(not IsAtStableMaster()) then
		OpenStablesButton:Disable();
		OpenStablesButton:SetText("Stable Disabled");
	else
		if(iStableMaster:Truncate(xOfs,3) ~= -500) then
			OpenStablesButton:SetText("Hide Stables");
		else
			OpenStablesButton:SetText("Show Stables");
		end
	end
end -- Updates Text On button that shows and hides PetStableFrame
hooksecurefunc("PetRename", function() 
	iStableMaster:SavePetInfoToWTF();
	if(StablesCollection:IsShown())then
		iStableMaster:SetPetScrollTilesContent();	 
		iStableMaster:SetPetModelView();
		iStableMaster:UpdateActiveCards();
	end 
	C_Timer.After(1.5, function()
		iStableMaster:SavePetInfoToWTF();
		if(StablesCollection:IsShown())then
			iStableMaster:SetPetScrollTilesContent();	 
			iStableMaster:SetPetModelView();
			iStableMaster:UpdateActiveCards(); 	 
		end
	end);
end); -- Blizzard Hook to update The AddOn Data if a Pet is renamed while the AddOn Is Loaded
----------------------------------------------------
---		Blizzard Layout Handling Values End		 ---
----------------------------------------------------
----------------------------------------------------
--        EVENT TRIGGERED FUNCTION HANDLERS       --
----------------------------------------------------
function iStableMaster:UpdateActiveCardsIfNewCallPetIsLearned()

	for i=1,5,1 do

		if(IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Hide();
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","DarkGreen"));
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateTexture(nil,"ARTWORK",nil, 3);
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"]:SetTexture("Interface\\PETBATTLES\\PetBattle-LockIcon");
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"]:SetSize(64,64);
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"],"CENTER",0,0);

			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormal");
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetPoint("TOP",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"],"TOP",0,-16);
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:GetWidth(),24);
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetFont("Fonts\FRIZQT__.TTF", 12, "MONOCHROME");
			--		local SpellName, SpellRank, icon, castTime, minRange, maxRange = GetSpellInfo(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]);
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetText("Requires: "..SpellName);
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetTextColor(1,0,0,1);
		end
	end


end
do--IS ADDON LOADED AOTH
	if(IsAddOnLoaded("AspectOfTheHunter")) then
		-- Maybe use AspectOfTheHunter as Optional Dependency for spell data?
	end
end--IS ADDON LOADED Aaspect Of The Hunter by Ravenclaw

----------------------------------------------------
--     EVENT TRIGGERED FUNCTION HANDLERS END      --
----------------------------------------------------
----------------------------------------------------
---			StablesCollection <Scripts>			 --- 
----------------------------------------------------

function StablesCollection_OnShow(self)
	
	--iStableMaster:Print("DEBUG:: Before self:GetParent():SetAttribute");
	-------------------------------------------------------------------------
	self:GetParent():SetAttribute("UIPanelLayout-pushable", 1);
	self:GetParent():SetAttribute("UIPanelLayout-allowOtherPanels", 1);
	--	PetStableFrame:SetAttribute("UIPanelLayout-pushable", 1);
	PetStableFrame:SetAttribute("UIPanelLayout-pushable", 1);
	PetStableFrame:SetAttribute("UIPanelLayout-allowOtherPanels", 1);
	------------------------------------------------------------------------
	--SetUIPanelAttribute(PetStableFrame,"UIPanelLayout-allowOtherPanels", 1)
	--SetUIPanelAttribute(CollectionsJournal,"UIPanelLayout-allowOtherPanels", 1)
	--SetUIPanelAttribute(PetStableFrame,"UIPanelLayout-pushable", 1)
	--SetUIPanelAttribute(CollectionsJournal,"UIPanelLayout-pushable", 0)
	-----------------------------------------------------------------------
	--iStableMaster:Print("DEBUG:: After self:GetParent():SetAttribute");
	PetStableFrame:ClearAllPoints();
	PetStableFrame:SetPoint("TOPLEFT",-500,-204);
	HideUIPanel(GossipFrame);
	----------------------------------------------------
	--iStableMaster:Print("DEBUG:: Before iStableMaster:PopulateSquadScrollFrame();");
	iStableMaster:PopulateSquadScrollFrame();
	--	iStableMaster:Print("DEBUG:: After iStableMaster:PopulateSquadScrollFrame();");
	--	iStableMaster:Print("DEBUG:: Before iStableMaster:SelectedPresetUpdate();");
	iStableMaster:SelectedPresetUpdate();
	--	iStableMaster:Print("DEBUG:: After iStableMaster:SelectedPresetUpdate();");
end
function StablesCollection_OnLoad(self)
	self:RegisterEvent("PET_STABLE_UPDATE");
	self:RegisterEvent("PET_STABLE_SHOW");
	self:RegisterEvent("PET_STABLE_CLOSED");
	self:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED");
	self:RegisterEvent("LEARNED_SPELL_IN_TAB");
	self:RegisterEvent("TRAIT_CONFIG_UPDATED");
	self:RegisterEvent("ACTIVE_COMBAT_CONFIG_CHANGED");
	PanelTemplates_SetNumTabs(self, 2);
	PanelTemplates_SetTab(self, 1);
	hooksecurefunc("PetAbandon",function() local squadslimit = iStableMaster:StringKeyTableLength(iStableMasterStableDB["SavedSquads"],"Squad");
		for i = 1, squadslimit do for j = 1, 5 do   if(GetStablePetInfo(j) == nil and iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j]["CurrentSlot"] == j) then iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j]  =  nil; end  end end end);
	self:RegisterEvent("ADDON_LOADED");
end
function StablesCollection_OnEvent(self, event, ...)
	local arg1 = ...;
	if( event == "TRAIT_CONFIG_UPDATED")then -- when a talent tree changes not when swapped!
		--print("TRIGGER");
	end
	if( event == "TRAIT_CONFIG_LIST_UPDATED")then -- NOT ADDED TO REGISTRATION
		--print("TRIGGER");
	end
	if( event == "TRAIT_NODE_CHANGED")then -- NOT ADDED TO REGISTRATION
		--print("TRIGGER");
	end
	if( event == "TRAIT_NODE_CHANGED_PARTIAL")then -- NOT ADDED TO REGISTRATION
		--print("TRIGGER Partial");
	end
	if( event == "TRAIT_CONFIG_CREATED")then -- NOT ADDED TO REGISTRATION
		--print("TRIGGER Created");
	end
	if( event == "TRAIT_CONFIG_DELETED")then -- NOT ADDED TO REGISTRATION
		--print("TRIGGER Deleted");
	end
	if( event == "TRAIT_SYSTEM_INTERACTION_STARTED")then -- NOT ADDED TO REGISTRATION
		--print("TRIGGER Interaction");
	end
	if( event == "ACTIVE_COMBAT_CONFIG_CHANGED")then -- Spec change
		--print("ACTIVE_COMBAT_CONFIG_CHANGED");
	end
	if( event == "SPECIALIZATION_CHANGE_CAST_FAILED")then 
		--print("SPECIALIZATION_CHANGE_CAST_FAILED");
	end
	if(event == "ACTIVE_TALENT_GROUP_CHANGED" or  "ACTIVE_COMBAT_CONFIG_CHANGED" or "TRAIT_CONFIG_UPDATED") then 
		local currentSpec = GetSpecialization();
		GlobalSpecialization = currentSpecName[currentSpec];
		local localSpecValue = GlobalActiveSlotLoopValue;
		if(GlobalSpecialization == "Beast Mastery") then 
			GlobalActiveSlotLoopValue = 6;
		else
			GlobalActiveSlotLoopValue = 5;
		end
		iStableMasterDB["Dynamics"]["D_STABLES_COLLECTION"]["ActiveSlotLoopValue"] = GlobalActiveSlotLoopValue;
		iStableMaster:UpdateFunctionsOnActiveCards();
		if ActivePetSlotsCards ~= nil then 
			iStableMaster:PopulateActiveCards();
			iStableMaster:UpdateActiveCards();
			iStableMaster:SetPetScrollTilesContent();
			if(iStableMaster:GetFilterValue("AnyFilter")) then
				iStableMaster:UpdateFilterSpecs(true);
			else
				iStableMaster:MasterFilterSort();
			end
			iStableMaster:PopulateSquadScrollFrame();
		end
	end
	if( event == "ADDON_LOADED") then
		-- Do nothing		
	end
	if (event == "PET_STABLE_SHOW" ) then
		if(IsAtStableMaster()) then
			OpenStablesButton:Enable(); 
		end
		OpenStablesButton:SetText("Show Stables");
		if(nil == iStableMaster.currentlySelectedPet) then
		end
	end
	if (event == "PET_STABLE_CLOSED") then
		if(not IsAtStableMaster()) then
			OpenStablesButton:Disable();
			OpenStablesButton:SetText("Stable Disabled");
		end
	end
	if(event == "LEARNED_SPELL_IN_TAB" or "ACTIVE_COMBAT_CONFIG_CHANGED" or "TRAIT_CONFIG_UPDATED") then
		if ActivePetSlotsCards ~= nil then 
			iStableMaster:UpdateActiveCardsIfNewCallPetIsLearned()
		end
	end	
	if (event == "PET_STABLE_UPDATE" or event == "LEARNED_SPELL_IN_TAB") then
		if ActivePetSlotsCards ~= nil then 
			-- fallback safety of squad info changed from stablemaster interface by blizzard
			--iStableMaster:UpdateSquadInfoOnStableUpdateEvent(); -- test basis
			iStableMaster:SavePetInfoToWTF();
			iStableMaster:SetPetScrollTilesContent();
			iStableMaster:SetPetModelView();
			iStableMaster:UpdateActiveCards();
			-- add some condition here to fit option for hidden slots
			if(iStableMaster:GetFilterValue("AnyFilter")) then
				iStableMaster:UpdateFilterSpecs(true);
			else
				iStableMaster:MasterFilterSort();
			end
			iStableMaster:SelectedPresetUpdate();
		end
	end
end
-- Functions BELOW IN REGION ARE CUSTOM FRAMEHANDLERS
function OpenStablesButton_OnClick()
	iStableMaster:StablesOpen();
end -- Handles Blizzard Frame Taint on PetStablesFrame
function StablesCollection_Show()
	CollectionsJournal:SetAttribute("UIPanelLayout-width", UIPanelWindows["CollectionsJournal"]["width"]);
	CollectionsJournal:SetWidth(UIPanelWindows["CollectionsJournal"]["width"]);
	StablesCollection:Show();
	if (iStableMaster.firstOpen) then 
		iStableMaster:InitPetInfoToWTF();
		iStableMaster:SavePetInfoToWTF();
		iStableMaster:PopulateCardContainer();
		iStableMaster:PopulateActiveCards();
		iStableMaster:PopulateScrollFrame();
		iStableMaster:UpdateActiveCards();
		StablesLeftFrame:SetBackdrop("Interface\\DRESSUPFRAME\\DressingRoomHunter"); -- Set The Backdrop of the 3D-model to the selected file.
		iStableMaster_hookOnDrag();
		iStableMaster.firstOpen = false;
	end
	iStableMaster:PopulateCardContainer();
	iStableMaster:PopulateActiveCards();
	iStableMaster:UpdateActiveCards();
	ActiveCardsContainerBg:SetVertexColor(iStableMaster:GetDBColour("Default","LightGreen"));
	StablesCollection:SetParent(CollectionsJournal);
	StablesCollection:ClearAllPoints();
	StablesCollection:SetAllPoints();
	CollectionsJournal:SetTitle(C_STABLES_COLLECTION["Title"]);
	CollectionsJournal:SetPortraitToAsset("Interface\\Icons\\Ability_Physical_Taunt");
	iStableMaster:StablesToggleButtonTextUpdate();
	if(iStableMasterOptionsDB.Layout == "Default" or iStableMasterOptionsDB.Layout == nil) then
		CollectionsJournal:SetAttribute("UIPanelLayout-width", 1000);
		CollectionsJournal:SetWidth(1000);
		iStableMaster:PetScrollFrameUpdateScrollFrameWidths(StablesRightFrame.ScrollFrame:GetWidth());
		CardContainerFrameInsetFramePetStableActiveBg:Hide();
		CardContainerFrameInsetFramePetStableActivePetsLabel:Hide()
		CardContainerFrameInsetFramePetStableAnimalCompanionLabel:Hide();
	elseif(iStableMasterOptionsDB.Layout == "Compact") then
		CollectionsJournal:SetAttribute("UIPanelLayout-width", 720);
		CollectionsJournal:SetWidth(720);
		iStableMaster:PetScrollFrameUpdateScrollFrameWidths(StablesRightFrame.ScrollFrame:GetWidth());
		--CardContainerFrameInsetFramePetStableActiveBg:Show();
		CardContainerFrameInsetFramePetStableActiveBg:Hide();
		CardContainerFrameInsetFramePetStableActivePetsLabel:Show();
		CardContainerFrameInsetFramePetStableAnimalCompanionLabel:Show(); 
		if(iStableMaster.firstOpenCompact) then
			local point, relativeTo, relativePoint, xOfs, yOfs = OpenStablesButton:GetPoint();
			--print(point, relativeTo, relativePoint, xOfs, yOfs);
			OpenStablesButton:SetPoint(point,relativeTo,relativePoint, (xOfs + 90),yOfs);
			iStableMaster.firstOpenCompact = false;
		end
	else
		CollectionsJournal:SetAttribute("UIPanelLayout-width", 1000);
		CollectionsJournal:SetWidth(1000);
		iStableMaster:PetScrollFrameUpdateScrollFrameWidths(StablesRightFrame.ScrollFrame:GetWidth());
	end
	iStableMaster:PopulateScrollFrame();
	iStableMaster:SetPetScrollTilesContent();
	iStableMaster:SetSelectedHighlight()
	iStableMaster:SetPetModelView();
	if(not IsAtStableMaster()) then
		OpenStablesButton:Disable();
		OpenStablesButton:SetText("Stable Disabled");
	end
	if(iStableMaster:GetFilterValue("AnyFilter")) then
		iStableMaster:UpdateFilterSpecs(true);
	else	
		iStableMaster:MasterFilterSort();
	end
	iStableMaster:CreateDataField3dModelBackDrops() 
end -- Show Sequence Routine of the StablesCollection Frame
function StablesCollection_Hide()
	-- DONT FORGET TO UNCOMMENT IF NOT WORKING
	PetStableFrame:SetPoint("TOPLEFT",-500,-204);
	---------------------------------
	iStableMaster:StablesToggleButtonTextUpdate();
	CollectionsJournal:SetAttribute("UIPanelLayout-width", 703);
	CollectionsJournal:SetWidth(703);
	iStableMaster:PetScrollFrameUpdateScrollFrameWidths(StablesRightFrame.ScrollFrame:GetWidth());
	StablesCollection:Hide();
end -- Hide Sequence Routine of the StablesCollection Frame
----------------------------------------------------
---	   	StablesCollection </Scripts>  END	     ---
----------------------------------------------------
----------------------------------------------------
---	 StablesCollection Add to SettingsCall       ---
----------------------------------------------------
function iStableMaster:OpeniStablesMasterSettings()
	if(firstclick == false) then
		if(not SettingsPanel:IsShown()) then
			Settings.OpenToCategory(iStableMasterSettingsFrame.name);				
			Settings.OpenToCategory(iStableMasterSettingsFrame.name);
			iStableMaster.fistclick = true;
		else
			HideUIPanel(SettingsPanel);
		end
	else
		if(not SettingsPanel:IsShown()) then
			Settings.OpenToCategory(iStableMasterSettingsFrame.name);
			Settings.OpenToCategory(iStableMasterSettingsFrame.name);		-- added to make up for unfunctioning logic
		else
			HideUIPanel(SettingsPanel);
		end
	end
end
----------------------------------------------------
---	 StablesCollection Add to SettingsCall  END  ---
----------------------------------------------------

----------------------------------------------------------------------------------------------- StablesCollection Frames Handling SECTION ------------------------------------------------------------------------------------------------
----------------------------------------------------
-- General Purpose StablesCollection Functions
----------------------------------------------------
iStableMaster.AreLayoutFreezeFXOn = false;
iStableMaster.FreezeFXInProgress = false;
function iStableMaster:FreezeLayoutFX(onoff)
	if(iStableMaster.FreezeFXInProgress) then
		return;
	end
	iStableMaster.FreezeFXInProgress = true;
	if(onoff) then 
		-- Set ALL colours desaturated
					-- first save a global table with all the colours about to be desaturated, so we can return colour only to those who aren't desaturated on purpose before the call
					-- then we desaturate the elements in our list
		-- Show FreezeFrame perhaps with an extra argument of the duration, this depends on the usage ofc.
	else
		-- Return ALL desaturated colours caused by this effect using the table created on onoff true
	end
	iStableMaster.FreezeFXInProgress = false;
end -- Intended to be used as a visual indicator for a "locked" interface
----------------------------------------------------
-- General Purpose StablesCollection Functions End
----------------------------------------------------



----------------------------------------------------
---		PetScrollFrame Search functions 		 ---
----------------------------------------------------
function iStableMaster:OnSearchSubmit() 
	_G["StablesRightFrameEditBox"]:HookScript("OnEnterPressed", function(self) 
		iStableMaster:SubmitSearch(self); -- this bit may fuck up future options as it calls default sorting
	end);
	_G["StablesRightFrameEditBox"]:HookScript("OnEditFocusGained", function(self) 
		local input = self:GetText();
		if(inpput == "" or input == nil or input == "Search") then
			self:SetText("");
			self:SetTextColor(iStableMaster:ColourNormalizer("#FFFFFF"));
		end
	end);
	_G["StablesRightFrameEditBox"]:HookScript("OnEditFocusLost", function(self) 
		local input = self:GetText();
		if(input == nil or input == "") then
			iStableMaster:SubmitSearch(self);  -- this bit may fuck up future options as it calls default sorting
			self:SetText("Search");
			self:SetTextColor(iStableMaster:ColourNormalizer("#A9A9A9"));
		else
			self:SetTextColor(iStableMaster:ColourNormalizer("#FFFFFF"));
		end
	end);
	_G["StablesRightFrameEditBox"]:HookScript("OnEscapePressed", function(self)
		local input = self:GetText();
		if(not(input == "Search" or input == nil or input == "")) then
			self:SetText(self.lastSearchSubmitted);
			iStableMaster:SubmitSearch2(self,self.lastSearchSubmitted);
		else
			self:SetText("");
			iStableMaster:SubmitSearch(self); -- this bit may fuck up future options as it calls default sorting		
		end
	end);
end
function iStableMaster:SubmitSearch(self) 
	local input = self:GetText();
	local startOfString, endOfString = string.find(input,input);
	if(endOfString < 1 or endOfString == nil) then
		if(iStableMaster:GetFilterValue("AnyFilter")) then
			iStableMaster:UpdateFilterSpecs(true);
		else
			iStableMaster:MasterFilterSort(input);
		end
	else 
		iStableMaster:MasterFilterSort(input);
	end   
	self:ClearFocus();
	if(input == nil or input == "") then
		self:SetText("Search");
		self:SetTextColor(iStableMaster:ColourNormalizer("#A9A9A9"));
	end
	self.lastSearchSubmitted = input;
end
function iStableMaster:SubmitSearch2(self,input) 
	local startOfString, endOfString = string.find(input,input);
	if(endOfString < 1 or endOfString == nil) then
		if(iStableMaster:GetFilterValue("AnyFilter")) then
			iStableMaster:UpdateFilterSpecs(true);
		else
			iStableMaster:MasterFilterSort(input);
		end
	else 
		iStableMaster:MasterFilterSort(input);
	end   
	self:ClearFocus();
	if(input == nil or input == "") then
		self:SetText("Search");
		self:SetTextColor(iStableMaster:ColourNormalizer("#A9A9A9"));
	end
	self.lastSearchSubmitted = input;
end
----------------------------------------------------
---		PetScrollFrame Search functions End		 ---
----------------------------------------------------
----------------------------------------------------
---					ToolTips				     ---
----------------------------------------------------
iStableMaster.dietTooltip = CreateFrame('GameTooltip', "iStableMaster_dietTooltip", nil, "GameTooltipTemplate");
iStableMaster.dataHeaderSpecTooltip = CreateFrame('GameTooltip', "iStableMaster_dataHeaderSpecTooltip", nil, "GameTooltipTemplate");
iStableMaster.dataHeaderFamTooltip = CreateFrame('GameTooltip', "iStableMaster_dataHeaderFamTooltip", nil, "GameTooltipTemplate");
function iStableMaster:DietMouseOver(parent,text,state)
	if(state) then 
		GameTooltip:ClearLines();
		GameTooltip:Hide();
	else
		if(not GameTooltip:IsShown()) then
			GameTooltip:SetOwner(parent,"ANCHOR_CURSOR");
			GameTooltip:AddLine("");
			GameTooltip:SetText("Diet: ","|cFFFFFFFF",true);
			GameTooltip:AddLine("");
			GameTooltip:AddLine("|cFFFFFFFF"..text);
			GameTooltip:Show();
		end
	end
end
function iStableMaster:PetMouseOver(parent,owner,state)
	if(state) then 
		GameTooltip:ClearLines();
		GameTooltip:Hide();
	else
		if(not GameTooltip:IsShown() and parent["PetInfo"]["name"] ~= "N/A") then
			GameTooltip:SetOwner(owner,"ANCHOR_CURSOR");
			GameTooltip:AddLine("");
			GameTooltip:SetText(parent["PetInfo"]["name"]..": ","|cFFFFFFFF",true);
			if(iStableMaster:IsExotic(parent["PetInfo"]["family"]))then
				GameTooltip:AddLine("");
				GameTooltip:AddLine("|cFF6E006E".."<Exotic>");
			end
			GameTooltip:AddLine("");
			GameTooltip:AddLine("|cFFFFFFFF".."Family: "..parent["PetInfo"]["family"]);
			GameTooltip:AddLine("");
			GameTooltip:AddLine("|cFFFFFFFF".."Specialization: "..parent["PetInfo"]["talent"]);
			GameTooltip:AddLine("");
			GameTooltip:AddLine("|cFFFFFFFF".."Level "..parent["PetInfo"]["level"]);
			GameTooltip:AddLine("");
			GameTooltip:AddLine("|cFFFFFFFF".."Expansion:\n"..iStableMaster.ExpansionName[iStableMaster:GetExpansionValue(parent["PetInfo"]["family"])]);
			local nullcheck = parent["PetInfo"]["name"];
			if nullcheck ~= "N/A" then
				for i=1,2 do
					GameTooltip:AddLine("");
					local name, rank, icon, castTime, minRange, maxRange = GetSpellInfo(iStableMasterDB["SpecializationAbilities"][parent["PetInfo"]["talent"]][i]);
					if name ~= nil then
						GameTooltip:AddLine(name);
					end
					if icon ~= nil then
						GameTooltip:AddTexture(icon);
					end
				end
			end
			GameTooltip:Show();
		end
	end
end
iStableMaster.dataHeaderFamIcon = iStableMaster.dataHeaderFamIcon or {};
function iStableMaster.dataHeaderFamIcon:MouseOver(parent,text,state)
	if(state) then 
		GameTooltip:ClearLines();
		GameTooltip:Hide();
	else
		if(not GameTooltip:IsShown()) then
			GameTooltip:SetOwner(parent,"ANCHOR_CURSOR");
			GameTooltip:AddLine("");
			GameTooltip:SetText("Family: ","|cFFFFFFFF",true);
			GameTooltip:AddLine("");
			GameTooltip:AddLine("|cFFFFFFFF"..text);
			GameTooltip:Show();
		end
	end
end
iStableMaster.dataHeaderSpecIcon = iStableMaster.dataHeaderSpecIcon or {};
function iStableMaster.dataHeaderSpecIcon:MouseOver(parent,text,state)
	if(state) then 
		GameTooltip:ClearLines();
		GameTooltip:Hide();
	else
		if(not GameTooltip:IsShown()) then
			GameTooltip:SetOwner(parent,"ANCHOR_CURSOR");
			GameTooltip:AddLine("");
			GameTooltip:SetText("Specialization: ","|cFFFFFFFF",true);
			GameTooltip:AddLine("");
			GameTooltip:AddLine("|cFFFFFFFF"..text);
			GameTooltip:Show();
		end
	end
end
function iStableMaster:SpellMouseOver(parent,details,state)
	if(state) then 
		GameTooltip:ClearLines();
		GameTooltip:Hide();
	else
		if(not GameTooltip:IsShown()) then
			GameTooltip:SetOwner(parent,"ANCHOR_CURSOR");
			GameTooltip:AddLine("");
			GameTooltip:SetHyperlink("spell:"..details);
			GameTooltip:Show();
		end
	end
end
----------------------------------------------------
---					ToolTips END			     ---
----------------------------------------------------
----------------------------------------------------
---				PetScrollFrame				     ---
----------------------------------------------------
function iStableMaster:SetPetScrollTilesContent(filtermode)
	if(iStableMaster.ScrollFrameArrElem == nil) then
		iStableMaster:Print("No Scroll Tiles were instantiated in: iStableMaster.ScrollFrameArrElem[]: Trying again!");
		if(backupAttempt == false) then
			iStableMaster:PopulateScrollFrame();
			iStableMaster:PopulateActiveCards();
			backupAttempt = true;
		end
		return;
	end
	if(filtermode == "default" or filtermode == nil) then
		for i=1, iStableMaster.StablesCollectionScrollbarMaxChildren,1 do 
			--local button = _G["PetStableStabledPet"..i];
			local petSlot = i;
			local petisStabled = nil;
			if(i < 6) then
				petSlot = PetStable_GetPetSlot(i, true);
				petisStabled = false;
			else
				petSlot = (i - 5);
				petisStabled = true;
			end
			local l_icon, l_name, l_level, l_family, l_talent = GetStablePetInfo(i);
			if(i < 6) then
				--if(iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"]) then
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i] = {};
				end
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"] = {};
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["icon"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["name"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["level"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["family"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["talent"];
				-- custom info
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["favourite"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["inStables"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["Slot"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["abilities"];
				--end
			else
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i] = {};
				end
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"] = {};
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["icon"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["name"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["level"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["family"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["talent"];
				-- custom info
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["favourite"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["inStables"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["Slot"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["abilities"];
			end
			-- setUp Frame
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"] == nil) then 
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"] = CreateFrame("Frame", nil, iStableMaster.ScrollFrameArrElem["ScrollElement"..i], BackdropTemplateMixin and "BackdropTemplate");
			end
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"]:SetSize(44,44);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"]:SetPoint("TOPLEFT",iStableMaster.ScrollFrameArrElem["ScrollElement"..i],"TOPLEFT");
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["icon"] ~= nil and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["icon"] ~= "N/A") then
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"]:CreateTexture(nil,"ARTWORK");
				end
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"]:CreateTexture(nil,"OVERLAY");
				end
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetTexture(nil);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetTexture(nil);
				--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetColorTexture(0,0,0,0);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetAlpha(1);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetTexture(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["icon"]);
				if(iStableMaster:IsExotic(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["family"]))then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetAlpha(1);
					--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetTexture("Interface\\AddOns\\iStableMaster\\BlizzStar 256x256 3");
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic Border 3-FAT.blp","ARTWORK");
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetVertexColor(0.5,0.1,1,1);
					--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetSize(18,18);
					--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"],"CENTER",14,12);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetSize(40,40);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"],"CENTER",0,0);
					--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetFrameLevel(2030);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetDrawLayer("ARTWORK", 5)
				end
				--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetMask("Interface\\PETBATTLES\\PetBattle-SelectedPetGlow");
				--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetFrameLevel(2020);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetSize(40,40);
				--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetAllPoints(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"]);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"],"CENTER");
			else
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"]:CreateTexture(nil,"ARTWORK");
				end
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"]:CreateTexture(nil,"OVERLAY");
				end
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["ExoticIconTexture"]:SetTexture(nil);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetTexture(nil);
				--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetColorTexture(nil);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetAlpha(1);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetTexture("Interface\\AddOns\\iStableMaster\\PetStable-Partsbuttonbg");
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetSize(40,40);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"],"CENTER");
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetDrawLayer("ARTWORK", 4)
			end
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"] == nil) then
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"] = CreateFrame("Frame","FavouriteStarFrame"..i,iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"], "FavouriteStarFrame");
			end
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"]:SetSize(20,20);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"]:ClearAllPoints();
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"],"LEFT",4,12);
			if(not iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["favourite"]) then
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"].bg:SetAlpha(0.2);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"].fill:SetAlpha(0);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"].frame:SetAlpha(0.75);
			else
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"].fill:SetAlpha(1);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"].bg:SetAlpha(0);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"].frame:SetAlpha(1);
			end
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"]:SetScript("OnEnter", function(self) 
				if(not iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i].PetInfo.favourite) then
					self.bg:SetAlpha(1);
					self.bg:SetVertexColor(1,1,1,0.653);
					--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"].fill:SetAlpha(0);
					self.frame:SetAlpha(1);
				else
					self.fill:SetAlpha(1);
					self.fill:SetVertexColor(0.953,953,0.253,1);
					self.bg:SetAlpha(0);
					self.frame:SetAlpha(1);
				end
			end);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"]:SetScript("OnLeave", function(self) 
				if(not iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["favourite"]) then
					--iStableMaster:SetPetScrollTilesContent(filtermode)
					--print("left Fav Star");
					self.bg:SetAlpha(0.2);
					self.bg:SetVertexColor(0.953,0.953,0.953,0.2);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"].fill:SetAlpha(0);
					self.frame:SetAlpha(0.75);
				else
					self.fill:SetVertexColor(0.753,0.753,0,1);
					self.fill:SetAlpha(1);
					self.bg:SetAlpha(0);
					self.frame:SetAlpha(1);
				end
				-- Update Scroll Frames
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"] == nil) then 
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"] = CreateFrame("Frame", nil, iStableMaster.ScrollFrameArrElem["ScrollElement"..i], BackdropTemplateMixin and "BackdropTemplate");
				end
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:GetWidth()-44,46);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:SetPoint("TOPLEFT",iStableMaster.ScrollFrameArrElem["ScrollElement"..i],"TOPLEFT",40,0);
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:CreateTexture(nil,"BACKGROUND");
				end
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormal"); 
				end
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:GetWidth(),46);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"],"TOPLEFT",4,0);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:SetFont("Fonts\FRIZQT__.TTF", 12, "MONOCHROME");
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:SetText(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["name"]);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:SetWidth(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:GetStringWidth());
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetTexture(nil);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetAlpha(1);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetAtlas("PetList-ButtonBackground");
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:GetSize());
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"],"CENTER");
				if(iStableMaster:IsExotic(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["family"]))then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetVertexColor(1,0,1,1);
				elseif (i <= 5) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetVertexColor(0,1,0,1);
				elseif (i == 6 and GlobalSpecialization == "Beast Mastery") then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetVertexColor(0,0,1,1);
				elseif (iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["favourite"]) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetVertexColor(1,1,0,1);
				else
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetVertexColor(0.5,0.5,0.5,1);
				end
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:CreateTexture(nil,"OVERLAY",nil,2);
				end
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetTexture(nil);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetAlpha(0);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetAtlas("PetList-ButtonHighlight");
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:GetSize());
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"],"CENTER");
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:CreateTexture(nil,"OVERLAY");
				end
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"]:SetTexture(nil);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"]:SetAlpha(0);
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"]:SetAtlas("PetList-ButtonSelect");
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"]:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:GetSize());
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"],"CENTER");
				iStableMaster:SetPetSpecIcon(i);
				iStableMaster:MasterFilterSort();
			end);
			_G["FavouriteStarFrame"..i].index = i;
			_G["FavouriteStarFrame"..i]:SetScript("OnMouseDown", function(self)iStableMaster:ChangeFavouriteSafe(self.index); 
				if(not iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["favourite"]) then
					self.bg:SetAlpha(1);
					self.bg:SetVertexColor(1,1,1,0.653);
					--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["FavouriteStarFrame"].fill:SetAlpha(0);
					self.frame:SetAlpha(1);
				else
					self.fill:SetAlpha(1);
					self.fill:SetVertexColor(0.953,953,0.253,1);
					self.bg:SetAlpha(0);
					self.frame:SetAlpha(1);
				end
				iStableMaster:MasterFilterSort();
			end);
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"] == nil) then 
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"] = CreateFrame("Frame", nil, iStableMaster.ScrollFrameArrElem["ScrollElement"..i], BackdropTemplateMixin and "BackdropTemplate");
			end
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:GetWidth()-44,46);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:SetPoint("TOPLEFT",iStableMaster.ScrollFrameArrElem["ScrollElement"..i],"TOPLEFT",40,0);
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"] == nil) then
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:CreateTexture(nil,"BACKGROUND");
			end
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"] == nil) then
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormal"); 
			end
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:GetWidth(),46);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"],"TOPLEFT",4,0);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:SetFont("Fonts\FRIZQT__.TTF", 12, "MONOCHROME");
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:SetText(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["name"]);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:SetWidth(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]["PetName"]:GetStringWidth());
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetTexture(nil);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetAlpha(1);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetAtlas("PetList-ButtonBackground");
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:GetSize());
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"],"CENTER");
			if(iStableMaster:IsExotic(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["family"]))then
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetVertexColor(1,0,1,1);
			elseif (i <= 5) then
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetVertexColor(0,1,0,1);
			elseif (i == 6 and GlobalSpecialization == "Beast Mastery") then
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetVertexColor(0,0,1,1);
			elseif (iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["favourite"]) then
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetVertexColor(1,1,0,1);
			else
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureBg"]:SetVertexColor(0.5,0.5,0.5,1);
			end
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"] == nil) then
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:CreateTexture(nil,"OVERLAY",nil,2);
			end
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetTexture(nil);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetAlpha(0);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetAtlas("PetList-ButtonHighlight");
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:GetSize());
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"],"CENTER");
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"] == nil) then
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:CreateTexture(nil,"OVERLAY");
			end
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"]:SetTexture(nil);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"]:SetAlpha(0);
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"]:SetAtlas("PetList-ButtonSelect");
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"]:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"]:GetSize());
			iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureSelected"]:SetPoint("CENTER",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorFrame"],"CENTER");
			iStableMaster:SetPetSpecIcon(i);
		end
	else
		--do nothing
	end
	if(_G["StablesRightFrameEditBox"]:GetText() ~= nil) then
		iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]);
	elseif(iStableMasterOptionsDB["ScrollList"]["HideEmptyStableSlots"]) then
		if(iStableMaster:GetFilterValue("AnyFilter")) then
			iStableMaster:UpdateFilterSpecs(true);
		else
			iStableMaster:MasterFilterSort();
		end
	else
		if(GlobalActiveSlotLoopValue == 5) then
			if(iStableMaster:GetFilterValue("AnyFilter")) then
				iStableMaster:UpdateFilterSpecs(true);
			else
				iStableMaster:MasterFilterSort();
			end
		else
			if(iStableMaster:GetFilterValue("AnyFilter")) then
				iStableMaster:UpdateFilterSpecs(true);
			else
				iStableMaster:MasterFilterSort();
			end
		end
	end
end
function iStableMaster:PopulateScrollFrame()
	if(_G["ScrollElement0"] ~= nil) then
		return;
	end
	
	local ElementSizeX = (StablesRightFrame.ScrollFrame:GetWidth());
	local ElementSizeY = 44;
	local mousePos = {x=0,y=0};
	iStableMaster.StablesCollectionScrollbarMaxChildren = 205;
	--local maxSizeX = (iStableMaster.StablesCollectionScrollbarMaxChildren + 0)* 127;
	local maxSizeY = (iStableMaster.StablesCollectionScrollbarMaxChildren * (ElementSizeY+4))-((iStableMaster.StablesCollectionScrollbarMaxChildren-2) * 4);
	iStableMaster.ScrollFrameArrElem["ScrollElement0"] = CreateFrame("Frame", "ScrollElement0", StablesRightFrame.ScrollFrame.ScrollBar, BackdropTemplateMixin and "BackdropTemplate");
	--iStableMaster.ScrollFrameArrElem["ScrollElement0"]:SetSize((StablesRightFrame.ScrollFrame:GetWidth()),maxSizeY);
	StablesRightFrame.ScrollFrame:SetScrollChild(iStableMaster.ScrollFrameArrElem["ScrollElement0"]);
	for i=1,iStableMaster.StablesCollectionScrollbarMaxChildren, 1 do 
		if(i > 0) then
			iStableMaster.ScrollFrameArrElem["ScrollElement"..i] = CreateFrame("Frame", "ScrollElement"..i, iStableMaster.ScrollFrameArrElem["ScrollElement0"], BackdropTemplateMixin and "BackdropTemplate");
			local point, relativeTo, relativePoint, xOfs, yOfs = iStableMaster.ScrollFrameArrElem["ScrollElement0"]:GetPoint(1);
			iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:SetPoint(point, 4,-(ElementSizeY*(i-1))-4);
			iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:SetSize(ElementSizeX,ElementSizeY);
		end
		iStableMaster.ScrollFrameArrElem["ScrollElement"..i] = CreateFrame("Frame", "ScrollElement"..i, iStableMaster.ScrollFrameArrElem["ScrollElement0"], BackdropTemplateMixin and "BackdropTemplate");
		local point, relativeTo, relativePoint, xOfs, yOfs = iStableMaster.ScrollFrameArrElem["ScrollElement0"]:GetPoint(1);
		iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:SetPoint(point, 4,-(ElementSizeY*(i-(GlobalActiveSlotLoopValue+1)))-4);
		iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:SetSize(ElementSizeX,ElementSizeY);
		iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:SetScript("OnMouseDown", function() iStableMaster:PetCardSelect(iStableMaster.ScrollFrameArrElem["ScrollElement"..i]) iStableMaster:SetSelectedHighlight() end);
		iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:SetScript("OnEnter", function(self) iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetAlpha(1); iStableMaster.currentHover = tonumber(i); iStableMaster:PetMouseOver(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i],self,false); end);
		iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:SetScript("OnLeave", function(self) iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetSelectorTextureHover"]:SetAlpha(0);  iStableMaster.currentHover = tonumber(i); iStableMaster:PetMouseOver(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i],self,true); end);
		-- copypaste code below here
		iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:HookScript("OnMouseDown", function(self, button)
			if(button == "RightButton" and clickedScrollFrame ~= nil) then
				--print("I was right");
			end
			if button == "LeftButton" and not self.isMoving then																	 
				mousePos = {x=0,y=0}
				mousePos.x, mousePos.y = GetCursorPosition();
				self.isLeftButtonDown = true;
				clickedScrollFrame = tonumber(i);
			end
		end);
		iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:HookScript("OnUpdate", function(self)
			if(self.tick == nil) then
				self.tick = 0;
				self.tickrate = 4;
			end
			if(math.fmod(self.tick,self.tickrate) == 0) then
				if(clickedScrollFrame ~= nil) then
					local mousePosTemp = {X=0,Y=0};
					mousePosTemp.X, mousePosTemp.Y = GetCursorPosition();
					if(mousePos.x == nil or mousePos.y == nil) then
						return;
					end;
					--print(math.floor(mousePos.x*10000),math.floor(mousePosTempX*10000),math.floor(mousePos.y*10000), math.floor(mousePosTempY*10000))
					if ((math.floor(mousePos.x*100) ~= math.floor(mousePosTemp.X*100)) or (math.floor(mousePos.y*100) ~= math.floor(mousePosTemp.Y*100)) ) then
						--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
						iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].cursorMoved = true;
						--print("GUT");
						mousePos.x, mousePos.y = mousePosTemp.X, mousePosTemp.Y;
					else
						--if(math.fmod(self.tick,self.tickrate) > 4) then
						iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].cursorMoved = false;
						--print("BAD!");
						--end
					end
					--print(mousePos.x.." - "..mousePos.y);
					--print(mousePosTempX, mousePosTempY);
					if(iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].isLeftButtonDown and
						iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].cursorMoved and 
							clickedScrollFrame ~= nil and 
								iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].isMoving ~= true ) then
									iStableMaster:PetOnDrag(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..clickedScrollFrame]["PetInfo"]["Slot"]);
									iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Down");
									iStableMaster:TempHideFiltersAndSorts();
									iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].isMoving = true;
									--print("GUD");
								end		
				end
			end
			--print(self.cursorMoved);
			self.tick = self.tick+1;
		end);
		iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:HookScript("OnMouseUp",function(self, button)
			if(clickedScrollFrame == nil) then
				iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Up");
				iStableMaster:TempHideFiltersAndSortsEnd();
				iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]);
				--iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].isLeftButtonDown = false;	
				--iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].isMoving = false;
				self.isLeftButtonDown = false;	
				self.isMoving = false;
			else
				if button == "LeftButton" and iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].isMoving then
					if(clickedScrollFrame ~= nil) then
						local slot = self:GetName();
						if(iStableMaster.currentHover ~= nil) then
							iStableMaster:PetOnDrop(iStableMaster.currentHover);
							--iStableMaster:PetOnDrop(tonumber(string.sub(slot, 14)));
						else
							ClearCursor();
						end
						iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]);
						iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].isLeftButtonDown = false;																		
						iStableMaster.ScrollFrameArrElem["ScrollElement"..clickedScrollFrame].isMoving = false;
						clickedScrollFrame = nil;
						iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Up");	
						iStableMaster:TempHideFiltersAndSortsEnd();
					end
				else
					ClearCursor();
				end
			end
			clickedScrollFrame = nil;
			clickedCardSocket = nil;
		end);
	end
	--local h1 = tonumber(select(3,iStableMaster.ScrollFrameArrElem["ScrollElement"..1]:GetPoint(1)));
	--local h2 = tonumber(select(3,iStableMaster.ScrollFrameArrElem["ScrollElement"..2]:GetPoint(1)));
	iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"] = ElementSizeY;
	iStableMaster.ScrollFrameArrElem["ScrollElementSizeX"] = ElementSizeX;
	StablesRightFrame.ScrollFrame:SetScript("OnMouseWheel",function(self,...) iStableMaster:PetScrollFrame_OnMouseWheel(self,...) end); 
end
function iStableMaster:SetPetSpecIcon(petSlot)
	local specindexName = select(5,GetStablePetInfo(petSlot));
	local specIndex = 0;
	if(specindexName == "Ferocity") then
		specIndex = 1;
	elseif(specindexName == "Tenacity") then
		specIndex = 2;
	elseif(specindexName == "Cunning") then
		specIndex = 3;
	end
	local id, name, description, icon, background, role = GetSpecializationInfo(specIndex, false , true);
	if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"] == nil) then
		iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSelectorFrame"]:CreateTexture(nil, "ARTWORK");  
	end
	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"]:SetPoint("RIGHT", iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSelectorFrame"], "RIGHT", 0, 0);
	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"]:SetSize(44,44); 
	--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"]:SetSize(88,44); 
	--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"]:SetTexCoord(0,1,0.25,0.75);
	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"]:SetTexture(icon);
	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"]:SetBlendMode("ADD");
	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"]:SetAlpha(0.8);
	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"]:SetMask("Interface\\PETBATTLES\\PetBattle-SelectedPetGlow");
	--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask");
	if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetInfo"]["icon"] == "N/A" or iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetInfo"]["icon"] == nil) then
		iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petSlot]["PetSpecializationIcon"]:SetAlpha(0);
	end
end
function iStableMaster:PetScrollFrame_OnMouseWheel(self,delta) -- Handles scroll snapping for the pet scrollframe -- This drifts due to the lables/separators in the list added, figure out a fix.
	local valueScrollNew
	--Snap to n times height of content frame on mouse wheel input change
	if(delta > 0) then
		valueScrollNew = self:GetVerticalScroll() - (iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"]);
	else
		valueScrollNew = self:GetVerticalScroll() + (iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"]);
	end
	--If new value is not n times height of contents, then regulate to nearest. Can happen after scroll thumb mouse drag.
	if(valueScrollNew % iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"] ~= 0 ) then
		if(iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"] - valueScrollNew > 0) then
			valueScrollNew = valueScrollNew + valueScrollNew % iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"];
		else
			valueScrollNew = valueScrollNew - valueScrollNew % iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"];
		end
	end
	if(valueScrollNew < 0) then
		valueScrollNew = 0;
	elseif(valueScrollNew > self:GetVerticalScrollRange()) then
		valueScrollNew = self:GetVerticalScrollRange();
	end
	self:SetVerticalScroll(valueScrollNew);
end -- Handles scroll snapping for the pet scrollframe -- This drifts due to the lables/separators in the list added, figure out a fix.
function iStableMaster:PetScrollFrameUpdateScrollFrameWidths(newWidth)
	iStableMaster:PopulateScrollFrame();
	iStableMaster:SetPetScrollTilesContent();
	for i=0,iStableMaster.StablesCollectionScrollbarMaxChildren, 1 do 
		if(i==0) then
			iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:SetWidth(newWidth+8);
		else 
			if(iStableMaster.ScrollFrameArrElem["ScrollElement"..i] ~= nil) then
				iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:SetWidth(newWidth);
			end
		end
	end
end
----------------------------------------------------
---				PetScrollFrame END			     ---
----------------------------------------------------
----------------------------------------------------
---				Active Pet Cards			     ---
----------------------------------------------------

function iStableMaster:PopulateCardContainer()
	if(ActivePetSlotsCards ~= nil)then
		return;
	end
	if(iStableMasterOptionsDB.Layout == "Default") then 
		ActivePetSlotsCards = {};
		local ElementSizeX = 180;
		--	local ElementSizeY = 167;
		local ElementSizeY = 187; -- experimental
		local PaddingX = ElementSizeX + 8;
		local PaddingY = ElementSizeY + 2; 
		local mousePos = {x=0,y=0};
		for i=1,6,1 do
			ActivePetSlotsCards["ActiveSlot"..i] = {};
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i] = CreateFrame("Frame", "ActiveSlotSocket"..i,CardContainerFrame,"HunterPetCardBgTemplate")
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetSize(ElementSizeX,ElementSizeY);
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetBackdrop({bgFile="Interface\\AddOns\\iStableMaster\\BestiaAzerothica_CardBackground2",
				edgeFile="", tile=false,tileSize=167,edgeSize=32,
				insets= {left=8,right=8,top=8,bottom=8}});
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border = ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic Border 3.blp","OVERLAY");
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetSize(ElementSizeX*0.90,ElementSizeY*0.90);
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i],"CENTER",0,0);
			if(i<6) then
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetVertexColor(iStableMaster:GetDBColour("Default","BoarderGreen")); -- should add this to the colour library and call it from there.
			else
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetVertexColor(iStableMaster:GetDBColour("Default","BoarderBlue"));
			end	
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetDrawLayer("OVERLAY",6)
			--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetTexture("Interface\\AddOns\\iStableMaster\\HeaderShadeAndGlow.blp");
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]:GetWidth(),24);
			--		--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetTexCoord(0.16,0.9,0.425,0.63);
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetTexCoord(0.16,0.9,0.45,0.50);
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"],"TOPLEFT",-4,0);
			--		ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetAlpha(0.5);
			if(i<6)then
				if(IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","DarkGreen"));
				end
			elseif(GlobalSpecialization == "Beast Mastery")then
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","DarkBlue"));
			else
				--do nothing
			end
			if(i < 3)then
				if(i == 1) then
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOPLEFT",_G["CardContainerFrame"],"TOPLEFT", 4, -2)
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOPRIGHT", CardContainerFrame, "TOPRIGHT", -4, -2)
				end
			elseif(i < 5)then
				if(i == 3) then
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOPLEFT", CardContainerFrame,"TOPLEFT", 4, -(PaddingY) + 11 )
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOPRIGHT", CardContainerFrame,"TOPRIGHT", -4, -(PaddingY) + 11)
				end
			elseif(i < 7)then
				if(i == 5) then
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOPLEFT", CardContainerFrame,"TOPLEFT", 4, -(PaddingY * 2) + 22)
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOPRIGHT", CardContainerFrame,"TOPRIGHT", -4, -(PaddingY * 2) + 22)
				end
			end
			local spellKnown = false;
			if(i < 6) then
				spellKnown = IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]);
			else
				lTalents = {};
				local lConfigID = C_ClassTalents.GetActiveConfigID();
				local lConfigInfo = C_Traits.GetConfigInfo(lConfigID);
				local lTreeIDs = lConfigInfo["treeIDs"];
				for i = 1, #lTreeIDs do
					for _, lNodeID in pairs(C_Traits.GetTreeNodes(lTreeIDs[i])) do
						local lNodeInfo = C_Traits.GetNodeInfo(lConfigID, lNodeID);
						local activeEntry = lNodeInfo.activeEntry;
						local activeRank = lNodeInfo.activeRank;
						if ( activeEntry and activeRank > 0 ) then
							local activeEntryID = activeEntry.entryID;
							local lEntryInfo = C_Traits.GetEntryInfo(lConfigID,activeEntryID);
							--if ( lEntryInfo ) then
							local lDefinitionID = lEntryInfo["definitionID"];
							--BA_Data["function LogTextLine"](string.format("def ID:%s",tostring(lDefinitionID)));
							local lDefinitionInfo = C_Traits.GetDefinitionInfo(lDefinitionID);
							--BA_Data["function LogTextLine"](string.format("def info:%s",tostring(lDefinitionInfo)));
							local spellID = lDefinitionInfo["spellID"];
							local spellName = GetSpellInfo(spellID);

							lTalents[spellName] = activeRank;
							--print(lTalents["Animal Companion"]);
						end
					end
				end
				if(GlobalSpecialization == "Beast Mastery")then	
					spellKnown = iStableMaster:HasTalent("Animal Companion");
					--print(spellKnown);
				else
					spellKnown = false;
				end
			end
			if(spellKnown)then
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function()  end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnEnter", function() 
					iStableMaster.currentHover = tonumber(i);
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLeave", function(self)
					iStableMaster.currentHover = nil;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].tickrate = 4;
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].tick = 0;
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function(self, button)
					iStableMaster:PetCardSelect(ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]);
					iStableMaster:SetSelectedHighlight();
					if button == "LeftButton" and not self.isMoving then																	 
						mousePos = {x=0,y=0}																		  
						mousePos.x, mousePos.y = GetCursorPosition();
						self.isLeftButtonDown = true;
						clickedCardSocket = tonumber(i);
					end
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLoad", function(self) 
					self.tick = 0;
					self.tickrate = 4;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnUpdate", function(self)
					if(self.tick == nil) then
						self.tick = 0;
						self.tickrate = 4;
						self.lastTick = 0;
					end
					if(math.fmod(self.tick,self.tickrate) == 0 and self.lastTick ~= self.tick) then
						if(clickedCardSocket ~= nil) then
							if(mousePos.x == nil) then 
								return;
							end
							local mousePosTemp = {};
							mousePosTemp.X, mousePosTemp.Y = GetCursorPosition();
							--print(((math.floor(mousePos.x*100) ~= math.floor(mousePosTemp.X*100)) or (math.floor(mousePos.y*100) ~= math.floor(mousePosTemp.Y*100)) ));
							if ((math.floor(mousePos.x*100) ~= math.floor(mousePosTemp.X*100)) or (math.floor(mousePos.y*100) ~= math.floor(mousePosTemp.Y*100))) then
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = true;
								mousePos.x, mousePos.y = mousePosTempX, mousePosTempY;
							else
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = false;
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
							end
							if(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown and 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved and 
									clickedCardSocket ~= nil and GetCursorInfo() == nil) then
										--ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving ~= true ) then
										--print("GUD2");
										iStableMaster:PetOnDrag(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["PetInfo"]["Slot"]);
										iStableMaster:TempHideFiltersAndSorts();
										iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Down");
										ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = true;
									end		
						end
					end
					--print(self.cursorMoved);
					self.lastTick = self.tick;
					self.tick = self.tick+1;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseUp",function(self, button)
					if(clickedCardSocket == nil) then
						iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Up");
						iStableMaster:TempHideFiltersAndSortsEnd();
						iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]);
						self.isLeftButtonDown = false;	
						self.isMoving = false;
					else
						if button == "LeftButton" and ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving then
							if(clickedCardSocket ~= nil) then
								local slot = self:GetName();
								if(iStableMaster.currentHover ~= nil) then
									iStableMaster:PetOnDrop(iStableMaster.currentHover);
								else
									ClearCursor();
								end
								iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]); 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown = false;																		
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = false;
								clickedCardSocket = nil;
								iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Up");
								iStableMaster:TempHideFiltersAndSortsEnd();
							end
						else
							ClearCursor();
						end
					end
					clickedCardSocket = nil;
					clickedScrollFrame = nil;
					--mousePos.x, mousePosY = nil,nil;
				end);
			else
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function() 
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnUpdate", function(self)
					if(self.tick == nil) then
						self.tick = 0;
						self.tickrate = 4;
						self.lastTick = 0;
					end
					if(math.fmod(self.tick,self.tickrate) == 0  and self.lastTick ~= self.tick) then
						if(self.mousePos == nil) then 
							return;
						end
						if(self.mousePos == nil) then
							return
						end
						if(clickedCardSocket ~= nil) then
							local mousePosTempX, mousePosTempY = GetCursorPosition();
							if ((math.floor(self.mousePos.x*100) ~= math.floor(mousePosTempX*100)) or (math.floor(self.mousePos.y*100) ~= math.floor(mousePosTempY*100)) ) then
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
								mousePos.x, mousePos.y = mousePosTempX, mousePosTempY;
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = true;
							else
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = false;
							end
							--print(mousePos.x.." - "..mousePos.y);
							--print(mousePosTempX, mousePosTempY);
							if(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown and 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved and 
									clickedCardSocket ~= nil and GetCursorInfo() == nil) then
										iStableMaster:PetOnDrag(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["PetInfo"]["Slot"]);
										iStableMaster:TempHideFiltersAndSorts();
										iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Down");
										ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = true;
									end	
						end
					end
					--print(self.cursorMoved);
					self.lastTick = self.tick;
					self.tick = self.tick+1;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnEnter", function() 
					iStableMaster.currentHover = tonumber(i);
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLeave", function(self)
					iStableMaster.currentHover = nil;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseUp",function(self, button)
					if button == "LeftButton" then
						ClearCursor();
					end
					clickedCardSocket = nil;
					clickedScrollFrame = nil;
				end);
			end
		end
	elseif(iStableMasterOptionsDB.Layout == "Compact" or iStableMasterOptionsDB.Layout == nil) then
		ActivePetSlotsCards = {};
		local ElementSizeX = 78;
		--	local ElementSizeY = 167;
		local ElementSizeY = 82.5; -- experimental
		local PaddingX = ElementSizeX + 8;
		local PaddingY = ElementSizeY + 2 -5; 
		local mousePos = {x=0,y=0};
		for i=1,6,1 do
			ActivePetSlotsCards["ActiveSlot"..i] = {};
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i] = CreateFrame("Frame", "ActiveSlotSocket"..i,CardContainerFrame,"HunterPetCardBgTemplate")
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetSize(ElementSizeX,ElementSizeY);
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetBackdrop({bgFile="Interface\\AddOns\\iStableMaster\\BestiaAzerothica_CardBackground2",
				edgeFile="", tile=false,tileSize=167,edgeSize=32,
				insets= {left=8,right=8,top=8,bottom=8}});
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border = ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic Border 3-FAT.blp","OVERLAY");
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetSize(ElementSizeX*0.87,ElementSizeY*0.87);
			ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i],"CENTER",0,0);
			--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetVertexColor(0.2,0.3,0.2,1);
			if(i<6) then
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetVertexColor(iStableMaster:GetDBColour("Default","BoarderGreen")); -- should add this to the colour library and call it from there.
			else
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetVertexColor(iStableMaster:GetDBColour("Default","BoarderBlue"));
			end	
			if(i<6)then
				if(IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","DarkGreen"));
				end
			elseif(GlobalSpecialization == "Beast Mastery")then
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","DarkBlue"));
			else
			end
			if(i < 3)then
				if(i == 1) then
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOP",_G["CardContainerFrame"],"TOP", 0, -2 -20)
				else
					--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOPRIGHT", CardContainerFrame, "TOPRIGHT", -4, -2)
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOP",_G["CardContainerFrame"],"TOP", 0, -(PaddingY) - 20)
				end
			elseif(i < 5)then
				if(i == 3) then
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOP", CardContainerFrame,"TOP", 0, -(PaddingY)*2 - 20)
				else
					--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOPRIGHT", CardContainerFrame,"TOPRIGHT", -4, -(PaddingY) + 11)
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOP", CardContainerFrame,"TOP", 0, -(PaddingY)*3 - 20)
				end
			elseif(i < 7)then
				if(i == 5) then
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOP", CardContainerFrame,"TOP", 0, -(PaddingY * 4) - 20)
				else
					--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("TOPRIGHT", CardContainerFrame,"TOPRIGHT", -4, -(PaddingY * 2) + 22)
					ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetPoint("BOTTOM", CardContainerFrame,"BOTTOM", 0, 12)
					CardContainerFrameInsetFramePetStableAnimalCompanionLabel:ClearAllPoints();
					CardContainerFrameInsetFramePetStableAnimalCompanionLabel:SetPoint("TOPLEFT", ActivePetSlotsCards["ActiveSlot"..6]["Socket"..6],"TOPLEFT",4,20);
					CardContainerFrameInsetFramePetStableAnimalCompanionLabel:SetPoint("RIGHT", ActivePetSlotsCards["ActiveSlot"..6]["Socket"..6],"TOPRIGHT",4);
					CardContainerFrameInsetFramePetStableAnimalCompanionLabel:SetText("Animal\nCompanion");
				end
			end
			local spellKnown = false;
			if(i < 6) then
				spellKnown = IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]);
			else
				if(GlobalSpecialization == "Beast Mastery")then
					--spellKnown = select(4,GetTalentInfoBySpecialization(1, 1, 2));
					--spellKnown = (lTalents["Animal Companion"] >=1 ) or false;
					spellKnown = iStableMaster:HasTalent("Animal Companion");
				else
					spellKnown = false;
				end
			end
			--print("IsSpellKnown: ",spellKnown);
			if(spellKnown)then
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function()  end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnEnter", function() 
					iStableMaster.currentHover = tonumber(i);
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLeave", function(self)
					iStableMaster.currentHover = nil;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].tickrate = 4;
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].tick = 0;
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function(self, button)
					iStableMaster:PetCardSelect(ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]);
					iStableMaster:SetSelectedHighlight();
					if button == "LeftButton" and not self.isMoving then																	 
						mousePos = {x=0,y=0}																		  
						mousePos.x, mousePos.y = GetCursorPosition();
						self.isLeftButtonDown = true;
						clickedCardSocket = tonumber(i);
					end
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLoad", function(self) 
					self.tick = 0;
					self.tickrate = 4;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnUpdate", function(self)
					if(self.tick == nil) then
						self.tick = 0;
						self.tickrate = 4;
						self.lastTick = 0;
					end
					if(math.fmod(self.tick,self.tickrate) == 0 and self.lastTick ~= self.tick) then
						if(clickedCardSocket ~= nil) then
							if(mousePos.x == nil) then 
								return;
							end
							local mousePosTemp = {};
							mousePosTemp.X, mousePosTemp.Y = GetCursorPosition();
							--print(((math.floor(mousePosX*100) ~= math.floor(mousePosTempX*100)) or (math.floor(mousePosY*100) ~= math.floor(mousePosTempY*100)) ));
							if ((math.floor(mousePos.x*100) ~= math.floor(mousePosTemp.X*100)) or (math.floor(mousePos.y*100) ~= math.floor(mousePosTemp.Y*100))) then
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = true;
								mousePos.x, mousePos.y = mousePosTemp.X, mousePosTemp.Y;
							else
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = false;
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
							end							
							if(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown and 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved and 
									clickedCardSocket ~= nil and GetCursorInfo() == nil) then
										--ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving ~= true ) then
										--print("GUD2");
										iStableMaster:PetOnDrag(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["PetInfo"]["Slot"]);
										iStableMaster:TempHideFiltersAndSorts();
										iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Down");
										ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = true;
									end		
						end
					end
					--print(self.cursorMoved);
					self.lastTick = self.tick;
					self.tick = self.tick+1;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseUp",function(self, button)
					if(clickedCardSocket == nil) then
						iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Up");
						iStableMaster:TempHideFiltersAndSortsEnd();
						iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]);
						self.isLeftButtonDown = false;	
						self.isMoving = false;
					else
						if button == "LeftButton" and ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving then
							if(clickedCardSocket ~= nil) then
								local slot = self:GetName();
								if(iStableMaster.currentHover ~= nil) then
									iStableMaster:PetOnDrop(iStableMaster.currentHover);
								else
									ClearCursor();
								end
								iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]); 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown = false;																		
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = false;
								clickedCardSocket = nil;
								iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Up");
								iStableMaster:TempHideFiltersAndSortsEnd();
							end
						else
							ClearCursor();
						end
					end
					clickedCardSocket = nil;
					clickedScrollFrame = nil;
					--mousePos.x, mousePosY = nil,nil;
				end);
			else
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function() 
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnUpdate", function(self)
					if(self.tick == nil) then
						self.tick = 0;
						self.tickrate = 4;
						self.lastTick = 0;
					end
					if(math.fmod(self.tick,self.tickrate) == 0  and self.lastTick ~= self.tick) then
						if(self.mousePos == nil) then 
							return;
						end
						if(self.mousePos == nil) then
							return
						end
						if(clickedCardSocket ~= nil) then
							local mousePosTempX, mousePosTempY = GetCursorPosition();
							if ((math.floor(self.mousePos.x*100) ~= math.floor(mousePosTempX*100)) or (math.floor(self.mousePos.y*100) ~= math.floor(mousePosTempY*100)) ) then
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
								mousePos.x, mousePos.y = mousePosTempX, mousePosTempY;
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = true;
							else
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = false;
							end
							--print(mousePos.x.." - "..mousePos.y);
							--print(mousePosTempX, mousePosTempY);
							if(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown and 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved and 
									clickedCardSocket ~= nil and GetCursorInfo() == nil) then
										--ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving ~= true ) then
										--print("GUD2");
										iStableMaster:PetOnDrag(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["PetInfo"]["Slot"]);
										iStableMaster:TempHideFiltersAndSorts();
										iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Down");
										ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = true;
									end	
						end
					end
					--print(self.cursorMoved);
					self.lastTick = self.tick;
					self.tick = self.tick+1;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnEnter", function() 
					iStableMaster.currentHover = tonumber(i);
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLeave", function(self)
					iStableMaster.currentHover = nil;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseUp",function(self, button)
					if button == "LeftButton" then
						ClearCursor();
					end
					clickedCardSocket = nil;
					clickedScrollFrame = nil;
				end);
			end
		end
	else
		--print(" NIL ");
	end
end -- Creates the Socket Frames
function iStableMaster:PopulateActiveCards() --[[
								<<<SUMMARY>>>
											Populates the ActivePetSlot Socket..n with ActivePetSlotCards, only runs if ActivePetSlotsCards == nil
								<<</SUMMARY>>>
								--]]
	if(ActivePetSlotsCards == nil ) then 
		return;
	end
	if(iStableMasterOptionsDB.Layout == "Default" or iStableMasterOptionsDB.Layout == nil) then
		--print(iStableMasterOptionsDB.Layout);		
		for i=1,6,1 do
			if(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"] == nil) then
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"] = {};
			end
			if(i<6) then
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["icon"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["name"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["level"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["family"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["talent"];
				-- custom info
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["favourite"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["inStables"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["Slot"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["abilities"];
			elseif(i==6) then
				--print(i);
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["icon"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["name"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["level"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["family"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["talent"];
				-- custom info
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["favourite"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["inStables"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["Slot"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["abilities"];
			end
		end
		--ActivePetSlotsCards["Cards"] = {};
		local ElementSizeX = 180;
		--	local ElementSizeY = 167;
		local ElementSizeY = 187; -- experimental
		local PaddingX = ElementSizeX + 8;
		local PaddingY = ElementSizeY + 3; 
		if(ActivePetSlotsCards == nil)then
			--iStableMaster:PopulateCardContainer();
			return;
		end
		if(ActivePetSlotsCards["ActiveSlot1"]["Card1"] ~= nil and (GlobalSpecialization == "Beast Mastery" and ActivePetSlotsCards["ActiveSlot6"]["Card6"] ~= nil))then
			ActivePetSlotsCards["ActiveSlot6"]["Card6"]["RequiresFrame"]:Hide();
			return;
		elseif ( GlobalSpecialization == "Beast Mastery" and ActivePetSlotsCards["ActiveSlot1"]["Card1"] ~= nil and ActivePetSlotsCards["ActiveSlot6"]["Card6"] == nil)then
			swappedToBMFirstTime = true;
			ActivePetSlotsCards["ActiveSlot"..6]["Card"..6]["RequiresFrame"]:Hide();
			return;
		elseif(swappedToBMFirstTime and GlobalSpecialization ~= "Beast Mastery") then
			ActivePetSlotsCards["ActiveSlot"..6]["Card"..6]["RequiresFrame"]:Show();
			return;
		elseif(ActivePetSlotsCards["ActiveSlot1"]["Card1"] ~= nil) then
			return;
		else
		end
		for i=1,6,1 do
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i] = CreateFrame("Frame", "ActiveSlotCard"..i,_G["ActiveSlotSocket"..i],"HunterPetCardBgTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetSize(ElementSizeX,ElementSizeY);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdrop({bgFile="Interface\\AddOns\\iStableMaster\\BestiaAzerothica_CardBackground2",
				edgeFile="", tile=false,tileSize=167,edgeSize=32,
				insets= {left=8,right=8,top=8,bottom=8}});
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:CreateTexture(nil,"ARTWORK",nil,7);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic Border 3.blp","OVERLAY");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetSize(ElementSizeX*0.92,ElementSizeY*0.92);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i],"CENTER",0,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetDrawLayer("OVERLAY",6)
			if(i<6) then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetVertexColor(iStableMaster:GetDBColour("Default","BoarderGreen")); -- should add this to the colour library and call it from there.
			else
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetVertexColor(iStableMaster:GetDBColour("Default","BoarderBlue"));
			end	
			if(GlobalSpecialization == "Beast Mastery") then 
				if(i<6) then
					if(IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","LightGreen"));
					else
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","BlackTintedBlue"));
					end
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","Blue"));
				end
			elseif(i<6) then
				if(IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","LightGreen"));
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","BlackTintedBlue"));
				end
			else
				--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","Blue"));
			end
			if(i < 3)then
				if(i == 1) then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("TOPLEFT",_G["ActiveSlotSocket"..i],"TOPLEFT", 0, 0)
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("TOPRIGHT", _G["ActiveSlotSocket"..i], "TOPRIGHT", 0, 0)
				end
			elseif(i < 5)then
				if(i == 3) then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("TOPLEFT", _G["ActiveSlotSocket"..i],"TOPLEFT", 0, 0)
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("TOPRIGHT", _G["ActiveSlotSocket"..i],"TOPRIGHT", 0, 0)
				end
			elseif(i < 7)then
				if(i == 5) then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("TOPLEFT", _G["ActiveSlotSocket"..i],"TOPLEFT", 0, 0)
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("TOPRIGHT", _G["ActiveSlotSocket"..i],"TOPRIGHT", 0, 0)
				end
			end
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"] = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:SetSize(32,32);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i],"TOPLEFT",12,-12);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconBorder"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:CreateTexture(nil,"ARTWORK",nil,3);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconBorder"]:SetAtlas("ui-hud-actionbar-IconFrame");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconBorder"]:SetSize(32,32);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconBorder"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"],"CENTER");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"],"CENTER",0,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"]:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"]:SetSize(42,42);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"]:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"])
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"] = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:SetSize((ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetWidth()-ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:GetWidth()-18),32);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i],"TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:GetWidth()+6,-6);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["Name"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormalLarge"); 
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["FamilyName"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormalSmall"); 
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["HeaderBg"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:CreateTexture(nil,"BACKGROUND",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["HeaderBg"]:SetTexture("Interface\\AddOns\\iStableMaster\\HeaderShadeAndGlow.blp");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["HeaderBg"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:GetWidth(),32);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["HeaderBg"]:SetTexCoord(0.16,0.9,0.45,0.50);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["HeaderBg"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"],"TOPLEFT",6,-6);
			--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetTexture(iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["icon"]);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["HeaderBg"]:SetAlpha(0.5);
			-- Abilities
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"] = CreateFrame("FRAME", nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i], BackdropTemplateMixin and "BackdropTemplate");	
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetWidth(),86);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"],"BOTTOMLEFT",-6,-5);
			--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:SetPoint("BOTTOMRIGHT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"TOPRIGHT",0,-5); -- Diet Frame doesn't exist yet.
			-- Family Abilities
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"] = CreateFrame("FRAME", nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"], BackdropTemplateMixin and "BackdropTemplate");	
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]:SetSize((ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:GetWidth()/2)-4,86);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"],"TOPLEFT",2,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]:SetPoint("BOTTOMRIGHT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"],"BOTTOMRIGHT",-(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:GetWidth()/2)-2,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["HeaderBg"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]:CreateTexture(nil,"BACKGROUND",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["HeaderBg"]:SetTexture("Interface\\AddOns\\iStableMaster\\HeaderShadeAndGlow.blp");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["HeaderBg"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]:GetWidth(),24);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["HeaderBg"]:SetTexCoord(0.16,0.9,0.45,0.50);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["HeaderBg"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"],"TOPLEFT",4,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["HeaderBg"]:SetAlpha(0.5);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["Name"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormalSmall"); 
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["Name"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["HeaderBg"],"CENTER",-7,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["Name"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["HeaderBg"]:GetWidth()-14,ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["HeaderBg"]:GetHeight());
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["Name"]:SetFont("Fonts\FRIZQT__.TFF",10,"MONOCHROME");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["Name"]:SetTextColor(iStableMaster:GetDBColour("Default","Blue"));
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["Name"]:SetText("Family Abilities");
			-- Spec Abilities
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"] = CreateFrame("FRAME", nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"], BackdropTemplateMixin and "BackdropTemplate");	
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]:SetSize((ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:GetWidth()/2)-8,86);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"],"TOPLEFT",(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:GetWidth()/2)+2,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]:SetPoint("BOTTOMRIGHT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"],"BOTTOMRIGHT",0,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]:CreateTexture(nil,"BACKGROUND",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetTexture("Interface\\AddOns\\iStableMaster\\HeaderShadeAndGlow.blp");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]:GetWidth(),24);
			--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetTexCoord(0.16,0.9,0.425,0.63);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetTexCoord(0.16,0.9,0.45,0.50);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"],"TOPLEFT",-4,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:SetAlpha(0.5);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["Name"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormalSmall"); 
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["Name"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"],"CENTER",-7,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["Name"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:GetWidth()-4,ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["HeaderBg"]:GetHeight());
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["Name"]:SetFont("Fonts\FRIZQT__.TFF",10, "MONOCHROME");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["Name"]:SetTextColor(iStableMaster:GetDBColour("Default","Blue"));
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["Name"]:SetText("Specialzation Abilities");
			local numabilities = iStableMaster:StringKeyTableLengthI(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"]["talent"]);
			if numabilities < 3 then
				numabilities = 3; -- THIS is a fix for empty active slots on load, this may be an issue for family abilities too especially since they can vary in number, likewise this will be an issue 2 if there someday is a third spec ability.
			end
			for j=1, numabilities do
				local ofsx = 0;
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j] = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"], BackdropTemplateMixin and "BackdropTemplate");
				if(j == 1) then
					ofsx = -j*13;
				else
					ofsx = (j-1)*13;
				end
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"],"CENTER",ofsx,0);	
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]:SetSize(24,24);				
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["Texture"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]:CreateTexture(nil,"ARTWORK",nil,2);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["BorderTexture"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]:CreateTexture(nil,"ARTWORK",nil,3);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["MaskTexture"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]:CreateMaskTexture();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["MaskTexture"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"],"CENTER",ofsx,0);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["MaskTexture"]:SetSize(32,32);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["MaskTexture"]:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["MaskTexture"]:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["Texture"]:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["MaskTexture"])
			end	
			local numfamabilities = iStableMaster:StringKeyTableLengthI(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"]["family"]);
			if numfamabilities < 3 then
				numfamabilities = 3; -- THIS is a fix for empty active slots on load, this may be an issue for family abilities too especially since they can vary in number, likewise this will be an issue 2 if there someday is a third spec ability.
			end
			for j=1, numfamabilities do
				local ofsx = 0;
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j] = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"], BackdropTemplateMixin and "BackdropTemplate");
				if(j == 1) then
					ofsx = -j*13;
				elseif( j == 3) then
					ofsx = (j)*13;
				else
					ofsx = (j-1)*13;
				end
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"],"CENTER",ofsx-14,0);	
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:SetSize(24,24);				
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["Texture"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:CreateTexture(nil,"ARTWORK",nil,2);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["BorderTexture"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:CreateTexture(nil,"ARTWORK",nil,3);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["MaskTexture"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:CreateMaskTexture();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["MaskTexture"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"],"CENTER",ofsx-14,0);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["MaskTexture"]:SetSize(32,32);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["MaskTexture"]:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["MaskTexture"]:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["Texture"]:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["MaskTexture"])
			end			
			-- Diets
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"] = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetWidth(),48);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i],"BOTTOMLEFT",0,54);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["HeaderBg"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"BACKGROUND",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["HeaderBg"]:SetTexture("Interface\\AddOns\\iStableMaster\\HeaderShadeAndGlow.blp");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["HeaderBg"]:SetSize((ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:GetWidth()-8),14);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["HeaderBg"]:SetTexCoord(0.16,0.9,0.45,0.50);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["HeaderBg"]:SetPoint("TOPLEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"TOPLEFT",12,13);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["HeaderBg"]:SetAlpha(0.5);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Name"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormal"); 
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Name"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["HeaderBg"],"CENTER",-7,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Name"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["HeaderBg"]:GetSize());
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Name"]:SetFont("Fonts\FRIZQT__.TFF",14,"MONOCHROME");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Name"]:SetTextColor(iStableMaster:GetDBColour("Default","Blue"));
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Name"]:SetText("Diet");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.BorderTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,4);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.MaskTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.BorderTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,4);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.MaskTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.BorderTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,4);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.MaskTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.BorderTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,4);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.MaskTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.BorderTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,4);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.MaskTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.BorderTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,4);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.MaskTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.BorderTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,4);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.MaskTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.BorderTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,4);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.MaskTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.BorderTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateTexture(nil,"ARTWORK",nil,4);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.MaskTexture = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"] = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetWidth(),ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetHeight());
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i],"CENTER",0,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Hide();
			if(i==6)then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Show();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:SetAlpha(0.5);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["AnimalCompanionIcon"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateTexture(nil,"ARTWORK",nil, 3);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["AnimalCompanionIcon"]:SetTexture("Interface\\ICONS\\ABILITY_HUNTER_BESTIALDISCIPLINE");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["AnimalCompanionIcon"]:SetSize(64,64);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["AnimalCompanionIcon"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i],"CENTER",0,-20);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormal");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetPoint("TOP",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"],"TOP",0,-16);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:GetWidth(),24);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetFont("Fonts\FRIZQT__.TTF", 12, "MONOCHROME");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormal");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"]:SetPoint("TOP",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"],"TOP",0,-42);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:GetWidth(),24);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"]:SetFont("Fonts\FRIZQT__.TTF", 12, "MONOCHROME");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetText("Requires: Specialization - Beast Mastery");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetTextColor(1,0,0,1);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"]:SetText("Requires: Talent - Animal Companion");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"]:SetTextColor(1,0,0,1);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Hide();
			end
			if(i==6 and GlobalSpecialization ~= "Beast Mastery")then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Show();
			end
			--selected highlight
			if(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"] == nil) then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:CreateTexture(nil,"OVERLAY");
			end
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetTexture(nil);
			--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetColorTexture(0,0,0,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetAlpha(0);
			--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetAtlas("PetList-ButtonSelect");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic highlight 5");
			--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetMask("Interface\\PETBATTLES\\PetBattle-SelectedPetGlow");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetWidth()*0.90,ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetHeight()*0.90);
			--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetAllPoints(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"]);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i],"CENTER");
			--ActivePetSlotsCards["ActiveSlot"..indexNumber]["Card"..indexNumber]["Selected"]
			if(i < 6)then
				if(not IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Show();
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateTexture(nil,"ARTWORK",nil, 3);
					--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"]:SetTexture("Interface\\PETBATTLES\\PetBattle-LockIcon");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"]:SetAtlas("UI-CharacterCreate-PadLock");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"]:SetSize(64,64);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"],"CENTER",0,0);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormal");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetPoint("TOP",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"],"TOP",0,-16);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:GetWidth(),24);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetFont("Fonts\FRIZQT__.TTF", 12, "MONOCHROME");
					local SpellName, SpellRank, icon, castTime, minRange, maxRange = GetSpellInfo(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetText("Requires: "..SpellName);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetTextColor(1,0,0,1);
				end
			end
		end
		iStableMaster:UpdateActiveCards();
	elseif(iStableMasterOptionsDB.Layout == "Compact") then
		for i=1,6,1 do
			if(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"] == nil) then
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"] = {};
			end
			if(i<6) then
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["icon"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["name"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["level"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["family"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["talent"];
				-- custom info
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["favourite"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["inStables"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["Slot"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["abilities"];
			elseif(i==6) then
				--print(i);
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["icon"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["name"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["level"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["family"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["talent"];
				-- custom info
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["favourite"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["inStables"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["Slot"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["abilities"];
			end
		end
		--ActivePetSlotsCards["Cards"] = {};
		local ElementSizeX = 90;
		--	local ElementSizeY = 167;
		local ElementSizeY = 93.5; -- experimental
		local PaddingX = ElementSizeX + 8;
		local PaddingY = ElementSizeY + 3; 
		if(ActivePetSlotsCards == nil)then
			--iStableMaster:PopulateCardContainer();
			return;
		end
		if(ActivePetSlotsCards["ActiveSlot1"]["Card1"] ~= nil and (GlobalSpecialization == "Beast Mastery" and ActivePetSlotsCards["ActiveSlot6"]["Card6"] ~= nil))then
			ActivePetSlotsCards["ActiveSlot6"]["Card6"]["RequiresFrame"]:Hide();
			return;
		elseif ( GlobalSpecialization == "Beast Mastery" and ActivePetSlotsCards["ActiveSlot1"]["Card1"] ~= nil and ActivePetSlotsCards["ActiveSlot6"]["Card6"] == nil)then
			swappedToBMFirstTime = true;
			ActivePetSlotsCards["ActiveSlot"..6]["Card"..6]["RequiresFrame"]:Hide();
			return;
		elseif(swappedToBMFirstTime and GlobalSpecialization ~= "Beast Mastery") then
			ActivePetSlotsCards["ActiveSlot"..6]["Card"..6]["RequiresFrame"]:Show();
			return;
		elseif(ActivePetSlotsCards["ActiveSlot1"]["Card1"] ~= nil) then
			return;
		else
		end
		for i=1,6,1 do
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i] = CreateFrame("Frame", "ActiveSlotCard"..i,_G["ActiveSlotSocket"..i],"HunterPetCardBgTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetSize(ElementSizeX*0.90,ElementSizeY*0.90);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdrop({bgFile="Interface\\AddOns\\iStableMaster\\BestiaAzerothica_CardBackground2",
				edgeFile="", tile=false,tileSize=167,edgeSize=32,
				insets= {left=8,right=8,top=8,bottom=8}});
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:CreateTexture(nil,"ARTWORK",nil,3);
			--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic Border 3-FAT.blp","OVERLAY");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetAtlas("ui-hud-actionbar-IconFrame");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetSize(ElementSizeX*0.80,ElementSizeY*0.80);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i],"CENTER",0,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetDrawLayer("ARTWORK",7)
			if(GlobalSpecialization == "Beast Mastery") then 
				if(i<6) then
					if(IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","LightGreen"));
					else
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","BlackTintedBlue"));
					end
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","Blue"));
				end
			elseif(i<6) then
				if(IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","LightGreen"));
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","BlackTintedBlue"));
				end
			else
				--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetBackdropColor(iStableMaster:GetDBColour("Default","Blue"));
			end
			if(i < 3)then
				if(i == 1) then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("CENTER",_G["ActiveSlotSocket"..i],"CENTER", 0, 0)
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("CENTER", _G["ActiveSlotSocket"..i],"CENTER", 0, 0)
				end
			elseif(i < 5)then
				if(i == 3) then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("CENTER", _G["ActiveSlotSocket"..i],"CENTER", 0, 0)
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("CENTER", _G["ActiveSlotSocket"..i],"CENTER", 0, 0)
				end
			elseif(i < 7)then
				if(i == 5) then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("CENTER", _G["ActiveSlotSocket"..i],"CENTER", 0, 0)
				else
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:SetPoint("CENTER",_G["ActiveSlotSocket"..i],"CENTER", 0, 0)
				end
			end
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"] = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:SetSize(ElementSizeX*0.90,ElementSizeY*0.90);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:SetAllPoints();
			--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i],"CENTER",0,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:CreateTexture(nil,"ARTWORK",nil,2);
			--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetSize(ElementSizeX*1.50,ElementSizeY*1.50);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:CreateMaskTexture();
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"],"CENTER",0,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"]:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"]:SetSize(ElementSizeX*1.10,ElementSizeY*1.10);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"]:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["IconMask"])
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"] = CreateFrame("FRAME",  nil, ActivePetSlotsCards["ActiveSlot"..i]["Card"..i], BackdropTemplateMixin and "BackdropTemplate");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetWidth(),ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetHeight());
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i],"CENTER",0,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Hide();
			if(i==6)then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Show();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:SetAlpha(0.5);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["AnimalCompanionIcon"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateTexture(nil,"ARTWORK",nil, 3);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["AnimalCompanionIcon"]:SetTexture("Interface\\ICONS\\ABILITY_HUNTER_BESTIALDISCIPLINE");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["AnimalCompanionIcon"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetWidth()*0.6,ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetHeight()*0.6);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["AnimalCompanionIcon"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i],"CENTER",0,0);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormal");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetPoint("TOP",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"],"TOP",0,6);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:GetWidth()+14,64);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetFont("Fonts\FRIZQT__.TTF", 2, "MONOCHROME");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormal");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"]:SetPoint("TOP",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"],"TOP",0,-16);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:GetWidth()+14,64);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"]:SetFont("Fonts\FRIZQT__.TTF", 2, "MONOCHROME");
				--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetText("Requires: Specialization BeastMastery");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetText("");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetTextColor(1,0,0,1);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"]:SetText("Requires:\n Talent Animal\n Compnanion");
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text2"]:SetTextColor(1,0,0,1);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Hide();
			end
			if(i==6 and GlobalSpecialization ~= "Beast Mastery")then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Show();
			end
			--selected highlight
			if(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"] == nil) then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:CreateTexture(nil,"OVERLAY");
			end
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetTexture(nil);
			--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetColorTexture(0,0,0,0);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetAlpha(0);
			--	ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetAtlas("PetList-ButtonSelect");    --- testing another glow
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic highlight 4");
			--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetMask("Interface\\PETBATTLES\\PetBattle-SelectedPetGlow");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetWidth()*0.72,ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:GetHeight()*0.72);
			--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconTexture"]:SetAllPoints(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetIconFrame"]);
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i],"CENTER");
			ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Selected"]:SetDrawLayer("OVERLAY",7);
			--ActivePetSlotsCards["ActiveSlot"..indexNumber]["Card"..indexNumber]["Selected"]
			if(i < 6)then
				if(not IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Show();
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateTexture(nil,"ARTWORK",nil, 3);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"]:SetTexture("Interface\\PETBATTLES\\PetBattle-LockIcon");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"]:SetSize(48*0.72,48*0.72);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["LockIconIcon"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"],"CENTER",0,-15);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"] = ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:CreateFontString(nil,"OVERLAY","GameFontNormal");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetPoint("TOP",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"],"TOP",0,-16);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetSize(ElementSizeX*0.72,24);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetFont("Fonts\FRIZQT__.TTF", 8, "MONOCHROME");
					local SpellName, SpellRank, icon, castTime, minRange, maxRange = GetSpellInfo(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetText("Requires:\n"..SpellName);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]["Text1"]:SetTextColor(1,0,0,1);
				end
			end
		end
		iStableMaster:UpdateActiveCards(); 
	else
		--print(" NIL ");
	end
end -- Populates the Sockets with Cards
function iStableMaster:UpdateFunctionsOnActiveCards() 
	if(ActivePetSlotsCards == nil ) then 
		return;
	end
	local mousePos = {x=0,y=0};
	for i=1,6,1 do
		local spellKnown = false;
		lTalents = {};
		local lConfigID = C_ClassTalents.GetActiveConfigID();
		local lConfigInfo = C_Traits.GetConfigInfo(lConfigID);
		local lTreeIDs = lConfigInfo["treeIDs"];
		for i = 1, #lTreeIDs do
			for _, lNodeID in pairs(C_Traits.GetTreeNodes(lTreeIDs[i])) do
				local lNodeInfo = C_Traits.GetNodeInfo(lConfigID, lNodeID);
				local activeEntry = lNodeInfo.activeEntry;
				local activeRank = lNodeInfo.activeRank;
				if ( activeEntry and activeRank > 0 ) then
					local activeEntryID = activeEntry.entryID;
					local lEntryInfo = C_Traits.GetEntryInfo(lConfigID,activeEntryID);
					--if ( lEntryInfo ) then
					local lDefinitionID = lEntryInfo["definitionID"];
					--BA_Data["function LogTextLine"](string.format("def ID:%s",tostring(lDefinitionID)));
					local lDefinitionInfo = C_Traits.GetDefinitionInfo(lDefinitionID);
					--BA_Data["function LogTextLine"](string.format("def info:%s",tostring(lDefinitionInfo)));
					local spellID = lDefinitionInfo["spellID"];
					local spellName = GetSpellInfo(spellID);

					lTalents[spellName] = activeRank;
					--print(lTalents["Animal Companion"]);
				end
			end
		end
		if(i < 6) then
			spellKnown = IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]);
		else
			if(GlobalSpecialization == "Beast Mastery")then
				spellKnown = iStableMaster:HasTalent("Animal Companion");
			else
				spellKnown = false;
			end
		end
		if(iStableMasterOptionsDB.Layout == "Default" or iStableMasterOptionsDB.Layout == nil) then
			if(spellKnown)then
				--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", nil);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnEnter", function() 
					iStableMaster.currentHover = tonumber(i);
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLeave", function(self)
					iStableMaster.currentHover = nil;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].tickrate = 4;
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].tick = 0;
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function(self, button)
					iStableMaster:PetCardSelect(ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]);
					iStableMaster:SetSelectedHighlight();
					if button == "LeftButton" and not self.isMoving then																	 
						mousePos = {x=0,y=0};																		  
						mousePos.x, mousePos.y = GetCursorPosition();
						self.isLeftButtonDown = true;
						clickedCardSocket = tonumber(i);
					end
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLoad", function(self) 
					self.tick = 0;
					self.tickrate = 4;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnUpdate", function(self)
					if(self.tick == nil) then
						self.tick = 0;
						self.tickrate = 4;
						self.lastTick = 0;
					end
					if(math.fmod(self.tick,self.tickrate) == 0 and self.lastTick ~= self.tick) then
						if(clickedCardSocket ~= nil) then
							if(mousePos.x == nil or mousePos.y == nil) then 
								return;
							end
							local mousePosTemp = {};
							mousePosTemp.X, mousePosTemp.Y = GetCursorPosition();
							if ((math.floor(mousePos.x*100) ~= math.floor(mousePosTemp.X*100)) or (math.floor(mousePos.y*100) ~= math.floor(mousePosTemp.Y*100))) then
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = true;
								mousePos.x, mousePos.y = mousePosTemp.X, mousePosTemp.Y;
							else
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = false;
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
							end
							if(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown and 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved and 
									clickedCardSocket ~= nil and GetCursorInfo() == nil) then
										iStableMaster:PetOnDrag(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["PetInfo"]["Slot"]);
										iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Down");
										-- hide filters while dragging
										iStableMaster:TempHideFiltersAndSorts();
										
										-- Set status is moving true
										ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = true;
									end		
						end
					end
					--print(self.cursorMoved);
					self.lastTick = self.tick;
					self.tick = self.tick+1;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseUp",function(self, button)
					if(clickedCardSocket == nil) then
						iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Up");
						iStableMaster:TempHideFiltersAndSortsEnd();
						iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]);
						self.isLeftButtonDown = false;	
						self.isMoving = false;
					else
						if button == "LeftButton" and ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving then
							if(clickedCardSocket ~= nil) then
								local slot = self:GetName();
								if(iStableMaster.currentHover ~= nil) then
									iStableMaster:PetOnDrop(iStableMaster.currentHover);
								else
									ClearCursor();
								end
								iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]); 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown = false;																		
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = false;
								clickedCardSocket = nil;
								iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Up");
								iStableMaster:TempHideFiltersAndSortsEnd();
								-- show filters after dragging done
								--if(FilterScrollFrame:IsVisible() and StablesRightFrameFilterSortButtonWrapperFilterSortBtn.isOpen) then
								

							end
						else
							ClearCursor();
						end
					end
					clickedCardSocket = nil;
					clickedScrollFrame = nil;
					--mousePos.x, mousePosY = nil,nil;
				end);
			else
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function() 
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnUpdate", function(self)
					if(self.tick == nil) then
						self.tick = 0;
						self.tickrate = 4;
						self.lastTick = 0;
					end
					if(math.fmod(self.tick,self.tickrate) == 0  and self.lastTick ~= self.tick) then
						if(self.mousePos == nil) then 
							return;
						end
						if(self.mousePos == nil) then
							return
						end
						if(clickedCardSocket ~= nil) then
							local mousePosTempX, mousePosTempY = GetCursorPosition();
							if ((math.floor(self.mousePos.x*100) ~= math.floor(mousePosTempX*100)) or (math.floor(self.mousePos.y*100) ~= math.floor(mousePosTempY*100)) ) then
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
								mousePos.x, mousePos.y = mousePosTempX, mousePosTempY;
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = true;

							else
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = false;
							end
							--print(mousePos.x.." - "..mousePos.y);
							--print(mousePosTempX, mousePosTempY);
							if(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown and 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved and 
									clickedCardSocket ~= nil and GetCursorInfo() == nil) then
										iStableMaster:PetOnDrag(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["PetInfo"]["Slot"]);
										iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Down");
										iStableMaster:TempHideFiltersAndSorts();
										ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = true;
									end	
						end
					end
					--print(self.cursorMoved);
					self.lastTick = self.tick;
					self.tick = self.tick+1;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnEnter", function() 
					iStableMaster.currentHover = tonumber(i);
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLeave", function(self)
					iStableMaster.currentHover = nil;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseUp",function(self, button)
					if button == "LeftButton" then
						ClearCursor();
					end
					clickedCardSocket = nil;
					clickedScrollFrame = nil;
				end);
			end
		elseif(iStableMasterOptionsDB.Layout == "Compact") then
			if(spellKnown)then
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function()  end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnEnter", function() 
					iStableMaster.currentHover = tonumber(i);
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLeave", function(self)
					iStableMaster.currentHover = nil;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].tickrate = 4;
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].tick = 0;
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function(self, button)
					iStableMaster:PetCardSelect(ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]);
					iStableMaster:SetSelectedHighlight();
					if button == "LeftButton" and not self.isMoving then																	 
						mousePos = {x=0,y=0}																		  
						mousePos.x, mousePos.y = GetCursorPosition();
						self.isLeftButtonDown = true;
						clickedCardSocket = tonumber(i);
					end
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLoad", function(self) 
					self.tick = 0;
					self.tickrate = 4;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnUpdate", function(self)
					if(self.tick == nil) then
						self.tick = 0;
						self.tickrate = 4;
						self.lastTick = 0;
					end
					if(math.fmod(self.tick,self.tickrate) == 0 and self.lastTick ~= self.tick) then
						if(clickedCardSocket ~= nil) then
							if(mousePos.x == nil or mousePos.y == nil) then 
								return;
							end
							local mousePosTemp = {};
							mousePosTemp.X, mousePosTemp.Y = GetCursorPosition();
							--print(((math.floor(mousePosX*100) ~= math.floor(mousePosTempX*100)) or (math.floor(mousePosY*100) ~= math.floor(mousePosTempY*100)) ));
							if ((math.floor(mousePos.x*100) ~= math.floor(mousePosTemp.X*100)) or (math.floor(mousePos.y*100) ~= math.floor(mousePosTemp.Y*100))) then
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = true;
								mousePos.x, mousePos.y = mousePosTemp.X, mousePosTemp.Y;
							else
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = false;
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
							end
							if(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown and 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved and 
									clickedCardSocket ~= nil and GetCursorInfo() == nil) then
										--ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving ~= true ) then
										iStableMaster:PetOnDrag(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["PetInfo"]["Slot"]);
										iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Down");
										iStableMaster:TempHideFiltersAndSorts();
										ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = true;
									end		
						end
					end
					--print(self.cursorMoved);
					self.lastTick = self.tick;
					self.tick = self.tick+1;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseUp",function(self, button)
					if(clickedCardSocket == nil) then
						iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Up");
						iStableMaster:TempHideFiltersAndSortsEnd();
						iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]);
						self.isLeftButtonDown = false;	
						self.isMoving = false;
					else
						if button == "LeftButton" and ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving then
							if(clickedCardSocket ~= nil) then
								local slot = self:GetName();
								if(iStableMaster.currentHover ~= nil) then
									iStableMaster:PetOnDrop(iStableMaster.currentHover);
								else
									ClearCursor();
								end
								iStableMaster:SubmitSearch(_G["StablesRightFrameEditBox"]); 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown = false;																		
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = false;
								clickedCardSocket = nil;
								iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Up");
								iStableMaster:TempHideFiltersAndSortsEnd();
							end
						else
							ClearCursor();
						end
					end
					clickedCardSocket = nil;
					clickedScrollFrame = nil;
					--mousePos.x, mousePosY = nil,nil;
				end);
			else
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseDown", function() 
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnUpdate", function(self)
					if(self.tick == nil) then
						self.tick = 0;
						self.tickrate = 4;
						self.lastTick = 0;
					end
					if(math.fmod(self.tick,self.tickrate) == 0  and self.lastTick ~= self.tick) then
						if(mousePos.x == nil or mousePos.y == nil) then 
							return;
						end
						if(self.mousePos == nil) then
							return
						end
						if(clickedCardSocket ~= nil) then
							local mousePosTemp = {};
							mousePosTemp.X, mousePosTemp.Y = GetCursorPosition();
							if ((math.floor(mousePos.x*100) ~= math.floor(mousePosTemp.X*100)) or (math.floor(mousePos.y*100) ~= math.floor(mousePosTemp.Y*100)) ) then
								--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
								mousePos.x, mousePos.y = mousePosTemp.X, mousePosTemp.Y;
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = true;
							else
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved = false;
							end
							--print(mousePos.x.." - "..mousePos.y);
							--print(mousePosTempX, mousePosTempY);
							if(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isLeftButtonDown and 
								ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].cursorMoved and 
									clickedCardSocket ~= nil and GetCursorInfo() == nil) then
										iStableMaster:PetOnDrag(ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["PetInfo"]["Slot"]);
										iStableMaster:TempHideFiltersAndSorts();
										iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Down");
										ActivePetSlotsCards["ActiveSlot"..clickedCardSocket]["Socket"..clickedCardSocket].isMoving = true;
									end	
						end
					end
					--print(self.cursorMoved);
					self.lastTick = self.tick;
					self.tick = self.tick+1;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnEnter", function() 
					iStableMaster.currentHover = tonumber(i);
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnLeave", function(self)
					iStableMaster.currentHover = nil;
				end);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i]:SetScript("OnMouseUp",function(self, button)
					if button == "LeftButton" then
						ClearCursor();
					end
					clickedCardSocket = nil;
					clickedScrollFrame = nil;
				end);
			end
		end
	end
end -- Probably keep this, but make it dynamic during the rework.
--- DATABASE HANDLERS
function iStableMaster:UpdateActiveCards() 
	if(ActivePetSlotsCards == nil) then
		--print("stack trace");
		return;
	end
	if(iStableMasterOptionsDB.Layout == "Default" or iStableMasterOptionsDB.Layout == nil) then
		if(iStableMasterStableDB["PetInfo"]["ActiveSlot"..1]["icon"] == nil ) then 
			iStableMaster:SavePetInfoToWTF()
		end
		for i=1,6,1 do
			if(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"] == nil) then
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"] = {};
			end
			if(i<6) then
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["icon"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["name"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["level"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["family"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["talent"];
				-- custom info
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["favourite"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["inStables"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["Slot"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["abilities"];
				--end
			elseif(i==6) then
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["icon"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["name"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["level"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["family"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["talent"];
				-- custom info
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["favourite"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["inStables"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["Slot"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["abilities"];
				--end
			end
			--BM frame
			lTalents = {};
			local lConfigID = C_ClassTalents.GetActiveConfigID();
			local lConfigInfo = C_Traits.GetConfigInfo(lConfigID);
			local lTreeIDs = lConfigInfo["treeIDs"];
			for i = 1, #lTreeIDs do
				for _, lNodeID in pairs(C_Traits.GetTreeNodes(lTreeIDs[i])) do
					local lNodeInfo = C_Traits.GetNodeInfo(lConfigID, lNodeID);
					local activeEntry = lNodeInfo.activeEntry;
					local activeRank = lNodeInfo.activeRank;
					if ( activeEntry and activeRank > 0 ) then
						local activeEntryID = activeEntry.entryID;
						local lEntryInfo = C_Traits.GetEntryInfo(lConfigID,activeEntryID);
						--if ( lEntryInfo ) then
						local lDefinitionID = lEntryInfo["definitionID"];
						--BA_Data["function LogTextLine"](string.format("def ID:%s",tostring(lDefinitionID)));
						local lDefinitionInfo = C_Traits.GetDefinitionInfo(lDefinitionID);
						--BA_Data["function LogTextLine"](string.format("def info:%s",tostring(lDefinitionInfo)));
						local spellID = lDefinitionInfo["spellID"];
						local spellName = GetSpellInfo(spellID);		
						lTalents[spellName] = activeRank;
						--print(lTalents["Animal Companion"]);
					end
				end
			end
			--local hasAnimalCompanionTalent = select(4,GetTalentInfoBySpecialization(1, 1, 2));
			--local hasAnimalCompanionTalent  = (lTalents["Animal Companion"] >=1 ) or false;
			local hasAnimalCompanionTalent  = iStableMaster:HasTalent("Animal Companion");
			if((GlobalSpecialization ~= "Beast Mastery" and i == 6) or (not hasAnimalCompanionTalent and GlobalSpecialization == "Beast Mastery" and i == 6)) then 
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Show();
				--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(0);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:Hide();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:Hide();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:Hide();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:Hide();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Show();
			elseif(i == 6) then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Show();
				--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(0);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:Show();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:Show();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:Show();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:Show();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Hide();
			end
			if(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] == nil or ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] == "N/A") then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Hide();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetAlpha(0);
				ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(1);
				if(GlobalSpecialization ~= "Beast Mastery" and i == 6) then 
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Show();
					--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(0);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetAlpha(1);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:Hide();
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:Hide();
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:Hide();
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:Hide();
				end
				if(i < 6)then
					if(not IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Show();
						--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(0);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:Hide();
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:Hide();
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:Hide();
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:Hide();
					end
				end
			else
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Show();
				--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(0);
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetAlpha(1);
				if(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] ~= nil and ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] ~= "N/A") then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetTexture(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetSize(32,32);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"],"CENTER");
				end
				if(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] ~= nil and ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] ~= "N/A") then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["Name"]:SetFont("Fonts\FRIZQT__.TTF", 14);
					--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["Name"]:SetSize(string.len(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"])*8,42);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["Name"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:GetWidth()-8,42);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["Name"]:SetJustifyH("LEFT");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["Name"]:SetTextHeight(16);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["Name"]:SetPoint("LEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"],"LEFT",0+12,5-6);	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["Name"]:SetText(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["Name"]:SetTextColor(iStableMaster:GetDBColour("Default","Blue"));
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["FamilyName"]:SetFont("Fonts\FRIZQT__.TTF", 8, "MONOCHROME");
					--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["FamilyName"]:SetSize(string.len(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"])*8,24);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["FamilyName"]:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:GetWidth()-8,42);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["FamilyName"]:SetJustifyH("LEFT");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["FamilyName"]:SetPoint("LEFT",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"],"LEFT",0+12,-10-6);	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["FamilyName"]:SetText(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]["FamilyName"]:SetTextColor(iStableMaster:GetDBColour("Default","Blue"));
				end
				for j=1,iStableMaster:StringKeyTableLengthI(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"]["talent"]) do
					local name, rank, icon, castTime, minRange, maxRange = GetSpellInfo(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"]["talent"][j])
					local ofsx = 0;
					if icon ~= nil and icon ~= "N/A" and icon ~= "" then
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["Texture"]:SetTexture(icon);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["BorderTexture"]:SetAtlas("ui-hud-actionbar-IconFrame");
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["Texture"]:SetSize(24,24);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["BorderTexture"]:SetSize(24,24);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["Texture"]:SetVertexColor(1,1,1,1);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]:HookScript("OnLeave",function(self)iStableMaster:SpellMouseOver(self,nil,true)end);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]:HookScript("OnEnter",function(self)iStableMaster:SpellMouseOver(self,ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"]["talent"][j],false)end);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["Texture"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j],"CENTER", 0, 0);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["BorderTexture"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j],"CENTER", 0, 0);
						--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["Texture"].tooltipname = "|cFFFF0000Bread";
					end
				end
				for j=1,iStableMaster:StringKeyTableLength(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"],"SpellIcon") do
					local name, rank, icon, castTime, minRange, maxRange = GetSpellInfo(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"]["family"][j])
					if icon == nil then
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:Hide();
					else
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:Show();
					end
				end
				for j=1,iStableMaster:StringKeyTableLengthI(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"]["family"]) do
					local name, rank, icon, castTime, minRange, maxRange = GetSpellInfo(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"]["family"][j])
					local ofsx = 0;
					if icon ~= nil and icon ~= "N/A" and icon ~= "" then
						if ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"]["family"][j] == nil then
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:Hide();
						else
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:Show();
						end
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["Texture"]:SetTexture(icon);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["BorderTexture"]:SetAtlas("ui-hud-actionbar-IconFrame");
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["Texture"]:SetMask("UI-HUD-ActionBar-IconFrame-Mask","CLAMPTOBLACKADDITIVE");
						--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["Texture"]:SetBlendMode("ADD")
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["Texture"]:SetSize(24,24);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["BorderTexture"]:SetSize(24,24);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["Texture"]:SetVertexColor(1,1,1,1);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:HookScript("OnLeave",function(self)iStableMaster:SpellMouseOver(self,nil,true)end);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]:HookScript("OnEnter",function(self)iStableMaster:SpellMouseOver(self,ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"]["family"][j],false)end);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["Texture"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j],"CENTER", 0, 0);
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j]["BorderTexture"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["FamilyFrame"]["SpellIcon"..j],"CENTER", 0, 0);
						--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]["SpecFrame"]["SpellIcon"..j]["Texture"].tooltipname = "|cFFFF0000Bread";
					end
				end
				if(GetStablePetFoodTypes(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"])~= nil) then
					local dietXSize, dietYSize = 20,20; 
					local points = {};
					points["4;5 - Standard"] = {}
					points["4;5 - Standard"]["x"] =	{
						-(dietXSize*1.5),
						-(dietXSize*0.5),
						(dietXSize*0.5),
						(dietXSize*1.5),
						-(dietXSize*2),
						-(dietXSize*1),
						0,
						(dietXSize*1),
						(dietXSize*2),
					};
					points["4;5 - Standard"]["y"] = {
						(dietYSize*0.5),
						(dietYSize*0.5),
						(dietYSize*0.5),
						(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
					};
					points["5;4 - Standard"] = {}
					points["5;4 - Standard"]["x"] =	{
						-(dietXSize*2),
						-(dietXSize*1),
						0,
						(dietXSize*1),
						(dietXSize*2),
						-(dietXSize*1.5),
						-(dietXSize*0.5),
						(dietXSize*0.5),
						(dietXSize*1),
					};
					points["5;4 - Standard"]["y"] = {
						(dietYSize*0.5),
						(dietYSize*0.5),
						(dietYSize*0.5),
						(dietYSize*0.5),
						(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
					};
					points["9x1 - Standard"] = {} --Does not fit in width.
					points["9x1 - Standard"]["x"] =	{
						-(dietXSize*3.5),
						-(dietXSize*2.5),
						-(dietXSize*1.5),
						-(dietXSize*0.5),
						(dietXSize*0.5),
						(dietXSize*1.5),
						(dietXSize*2.5),
						(dietXSize*3.5),
						-(dietXSize*4.5),
					};
					points["9x1 - Standard"]["y"] = {
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
						-(dietYSize*0.5),
					};
					local foodarrtype = "4;5 - Standard";
					--local foodarrtype = "5;4 - Standard";
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_08");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.BorderTexture:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.MaskTexture:SetSize(dietXSize+8,dietYSize+8);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.BorderTexture:SetAtlas("ui-hud-actionbar-IconFrame");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.BorderTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][1],points[foodarrtype]["y"][1])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.BorderTexture:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][1],points[foodarrtype]["y"][1]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"].tooltipname = "|cFFFF0000Bread";
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.MaskTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][1],points[foodarrtype]["y"][1])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.MaskTexture:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.MaskTexture:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].Bread:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.MaskTexture)
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:GetSize());
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame:SetPoint(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:GetPoint(1));
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame:HookScript("OnLeave",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],nil,true)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame:HookScript("OnEnter",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"].tooltipname,false)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_04");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"]:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.BorderTexture:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.MaskTexture:SetSize(dietXSize+8,dietYSize+8);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.BorderTexture:SetAtlas("ui-hud-actionbar-IconFrame");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.BorderTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][2],points[foodarrtype]["y"][2])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.BorderTexture:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"]:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][2],points[foodarrtype]["y"][2]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"].tooltipname = "|cFFFF0000Cheese";
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.MaskTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][2],points[foodarrtype]["y"][2])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.MaskTexture:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.MaskTexture:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].Cheese:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.MaskTexture)
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"]:GetSize());
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame:SetPoint(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"]:GetPoint(1));
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame:HookScript("OnLeave",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],nil,true)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame:HookScript("OnEnter",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"].tooltipname,false)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_75");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.BorderTexture:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.MaskTexture:SetSize(dietXSize+8,dietYSize+8);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.BorderTexture:SetAtlas("ui-hud-actionbar-IconFrame");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.BorderTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][3],points[foodarrtype]["y"][3])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.BorderTexture:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][3],points[foodarrtype]["y"][3]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"].tooltipname = "|cFFFF0000Fish";
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.MaskTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][3],points[foodarrtype]["y"][3])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.MaskTexture:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.MaskTexture:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].Fish:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.MaskTexture)
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:GetSize());
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame:SetPoint(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:GetPoint(1));
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame:HookScript("OnLeave",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],nil,true)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame:HookScript("OnEnter",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"].tooltipname,false)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_19");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.BorderTexture:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.MaskTexture:SetSize(dietXSize+8,dietYSize+8);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.BorderTexture:SetAtlas("ui-hud-actionbar-IconFrame");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.BorderTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][4],points[foodarrtype]["y"][4])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.BorderTexture:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][4],points[foodarrtype]["y"][4]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"].tooltipname = "|cFFFF0000Fruit";
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.MaskTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][4],points[foodarrtype]["y"][4])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.MaskTexture:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.MaskTexture:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].Fruit:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.MaskTexture)
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:GetSize());
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame:SetPoint(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:GetPoint(1));
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame:HookScript("OnLeave",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],nil,true)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame:HookScript("OnEnter",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"].tooltipname,false)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:SetTexture("Interface\\ICONS\\INV_Mushroom_07");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.BorderTexture:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.MaskTexture:SetSize(dietXSize+8,dietYSize+8);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.BorderTexture:SetAtlas("ui-hud-actionbar-IconFrame");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.BorderTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][5],points[foodarrtype]["y"][5])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.BorderTexture:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][5],points[foodarrtype]["y"][5]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"].tooltipname = "|cFFFF0000Fungus";
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.MaskTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][5],points[foodarrtype]["y"][5])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.MaskTexture:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.MaskTexture:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].Fungus:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.MaskTexture)
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:GetSize());
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame:SetPoint(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:GetPoint(1));
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame:HookScript("OnLeave",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],nil,true)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame:HookScript("OnEnter",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"].tooltipname,false)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_18");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.BorderTexture:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.MaskTexture:SetSize(dietXSize+8,dietYSize+8);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.BorderTexture:SetAtlas("ui-hud-actionbar-IconFrame");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.BorderTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][6],points[foodarrtype]["y"][6])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.BorderTexture:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][6],points[foodarrtype]["y"][6]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"].tooltipname = "|cFFFF0000Meat";
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.MaskTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][6],points[foodarrtype]["y"][6])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.MaskTexture:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.MaskTexture:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].Meat:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.MaskTexture)
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:GetSize());
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame:SetPoint(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:GetPoint(1));
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame:HookScript("OnLeave",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],nil,true)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame:HookScript("OnEnter",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"].tooltipname,false)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:SetTexture("Interface\\ICONS\\INV_Misc_Gear_08");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.BorderTexture:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.MaskTexture:SetSize(dietXSize+8,dietYSize+8);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.BorderTexture:SetAtlas("ui-hud-actionbar-IconFrame");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.BorderTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][7],points[foodarrtype]["y"][7])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.BorderTexture:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][7],points[foodarrtype]["y"][7]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"].tooltipname = "|cFFFF0000Mechanical Bits";
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.MaskTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][7],points[foodarrtype]["y"][7])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.MaskTexture:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.MaskTexture:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.MaskTexture)
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:GetSize());
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame:SetPoint(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:GetPoint(1));
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame:HookScript("OnLeave",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],nil,true)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame:HookScript("OnEnter",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"].tooltipname,false)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:SetTexture("Interface\\ICONS\\INV_Misc_Fish_07");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.BorderTexture:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.MaskTexture:SetSize(dietXSize+8,dietYSize+8);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.BorderTexture:SetAtlas("ui-hud-actionbar-IconFrame");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.BorderTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][8],points[foodarrtype]["y"][8])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.BorderTexture:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][8],points[foodarrtype]["y"][8]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"].tooltipname = "|cFFFF0000Raw Fish";
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.MaskTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][8],points[foodarrtype]["y"][8])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.MaskTexture:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.MaskTexture:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.MaskTexture)
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:GetSize());
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame:SetPoint(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:GetPoint(1));
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame:HookScript("OnLeave",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],nil,true)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame:HookScript("OnEnter",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"].tooltipname,false)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_72");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.BorderTexture:SetSize(dietXSize,dietYSize);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.MaskTexture:SetSize(dietXSize+8,dietYSize+8);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.BorderTexture:SetAtlas("ui-hud-actionbar-IconFrame");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.BorderTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][9],points[foodarrtype]["y"][9])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.BorderTexture:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:SetVertexColor(0.5,0.5,0.5,0.2);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][9],points[foodarrtype]["y"][9]);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"].tooltipname = "|cFFFF0000Raw Meat";
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.MaskTexture:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],"CENTER",points[foodarrtype]["x"][9],points[foodarrtype]["y"][9])	
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.MaskTexture:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.MaskTexture:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:AddMaskTexture(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.MaskTexture)
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame:SetSize(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:GetSize());
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame:SetPoint(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:GetPoint(1));
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame:HookScript("OnLeave",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],nil,true)end);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame:HookScript("OnEnter",function()iStableMaster:DietMouseOver(ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"],ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"].tooltipname,false)end);
					local DietList = { GetStablePetFoodTypes(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"]) };
					for j=1,9,1 do
						if(DietList[j] == "Bread") then
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:SetTexture(nil);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"].tooltipname = "|cFF00FF00Bread";
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_08");
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:SetVertexColor(0.5,0.5,0.5,1);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].breadFrame.BorderTexture:SetVertexColor(1,1,1,1);
						elseif(DietList[j] == "Cheese") then
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"]:SetTexture(nil);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"].tooltipname = "|cFF00FF00Cheese";
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_04");
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"]:SetVertexColor(0.5,0.5,0.5,1);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].cheeseFrame.BorderTexture:SetVertexColor(1,1,1,1);
						elseif(DietList[j] == "Fish") then
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:SetTexture(nil);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"].tooltipname = "|cFF00FF00Fish";
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_75");
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:SetVertexColor(0.5,0.5,0.5,1);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fishFrame.BorderTexture:SetVertexColor(1,1,1,1);
						elseif(DietList[j] == "Fruit") then
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:SetTexture(nil);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"].tooltipname = "|cFF00FF00Fruit";
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_19");
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:SetVertexColor(0.5,0.5,0.5,1);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fruitFrame.BorderTexture:SetVertexColor(1,1,1,1);
						elseif(DietList[j] == "Fungus") then
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:SetTexture(nil);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"].tooltipname = "|cFF00FF00Fungus";
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:SetTexture("Interface\\ICONS\\INV_Mushroom_07");
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:SetVertexColor(0.5,0.5,0.5,1);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].fungusFrame.BorderTexture:SetVertexColor(1,1,1,1);
						elseif(DietList[j] == "Meat") then
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:SetTexture(nil);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"].tooltipname = "|cFF00FF00Meat";
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_18");
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:SetVertexColor(0.5,0.5,0.5,1);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].meatFrame.BorderTexture:SetVertexColor(1,1,1,1);
						elseif(DietList[j] == "Mechanical Bits") then
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:SetTexture(nil);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"].tooltipname = "|cFF00FF00Mechanical Bits";
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:SetTexture("Interface\\ICONS\\INV_Misc_Gear_08");
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:SetVertexColor(0.5,0.5,0.5,1);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].mechanicalBitsFrame.BorderTexture:SetVertexColor(1,1,1,1);
						elseif(DietList[j] == "Raw Fish") then
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:SetTexture(nil);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"].tooltipname = "|cFF00FF00Raw Fish";
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:SetTexture("Interface\\ICONS\\INV_Misc_Fish_07");
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:SetVertexColor(0.5,0.5,0.5,1);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawFishFrame.BorderTexture:SetVertexColor(1,1,1,1);
						elseif(DietList[j] == "Raw Meat") then
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:SetTexture(nil);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"].tooltipname = "|cFF00FF00Raw Meat";
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:SetTexture("Interface\\ICONS\\INV_Misc_Food_72");																								
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:SetVertexColor(0.5,0.5,0.5,1);
							ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"].rawMeatFrame.BorderTexture:SetVertexColor(1,1,1,1);
						end
					end
				end
			end
		end
	elseif(iStableMasterOptionsDB.Layout == "Compact") then
		local ElementSizeX = 90;
		local ElementSizeY = 93.5;
		if(iStableMasterStableDB["PetInfo"]["ActiveSlot"..1]["icon"] == nil ) then 
			iStableMaster:SavePetInfoToWTF()
		end
		for i=1,6,1 do
			if(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"] == nil) then
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"] = {};
			end
			if(i<6) then
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["icon"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["name"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["level"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["family"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["talent"];
				-- custom info
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["favourite"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["inStables"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["Slot"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["abilities"];
				--end
			elseif(i==6) then
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["icon"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["name"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["level"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["family"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["talent"];
				-- custom info
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["favourite"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["inStables"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["Slot"];
				ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["abilities"];
				--end
			end
			--BM frame
			lTalents = {};
			local lConfigID = C_ClassTalents.GetActiveConfigID();
			local lConfigInfo = C_Traits.GetConfigInfo(lConfigID);
			local lTreeIDs = lConfigInfo["treeIDs"];
			for i = 1, #lTreeIDs do
				for _, lNodeID in pairs(C_Traits.GetTreeNodes(lTreeIDs[i])) do
					local lNodeInfo = C_Traits.GetNodeInfo(lConfigID, lNodeID);
					local activeEntry = lNodeInfo.activeEntry;
					local activeRank = lNodeInfo.activeRank;
					if ( activeEntry and activeRank > 0 ) then
						local activeEntryID = activeEntry.entryID;
						local lEntryInfo = C_Traits.GetEntryInfo(lConfigID,activeEntryID);
						--if ( lEntryInfo ) then
						local lDefinitionID = lEntryInfo["definitionID"];
						--BA_Data["function LogTextLine"](string.format("def ID:%s",tostring(lDefinitionID)));
						local lDefinitionInfo = C_Traits.GetDefinitionInfo(lDefinitionID);
						--BA_Data["function LogTextLine"](string.format("def info:%s",tostring(lDefinitionInfo)));
						local spellID = lDefinitionInfo["spellID"];
						local spellName = GetSpellInfo(spellID);
						
						lTalents[spellName] = activeRank;
						--print(lTalents["Animal Companion"]);
					end
				end
			end
			--local hasAnimalCompanionTalent = select(4,GetTalentInfoBySpecialization(1, 1, 2));
			--local hasAnimalCompanionTalent  = (lTalents["Animal Companion"] >=1 ) or false;	
			local hasAnimalCompanionTalent  = iStableMaster:HasTalent("Animal Companion");
			if((GlobalSpecialization ~= "Beast Mastery" and i == 6) or (not hasAnimalCompanionTalent and GlobalSpecialization == "Beast Mastery" and i == 6)) then 
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Show();
				--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(0);
				--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:Hide();
				--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:Hide();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:Hide();
				--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:Hide();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Show();
			elseif(i == 6) then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Show();
				--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(0);
				--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:Show();
				--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:Show();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:Show();
				--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:Show();
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["RequiresFrame"]:Hide();
			end
			if(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] == nil or ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] == "N/A") then
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Hide();
				--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(1);
				--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i].border:SetAlpha(0);
				if(GlobalSpecialization ~= "Beast Mastery" and i == 6) then 
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Show();
					--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(0);
					--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:Hide();
					--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:Hide();
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:Hide();
					--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:Hide();
				end
				if(i < 6)then
					if(not IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][i]))then
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Show();
						--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(0);
						--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]:Hide();
						--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["NameFrame"]:Hide();
						ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:Hide();
						--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["Abilities"]:Hide();
					end
				end
			else
				ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]:Show();
				--ActivePetSlotsCards["ActiveSlot"..i]["Socket"..i].border:SetAlpha(0);
				if(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] ~= nil and ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] ~= "N/A") then
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetTexture(ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"]);
					--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetBlendMode("ADD");
					--ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetSize(ElementSizeX,ElementSizeY);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetPoint("CENTER",ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"],"CENTER");
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]:EnableMouse(false);
					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["IconFrame"]["Icon"]:SetDrawLayer("ARTWORK",5);
				end
			end
		end
	else
		--print(" NIL ");
	end
end -- Updates the Data Base Values for active Cards

----------------------------------------------------
---				Active Pet Cards END			 ---
----------------------------------------------------
----------------------------------------------------
---				Pet Drag And Drop			     ---
----------------------------------------------------
function iStableMaster:TempHideFiltersAndSorts()
	if(not StablesFilterSortFrame:IsVisible() ) then
		return;
	end
		iStableMaster.isFilterSortsShown = true;
	--	print("hide filters");
		iStableMaster:TempHideFiltersFrame();
	--end
	
end
function iStableMaster:TempHideFiltersAndSortsEnd()
	
	--if(not StablesFilterSortFrame:IsVisible() and ) then
	--	print("hide filters");
	if(iStableMaster.isFilterSortsShown) then
		iStableMaster:TempHideFiltersFrame();
		iStableMaster.isFilterSortsShown = false;
	end
	--end
end
function iStableMaster:PetOnDrag(arg)
	PickupStablePet(arg);
	if(noloop) then
		if(iStableMaster:GetFilterValue("AnyFilter")) then
			iStableMaster:UpdateFilterSpecs(true);
		else
			--MoveOccupiedSlotsToBottomOfScroll(); 
			
		end
		noloop = false;
	end
end
function iStableMaster:PetOnDrop(arg)
	local cursorType, petSlot = GetCursorInfo();
	if (cursorType == "pet") then
		SetPetSlot(petSlot, arg);
		iStableMaster:UpdateSquadCurrentSlots(petSlot,arg);
		iStableMaster:UpdateFavStatus(petSlot,arg)
		ClearCursor();
		noloop = true;
	end
end
function iStableMaster:ShowEmptyStableSlotsOnDragOnly(bool,state)
	if(bool) then 
		iStableMaster:SavePetInfoToWTF();
		for i=1, iStableMaster.StablesCollectionScrollbarMaxChildren,1 do 
			local petSlot = i;
			local petisStabled = nil;
			if(i < 6) then
				petSlot = PetStable_GetPetSlot(i, true);
				petisStabled = false;
			else
				petSlot = (i - 5);
				petisStabled = true;
			end
			local l_icon, l_name, l_level, l_family, l_talent = GetStablePetInfo(i);		
			if(i < 6) then
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i] = {};
				end
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"] = {};
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["icon"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["name"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["level"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["family"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["talent"];
				-- custom info
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["favourite"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["inStables"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..petSlot]["Slot"];
				--end
			else
				if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i] == nil) then
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i] = {};
				end
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"] = {};
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["icon"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["name"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["level"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["family"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["talent"];
				-- custom info
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["favourite"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["inStables"];
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot]["Slot"];
				--end
			end
		end
		if(state == "Up")then
			if(iStableMaster:GetFilterValue("AnyFilter")) then
				iStableMaster:UpdateFilterSpecs(true);
			else				
				iStableMaster:MasterFilterSort("",false);
			end
		elseif(state == "Down")then	
			if(iStableMaster:GetFilterValue("AnyFilter")) then
				iStableMaster:UpdateFilterSpecs(false);
			else
				iStableMaster:MasterFilterSort("",true);
			end
		end
	end
end
----------------------------------------------------
---				Pet Drag And Drop End   	     ---
----------------------------------------------------
----------------------------------------------------
---				BeastSquads ScrollFrame   	     ---
----------------------------------------------------
-- presetScrollFrame
function iStableMaster:PopulateSquadScrollFrame()
	if iStableMasterStableDB["SavedSquads"] == nil then
		return;
	end
	if(StablesCollectionPresetsFrameScrollFrame.scrollChild == nil) then
		StablesCollectionPresetsFrameScrollFrame.scrollChild = CreateFrame("Frame", ScrollChild, StablesCollectionPresetsFrameScrollFrameScrollBar, BackdropTemplateMixin and "BackdropTemplate");
		StablesCollectionPresetsFrameScrollFrame:SetScrollChild(StablesCollectionPresetsFrameScrollFrame.scrollChild);
		StablesCollectionPresetsFrameScrollFrame.scrollChild:SetSize(127,42);
		StablesCollectionPresetsFrameScrollFrame.scrollChild:SetHeight(StablesCollectionPresetsFrameScrollFrame:GetHeight());
	end
	local squadslimit = iStableMaster:StringKeyTableLength(iStableMasterStableDB["SavedSquads"],"Squad");
	StablesCollectionPresetsFrameScrollFrame.scrollChild:SetPoint(StablesCollectionPresetsFrameScrollFrame:GetPoint(1));
	local point1, relativeTo1, relativePoint1, xOfs1, yOfs1 = StablesCollectionPresetsFrameScrollFrame.scrollChild:GetPoint(1);
	for i = 1, squadslimit do
		if(StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i] == nil) then
			StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i] = CreateFrame("Button", "Squad"..i ,StablesCollectionPresetsFrameScrollFrame.scrollChild, "SquadButtonTemplate");
			--StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i] = CreateFrame("Button", "Squad"..i ,StablesCollectionPresetsFrameScrollFrame.scrollChild);
		end
		--print("makeFrame");
		StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:SetPoint("TOPLEFT", StablesCollectionPresetsFrameScrollFrame.scrollChild, "TOPLEFT", 8,-((StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:GetHeight()-10)*(i-1))-2);
		--StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:SetPoint(point2, yOfs2,-(StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:GetHeight()*(i+1))-4);
		--StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:SetWidth(StablesCollectionPresetsFrameScrollFrame.scrollChild:GetWidth());
		StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:SetSize(128,42);
		StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:SetHeight(42);
		StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:SetWidth(128);
		StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:RegisterForClicks("LeftButtonDown", "RightButtonDown");
		StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:SetScript("OnClick", function(self, button)
			if button == "LeftButton" then iStableMaster:ApplySquad(i); -- USING i Will cause problems if there are gaps in the presets .... I belived i fixed this lately
				--iStableMaster:Print("THIS IS WORKING SOMEHOW!");
			elseif button == "RightButton" then -- MAKE DROP DOWN WITH DELETE OPTION HERE
				BeastSquadsManagerFrame.caller = iStableMasterStableDB["SavedSquads"]["Squad"..i];
				BeastSquadsManagerFrame.caller.index = i;
				iStableMaster:EditSquad(i);
				--	if(BeastSquadsManagerFrame:IsShown()) then
				--		HideUIPanel(BeastSquadsManagerFrame);
				--	end
				--		ShowUIPanel(BeastSquadsManagerFrame);
				--BeastSquadsManagerFrame:Show();
			else
				--print("MOUSE BUTTON WAS PRESSED");
			end
		end);
		if((iStableMasterStableDB.SavedSquads["Squad"..i] ~= nil) and (not StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:IsShown()))then -- if squad exist in DB and not StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:IsShown()
			StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:Show();
		end
	end
	if(StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..1] ~= nil) then
		StablesCollectionPresetsFrameScrollFrame.scrollChild:SetHeight((StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..1]:GetHeight()-10)*(squadslimit+1)-20);
	end
end
-- presetChange Handle ScrollFrame
function iStableMaster:UpdateSquadList()
	if(not StablesCollectionPresetsFrameScrollFrame:IsShown()) then
		return;
	end
	local squadslimit = iStableMaster:StringKeyTableLength(iStableMasterStableDB["SavedSquads"],"Squad");
	--StablesCollectionPresetsFrameScrollFrame.scrollChild:SetPoint(StablesCollectionPresetsFrameScrollFrame:GetPoint(1));
	local point1, relativeTo1, relativePoint1, xOfs1, yOfs1 = StablesCollectionPresetsFrameScrollFrame.scrollChild:GetPoint(1);
	--StablesCollectionPresetsFrameScrollFrame.scrollChild:SetPoint(point1,relativeTo1,"TOPRIGHT",xOfs,-21);
	--local point2, relativeTo2, relativePoint2, xOfs2, yOfs2 = StablesCollectionPresetsFrameScrollFrame.scrollChild:GetPoint(2);
	local removedFrameCount = 0;
	for i = 1, squadslimit do
		if(StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i] == nil) then
			return;
		end
		--print("makeFrame");
		if(StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..i]:IsShown() == false) then
			removedFrameCount = removedFrameCount + 1;
		else
			--print("Debug");
		end
		if(i == 1 and removedFrameCount == 1) then
		else
			StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..(i-removedFrameCount)]:ClearAllPoints();
			StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..(i-removedFrameCount)]:SetPoint("TOPLEFT", StablesCollectionPresetsFrameScrollFrame.scrollChild, "TOPLEFT", 8,-((StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..(i-removedFrameCount)]:GetHeight()-10)*((i-removedFrameCount)-1))-2);
		end	
	end
end -- Does NOT update icon and name and shouldn't, delegate to separate functions.
----------------------------------------------------
---			BeastSquads ScrollFrame End          ---
----------------------------------------------------
----------------------------------------------------
---				BeastSquads Manager        	     ---
----------------------------------------------------
function iStableMaster:ActiveChangesIndicatorsOnOff(queueVal,currentVal,frame)  -- Takes a queued value and compares to the actual value if different then a change is queued and the third arg the frame is hid or shown
	if(queueVal ~= currentVal) then 
		frame:Show();
	else
		frame:Hide();
	end
end
function iStableMaster:RenameSquad() -- Set the text in the EditBox to the Name in the Queue (should be called on focus lost)
	SquadChangesQueueTable.Name = SquadNameEditBox:GetText();
	--iStableMaster:Print("DEBUG:: iStableMaster:RenameSquad() executed");
end 
function iStableMaster:RevertSquadName(index) -- Sets the Queued SquadName to the Current Squadname Value
	SquadChangesQueueTable.Name = iStableMasterStableDB["SavedSquads"]["Squad"..index].Name;
	SquadNameEditBox:SetText(SquadChangesQueueTable.Name);
end 
function iStableMaster:OpenSquadIconSelector(icon,index) end -- Loads a frame with selectible icons and highlights the current icon
function iStableMaster:CloseSquadIconSelector(icon,index) end -- Closes the Frame with selectible icons, and sets the indexed icon to the queue table
function iStableMaster:CreateNewSquadAndOpenManager() -- CreateSquad > Open Squad manager > Init Changes table using existing values function
	iStableMaster:SaveActivePetsAsSquad();
	iStableMaster:InitExistingValuesToSquadQueueChanges(iStableMaster.LATEST_ADDED_BEASTSQUAD);
	BeastSquadsManagerFrame.caller = iStableMasterStableDB["SavedSquads"]["Squad"..iStableMaster.LATEST_ADDED_BEASTSQUAD];
	BeastSquadsManagerFrame.caller.index = iStableMaster.LATEST_ADDED_BEASTSQUAD;
	iStableMaster:EditSquad(iStableMaster.LATEST_ADDED_BEASTSQUAD);
end 
function iStableMaster:ClearSquadChangesQueue() -- Clear Queue and handle save in apply Queued Changes function
	SquadChangesQueueTable = nil;
	_G["BSMgrInnerFrameSave And Close"]:Disable();
end
function iStableMaster:ApplyQueuedSquadChanges(index) -- Set Squad Values to Queued Values > Clear Queue > Close SquadManager
	for i = 1, 6 do
		iStableMasterStableDB["SavedSquads"]["Squad"..index]["Pet"..i] = SquadChangesQueueTable["Pet"..i];
	end
	iStableMasterStableDB["SavedSquads"]["Squad"..index].Name = SquadChangesQueueTable.Name;
	iStableMasterStableDB["SavedSquads"]["Squad"..index].Icon = SquadChangesQueueTable.Icon;
	iStableMaster:ClearSquadChangesQueue();
	HideUIPanel(BeastSquadsManagerFrame);
end
function iStableMaster:InitExistingValuesToSquadQueueChanges(index) -- Initialise Squad Queue Changes Table by setting it to values for the indexed squad.
	SquadChangesQueueTable = {Pet1 = {},Pet2 = {},Pet3 = {},Pet4 = {},Pet5 = {},Pet6 = {}, Name = "name", Icon = "string"};
	for i = 1, 6 do 
		SquadChangesQueueTable["Pet"..i] = iStableMasterStableDB["SavedSquads"]["Squad"..index]["Pet"..i];
	end
	SquadChangesQueueTable.Name = (iStableMasterStableDB["SavedSquads"]["Squad"..index].Name or "Unnamed Squad");
	SquadChangesQueueTable.Icon = (iStableMasterStableDB["SavedSquads"]["Squad"..index].Icon or "Ability_Hunter_Pet_Assist");
	--iStableMaster:Print("DEBUG:: "..SquadChangesQueueTable.Name);
	_G["BSMgrInnerFrameSave And Close"]:Enable();
end 
function iStableMaster:EditSquad(index) -- Open SquadManager > Init Changes table using existing values function
	--BeastSquadsManagerFrame.caller = iStableMasterStableDB["SavedSquads"]["Squad"..index];
	--BeastSquadsManagerFrame.caller.index = i;
	if(BeastSquadsManagerFrame:IsShown()) then
		if(SquadChangesQueueTable == nil) then 
			HideUIPanel(BeastSquadsManagerFrame);
			return;
		elseif (SquadChangesQueueTable.Name == BeastSquadsManagerFrame.caller.Name) then
			-- handle clicking the same squad as is open
			return;
		else
			-- handle swapping to another squad than the open one
			-- Default should be to discard changes.
			iStableMaster:ClearSquadChangesQueue()
			iStableMaster:InitExistingValuesToSquadQueueChanges(index);
			HideUIPanel(BeastSquadsManagerFrame);
		end
	else
		--print("Debug this");
		iStableMaster:InitExistingValuesToSquadQueueChanges(index);
	end
	ShowUIPanel(BeastSquadsManagerFrame);
end 
function iStableMaster:ManagerDisbandSquad(index) -- Clear Queue and disable Save Changes > iStableMaster:DeleteSquad(index) > iStableMaster:UpdateSquadList > Close SquadManager
	--- crude should add a confirm pop up window to this before executing the below
	
	iStableMaster:ClearSquadChangesQueue();
	iStableMaster:DeleteSquad(index);
	HideUIPanel(BeastSquadsManagerFrame);
	iStableMaster:UpdateSquadList();
	--StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..index]:Hide();
	local squadslimit = iStableMaster:StringKeyTableLength(iStableMasterStableDB["SavedSquads"],"Squad");
	StablesCollectionPresetsFrameScrollFrame.scrollChild["SquadButton"..squadslimit+1]:Hide();
end 
function iStableMaster:RevertIconChangeToCurrentIcon(index) -- Sets the Queued Icon Value to the Current Icon


end 
function iStableMaster:ClearAndCloseSquadManager() 

	iStableMaster:ClearSquadChangesQueue();
	HideUIPanel(BeastSquadsManagerFrame);

end
function iStableMaster:UpdateBeastSquadManagerVisibleState(caller) -- Updates wether or not highlights should be visible and if revert buttons should be visible.
	--iStableMaster:Print("DEBUG:: "..(tostring(caller) or "nil"));
	local index = caller.index;
	--iStableMaster:Print("DEBUG:: Updating BeastSquadManager Visible State");
	if(SquadChangesQueueTable == nil) then 
		return;


	else
		iStableMaster:ActiveChangesIndicatorsOnOff(SquadChangesQueueTable.Name,iStableMasterStableDB["SavedSquads"]["Squad"..index].Name,UndoNameChange);
		iStableMaster:ActiveChangesIndicatorsOnOff(SquadChangesQueueTable.Icon,iStableMasterStableDB["SavedSquads"]["Squad"..index].Icon,UndoIconChange);
		for i = 1, 6 do
			iStableMaster:ActiveChangesIndicatorsOnOff(SquadChangesQueueTable["Pet"..i],iStableMasterStableDB["SavedSquads"]["Squad"..index]["Pet"..i],_G["SquadPetFrame"..i.."ChangeMarkerFrameTexture"]);
			iStableMaster:ActiveChangesIndicatorsOnOff(SquadChangesQueueTable["Pet"..i],iStableMasterStableDB["SavedSquads"]["Squad"..index]["Pet"..i],_G["SquadPetFrame"..i.."ChangeMarkerFrameUndoButton"]);
		end

	end
end
--- hooked from the BeastSquadsManagerFrame.Lua file

----------------------------------------------------
---			BeastSquads Manager End              ---
----------------------------------------------------

----------------------------------------------------
---				BeastSquads Backend  	         ---
----------------------------------------------------
function iStableMaster:UpdateSquadInfoOnStableUpdateEvent() 
	for i = 1, 205 do
		local l_icon, l_name, l_level, l_family, l_talent = GetStablePetInfo(i);
		if l_talent == nil then 
			l_talent = "N/A";
		end
		if l_name == nil then 
			l_name = "N/A";
		end
		for j = 1, 205 do
			local j_icon = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["icon"];
			local j_name = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["name"];
			local j_level = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["level"];
			local j_family = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"];
			local j_talent = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["talent"];
			--local j_icon, j_name, j_level, j_family, j_talent = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["Slot"]
			if(j_name == l_name and j_talent == l_talent and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["Slot"] == i) then
				iStableMaster:UpdateSquadCurrentSlots(i,j);
				iStableMaster:Print(i..", name: "..l_name..","..j..","..j_name);
				break;
			end
			break;
		end
	end
end -- Probably keep this, but make it dynamic during the rework.
function iStableMaster:DeleteSquad(index)
	iStableMasterStableDB["SavedSquads"]["Squad"..index] = nil;
	squadslimit = iStableMaster:StringKeyTableLength(iStableMasterStableDB["SavedSquads"],"Squad");
	for i = index, squadslimit do -- because we just removed 1 we dont care about the index i+1 because we will only ever get to length-1 from before.
		iStableMasterStableDB["SavedSquads"]["Squad"..i] = iStableMasterStableDB["SavedSquads"]["Squad"..i+1];
	end
	iStableMasterStableDB["SavedSquads"]["Squad"..squadslimit+1] = nil;
end
function iStableMaster:SaveActivePetsAsSquad() 
	if(iStableMasterStableDB["SavedSquads"] == nil) then
		iStableMasterStableDB["SavedSquads"] = {};
	end
	local indexToSaveAt = 1;
	for i = 1, iStableMaster:StringKeyTableLength(iStableMasterStableDB["SavedSquads"],"Squad")+1 do
		if(iStableMasterStableDB["SavedSquads"]["Squad"..i] == nil) then
			iStableMasterStableDB["SavedSquads"]["Squad"..i] = {};
			indexToSaveAt = i;
			break;
		end
	end
	local listToPrint = "";
	for i = 1,6 do
		if( i < 6 )then
			if(iStableMasterStableDB["PetInfo"]["ActiveSlot"..i]["name"] ~= "N/A") then
				iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt]["Pet"..i] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..i];
				iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt]["Pet"..i]["CurrentSlot"] = i;
				iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt]["Pet"..i]["Slot"] = i;
				if(i == 1) then
					listToPrint = "Squad Saved: "..iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt]["Pet"..i]["name"];
				else
					listToPrint = listToPrint..", "..iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt]["Pet"..i]["name"];
				end
			else
				if(i == 1) then
					listToPrint = "Squad Saved: EmptySlot"..i;
				else
					listToPrint = listToPrint..", EmptySlot"..i;
				end
			end
		else
			if(iStableMasterStableDB["PetInfo"]["StableSlot"..1]["name"] ~= "N/A") then
				iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt]["Pet"..i] = iStableMasterStableDB["PetInfo"]["StableSlot1"];
				iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt]["Pet"..i]["CurrentSlot"] = i;
				iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt]["Pet"..i]["Slot"] = i;
				if(i == 1) then
					listToPrint = "Squad Saved: "..iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt]["Pet"..i]["name"];
				else
					listToPrint = listToPrint..", "..iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt]["Pet"..i]["name"];
				end
			else
				if(i == 1) then
					listToPrint = "Squad Saved: EmptySlot"..i;
				else
					listToPrint = listToPrint..", EmptySlot"..i;
				end
			end
		end
	end
	iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt].Name = "Squad"..indexToSaveAt;
	iStableMasterStableDB["SavedSquads"]["Squad"..indexToSaveAt].Icon = "Ability_Hunter_Pet_Assist" -- Interface\ICONS\..
	iStableMaster.LATEST_ADDED_BEASTSQUAD = indexToSaveAt;
	iStableMaster:PopulateSquadScrollFrame();
	iStableMaster:Print(listToPrint);
	iStableMaster:SelectedPresetUpdate();
end
iStableMaster.ApplyingSquad = false; -- used by ApllySquad to avoid sibling runs.
function iStableMaster:ApplySquad(squadindex)
	if(iStableMaster.ApplyingSquad)then
	return;
	end
	
	-- failsafe incase anyone plays with the functions:
	if(squadindex > iStableMaster:StringKeyTableLength(iStableMasterStableDB["SavedSquads"],"Squad")) then 
		return;
	end
	iStableMaster.ApplyingSquad = true;
	-- actual function
	iStableMaster.temp = {};
	iStableMaster.temp2 = 0;
	

	--for i = 1, 6 do
	--	if( iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i] ~= nil ) then
	--		if(iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["Slot"] ~= iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["CurrentSlot"] and iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["name"] ~= "N/A") then
				
	--			--print(iStableMaster.temp[#iStableMaster.temp].cur)
	--		end
	--	end
	--end

	for i = 1, 6 do
	--for i = 1, iStableMaster:StringKeyTableLengthI(iStableMaster.temp) do		
		if( iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i] ~= nil ) then
			if(iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["Slot"] ~= iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["CurrentSlot"] and iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["name"] ~= "N/A") then				
			iStableMaster:FreezeLayoutFX(true); -- false turn FX off true turn FX on
				
				C_Timer.After(i,function() -- What if instead of a timer, i make a callback function that sets a global to false for SetPet() Completion, then instead add a do while ( global == true) to "sleep" the execution.
					if(IsAtStableMaster()) then
					iStableMaster.temp2 = i;
					iStableMaster.temp[#iStableMaster.temp+1] = {cur = iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["CurrentSlot"], nex = iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["Slot"]};

					local targetSlot = iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["Slot"];
					SetPetSlot(iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["CurrentSlot"], iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["Slot"]);
					--SetPetSlot(iStableMaster.temp[i].cur,iStableMaster.temp[i].nex);
					if(iStableMaster.debugEnabled.presets_Swaps) then
						print(iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["CurrentSlot"].."to slot"..iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["Slot"]);
						--print(iStableMaster.temp[i].cur,iStableMaster.temp[i].nex);
					end
					
					--iStableMaster:UpdateSquadCurrentSlots(iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["CurrentSlot"],iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["Slot"],(targetSlot == iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["CurrentSlot"]));
					--iStableMaster:UpdateSquadCurrentSlots(iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..iStableMaster.temp2]["CurrentSlot"],iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..iStableMaster.temp2]["Slot"],(targetSlot == iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..iStableMaster.temp2]["CurrentSlot"]));
					--iStableMaster:UpdateSquadCurrentSlots(iStableMaster.temp[i].cur,iStableMaster.temp[i].nex);
					end
				end);
				
				-- THIS IDEA DOES NOT WORK
				--local targetSlot = iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["Slot"];
				--	SetPetSlot(iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["CurrentSlot"], iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["Slot"]);
				--while(not iStableMaster.SetPetSlotCompleted) do end
				--iStableMaster.SetPetSlotCompleted = false;
				--------------------

				---i need to add a safety for exotic pets here when not specced as beast mastery - This has been done, but from within reliant functions
				--if(not GlobalSpecialization == "Beast Mastery") then -- i think this causes an issue to have outside UpdateSquadeCurrentSlots as it prevents it from being called properly
				----and exits the function. Break might also fix the issue but since its checked in the method to be called later it shouldnt be needed.
				--if(tContains(iStableMaster.ExoticFamilies,iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["family"])) then
				--return;
				--end					 
				--end												
				--iStableMasterStableDB["SavedSquads"]["Squad"..squadindex]["Pet"..i]["CurrentSlot"] = i; -- updates own current slot to be the target slot
				
				
			end
		end
			
	end
	-- should fire some kind of event here. a function that i can post-hook on to.
	C_Timer.After(7,function()
			for i = 1, iStableMaster:StringKeyTableLengthI(iStableMaster.temp) do		
				iStableMaster:UpdateFavStatus(iStableMaster.temp[i].cur,iStableMaster.temp[i].nex, true);
				iStableMaster:UpdateSquadCurrentSlots(iStableMaster.temp[i].cur,iStableMaster.temp[i].nex, true);

			end
	iStableMaster:FreezeLayoutFX(false); -- false turn FX off true turn FX on

	--iStableMaster:UpdateScrollListMainCall();
	iStableMaster:SelectedPresetUpdate()
	iStableMaster.ApplyingSquad = false;
	--assert(nil,"Fav Status swaps and is bugged, also read the comments in the code")
	end);
end
function iStableMaster:WipeAllSquads()
	local squadslimit = iStableMaster:StringKeyTableLength(iStableMasterStableDB["SavedSquads"],"Squad");
	for i = 1, squadslimit do
		iStableMaster:DeleteSquad(i)
	end
end
function iStableMaster:UpdateSquadCurrentSlots(slot,newSlot,...) 
	local completedSwapLingerCheck = ... or false;
	if(not IsAtStableMaster() and not completedSwapLingerCheck) then
		return; 
	end
	
	if( iStableMasterStableDB["SavedSquads"] == nil ) then
		iStableMaster.temp = {};
		return;
	end
	if(newSlot < 6) then
		if(not IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][newSlot])) then
			return;
		end
		if(not GlobalSpecialization == "Beast Mastery") then -- prevents false tracking when drag and drop eventually fails on exotic creatues while not specced as Beast Mastery -- adding failsafe for locked or failed move
			if(iStableMaster:IsStabledPetExotic(newSlot) or iStableMaster:IsStabledPetExotic(slot)) then
				return;
			end
		end
	end
	local squadslimit = iStableMaster:StringKeyTableLength(iStableMasterStableDB["SavedSquads"],"Squad");
	for i = 1, squadslimit do																
		for j = 1, 6 do
			if(iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j] ~= nil) then		
				if(iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j]["CurrentSlot"] == newSlot) then -- takes target being moved's currentSlot's value and set the target at destination's new CurrentSlot
					iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j]["CurrentSlot"] = slot;
				elseif(iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j]["CurrentSlot"] == slot) then -- updates own current slot to be the target slot
					iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j]["CurrentSlot"] = newSlot;
				end
			end
		end
	end
end -- Called from other bits that change the premise of a squads data
----------------------------------------------------
---			BeastSquads Backend End              ---
----------------------------------------------------

----------------------------------------------------
---				Selector functions       	     ---
----------------------------------------------------
function iStableMaster:PetCardSelect(caller)
	iStableMaster.currentlySelectedPet = caller;
	iStableMaster:SetPetModelView();
end
function iStableMaster:SetSelectedHighlight() 
	local namelengthDefault = 14;
	local firstIndex=1;
	if(not iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"]) then
		firstIndex = GlobalActiveSlotLoopValue + 1;
	end
	if(iStableMaster.ScrollFrameArrElem["ScrollElement"..firstIndex] ~= nil) then
		local fname = iStableMaster.ScrollFrameArrElem["ScrollElement"..firstIndex]:GetName();
	else
		local fname = ActivePetSlotsCards["ActiveSlot"..firstIndex]["Socket"..firstIndex]:GetName();
		namelengthDefault = 17;
	end
	if(iStableMaster.currentlySelectedPet ~= nil) then
		fname = iStableMaster.currentlySelectedPet:GetName();
		if(string.find(fname,"ActiveSlotSocket") ~= nil) then
			local startOfSocket, placeToSplit = string.find(fname,"ActiveSlotSocket");
			--print(placeToSplit + 1);
			namelengthDefault = placeToSplit + 1;
		elseif(string.find(fname,"ScrollElementChild") ~= nil) then
			local startOfSocket, placeToSplit = string.find(fname,"ScrollElementChild");

			namelengthDefault = placeToSplit + 1;
		else
			-- Do nothing
		end
	end

	if(iStableMaster.ScrollFrameArrElem["ScrollElement"..firstIndex] ~= nil) then
		local indexNumber = 1;
		if(fname ~= nil) then
			indexNumber = tonumber(string.sub(fname, namelengthDefault));
		end
		local petSlot = nil;
		if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber] ~= nil)then
			petSlot = tonumber(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber]["PetInfo"]["Slot"]);
		end
		local icon = nil;
		local name = nil;
		if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber] ~= nil)then
			--icon = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber]["PetInfo"]["icon"];
			--name = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber]["PetInfo"]["name"];
			if(currentlyActiveHighlight ~= nil) then
				if(currentlyActiveHighlight < GlobalActiveSlotLoopValue + 1) then
					ActivePetSlotsCards["ActiveSlot"..currentlyActiveHighlight]["Card"..currentlyActiveHighlight]["Selected"]:SetAlpha(0);
				else
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..currentlyActiveHighlight]["PetSelectorTextureSelected"]:SetAlpha(0);
				end
			end
			if(indexNumber < GlobalActiveSlotLoopValue + 1) then
				ActivePetSlotsCards["ActiveSlot"..indexNumber]["Card"..indexNumber]["Selected"]:SetAlpha(1);
			else
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber]["PetSelectorTextureSelected"]:SetAlpha(1);
			end
			currentlyActiveHighlight = indexNumber;
		end
		if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber] == nil)then
			--icon = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber]["PetInfo"]["icon"];
			--name = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber]["PetInfo"]["name"];
			if(currentlyActiveHighlight ~= nil) then
				if(currentlyActiveHighlight < GlobalActiveSlotLoopValue + 1) then
					ActivePetSlotsCards["ActiveSlot"..currentlyActiveHighlight]["Card"..currentlyActiveHighlight]["Selected"]:SetAlpha(0);
				else
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..currentlyActiveHighlight]["PetSelectorTextureSelected"]:SetAlpha(0);
				end
			end
			if(indexNumber < GlobalActiveSlotLoopValue + 1) then
				ActivePetSlotsCards["ActiveSlot"..indexNumber]["Card"..indexNumber]["Selected"]:SetAlpha(1);
			else
				iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber]["PetSelectorTextureSelected"]:SetAlpha(1);
			end
			currentlyActiveHighlight = indexNumber;
		end
	else
		-- DO NOTHING
	end
end -- Acts on both ActiveCards and PetScrollFrame PetTiles
function iStableMaster:SelectedPresetUpdate()
	if iStableMasterStableDB["SavedSquads"] == nil then 
		return;
	end
	local squadslimit = iStableMaster:StringKeyTableLength(iStableMasterStableDB["SavedSquads"],"Squad");
	local isActive = false;
	for i = 1, squadslimit do
		isActive = false;
		for j = 1, 6 do
			if(iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j] ~= nil) then
				if(j < 6) then 
					isActive = (iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j]["Slot"] == iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j]["CurrentSlot"]);
					if(iStableMaster.debugEnabled[presets_Swap]) then
						iStableMaster:Print(isActive);
					end
				else 
					isActive = (iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j]["Slot"] == iStableMasterStableDB["SavedSquads"]["Squad"..i]["Pet"..j]["CurrentSlot"]);
					if(iStableMaster.debugEnabled[presets_Swap]) then
						iStableMaster:Print(isActive);
					end
				end 
				if(not isActive)then
					break;
				end
			end
		end
		if(isActive) then
			_G["Squad"..i.."selectedOverlayBL"]:Show();
			_G["Squad"..i.."selectedOverlayBR"]:Show();
			_G["Squad"..i.."selectedOverlayTL"]:Show();
			_G["Squad"..i.."selectedOverlayTR"]:Show();
			_G["Squad"..i.."selectedOverlayR"]:Show();
			_G["Squad"..i.."selectedOverlayL"]:Show();
			_G["Squad"..i.."selectedOverlayH"]:Show();
		else
			_G["Squad"..i.."selectedOverlayBL"]:Hide();
			_G["Squad"..i.."selectedOverlayBR"]:Hide();
			_G["Squad"..i.."selectedOverlayTL"]:Hide();
			_G["Squad"..i.."selectedOverlayTR"]:Hide();
			_G["Squad"..i.."selectedOverlayR"]:Hide();
			_G["Squad"..i.."selectedOverlayL"]:Hide();
			_G["Squad"..i.."selectedOverlayH"]:Hide();
		end
	end
end -- Acts as Highlight/Pressed Status of BeastSquad ScrollFrame Squad Tiles
----------------------------------------------------
---			  Selector functions End             ---
----------------------------------------------------
----------------------------------------------------
---				3D MODEL VIEWER FRAME			 ---
----------------------------------------------------
function iStableMaster:CreateDataField3dModelBackDrops() 
	if(SelectedPetDataFrameHeader ~= nil) then 
		return;
	end
	---[[ BACKGROUND SETUP BEGINS HERE  ]]
	do
		local Backdrop = SelectedPetDataFrameHeader;
		if(SelectedPetDataFrameHeader == nil) then 
			Backdrop = CreateFrame("Frame", "SelectedPetDataFrameHeader", CollectionsPetStableModel, BackdropTemplateMixin and "BackdropTemplate");
			--print(true);
		end
		Backdrop:SetBackdrop({bgFile=nil,
			edgeFile="", tile=false,tileSize=CollectionsPetStableModel:GetWidth()-16,edgeSize=32,
			insets= {left=8,right=8,top=8,bottom=8}});
		Backdrop:SetSize(CollectionsPetStableModel:GetWidth()-16,86);
		Backdrop:SetPoint("TOPLEFT", CollectionsPetStableModel, "TOPLEFT", 8, -8);
		if( Backdrop.Texture == nil )then 
			Backdrop.Texture = Backdrop:CreateTexture(nil,"ARTWORK");
		end
		Backdrop.Texture:SetTexture(nil);
		--Backdrop.Texture:SetAlpha(1);
		Backdrop.Texture:SetTexture("Interface\\AddOns\\iStableMaster\\HeaderShadeAndGlow.blp");
		Backdrop.Texture:SetSize(Backdrop:GetSize());
		--Backdrop.Texture:SetTexCoord(0.16,0.9,0.45,0.50);
		Backdrop.Texture:SetTexCoord(0.16,0.8,0.45,0.50);
		Backdrop.Texture:SetPoint("CENTER",Backdrop,"CENTER");
		--Backdrop.Texture:SetAllPoints();
		--Backdrop.Texture:SetColorTexture(1,1,1,0.2);
		Backdrop.Texture:SetVertexColor(5,0,5,0.8);
		local BackdropBot = SelectedPetDataFrameFooter;
		if(SelectedPetDataFrameFooter == nil) then 
			BackdropBot = CreateFrame("Frame", "SelectedPetDataFrameFooter", CollectionsPetStableModel, BackdropTemplateMixin and "BackdropTemplate");
			--print(true);
		end
		BackdropBot:SetBackdrop({bgFile=nil,
			edgeFile="", tile=false,tileSize=CollectionsPetStableModel:GetWidth()-16,edgeSize=32,
			insets= {left=8,right=8,top=8,bottom=8}});
		BackdropBot:SetSize(CollectionsPetStableModel:GetWidth()-16,150);
		BackdropBot:SetPoint("BOTTOMLEFT", CollectionsPetStableModel, "BOTTOMLEFT", 8, 8);
		if( BackdropBot.Texture == nil )then 
			BackdropBot.Texture = BackdropBot:CreateTexture(nil,"ARTWORK");
		end
		BackdropBot.Texture:SetTexture(nil);
		--BackdropBot.Texture:SetAlpha(1);
		BackdropBot.Texture:SetTexture("Interface\\AddOns\\iStableMaster\\HeaderShadeAndGlow.blp");
		BackdropBot.Texture:SetSize(BackdropBot:GetSize());
		--BackdropBot.Texture:SetTexCoord(0.16,0.9,0.45,0.50);
		BackdropBot.Texture:SetTexCoord(0.16,0.8,0.45,0.50);
		BackdropBot.Texture:SetVertexColor(5,0,5,0.8);
		BackdropBot.Texture:SetPoint("CENTER",BackdropBot,"CENTER");
		--BackdropBot.Texture:SetAllPoints();
		--BackdropBot.Texture:SetColorTexture(1,1,1,0.2);
	end
	---[[ BACKGROUND SETUP COMPLETED  ]]
	
	---[[NAME AND ICON CREATION FOR HEADER BEGINS HERE ]]
	do
		if(SelectedPetDataFrameHeader.icon == nil) then
			local iconSize = 64;
			SelectedPetDataFrameHeader.icon = SelectedPetDataFrameHeader:CreateTexture(nil,"OVERLAY");
			SelectedPetDataFrameHeader.icon:SetSize(iconSize,iconSize);
			SelectedPetDataFrameHeader.icon:SetPoint("LEFT",SelectedPetDataFrameHeader,"LEFT",16,0);
			SelectedPetDataFrameHeader.icon.border = SelectedPetDataFrameHeader:CreateTexture(nil, "OVERLAY");
			--SelectedPetDataFrameHeader.icon.border:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic Border 3-FAT.blp");
			SelectedPetDataFrameHeader.icon.border:SetAtlas("ui-hud-actionbar-IconFrame");
			SelectedPetDataFrameHeader.icon.border:SetDrawLayer("OVERLAY",7);
			SelectedPetDataFrameHeader.icon.border:SetSize(iconSize,iconSize);
			SelectedPetDataFrameHeader.icon.border:SetPoint(SelectedPetDataFrameHeader.icon:GetPoint(1));
			SelectedPetDataFrameHeader.icon.maskFrame = CreateFrame("Frame", "SelectedPetDataFrameHeaderFamilyIconMaskFrame", SelectedPetDataFrameHeader, BackdropTemplateMixin and "BackdropTemplate");
			SelectedPetDataFrameHeader.icon.maskFrame:SetPoint("CENTER",SelectedPetDataFrameHeader.icon,"CENTER",0,0);
			SelectedPetDataFrameHeader.icon.maskFrame:SetSize(iconSize,iconSize);
			SelectedPetDataFrameHeader.icon.mask = SelectedPetDataFrameHeader.icon.maskFrame:CreateMaskTexture()
			SelectedPetDataFrameHeader.icon.mask:SetPoint("CENTER",SelectedPetDataFrameHeader.icon.maskFrame,"CENTER",0,0);
			SelectedPetDataFrameHeader.icon.mask:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
			SelectedPetDataFrameHeader.icon.mask:SetSize(iconSize+24,iconSize+24);
			SelectedPetDataFrameHeader.icon:AddMaskTexture(SelectedPetDataFrameHeader.icon.mask)
			SelectedPetDataFrameHeader.iconInteractiveregion = CreateFrame("Frame", "SelectedPetDataFrameHeaderFamilyIconRegion", SelectedPetDataFrameHeader);
			SelectedPetDataFrameHeader.iconInteractiveregion:SetPoint(SelectedPetDataFrameHeader.icon:GetPoint(1));
			SelectedPetDataFrameHeader.iconInteractiveregion:SetSize(iconSize,iconSize);
			SelectedPetDataFrameHeader.icon.mask:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
		end
		if(SelectedPetDataFrameHeader.sicon == nil) then
			local iconSize = 64;
			SelectedPetDataFrameHeader.sicon = SelectedPetDataFrameHeader:CreateTexture(nil,"OVERLAY");
			SelectedPetDataFrameHeader.sicon:SetSize(iconSize,iconSize);
			SelectedPetDataFrameHeader.sicon:SetPoint("RIGHT",SelectedPetDataFrameHeader,"RIGHT",-16,0);
			SelectedPetDataFrameHeader.sicon.border = SelectedPetDataFrameHeader:CreateTexture(nil, "OVERLAY");
			--	SelectedPetDataFrameHeader.sicon.border:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic Border 3-FAT.blp");
			SelectedPetDataFrameHeader.sicon.border:SetAtlas("ui-hud-actionbar-IconFrame");
			SelectedPetDataFrameHeader.sicon.border:SetDrawLayer("OVERLAY",7);
			SelectedPetDataFrameHeader.sicon.border:SetSize(iconSize,iconSize);
			SelectedPetDataFrameHeader.sicon.border:SetPoint(SelectedPetDataFrameHeader.sicon:GetPoint(1));
			SelectedPetDataFrameHeader.sicon.maskFrame = CreateFrame("Frame", "SelectedPetDataFrameHeaderSpecializationIconMaskFrame", SelectedPetDataFrameHeader, BackdropTemplateMixin and "BackdropTemplate");
			SelectedPetDataFrameHeader.sicon.maskFrame:SetPoint("CENTER",SelectedPetDataFrameHeader.sicon,"CENTER",0,0);
			SelectedPetDataFrameHeader.sicon.maskFrame:SetSize(iconSize,iconSize);
			SelectedPetDataFrameHeader.sicon.mask = SelectedPetDataFrameHeader.sicon.maskFrame:CreateMaskTexture()
			SelectedPetDataFrameHeader.sicon.mask:SetPoint("CENTER",SelectedPetDataFrameHeader.sicon.maskFrame,"CENTER",0,0);
			SelectedPetDataFrameHeader.sicon.mask:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
			SelectedPetDataFrameHeader.sicon.mask:SetSize(iconSize+24,iconSize+24);
			SelectedPetDataFrameHeader.sicon:AddMaskTexture(SelectedPetDataFrameHeader.sicon.mask)
			SelectedPetDataFrameHeader.siconInteractiveregion = CreateFrame("Frame", "SelectedPetDataFrameHeaderFamilyIconRegion", SelectedPetDataFrameHeader);
			SelectedPetDataFrameHeader.siconInteractiveregion:SetPoint(SelectedPetDataFrameHeader.sicon:GetPoint(1));
			SelectedPetDataFrameHeader.siconInteractiveregion:SetSize(iconSize,iconSize);
			SelectedPetDataFrameHeader.sicon.mask:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask");
		end
		if(SelectedPetDataFrameHeader.name == nil) then
			SelectedPetDataFrameHeader.name = SelectedPetDataFrameHeader:CreateFontString(nil,"OVERLAY","GameFontNormalLarge");
			SelectedPetDataFrameHeader.name:SetPoint("LEFT",SelectedPetDataFrameHeader.icon,"RIGHT",8,16);
			SelectedPetDataFrameHeader.name:SetSize(SelectedPetDataFrameHeader:GetWidth()-(SelectedPetDataFrameHeader.icon:GetWidth()+SelectedPetDataFrameHeader.sicon:GetWidth())-48,32);
			--print(SelectedPetDataFrameHeader:GetWidth()-SelectedPetDataFrameHeader.icon:GetWidth()-86);
			SelectedPetDataFrameHeader.name:SetFont("Fonts\FRIZQT__.TTF",86,"MONOCHROME");
			SelectedPetDataFrameHeader.name:SetJustifyH("CENTER");
			--SelectedPetDataFrameHeader.name:SetTextColor(iStableMaster:GetDBColour("Default","Blue"));
		end
		if(SelectedPetDataFrameHeader.fname == nil) then
			SelectedPetDataFrameHeader.fname = SelectedPetDataFrameHeader:CreateFontString(nil,"OVERLAY","GameFontNormalLarge");
			SelectedPetDataFrameHeader.fname:SetPoint("LEFT",SelectedPetDataFrameHeader.icon,"RIGHT",8,-16);
			SelectedPetDataFrameHeader.fname:SetSize(SelectedPetDataFrameHeader:GetWidth()-(SelectedPetDataFrameHeader.icon:GetWidth()+SelectedPetDataFrameHeader.sicon:GetWidth())-48,32);
			--print(SelectedPetDataFrameHeader:GetWidth()-SelectedPetDataFrameHeader.icon:GetWidth()-86);
			SelectedPetDataFrameHeader.fname:SetFont("Fonts\FRIZQT__.TTF",86,"MONOCHROME");
			SelectedPetDataFrameHeader.fname:SetJustifyH("CENTER");
			--SelectedPetDataFrameHeader.fname:SetTextColor(iStableMaster:GetDBColour("Default","Blue"));
		end
	end
	---[[NAME AND ICON CREATION FOR HEADER COMPLETED ]]
	---[[FOOTER INFO: FAMILY ABILITIES, SPEC ABILITIES AND DIET BEGINS HERE]]
	do
		-- FIRST we create 3 frames for region anchors for the 3 sub sections.
		local  Footer = SelectedPetDataFrameFooter;
		if(Footer.LeftFrame == nil) then 
			Footer.LeftFrame = CreateFrame("Frame","SelectedPetDataFrameFooterLeftFrame", SelectedPetDataFrameFooter, BackdropTemplateMixin and "BackdropTemplate");
		end	
		Footer.LeftFrame:SetBackdrop({bgFile=nil,
			edgeFile="", tile=false,tileSize=CollectionsPetStableModel:GetWidth()-16,edgeSize=32,
			insets= {left=8,right=8,top=8,bottom=8}});
		Footer.LeftFrame:SetSize((CollectionsPetStableModel:GetWidth()-16)/3-16,Footer:GetHeight()-16);
		Footer.LeftFrame:SetPoint("TOPLEFT", SelectedPetDataFrameFooter, "TOPLEFT", 8, -8);
		if(Footer.CenterFrame == nil) then 
			Footer.CenterFrame = CreateFrame("Frame","SelectedPetDataFrameFooterCenterFrame", SelectedPetDataFrameFooter, BackdropTemplateMixin and "BackdropTemplate");
		end	
		Footer.CenterFrame:SetBackdrop({bgFile=nil,
			edgeFile="", tile=false,tileSize=CollectionsPetStableModel:GetWidth()-16,edgeSize=32,
			insets= {left=8,right=8,top=8,bottom=8}});
		Footer.CenterFrame:SetSize((CollectionsPetStableModel:GetWidth()-16)/3-16,Footer:GetHeight()-16);
		Footer.CenterFrame:SetPoint("CENTER", SelectedPetDataFrameFooter,"CENTER", 0, 0);
		if(Footer.RightFrame == nil) then 
			Footer.RightFrame = CreateFrame("Frame","SelectedPetDataFrameFooterRightFrame", SelectedPetDataFrameFooter, BackdropTemplateMixin and "BackdropTemplate");
		end	
		Footer.RightFrame:SetBackdrop({bgFile=nil,
			edgeFile="", tile=false,tileSize=CollectionsPetStableModel:GetWidth()-16,edgeSize=32,
			insets= {left=8,right=8,top=8,bottom=8}});
		Footer.RightFrame:SetSize((CollectionsPetStableModel:GetWidth()-16)/3-16,Footer:GetHeight()-16);
		Footer.RightFrame:SetPoint("TOPRIGHT", SelectedPetDataFrameFooter, "TOPRIGHT", -8, -8);
		-- SECONDLY we fill out each frame we just created with eventually based on saved variable values, but for now just 1 layout: 2x2, 2x1, 3x3
		Footer.LeftFrame.Abilities = {};
		Footer.CenterFrame.Abilities = {};
		Footer.RightFrame.Diets = {};
		Footer.RightFrame.DietFrames = {};
		Footer.LeftFrame.AbilitiesFrames = {};
		Footer.CenterFrame.AbilitiesFrames = {};
		for i = 1,4,1 do
			if(Footer.LeftFrame.Abilities[i] == nil) then
				Footer.LeftFrame.Abilities[i] = Footer.LeftFrame:CreateTexture(nil,"OVERLAY");
			end
			if(Footer.LeftFrame.AbilitiesFrames[i] == nil) then 
				Footer.LeftFrame.AbilitiesFrames[i] = CreateFrame("Frame","SelectedPetDataFrameFooterLeftFrameAbilityFrame"..i,SelectedPetDataFrameFooterLeftFrame, BackdropTemplateMixin and "BackdropTemplate");
				Footer.LeftFrame.AbilitiesFrames[i]:SetBackdrop({bgFile=nil,
					edgeFile="", tile=false,tileSize=CollectionsPetStableModel:GetWidth()-16,edgeSize=32,
					insets= {left=8,right=8,top=8,bottom=8}});
				Footer.LeftFrame.AbilitiesFrames[i]:SetSize(48,48);
			end
			Footer.LeftFrame.Abilities[i]:SetSize(48,48);
			--Footer.LeftFrame.Abilities[i]:SetTexture("Interface\\ICONS\\INV_Misc_Food_08");
			if(i==1) then 
				Footer.LeftFrame.Abilities[i]:SetPoint("TOPLEFT",SelectedPetDataFrameFooter.LeftFrame,"TOPLEFT",0,-32);
				Footer.LeftFrame.AbilitiesFrames[i]:SetPoint("TOPLEFT",SelectedPetDataFrameFooter.LeftFrame,"TOPLEFT",0,-32);
			elseif(i==2) then
				Footer.LeftFrame.Abilities[i]:SetPoint("TOPRIGHT",SelectedPetDataFrameFooter.LeftFrame,"TOPRIGHT",0,-32);
				Footer.LeftFrame.AbilitiesFrames[i]:SetPoint("TOPRIGHT",SelectedPetDataFrameFooter.LeftFrame,"TOPRIGHT",0,-32);
			elseif(i==3) then
				Footer.LeftFrame.Abilities[i]:SetPoint("BOTTOMLEFT",SelectedPetDataFrameFooter.LeftFrame,"BOTTOMLEFT",0,4);
				Footer.LeftFrame.AbilitiesFrames[i]:SetPoint("BOTTOMLEFT",SelectedPetDataFrameFooter.LeftFrame,"BOTTOMLEFT",0,4);
			elseif(i==4) then
				Footer.LeftFrame.Abilities[i]:SetPoint("BOTTOMRIGHT",SelectedPetDataFrameFooter.LeftFrame,"BOTTOMRIGHT",0,4);
				Footer.LeftFrame.AbilitiesFrames[i]:SetPoint("BOTTOMRIGHT",SelectedPetDataFrameFooter.LeftFrame,"BOTTOMRIGHT",0,4);
			end
			Footer.LeftFrame.Abilities[i].border = Footer.LeftFrame:CreateTexture(nil, "OVERLAY");
			--Footer.LeftFrame.Abilities[i].border:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic Border 3-FAT.blp");
			Footer.LeftFrame.Abilities[i].border:SetAtlas("ui-hud-actionbar-IconFrame");
			Footer.LeftFrame.Abilities[i].border:SetDrawLayer("OVERLAY",7);
			Footer.LeftFrame.Abilities[i].border:SetSize(48,48);
			Footer.LeftFrame.Abilities[i].border:SetPoint(Footer.LeftFrame.Abilities[i]:GetPoint(1));
		end
		for i = 1,2,1 do
			local iconSize = 48;
			if(Footer.CenterFrame.Abilities[i] == nil) then
				Footer.CenterFrame.Abilities[i] = Footer.CenterFrame:CreateTexture(nil,"OVERLAY");
			end

			if(Footer.CenterFrame.AbilitiesFrames[i] == nil) then 
				Footer.CenterFrame.AbilitiesFrames[i] = CreateFrame("Frame","SelectedPetDataFrameFooterCenterFrameAbilityFrame"..i,SelectedPetDataFrameFooterCenterFrame, BackdropTemplateMixin and "BackdropTemplate");

				Footer.CenterFrame.AbilitiesFrames[i]:SetBackdrop({bgFile=nil,
					edgeFile="", tile=false,tileSize=CollectionsPetStableModel:GetWidth()-16,edgeSize=32,
					insets= {left=8,right=8,top=8,bottom=8}});

				Footer.CenterFrame.AbilitiesFrames[i]:SetSize(iconSize,iconSize);
			end
			Footer.CenterFrame.Abilities[i]:SetSize(iconSize,iconSize);
			Footer.CenterFrame.Abilities[i]:SetTexture("Interface\\ICONS\\INV_Misc_Food_08");
			Footer.CenterFrame.Abilities[i]:SetAlpha(0);
			if(i==1) then 
				Footer.CenterFrame.Abilities[i]:SetPoint("TOPLEFT",SelectedPetDataFrameFooter.CenterFrame,"TOPLEFT",0,-32);
				Footer.CenterFrame.AbilitiesFrames[i]:SetPoint("TOPLEFT",SelectedPetDataFrameFooter.CenterFrame,"TOPLEFT",0,-32);
			elseif(i==2) then
				Footer.CenterFrame.Abilities[i]:SetPoint("TOPRIGHT",SelectedPetDataFrameFooter.CenterFrame,"TOPRIGHT",0,-32);
				Footer.CenterFrame.AbilitiesFrames[i]:SetPoint("TOPRIGHT",SelectedPetDataFrameFooter.CenterFrame,"TOPRIGHT",0,-32);
				--elseif(i==3) then
				--	Footer.CenterFrame.Abilities[i]:SetPoint("BOTTOMLEFT",SelectedPetDataFrameFooter.CenterFrame,"BOTTOMLEFT",16,16);
				--elseif(i==4) then
				--	Footer.CenterFrame.Abilities[i]:SetPoint("BOTTOMRIGHT",SelectedPetDataFrameFooter.CenterFrame,"BOTTOMRIGHT",-16,16);
			end
			Footer.CenterFrame.Abilities[i].border = Footer.CenterFrame:CreateTexture(nil, "OVERLAY");
			--Footer.CenterFrame.Abilities[i].border:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic Border 3-FAT.blp");
			Footer.CenterFrame.Abilities[i].border:SetAtlas("ui-hud-actionbar-IconFrame");				
			Footer.CenterFrame.Abilities[i].border:SetDrawLayer("OVERLAY",7);
			Footer.CenterFrame.Abilities[i].border:SetSize(iconSize,iconSize);
			Footer.CenterFrame.Abilities[i].border:SetPoint(Footer.CenterFrame.Abilities[i]:GetPoint(1));
			Footer.CenterFrame.Abilities[i].iconMask = Footer.CenterFrame.AbilitiesFrames[i]:CreateMaskTexture();
			Footer.CenterFrame.Abilities[i].iconMask:SetPoint("CENTER",Footer.CenterFrame.AbilitiesFrames[i],"CENTER",0,0)
			Footer.CenterFrame.Abilities[i].iconMask:SetSize(iconSize+16,iconSize+16);
			Footer.CenterFrame.Abilities[i].iconMask:SetTexture("Interface/CHARACTERFRAME/TempPortraitAlphaMask", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
			Footer.CenterFrame.Abilities[i]:AddMaskTexture(Footer.CenterFrame.Abilities[i].iconMask);
			Footer.CenterFrame.Abilities[i].iconMask:SetAtlas("UI-HUD-ActionBar-IconFrame-Mask")
		end
		for i = 1,9,1 do
			if(Footer.RightFrame.Diets[i] == nil) then
				Footer.RightFrame.Diets[i] = Footer.RightFrame:CreateTexture(nil,"OVERLAY");
				Footer.RightFrame.Diets[i].mask = Footer.RightFrame:CreateMaskTexture()
				--Footer.RightFrame.Diets[i].mask:SetAllPoints(Footer.RightFrame.Diets[i].mask)
				Footer.RightFrame.Diets[i]:SetSize(32,32);
			end
			if(Footer.RightFrame.DietFrames[i] == nil) then 
				Footer.RightFrame.DietFrames[i] = CreateFrame("Frame","SelectedPetDataFrameFooterRightFrameDietFrame"..i,SelectedPetDataFrameFooterRightFrame, BackdropTemplateMixin and "BackdropTemplate");
				Footer.RightFrame.DietFrames[i]:SetBackdrop({bgFile=nil,
					edgeFile="", tile=false,tileSize=CollectionsPetStableModel:GetWidth()-16,edgeSize=32,
					insets= {left=8,right=8,top=8,bottom=8}});
				Footer.RightFrame.DietFrames[i]:SetSize(32,32);
			end
			if(i==1) then 
				Footer.RightFrame.Diets[i]:SetPoint("TOPLEFT",SelectedPetDataFrameFooter.RightFrame,"TOPLEFT",0,-32);
				Footer.RightFrame.DietFrames[i]:SetPoint("TOPLEFT",SelectedPetDataFrameFooter.RightFrame,"TOPLEFT",0,-32);
				Footer.RightFrame.DietFrames[i].text = "|cFFFF0000Bread"
				--  Footer.RightFrame.DietFrames[i]:SetScript("OnEnter",function(self)iStableMaster:DietMouseOver(Footer.RightFrame,self.text,false)end);
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnLeave",function()iStableMaster:DietMouseOver(Footer.RightFrame,nil,true)end);
			elseif(i==2) then
				Footer.RightFrame.Diets[i]:SetPoint("TOP",SelectedPetDataFrameFooter.RightFrame,"TOP",0,-32);
				Footer.RightFrame.DietFrames[i]:SetPoint("TOP",SelectedPetDataFrameFooter.RightFrame,"TOP",0,-32);
				Footer.RightFrame.DietFrames[i].text = "|cFFFF0000Cheese"
				--  Footer.RightFrame.DietFrames[i]:HookScript("OnLeave",function()iStableMaster:DietMouseOver(Footer.RightFrame,nil,true)end);
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnEnter",function(self)iStableMaster:DietMouseOver(Footer.RightFrame,self.text,false)end);
			elseif(i==3) then
				Footer.RightFrame.Diets[i]:SetPoint("TOPRIGHT",SelectedPetDataFrameFooter.RightFrame,"TOPRIGHT",0,-32);
				Footer.RightFrame.DietFrames[i]:SetPoint("TOPRIGHT",SelectedPetDataFrameFooter.RightFrame,"TOPRIGHT",0,-32);
				Footer.RightFrame.DietFrames[i].text = "|cFFFF0000Fish"
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnLeave",function()iStableMaster:DietMouseOver(Footer.RightFrame,nil,true)end);
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnEnter",function(self)iStableMaster:DietMouseOver(Footer.RightFrame,self.text,false)end);
			elseif(i==4) then
				Footer.RightFrame.Diets[i]:SetPoint("LEFT",SelectedPetDataFrameFooter.RightFrame,"LEFT",0,-12);
				Footer.RightFrame.DietFrames[i]:SetPoint("LEFT",SelectedPetDataFrameFooter.RightFrame,"LEFT",0,-12);
				Footer.RightFrame.DietFrames[i].text = "|cFFFF0000Fruit"
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnLeave",function()iStableMaster:DietMouseOver(Footer.RightFrame,nil,true)end);
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnEnter",function(self)iStableMaster:DietMouseOver(Footer.RightFrame,self.text,false)end);
			elseif(i==5) then
				Footer.RightFrame.Diets[i]:SetPoint("CENTER",SelectedPetDataFrameFooter.RightFrame,"CENTER",0,-12);
				Footer.RightFrame.DietFrames[i]:SetPoint("CENTER",SelectedPetDataFrameFooter.RightFrame,"CENTER",0,-12);
				Footer.RightFrame.DietFrames[i].text = "|cFFFF0000Fungi"
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnLeave",function()iStableMaster:DietMouseOver(Footer.RightFrame,nil,true)end);
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnEnter",function(self)iStableMaster:DietMouseOver(Footer.RightFrame,self.text,false)end);
			elseif(i==6) then
				Footer.RightFrame.Diets[i]:SetPoint("RIGHT",SelectedPetDataFrameFooter.RightFrame,"RIGHT",0,-12);
				Footer.RightFrame.DietFrames[i]:SetPoint("RIGHT",SelectedPetDataFrameFooter.RightFrame,"RIGHT",0,-12);
				Footer.RightFrame.DietFrames[i].text = "|cFFFF0000Meat"
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnLeave",function()iStableMaster:DietMouseOver(Footer.RightFrame,nil,true)end);
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnEnter",function(self)iStableMaster:DietMouseOver(Footer.RightFrame,self.text,false)end);
			elseif(i==7) then
				Footer.RightFrame.Diets[i]:SetPoint("BOTTOMLEFT",SelectedPetDataFrameFooter.RightFrame,"BOTTOMLEFT",0,8);
				Footer.RightFrame.DietFrames[i]:SetPoint("BOTTOMLEFT",SelectedPetDataFrameFooter.RightFrame,"BOTTOMLEFT",0,8);
				Footer.RightFrame.DietFrames[i].text = "|cFFFF0000Mechanical Bits"
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnLeave",function()iStableMaster:DietMouseOver(Footer.RightFrame,nil,true)end);
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnEnter",function(self)iStableMaster:DietMouseOver(Footer.RightFrame,self.text,false)end);
			elseif(i==8) then
				Footer.RightFrame.Diets[i]:SetPoint("BOTTOM",SelectedPetDataFrameFooter.RightFrame,"BOTTOM",0,8);
				Footer.RightFrame.DietFrames[i]:SetPoint("BOTTOM",SelectedPetDataFrameFooter.RightFrame,"BOTTOM",0,8);
				Footer.RightFrame.DietFrames[i].text = "|cFFFF0000Raw Fish"
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnLeave",function()iStableMaster:DietMouseOver(Footer.RightFrame,nil,true)end);
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnEnter",function(self)iStableMaster:DietMouseOver(Footer.RightFrame,self.text,false)end);
			elseif(i==9) then
				Footer.RightFrame.Diets[i]:SetPoint("BOTTOMRIGHT",SelectedPetDataFrameFooter.RightFrame,"BOTTOMRIGHT",0,8);
				Footer.RightFrame.DietFrames[i]:SetPoint("BOTTOMRIGHT",SelectedPetDataFrameFooter.RightFrame,"BOTTOMRIGHT",0,8);
				Footer.RightFrame.DietFrames[i].text = "|cFFFF0000Raw Meat"
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnLeave",function()iStableMaster:DietMouseOver(Footer.RightFrame,nil,true)end);
				--	Footer.RightFrame.DietFrames[i]:HookScript("OnEnter",function(self)iStableMaster:DietMouseOver(Footer.RightFrame,self.text,false)end);
			end
			Footer.RightFrame.Diets[i].border = Footer.RightFrame:CreateTexture(nil, "OVERLAY");
			--Footer.RightFrame.Diets[i].border:SetTexture("Interface\\AddOns\\iStableMaster\\Quadratic Border 3-FAT.blp");
			Footer.RightFrame.Diets[i].border:SetAtlas("ui-hud-actionbar-IconFrame");
			Footer.RightFrame.Diets[i].border:SetDrawLayer("OVERLAY",7);
			Footer.RightFrame.Diets[i].border:SetSize(32,32);
			Footer.RightFrame.Diets[i].border:SetPoint(Footer.RightFrame.Diets[i]:GetPoint(1));
		end
		SelectedPetDataFrameFooter.RightFrame.Diets[1]:SetTexture("Interface\\ICONS\\INV_Misc_Food_08");
		SelectedPetDataFrameFooter.RightFrame.Diets[2]:SetTexture("Interface\\ICONS\\INV_Misc_Food_04");
		SelectedPetDataFrameFooter.RightFrame.Diets[3]:SetTexture("Interface\\ICONS\\INV_Misc_Food_75");
		SelectedPetDataFrameFooter.RightFrame.Diets[4]:SetTexture("Interface\\ICONS\\INV_Misc_Food_19");
		SelectedPetDataFrameFooter.RightFrame.Diets[5]:SetTexture("Interface\\ICONS\\INV_Mushroom_07");
		SelectedPetDataFrameFooter.RightFrame.Diets[6]:SetTexture("Interface\\ICONS\\INV_Misc_Food_18");
		SelectedPetDataFrameFooter.RightFrame.Diets[7]:SetTexture("Interface\\ICONS\\INV_Misc_Gear_08");
		SelectedPetDataFrameFooter.RightFrame.Diets[8]:SetTexture("Interface\\ICONS\\INV_Misc_Fish_07");
		SelectedPetDataFrameFooter.RightFrame.Diets[9]:SetTexture("Interface\\ICONS\\INV_Misc_Food_72");
		--SelectedPetDataFrameFooter.RightFrame.mask:SetTexture("Interface\\AddOns\\iStableMaster\\IconMask5", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
		--for ma=1,9,1 do
		--SelectedPetDataFrameFooter.RightFrame.Diets[ma].mask:SetTexture("Interface\\AddOns\\iStableMaster\\IconMask5")
		--SelectedPetDataFrameFooter.RightFrame.Diets[ma]:AddMaskTexture(SelectedPetDataFrameFooter.RightFrame.Diets[ma].mask)
		--end
		--SelectedPetDataFrameFooter.RightFrame.Diets[1]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		--SelectedPetDataFrameFooter.RightFrame.Diets[2]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		--SelectedPetDataFrameFooter.RightFrame.Diets[3]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		--SelectedPetDataFrameFooter.RightFrame.Diets[4]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		--SelectedPetDataFrameFooter.RightFrame.Diets[5]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		--SelectedPetDataFrameFooter.RightFrame.Diets[6]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		--SelectedPetDataFrameFooter.RightFrame.Diets[7]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		--SelectedPetDataFrameFooter.RightFrame.Diets[8]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		--SelectedPetDataFrameFooter.RightFrame.Diets[9]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		SelectedPetDataFrameFooter.RightFrame.Diets[1]:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
		SelectedPetDataFrameFooter.RightFrame.Diets[2]:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
		SelectedPetDataFrameFooter.RightFrame.Diets[3]:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
		SelectedPetDataFrameFooter.RightFrame.Diets[4]:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
		SelectedPetDataFrameFooter.RightFrame.Diets[5]:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
		SelectedPetDataFrameFooter.RightFrame.Diets[6]:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
		SelectedPetDataFrameFooter.RightFrame.Diets[7]:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
		SelectedPetDataFrameFooter.RightFrame.Diets[8]:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
		SelectedPetDataFrameFooter.RightFrame.Diets[9]:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
		-- THIRDLY We need to add some headers to the three Data fields
		if(Footer.LeftFrame.header == nil) then
			Footer.LeftFrame.header = Footer.LeftFrame:CreateFontString(nil,"OVERLAY","GameFontNormal");
			Footer.LeftFrame.header:SetPoint("TOP",Footer.LeftFrame,"TOP",0,0);
			Footer.LeftFrame.header:SetSize(Footer.LeftFrame:GetWidth(),32);
			Footer.LeftFrame.header:SetFont("Fonts\FRIZQT__.TTF",86,"MONOCHROME");
			Footer.LeftFrame.header:SetJustifyH("CENTER");
			--Footer.LeftFrame.header:SetTextColor(iStableMaster:GetDBColour("Default","Blue"));
			Footer.LeftFrame.header:SetText("Family Abilities");
		end
		if(Footer.CenterFrame.header == nil) then
			Footer.CenterFrame.header = Footer.CenterFrame:CreateFontString(nil,"OVERLAY","GameFontNormal");
			Footer.CenterFrame.header:SetPoint("TOP",Footer.CenterFrame,"TOP",0,0);
			Footer.CenterFrame.header:SetSize(Footer.CenterFrame:GetWidth(),32);
			Footer.CenterFrame.header:SetFont("Fonts\FRIZQT__.TTF",86,"MONOCHROME");
			Footer.CenterFrame.header:SetJustifyH("CENTER");
			--Footer.CenterFrame.header:SetTextColor(iStableMaster:GetDBColour("Default","Blue"));
			Footer.CenterFrame.header:SetText("Spec Abilities");
		end
		if(Footer.RightFrame.header == nil) then
			Footer.RightFrame.header = Footer.RightFrame:CreateFontString(nil,"OVERLAY","GameFontNormal");
			Footer.RightFrame.header:SetPoint("TOP",Footer.RightFrame,"TOP",0,0);
			Footer.RightFrame.header:SetSize(Footer.RightFrame:GetWidth(),32);
			Footer.RightFrame.header:SetFont("Fonts\FRIZQT__.TTF",86,"MONOCHROME");
			Footer.RightFrame.header:SetJustifyH("CENTER");
			--Footer.RightFrame.header:SetTextColor(iStableMaster:GetDBColour("Default","Blue"));
			Footer.RightFrame.header:SetText("Diet");
		end
	end
	---[[FOOTER INFO: FAMILY ABILITIES, SPEC ABILITIES AND DIET COMPLETED]]
end
function iStableMaster:UpdateSelectedPetDataFields(index) 
	if(SelectedPetDataFrameHeader == nil) then 
		return;
	end



	local specindexName = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.talent;
	local specIndex = 0;
	--print(specindexName);
	local name = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.name;
	local fname = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.family;

	local icon = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.icon;
	local diet = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.diet; -- this might need some work.

	SelectedPetDataFrameHeader.iconInteractiveregion:SetScript("OnEnter",function(self)iStableMaster.dataHeaderFamIcon:MouseOver(SelectedPetDataFrameHeader.iconInteractiveregion,fname,false) end);
	SelectedPetDataFrameHeader.iconInteractiveregion:SetScript("OnLeave",function(self)iStableMaster.dataHeaderFamIcon:MouseOver(SelectedPetDataFrameHeader.iconInteractiveregion,nil,true)end);
	SelectedPetDataFrameHeader.siconInteractiveregion:SetScript("OnEnter",function(self)iStableMaster.dataHeaderSpecIcon:MouseOver(SelectedPetDataFrameHeader.siconInteractiveregion,specindexName,false) end);
	SelectedPetDataFrameHeader.siconInteractiveregion:SetScript("OnLeave",function(self)iStableMaster.dataHeaderSpecIcon:MouseOver(SelectedPetDataFrameHeader.siconInteractiveregion,nil,true)end);

	
	--if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.abilities.talent == nil) then 
	--return

	--end

	--if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.abilities.family == nil) then 

	--return

	--end

	--local specAbilities = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.abilities.talent;
	--local familyAbilities = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.abilities.family;
	--if(index<6) then
	--		icon = iStableMasterStableDB["PetInfo"]["ActiveSlot"..index]["icon"];
	--		name = iStableMasterStableDB["PetInfo"]["ActiveSlot"..index]["name"];

	--		fname = iStableMasterStableDB["PetInfo"]["ActiveSlot"..index]["family"];
	--		specindexName = iStableMasterStableDB["PetInfo"]["ActiveSlot"..index]["talent"];

	--		-- custom info
	--		--ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..index]["favourite"];
	--		--ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..index]["inStables"];
	--		--ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..index]["Slot"];
	--		ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["ActiveSlot"..index]["abilities"];
	--		elseif(index==6) then
	--		--print(i);

	--		ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["icon"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["icon"];
	--		ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["name"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["name"];
	--		ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["level"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["level"];
	--		ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["family"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["family"];
	--		ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["talent"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["talent"];

	--		-- custom info
	--		ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["favourite"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["favourite"];
	--		ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["inStables"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["inStables"];
	--		ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["Slot"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["Slot"];
	--		ActivePetSlotsCards["ActiveSlot"..i]["PetInfo"]["abilities"] = iStableMasterStableDB["PetInfo"]["StableSlot"..1]["abilities"];
	--		end







	--print(familyAbilities[1], specAbilities[1] );
	if(specindexName == "Ferocity") then
		specIndex = 1;

	elseif(specindexName == "Tenacity") then
		specIndex = 2;

	elseif(specindexName == "Cunning") then
		specIndex = 3;

	end

	--print(specIndex);
	local sicon;
	if(specIndex == 0) then 
		sicon = nil;
	else
		sicon = select(4,GetSpecializationInfo(specIndex, false , true));
	end



	--print(sicon);

	if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.name == "N/A") then
		SelectedPetDataFrameHeader.name:SetText("This Stable Pen is Empty");
		SelectedPetDataFrameHeader.icon:SetAlpha(0);
		SelectedPetDataFrameHeader.icon.border:SetAlpha(0);
	else
		SelectedPetDataFrameHeader.icon:SetAlpha(1);
		SelectedPetDataFrameHeader.icon.border:SetAlpha(1);
		SelectedPetDataFrameHeader.name:SetText(""..name);
		SelectedPetDataFrameHeader.icon:SetTexture(icon); 
		SelectedPetDataFrameHeader.icon:SetBlendMode("ADD");

		--SelectedPetDataFrameHeader.icon:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		SelectedPetDataFrameHeader.icon:SetMask("UI-HUD-ActionBar-IconFrame-Mask");
	end


	--SelectedPetDataFrameHeader.icon:SetBlendMode("MULTIPLY");
	--local mask = SelectedPetDataFrameHeader.icon:CreateMaskTexture();
	--		mask:SetTexture("Interface\\AddOns\\iStableMaster\\IconMask3.blp", "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE")
	--		mask:SetPoint("TOPLEFT", 0, 0)
	--		mask:SetPoint("BOTTOMRIGHT", -0, 0)
	--		SelectedPetDataFrameHeader.icon.MaskTexture = mask;

	--SelectedPetDataFrameHeader.icon:AddMaskTexture(mask);

	--SelectedPetDataFrameHeader.icon:SetMask("Interface\\GUILDFRAME\\GuildLogoMask_L");
	--print(fname);
	if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.name ~= "N/A") then 

		if(iStableMaster:IsExotic(fname)) then

			SelectedPetDataFrameHeader.fname:SetText(""..fname.." |cFF6E006E<Exotic>");
		else
			SelectedPetDataFrameHeader.fname:SetText(""..fname);

		end
		SelectedPetDataFrameHeader.sicon:SetAlpha(1);
		SelectedPetDataFrameHeader.sicon.border:SetAlpha(1);
		SelectedPetDataFrameHeader.sicon:SetTexture(sicon); 
		SelectedPetDataFrameHeader.sicon:SetBlendMode("ADD");
		--SelectedPetDataFrameHeader.sicon:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
		SelectedPetDataFrameHeader.sicon:SetMask("UI-HUD-ActionBar-IconFrame-Mask");

	else

		SelectedPetDataFrameHeader.fname:SetText(" ");
		SelectedPetDataFrameHeader.sicon:SetAlpha(0);
		SelectedPetDataFrameHeader.sicon.border:SetAlpha(0);

	end



	--SelectedPetDataFrameFooter.diet = diet;



	--SelectedPetDataFrameFooter.RightFrame.Diets[1]:SetAlpha(1);
	--SelectedPetDataFrameFooter.RightFrame.Diets[1]:SetVertexColor(0.5,0,0,0.2);
	--SelectedPetDataFrameFooter.RightFrame.Diets[1]:SetBlendMode("ADD");
	--SelectedPetDataFrameFooter.RightFrame.DietFrames[1].text = "|cFFFF0000Bread";
	--SelectedPetDataFrameFooter.RightFrame.Diets[2]:SetAlpha(1);
	--SelectedPetDataFrameFooter.RightFrame.Diets[2]:SetVertexColor(0.5,0,0,0.2);
	--SelectedPetDataFrameFooter.RightFrame.Diets[2]:SetBlendMode("ADD");
	--SelectedPetDataFrameFooter.RightFrame.DietFrames[2].text = "|cFFFF0000Cheese";
	--SelectedPetDataFrameFooter.RightFrame.Diets[3]:SetAlpha(1);
	--SelectedPetDataFrameFooter.RightFrame.Diets[3]:SetVertexColor(0.5,0,0,0.2);
	--SelectedPetDataFrameFooter.RightFrame.Diets[3]:SetBlendMode("ADD");
	--SelectedPetDataFrameFooter.RightFrame.DietFrames[3].text = "|cFFFF0000Fish";
	--SelectedPetDataFrameFooter.RightFrame.Diets[4]:SetAlpha(1);
	--SelectedPetDataFrameFooter.RightFrame.Diets[4]:SetVertexColor(0.5,0,0,0.2);
	--SelectedPetDataFrameFooter.RightFrame.Diets[4]:SetBlendMode("ADD");
	--SelectedPetDataFrameFooter.RightFrame.DietFrames[4].text = "|cFFFF0000Fruit";
	--SelectedPetDataFrameFooter.RightFrame.Diets[5]:SetAlpha(1);
	--SelectedPetDataFrameFooter.RightFrame.Diets[5]:SetVertexColor(0.5,0,0,0.2);
	--SelectedPetDataFrameFooter.RightFrame.Diets[5]:SetBlendMode("ADD");
	--SelectedPetDataFrameFooter.RightFrame.DietFrames[5].text = "|cFFFF0000Fungi";
	--SelectedPetDataFrameFooter.RightFrame.Diets[6]:SetAlpha(1);
	--SelectedPetDataFrameFooter.RightFrame.Diets[6]:SetVertexColor(0.5,0,0,0.2);
	--SelectedPetDataFrameFooter.RightFrame.Diets[6]:SetBlendMode("ADD");
	--SelectedPetDataFrameFooter.RightFrame.DietFrames[6].text = "|cFFFF0000Meat";
	--SelectedPetDataFrameFooter.RightFrame.Diets[7]:SetAlpha(1);
	--SelectedPetDataFrameFooter.RightFrame.Diets[7]:SetVertexColor(0.5,0,0,0.2);
	--SelectedPetDataFrameFooter.RightFrame.Diets[7]:SetBlendMode("ADD");
	--SelectedPetDataFrameFooter.RightFrame.DietFrames[7].text = "|cFFFF0000Mechanical Bits";
	--SelectedPetDataFrameFooter.RightFrame.Diets[8]:SetAlpha(1);
	--SelectedPetDataFrameFooter.RightFrame.Diets[8]:SetVertexColor(0.5,0,0,0.2);
	--SelectedPetDataFrameFooter.RightFrame.Diets[8]:SetBlendMode("ADD");
	--SelectedPetDataFrameFooter.RightFrame.DietFrames[8].text = "|cFFFF0000Raw Fish";
	--SelectedPetDataFrameFooter.RightFrame.Diets[9]:SetAlpha(1);
	--SelectedPetDataFrameFooter.RightFrame.Diets[9]:SetVertexColor(0.5,0,0,0.2);
	--SelectedPetDataFrameFooter.RightFrame.Diets[9]:SetBlendMode("ADD");
	--SelectedPetDataFrameFooter.RightFrame.DietFrames[9].text = "|cFFFF0000Raw Meat";



	local l_DietList = { GetStablePetFoodTypes(index) };

	for j=1,9,1 do
		SelectedPetDataFrameFooter.RightFrame.DietFrames[j].text = "|cFFFF0000"..string.sub(SelectedPetDataFrameFooter.RightFrame.DietFrames[j].text,11);

		--SelectedPetDataFrameFooter.RightFrame.DietFrames[j].text = "|cFFFF0000TESTER!";

		SelectedPetDataFrameFooter.RightFrame.Diets[j]:SetBlendMode("ADD");

		SelectedPetDataFrameFooter.RightFrame.Diets[j]:SetVertexColor(1,0,0,0.2);
		--print(j,l_DietList[j], SelectedPetDataFrameFooter.RightFrame.DietFrames[j].text)		
	end	

	for j=1,9,1 do

		--print(l_DietList[j] or j);





		if(l_DietList[j] == "Bread") then
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:SetTexture(nil);
			--SelectedPetDataFrameFooter.RightFrame.Diets[j]:SetBlendMode("ADD");
			--print(j,l_DietList[j])		
			SelectedPetDataFrameFooter.RightFrame.DietFrames[1].text = "|cFF00FF00Bread";
			--SelectedPetDataFrameFooter.RightFrame.Diets[1]:SetVertexColor(1,1,1,0);


			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Bread"]:

			--SelectedPetDataFrameFooter.RightFrame.Diets[j]:SetAlpha(1);

			SelectedPetDataFrameFooter.RightFrame.Diets[1]:SetVertexColor(1,1,1,1);





		elseif(l_DietList[j] == "Cheese") then
			--SelectedPetDataFrameFooter.RightFrame.Diets[2]:SetTexture(nil);
			SelectedPetDataFrameFooter.RightFrame.DietFrames[2].text = "|cFF00FF00Cheese";
			--print(j,l_DietList[j]) 

			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Cheese"]:SetVertexColor(0.5,0.5,0.5,1);
			SelectedPetDataFrameFooter.RightFrame.Diets[2]:SetVertexColor(1,1,1,1);

		elseif(l_DietList[j] == "Fish") then
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:SetTexture(nil);
			SelectedPetDataFrameFooter.RightFrame.DietFrames[3].text = "|cFF00FF00Fish";
			--print(j,l_DietList[j])
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fish"]:SetVertexColor(0.5,0.5,0.5,1);
			SelectedPetDataFrameFooter.RightFrame.Diets[3]:SetVertexColor(1,1,1,1);

		elseif(l_DietList[j] == "Fruit") then
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:SetTexture(nil);
			SelectedPetDataFrameFooter.RightFrame.DietFrames[4].text = "|cFF00FF00Fruit";
			--print(j,l_DietList[j])
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fruit"]:SetVertexColor(0.5,0.5,0.5,1);
			SelectedPetDataFrameFooter.RightFrame.Diets[4]:SetVertexColor(1,1,1,1);
		elseif(l_DietList[j] == "Fungus") then
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:SetTexture(nil);
			SelectedPetDataFrameFooter.RightFrame.DietFrames[5].text = "|cFF00FF00Fungi";
			--print(j,l_DietList[j])
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Fungus"]:SetVertexColor(0.5,0.5,0.5,1);
			SelectedPetDataFrameFooter.RightFrame.Diets[5]:SetVertexColor(1,1,1,1);

		elseif(l_DietList[j] == "Meat") then
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:SetTexture(nil);
			SelectedPetDataFrameFooter.RightFrame.DietFrames[6].text = "|cFF00FF00Meat";
			--print(j,l_DietList[j])
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Meat"]:SetVertexColor(0.5,0.5,0.5,1);
			SelectedPetDataFrameFooter.RightFrame.Diets[6]:SetVertexColor(1,1,1,1);
		elseif(l_DietList[j] == "Mechanical Bits") then
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:SetTexture(nil);
			SelectedPetDataFrameFooter.RightFrame.DietFrames[7].text = "|cFF00FF00Mechanical Bits";
			--print(j,l_DietList[j])
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Mechanical Bits"]:SetVertexColor(0.5,0.5,0.5,1);
			SelectedPetDataFrameFooter.RightFrame.Diets[7]:SetVertexColor(1,1,1,1);


		elseif(l_DietList[j] == "Raw Fish") then
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:SetTexture(nil);
			SelectedPetDataFrameFooter.RightFrame.DietFrames[8].text = "|cFF00FF00Raw Fish";
			--print(j,l_DietList[j])
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Fish"]:SetVertexColor(0.5,0.5,0.5,1);
			SelectedPetDataFrameFooter.RightFrame.Diets[8]:SetVertexColor(1,1,1,1);
		elseif(l_DietList[j] == "Raw Meat") then
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:SetTexture(nil);
			SelectedPetDataFrameFooter.RightFrame.DietFrames[9].text = "|cFF00FF00Raw Meat";
			--print(j,l_DietList[j])																							
			--					ActivePetSlotsCards["ActiveSlot"..i]["Card"..i]["DietFrame"]["Raw Meat"]:SetVertexColor(0.5,0.5,0.5,1);
			SelectedPetDataFrameFooter.RightFrame.Diets[9]:SetVertexColor(1,1,1,1);



		end

	end
	for j=1,9,1 do
		SelectedPetDataFrameFooter.RightFrame.DietFrames[j]:SetScript("OnLeave",function(self)iStableMaster:DietMouseOver(SelectedPetDataFrameFooter.RightFrame,nil,true)end);
		SelectedPetDataFrameFooter.RightFrame.DietFrames[j]:SetScript("OnEnter",function(self)iStableMaster:DietMouseOver(SelectedPetDataFrameFooter.RightFrame,SelectedPetDataFrameFooter.RightFrame.DietFrames[j].text,false) end);
	end

	--SelectedPetDataFrameFooter.specAbilities = specAbilities;
	if(iStableMasterDB["SpecializationAbilities"][specindexName] ~= nil) then

		local numabilities = #iStableMasterDB["SpecializationAbilities"][specindexName]
		--print(l_iStableMasterDB["SpecializationAbilities"][specindexName][1]);
	end


	for j=1,2 do
		--local anameS, arankS, aiconS, acastTimeS, aminRangeS, amaxRangeS = GetSpellInfo(specAbilities[j])
		local anameS, arankS, aiconS, acastTimeS, aminRangeS, amaxRangeS;
		if(specIndex == 0) then

			anameS, arankS, aiconS, acastTimeS, aminRangeS, amaxRangeS = "Nothing Is Selected", nil, nil, nil, nil, nil;


		else

			anameS, arankS, aiconS, acastTimeS, aminRangeS, amaxRangeS = GetSpellInfo(iStableMasterDB["SpecializationAbilities"][specindexName][j])	
		end




		SelectedPetDataFrameFooter.CenterFrame.Abilities[j]:SetAlpha(1);
		SelectedPetDataFrameFooter.CenterFrame.Abilities[j].border:SetAlpha(1);
		--SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetBlendMode("DISABLE");
		--SelectedPetDataFrameFooter.CenterFrame.Abilities[j]:SetMask(nil);
		SelectedPetDataFrameFooter.CenterFrame.Abilities[j]:SetTexture(nil);

		if(anameS ~= nil and anameS ~= "Nothing Is Selected") then
			SelectedPetDataFrameFooter.CenterFrame.AbilitiesFrames[j]:Show();
			SelectedPetDataFrameFooter.CenterFrame.Abilities[j]:SetTexture(aiconS);
			SelectedPetDataFrameFooter.CenterFrame.Abilities[j]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");
			SelectedPetDataFrameFooter.CenterFrame.Abilities[j]:SetBlendMode("ADD");
			--print("anameS",aname);
			SelectedPetDataFrameFooter.CenterFrame.AbilitiesFrames[j]:SetScript("OnLeave",function()iStableMaster:SpellMouseOver(SelectedPetDataFrameFooter.CenterFrame,nil,true)end);
			local l_details = iStableMasterDB["SpecializationAbilities"][specindexName][j];

			--SelectedPetDataFrameFooter.CenterFrame.AbilitiesFrames[j]:SetScript("OnEnter",function()iStableMaster:SpellMouseOver(SelectedPetDataFrameFooter.CenterFrame,nil,false)end);
			SelectedPetDataFrameFooter.CenterFrame.AbilitiesFrames[j]:SetScript("OnEnter",function()iStableMaster:SpellMouseOver(SelectedPetDataFrameFooter.CenterFrame,l_details,false)end);

		end

		if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.name == "N/A") then 
			--print("anameS");
			SelectedPetDataFrameFooter.CenterFrame.Abilities[j]:SetTexture("Interface\\ICONS\\INV_Misc_Food_18");
			SelectedPetDataFrameFooter.CenterFrame.Abilities[j]:SetAlpha(0);
			SelectedPetDataFrameFooter.CenterFrame.Abilities[j].border:SetAlpha(0);
			SelectedPetDataFrameFooter.CenterFrame.AbilitiesFrames[j]:Hide();
		end



	end



	

	--iStableMaster:PrintPairs(iStableMasterDB["FamilyAbilities"][name]);


	--local forlimit = iStableMaster:StringKeyTableLengthI(select(1,GetSpellInfo(iStableMasterDB["FamilyAbilities"][name]))) or 0
	if(iStableMasterDB["FamilyAbilities"][fname] ~= nil) then

		local numabilities = #iStableMasterDB["FamilyAbilities"][fname]
		--print(iStableMasterDB["FamilyAbilities"][fname][1]);
	end

	if(iStableMasterDB["FamilyAbilities"][fname] ~= nil or iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.name == "N/A") then
		for j=1,4 do

			local aname, arank, aicon, acastTime, aminRange, amaxRange;

			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.name == "N/A") then
				aname, arank, aicon, acastTime, aminRange, amaxRange = nil, nil, nil, nil, nil, nil;


			else
				aname, arank, aicon, acastTime, aminRange, amaxRange = GetSpellInfo(iStableMasterDB["FamilyAbilities"][fname][j])

			end



			--local aname, arank, aicon, acastTime, aminRange, amaxRange = GetSpellInfo(familyAbilities[j])
			--SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetBlendMode("DISABLE");
			--SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetTexture(nil);

			SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetAlpha(1);
			SelectedPetDataFrameFooter.LeftFrame.Abilities[j].border:SetAlpha(1);
			--SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetBlendMode("DISABLE");
			SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetTexture(nil);
			--SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetMask(nil);


			if(aname ~= nil) then 

				SelectedPetDataFrameFooter.LeftFrame.AbilitiesFrames[j]:Show();
				SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetTexture(aicon);
				SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetMask("Interface\\AddOns\\iStableMaster\\IconMask5");



				--print(l_iStableMasterDB["FamilyAbilities"][fname][j]);

				SelectedPetDataFrameFooter.LeftFrame.AbilitiesFrames[j]:SetScript("OnEnter",function()iStableMaster:SpellMouseOver(SelectedPetDataFrameFooter.LeftFrame,iStableMasterDB["FamilyAbilities"][fname][j],false)end);

				--iStableMaster:SpellMouseOver(parent,details,state)

				SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetBlendMode("ADD");

				--print("anameF",aname);

			elseif(aname == nil or iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index].PetInfo.name == "N/A") then 
				--print("anameF",aname);
				SelectedPetDataFrameFooter.LeftFrame.AbilitiesFrames[j]:Hide();
				SelectedPetDataFrameFooter.LeftFrame.Abilities[j]:SetAlpha(0);
				SelectedPetDataFrameFooter.LeftFrame.Abilities[j].border:SetAlpha(0);


			end
			SelectedPetDataFrameFooter.LeftFrame.AbilitiesFrames[j]:SetScript("OnLeave",function()iStableMaster:SpellMouseOver(SelectedPetDataFrameFooter.LeftFrame,nil,true)end);


		end

	end
	--SelectedPetDataFrameFooter.familyAbilities = familyAbilities;

end
function iStableMaster:SetPetModelView() 
	local namelengthDefault = 14;
	StablesCollection.StablesLeftFrame:SetBackdrop({bgFile="Interface\\DRESSUPFRAME\\DressingRoomHunter",
		edgeFile="", tile=false,tileSize=264,edgeSize=32,
		insets= {left=3,top=3,right=-18,bottom=-9}});   --5,5
	local firstIndex=1;
	if(not iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"]) then
		firstIndex = GlobalActiveSlotLoopValue + 1;
	end
	if(iStableMaster.ScrollFrameArrElem["ScrollElement"..firstIndex] ~= nil) then
		local fname = iStableMaster.ScrollFrameArrElem["ScrollElement"..firstIndex]:GetName();
	else
		local fname = ActivePetSlotsCards["ActiveSlot"..firstIndex]["Socket"..firstIndex]:GetName();
		namelengthDefault = 17;
	end
	if(iStableMaster.currentlySelectedPet ~= nil) then
		fname = iStableMaster.currentlySelectedPet:GetName();
		if(string.find(fname,"Socket") ~= nil) then
			local startOfSocket, placeToSplit = string.find(fname,"Socket");
			namelengthDefault = placeToSplit + 1;
		elseif(string.find(fname,"ScrollElementChild") ~= nil) then
			local startOfSocket, placeToSplit = string.find(fname,"ScrollElementChild");
			namelengthDefault = placeToSplit + 1;
		else
			--Do nothing
		end
	end
	if(iStableMaster.ScrollFrameArrElem["ScrollElement"..firstIndex] ~= nil and namelengthDefault==14) then
		local indexNumber = 1;
		if(fname ~= nil) then
			indexNumber = tonumber(string.sub(fname, namelengthDefault));
		end
		local petSlot = nil;
		if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber] ~= nil)then
			petSlot = tonumber(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber]["PetInfo"]["Slot"]);
		end
		local icon = nil;
		local name = nil;
		if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber] ~= nil)then
			icon = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber]["PetInfo"]["icon"];
			name = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..indexNumber]["PetInfo"]["name"];
		end
		if(icon == nil or icon == "N/A") then
			CollectionsPetStableModel:ClearModel();
			iStableMaster:UpdateSelectedPetDataFields(petSlot)
		else
			SetPetStablePaperdoll(CollectionsPetStableModel, petSlot);
			iStableMaster:UpdateSelectedPetDataFields(petSlot);
		end
	else
		local indexNumber = 1;
		if(fname ~= nil) then
			indexNumber = tonumber(string.sub(fname, namelengthDefault));
		end
		local petSlot = nil;
		if(ActivePetSlotsCards["ActiveSlot"..indexNumber] ~= nil)then
			petSlot = tonumber(ActivePetSlotsCards["ActiveSlot"..indexNumber]["PetInfo"]["Slot"]);
		end
		local icon = nil;
		local name = nil;
		if(ActivePetSlotsCards["ActiveSlot"..indexNumber] ~= nil)then
			icon = ActivePetSlotsCards["ActiveSlot"..indexNumber]["PetInfo"]["icon"];
			name = ActivePetSlotsCards["ActiveSlot"..indexNumber]["PetInfo"]["name"];
		end
		if(icon == nil or icon == "N/A") then
			CollectionsPetStableModel:ClearModel();
			iStableMaster:UpdateSelectedPetDataFields(petSlot)
		else
			SetPetStablePaperdoll(CollectionsPetStableModel, petSlot);
			iStableMaster:UpdateSelectedPetDataFields(petSlot);
		end
	end
	CollectionsJournal:SetAttribute("UIPanelLayout-pushable", 1)
	CollectionsJournal:SetAttribute("UIPanelLayout-allowOtherPanels", 1)
	PetStableFrame:SetAttribute("UIPanelLayout-pushable", 1)
	--PetStableFrame:SetAttribute("UIPanelLayout-pushable", 0)
	PetStableFrame:SetAttribute("UIPanelLayout-allowOtherPanels", 1)
	PetStableFrame.ignoreFramePositionManager = true;
	PetStableFrame:SetAttribute("panel-show", 1)
end
----------------------------------------------------
---			3D MODEL VIEWER FRAME END			 ---
----------------------------------------------------
----------------------------------------------------
---				FAVOURITE GETSET				 ---
----------------------------------------------------
function iStableMaster:UpdateFavStatus(origin,target,...)
	local completedSwapLingerCheck = ... or false;
	if((not IsAtStableMaster() and not completedSwapLingerCheck) or ((target < 6) and (not IsSpellKnown(iStableMasterDB["Constants"]["CALL_PET_SPELL_IDS"][target])))) then	
		--print("returned")
		iStableMaster:Print("Stables Closed! Squad Activation was aborted, - aborting favourite property swap");
		return; 

	end
	if(target < 6) then
		if(not GlobalSpecialization == "Beast Mastery") then -- prevents false tracking when drag and drop eventually fails on exotic creatues while not specced as Beast Mastery -- adding failsafe for locked or failed move
			if(iStableMaster:IsStabledPetExotic(origin)) then
				-- probably do some error message if not on by default
				iStableMaster:Print("Exotic pets in active slots requires specialization: 'Beast Mastery', - aborting favourite property swap");
				return;
			end
		end
	end

	local temp = false;
	temp = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["PetInfo"]["favourite"];
	--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["PetInfo"]["favourite"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["PetInfo"]["favourite"];
	--iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["PetInfo"]["favourite"] = temp;	
	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["PetInfo"]["favourite"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["PetInfo"]["favourite"];
	if(origin > 6) then
	iStableMasterStableDB["PetInfo"]["StableSlot"..(origin-5)]["favourite"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["PetInfo"]["favourite"];
	elseif( origin == 6) then 
	iStableMasterStableDB["PetInfo"]["StableSlot"..1]["favourite"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["PetInfo"]["favourite"];
	else
	iStableMasterStableDB["PetInfo"]["ActiveSlot"..origin]["favourite"] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["PetInfo"]["favourite"];
	end


	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["PetInfo"]["favourite"] = temp;
	if(target > 6) then
	iStableMasterStableDB["PetInfo"]["StableSlot"..(target-5)]["favourite"] = temp;
	elseif( target == 6) then 
	iStableMasterStableDB["PetInfo"]["StableSlot"..1]["favourite"] = temp;
	else
	iStableMasterStableDB["PetInfo"]["ActiveSlot"..target]["favourite"] = temp;
	end
	
	if(not iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["PetInfo"]["favourite"]) then
					--iStableMaster:SetPetScrollTilesContent(filtermode)
					--print("left Fav Star");
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["FavouriteStarFrame"].bg:SetAlpha(0.2);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["FavouriteStarFrame"].bg:SetVertexColor(0.953,0.953,0.953,0.2);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["FavouriteStarFrame"].fill:SetAlpha(0);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["FavouriteStarFrame"].frame:SetAlpha(0.75);
				else
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["FavouriteStarFrame"].fill:SetVertexColor(0.753,0.753,0,1);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["FavouriteStarFrame"].fill:SetAlpha(1);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["FavouriteStarFrame"].bg:SetAlpha(0);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["FavouriteStarFrame"].frame:SetAlpha(1);
	end
	if(not iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["PetInfo"]["favourite"]) then
					--iStableMaster:SetPetScrollTilesContent(filtermode)
					--print("left Fav Star");
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["FavouriteStarFrame"].bg:SetAlpha(0.2);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["FavouriteStarFrame"].bg:SetVertexColor(0.953,0.953,0.953,0.2);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["FavouriteStarFrame"].fill:SetAlpha(0);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["FavouriteStarFrame"].frame:SetAlpha(0.75);
				else
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["FavouriteStarFrame"].fill:SetVertexColor(0.753,0.753,0,1);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["FavouriteStarFrame"].fill:SetAlpha(1);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["FavouriteStarFrame"].bg:SetAlpha(0);
					iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["FavouriteStarFrame"].frame:SetAlpha(1);
	end
	--print("swap: "..origin.."to "..target);
	--print(origin,"to "..tostring(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..origin]["PetInfo"]["favourite"]),target,"to "..tostring(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..target]["PetInfo"]["favourite"]));
iStableMaster:SavePetInfoToWTF();
end 
function iStableMaster:SetAsFavourite(petIndex)

	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..petIndex]["PetInfo"]["favourite"] = true;
	if(petIndex < 6) then
		iStableMasterStableDB["PetInfo"]["ActiveSlot"..petIndex]["favourite"] = true;
	elseif(petIndex == 6 and GlobalSpecialization == "Beast Mastery") then
		iStableMasterStableDB["PetInfo"]["ActiveSlot"..petIndex]["favourite"] = true;
	else
		iStableMasterStableDB["PetInfo"]["StableSlot"..petSlot-5]["favourite"] = true;
	end


end
function iStableMaster:SetAsFavouriteSafe(i)
	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["favourite"] = true;
	iStableMasterStableDB["PetInfo"]["StableSlot"..i]["favourite"] = true;
end
function iStableMaster:ChangeFavouriteSafe(index)
	local l_i = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index]["PetInfo"]["Slot"];
	local boolValue = not iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index]["PetInfo"]["favourite"];
	if(l_i<6) then

		-- custom info
		ActivePetSlotsCards["ActiveSlot"..l_i]["PetInfo"]["favourite"] = boolValue;
		iStableMasterStableDB["PetInfo"]["ActiveSlot"..l_i]["favourite"] = boolValue;
		--end

	elseif(i==6) then
		
		-- custom info
		ActivePetSlotsCards["ActiveSlot"..l_i]["PetInfo"]["favourite"] = boolValue;
		iStableMasterStableDB["PetInfo"]["StableSlot"..1]["favourite"] = boolValue;
		--end

	end
	iStableMaster.ScrollFrameArrElem["ScrollElementChild"..index]["PetInfo"]["favourite"] = boolValue;
	iStableMaster:SavePetInfoToWTF();
end
----------------------------------------------------
---				FAVOURITE GETSET END			 ---
----------------------------------------------------

----------------------------------------------------
---					SETTINGS					 ---
----------------------------------------------------
function iStableMaster:LayoutSelector()
	if(iStableMasterOptionsDB.Layout == "Default") then
		--print("Layout is read as "..iStableMasterOptionsDB.Layout);
	else
		--print("Layout is read as "..(iStableMasterOptionsDB.Layout or "nil"));	
		for i=1,6,1 do
			--ActivePetSlotsCards["ActiveSlot"..i]:Hide();
		end
	end
end
----------------------------------------------------
---					SETTINGS END				 ---
----------------------------------------------------


------------------------------------------------------------------------------------------------------- FILTER AND SORTING ALGORITHIM SECTION ------------------------------------------------------------------------------------------


--#########################################################--
--		EVERYTHING SORTING AND FILTERING IMPLEMENTATION    --
--#########################################################--
function iStableMaster:UpdateScrollListMainCall()
	if(iStableMaster:GetFilterValue("AnyFilter")) then
		iStableMaster:UpdateFilterSpecs(true);
	else
		--HideEmptyScrollSlots();
		--MoveEmptySlotsToBottomOfScroll();
		iStableMaster:MasterFilterSort();
	end
end -- CALL THIS FOR REFRESHING THE PET SCROLLLIST --- 63 occurrences that's.... TOO MUCH!
do---  OVERALL MASTER PLAN FOR SORTING
	--Using stack splitting we can filter out all the things that are not set to true in the filters, and add those together in the top of a list, while sorting the stack which contains only the filtered content, and then put the Empty slots either first or last

	----- Stack 0 -----
	--	/		\
	--Stack 1  Stack 2	   Filter 1
	--			/	--
	--		/		--	
	--	/			--
	--Stack 1.1 Stack 2.2  Filter 2
	--			/	--
	--		/		--	
	--	/			--
	--Stack 1.2 Stack 2.3  Filter 3



	-- (Stack 0 : EMPTY) > (Stack 2.3 :SORT) > (Stack 1.2 :HIDE)
	--     1					   ....						2
end---  OVERALL MASTER PLAN FOR SORTING


-------------------------------------------------------------------------------------
function iStableMaster:MasterFilterSort(input,shouldflip)
	-- Variable declaration
	PetCounter1:SetText(""..iStableMaster:CountStabledPets().."/200");
	local flip = shouldflip or false;
	local stack0 = {};
	local stack1 = {};
	local stack2 = {};
	local stack3 = {};
	local point, relativeTo, relativePoint, xOfs, yOfs = iStableMaster.ScrollFrameArrElem["ScrollElement0"]:GetPoint(1);
	local ElementSizeY = iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"];
	do
		iStableMaster.ScrollFrameArrElem.length = iStableMaster:StringKeyTableLength(iStableMaster.ScrollFrameArrElem,"ScrollElement");
		stack0.length = iStableMaster:StringKeyTableLengthI(stack0)+1;
		stack1.length = iStableMaster:StringKeyTableLengthI(stack1)+1;
		stack2.length = iStableMaster:StringKeyTableLengthI(stack2)+1;
		stack3.length = iStableMaster:StringKeyTableLengthI(stack3)+1;
	end
	--Variable declaration END
	-- Find All Empty Slots
	do
		for i = 1,iStableMaster.ScrollFrameArrElem.length-1 do	
			iStableMaster.ScrollFrameArrElem["ScrollElement"..i]:Show();
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..i]["PetInfo"]["name"] == "N/A") then
				stack0[#stack0+1] = i;
				_G["ScrollElement"..i]:Hide(); 
			else
				stack1[#stack1+1] = i;
			end
		end
	end
	if(iStableMaster:GetFilterValue("AnyFilter")) then
		-- DietsFilter
		do
			for i = 1,#stack1 do
				local dietList = { GetStablePetFoodTypes(stack1[i]) };
				local filterFood = iStableMaster:GetFilterValue("Diets");
				local hasFood = false;
				for count = 1,9 do 
					if(filterFood[dietList[count]]) then
						hasFood = true;
					end
				end
				if(hasFood) then
					stack2[#stack2+1] = stack1[i];
				else
					stack3[#stack3+1] = stack1[i];
				end
			end
		end	
		-- UpdateStack1
		do
			stack1 = {};
			for i = 1,#stack2 do	
				stack1[#stack1+1] = stack2[i];
			end
			wipe(stack2);
			stack2 = {};
		end
		-- Update Done		
		-- SpecFilter
		do
			for i = 1,#stack1 do
				if(iStableMaster:GetFilterValue(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["talent"])) then
					stack2[#stack2+1] = stack1[i];
				else
					stack3[#stack3+1] = stack1[i];
				end	
			end
		end	
		-- UpdateStack1
		do
			stack1 = {};
			for i = 1,#stack2 do	
				stack1[#stack1+1] = stack2[i];
			end
			stack2 = {};
		end
		-- Update Done
		-- FamilyFilter
		do
			for i = 1,#stack1 do
				if(iStableMaster:GetFilterValue(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["family"])) then
					stack2[#stack2+1] = stack1[i];
				else
					stack3[#stack3+1] = stack1[i];
				end	
			end
		end
		-- UpdateStack1 
		do
			stack1 = {};
			for i = 1,#stack2 do	
				stack1[#stack1+1] = stack2[i];
			end
			stack2 = {};
		end
		-- Update Done
		-- FamilyBonusAbilitiesFilter
		do
			for i = 1,#stack1 do
				if(iStableMaster:SetContains(iStableMasterDB.BonusFamilyAbilities, iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["family"])) then
					if(iStableMaster:GetFilterValue("BonusFamilyAbilities")) then
						stack2[#stack2+1] = stack1[i];
					else
						stack3[#stack3+1] = stack1[i];
					end
				else
					stack2[#stack2+1] = stack1[i];
				end
			end
		end
		-- UpdateStack1 
		do
			stack1 = {};
			for i = 1,#stack2 do	
				stack1[#stack1+1] = stack2[i];
			end
			stack2 = {};
		end
		-- Update Done
		-- FamilyDefenseAbilitiesFilter
		do
			for i = 1,#stack1 do
				if(iStableMaster:SetContains(iStableMasterDB["Defense"], iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["family"])) then
					if(iStableMaster:GetFilterValue("Defense")) then
						stack2[#stack2+1] = stack1[i];
					else
						stack3[#stack3+1] = stack1[i];
					end
				else
					stack2[#stack2+1] = stack1[i];
				end
			end
		end
		-- UpdateStack1 
		do
			stack1 = {};
			for i = 1,#stack2 do	
				stack1[#stack1+1] = stack2[i];
			end
			stack2 = {};
		end
		-- Update Done
		-- TrickAbilityFilter
		do
			for i = 1,#stack1 do
				if(iStableMaster:SetContains(iStableMasterDB["Trick"], iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["family"])) then
					if(iStableMaster:GetFilterValue("Trick")) then
						stack2[#stack2+1] = stack1[i];
					else
						stack3[#stack3+1] = stack1[i];
					end
				else
					stack2[#stack2+1] = stack1[i];
				end
			end
		end
		-- UpdateStack1 
		do
			stack1 = {};
			for i = 1,#stack2 do	
				stack1[#stack1+1] = stack2[i];
			end
			stack2 = {};
		end
		-- Update Done
		-- RenamedFilter ( IF checked show renamed, if unchecked do not show renamed.) I should have a show renamed only too)
		do
			for i = 1,#stack1 do		
				if(iStableMaster:GetFilterValue("Named") ) then
					stack2[#stack2+1] = stack1[i];
				elseif(not iStableMaster:GetFilterValue("Named") and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["name"] ~= iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["family"]) then
					stack3[#stack3+1] = stack1[i];
				else
					stack2[#stack2+1] = stack1[i];
				end	
			end
		end	
		-- UpdateStack1
		do
			stack1 = {};
			for i = 1,#stack2 do	
				stack1[#stack1+1] = stack2[i];
			end
			stack2 = {};
		end
		-- Update Done
		do
			for i = 1,#stack1 do		
				if(iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"]) then
					stack2[#stack2+1] = stack1[i];
				elseif(not iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"] and stack1[i] <= GlobalActiveSlotLoopValue ) then
					stack3[#stack3+1] = stack1[i];
				else
					stack2[#stack2+1] = stack1[i];
				end	
			end
		end
		-- UpdateStack1
		do
			stack1 = {};
			for i = 1,#stack2 do	
				stack1[#stack1+1] = stack2[i];
			end
			stack2 = {};
		end
		-- Update Done
		-- FavouritesFilter
		do
			for i = 1,#stack1 do
				if(iStableMaster:GetFilterValue("Favourite")) then
					stack2[#stack2+1] = stack1[i];
				elseif(not iStableMaster:GetFilterValue("Favourite") and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["favourite"]) then
					stack3[#stack3+1] = stack1[i];
				else
					stack2[#stack2+1] = stack1[i];
				end	
			end
		end
		-- UpdateStack1
		do
			stack1 = {};
			for i = 1,#stack2 do	
				stack1[#stack1+1] = stack2[i];
			end
			stack2 = {};
		end
		-- Update Done
		-- ExoticFilter ( IF checked show exotic, if unchecked do not show exotic.) I should have a show exotic only too)
		do
			for i = 1,#stack1 do		
				if(iStableMaster:GetFilterValue("Exotic")) then
					stack2[#stack2+1] = stack1[i];
				elseif(not iStableMaster:GetFilterValue("Exotic") and iStableMaster:IsExotic(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["family"])) then
					stack3[#stack3+1] = stack1[i];
				else
					stack2[#stack2+1] = stack1[i];
				end	
			end
		end	
		-- UpdateStack1
		do
			stack1 = {};
			for i = 1,#stack2 do	
				stack1[#stack1+1] = stack2[i];
			end
			stack2 = {};
		end
		-- Update Done
	end -- filtersend

	-- sort filtered stack begin:
	-- This is where Search is included as the outer most layer.
	-- Sort Variable declaration and init
	local sortpriority = {iStableMasterDB["ActiveSorts"]["CurrentSort"].primary,iStableMasterDB["ActiveSorts"]["CurrentSort"].secondary,iStableMasterDB["ActiveSorts"]["CurrentSort"].tertiary} 
	if type(iStableMaster:GetSortPriority(1,2,3)) == "table" then
		--sortpriority =  iStableMaster:GetSortPriority(1,2,3);	
	end
	--print(sortpriority[1],sortpriority[2],sortpriority[3]);
	local subStack1 = {}; -- IN USE
	local subStack2 = {}; -- IN USE
	local subStack3 = {}; --IN USE
	local subStack8 = {}; -- IN USE
	StackOfIndiciesAndWeights = {Weight = {}, Value={}, Param={}};
	outsort = {0,1,2,3};
	outsort[0] = {Weight = {}, Value={}, Param={}};
	outsort[1] = {Weight = {}, Value={}, Param={}};
	outsort[2] = {Weight = {}, Value={}, Param={}};
	outsort[3] = {Weight = {}, Value={}, Param={}};
	for i = 1,#stack1 do
		StackOfIndiciesAndWeights.Weight[stack1[i]] = 0;
		StackOfIndiciesAndWeights.Value[i] = stack1[i];
		StackOfIndiciesAndWeights.Param[i] = nil;
	end
	subStack1ParamStack = {};
	subStack2ParamStack = {};
	subStack3ParamStack = {};
	SortStackTrace = {};
	tableOfStringsToPrint = {}
	tableOfStringsToPrint[0] = {};
	tableOfStringsToPrint[1] = {};
	tableOfStringsToPrint[2] = {};
	tableOfStringsToPrint[3] = {};
	for i=1, #stack1 do
		tableOfStringsToPrint[0][i] = {};
		tableOfStringsToPrint[1][i] = {};
		tableOfStringsToPrint[2][i] = {};
		tableOfStringsToPrint[3][i] = {};
	end
	local stringOut = {};
	for i=1, #stack1 do
		SortStackTrace[i] = {};
		SortStackTrace[i]["Index"] = stack1[i];
		SortStackTrace[i][0] = 0; -- im not sure if nil == nil will throw a nil pointer error or accept as true.
		SortStackTrace[i][1] = 0;
		SortStackTrace[i][2] = 0;
		SortStackTrace[i][3] = 0;
	end		
	-- Sort Variable declaration and init END
	do
		for i=0,3 do
			subStack1ParamStack = {};
			subStack2ParamStack = {};
			subStack3ParamStack = {};
			subStack1 = stack1;
			subStack2 = {};
			subStack3 = {};
			-- Drop subsortintervals. Instead we sort every time, and add weights that are spaced 205^i such that sorting by weights will sort all layers correctly. Reset the Weights every call at the very first thing in the loop.
			repeat
				if((input == "N/A" or input == nil or input == "") and i == 0) then 
					--iStableMaster:Print("|cc224488f DEBUG: |fffffff"..""); 
					--iStableMaster:Print("|cc884422f DEBUG: |ccfffffff".." "..(input or ""));
					break end;
				if(i == 0 and input ~= "N/A" and input ~= nil and input ~= "") then --search function here

					subStack1 = stack1;
					for j = 1,#subStack1  do 
						if(string.find(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["name"],input) ~= nil) then
							subStack1ParamStack[#subStack1ParamStack+1] = select(1,string.find(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["name"],input));
							--print("Name: "..iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["name"].." Score: "..subStack1ParamStack[#subStack1ParamStack].." Input: "..input);
							subStack2ParamStack[#subStack2ParamStack+1] = select(2,string.find(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["name"],input)) - select(1,string.find(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["name"],input));
							subStack2[#subStack2+1] = subStack1[j];
						elseif(string.find(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["name"],input) == nil) then
							subStack3[#subStack3+1] = subStack1[j];
						end
					end
					subStack2, subStack1ParamStack = iStableMaster:BubbleSortTableAndParamtableByParamtable(subStack2,subStack1ParamStack,-1);
					for j = 1, #subStack2 do
						-- print("Name: "..iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack2[j]]["PetInfo"]["name"].." Score: "..subStack1ParamStack[j]);
					end
					for j = 1, #subStack3 do
						if(#subStack1ParamStack == 0) then 
							-- print("Name: "..iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack3[j]]["PetInfo"]["name"].." Score: "..1);
						else 
							-- print("Name: "..iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack3[j]]["PetInfo"]["name"].." Score: "..(subStack1ParamStack[1]+1));
						end
					end
					local WorstMachedCharPos = 1;
					for j = 1, #subStack2 do
						if ( WorstMachedCharPos <= subStack1ParamStack[j]) then 
							WorstMachedCharPos = subStack1ParamStack[j]+1
						end
						--	print("|cff4b705a Name: "..iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack2[j]]["PetInfo"]["name"].." Score: ".. subStack1ParamStack[j]);
					end

					for j = 1, #subStack3 do
						subStack2[#subStack2+1] = subStack3[j];
						subStack1ParamStack[#subStack1ParamStack+1] = WorstMachedCharPos;
					end 
					for j = 1,#subStack2 do
						--print("|cff4b705a Name: "..iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["name"].." Score: ".. subStack1ParamStack[j]);
					end
					subStack1, subStack1ParamStack = iStableMaster:BubbleSortTableAndParamtableByParamtable(subStack2,subStack1ParamStack,1);
					for j=1, #subStack1 do 
						--print("|cff4b705a Name: "..iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["name"].." Score: ".. subStack1ParamStack[j]);
					end
					for j=1, #subStack1 do  -- fill the parameters into the sortstacktrace using a look up function
						local temp = iStableMaster:FindValueFromKey(subStack1,SortStackTrace[j]["Index"]);  
						SortStackTrace[j][i] = subStack1ParamStack[temp]*-1;
					end
				end
				if( not iStableMaster:GetSortingValue("AnySort")) then --this is where we sort stack 1 and ofc wipe stack2 at the end if its been used. The sorting parameters can be one of many
					break;
				else
					if(i == 1) then 
						if DebugMessageLimiter == 1 then 
							--iStableMaster:Print("|cfff88c00Attention:|cffffffff Sorting is still in development, and not everything is working as intended. It is also reccomended that you clear your saved variables in: |cc00ff00f".." 'World of Warcraft\\_retail_\\WTF\\Account\\{accountnumber}\\SavedVariables\\iStableMaster.lua' ".."|cffffffff For the best results.");
						end
					end
				end
				if(i~=0) then
					subStack1 = stack1;
					if type(iStableMaster:GetSortPriority(1,2,3)) == "boolean" then
						break;
					end
					if sortpriority[i] == "Expansion" then
						for j=1,#stack1 do
							if(iStableMaster:GetSortDirection("Expansion")>0) then -- I wonder why not just use sorting direction as the value why the logic ... is it due to possibility of 0? it should not matter considder this instead: SortStackTrace[j][i] = iStableMaster:GetExpansionValue(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[j]]["PetInfo"]["family"]) * iStableMaster:GetSortDirection("Expansion");
								SortStackTrace[j][i] = iStableMaster:GetExpansionValue(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[j]]["PetInfo"]["family"])
							else
								SortStackTrace[j][i] = iStableMaster:GetExpansionValue(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[j]]["PetInfo"]["family"]) *-1;
							end
						end		
					elseif sortpriority[i] == "Specialization" then
						for j = 1,#subStack1  do 
							subStack1ParamStack[#subStack1ParamStack+1] = iStableMaster:GetSortingValue("Specialization",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["talent"]);
							subStack2[#subStack2+1] = subStack1[j];
						end
						subStack1 = {};
						subStack1, subStack1ParamStack = iStableMaster:BubbleSortTableAndParamtableByParamtable(subStack2,subStack1ParamStack,iStableMaster:GetSortingValue("Specialization","Direction"));
						for j=1, #subStack1 do  -- fill the parameters into the sortstacktrace using a look up function
							local temp = iStableMaster:FindValueFromKey(subStack1,SortStackTrace[j]["Index"]);  
							SortStackTrace[j][i] = subStack1ParamStack[temp];
						end
					elseif sortpriority[i] == "Name" then
						-- name sorting here
						if(iStableMaster:GetSortingValue("Name") < 0) then
							subStack2, subStack2ParamStack = iStableMaster:NameSortAZ(subStack1);
						else
							subStack2, subStack2ParamStack = iStableMaster:NameSortZA(subStack1);
						end
						local equityCounter = 1;
						for j = 1,#subStack1  do 
							-- we need to look for equities and then add once we find a different value:
							if (subStack2ParamStack[j-1] == subStack2ParamStack[j]) or (j == 1) then 
								subStack1ParamStack[#subStack1ParamStack+1] = equityCounter;
							else
								equityCounter = equityCounter+1;
								subStack1ParamStack[#subStack1ParamStack+1] = equityCounter;
							end
						end
						subStack1 = {};
						subStack1, subStack1ParamStack = iStableMaster:BubbleSortTableAndParamtableByParamtable(subStack2,subStack1ParamStack,-1);
						for j=1, #subStack1 do  -- fill the parameters into the sortstacktrace using a look up function

							local temp = iStableMaster:FindValueFromKey(subStack1,SortStackTrace[j]["Index"]);  
							SortStackTrace[j][i] = subStack1ParamStack[temp];
						end
						----------------------- end copied from search
					elseif sortpriority[i] == "Family" then 
						for j = 1,#subStack1 do 
							subStack1ParamStack[#subStack1ParamStack+1] = iStableMaster:GetSortingValue("Family",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["family"]) or -1;
							subStack2[#subStack2+1] = subStack1[j];
							if(iStableMaster:GetSortingValue("Family",iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["family"]) == nil) then 
								iStableMaster:Print("An Error has been spottet in your WTF folder: Please check the |cc00ff00f".." 'World of Warcraft\\_retail_\\WTF\\Account\\{accountnumber}\\SavedVariables\\iStableMaster.lua'".."|ccfffffff ".."while the game is closed and correct the family name for:"..iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"].name.." Or delete the file, but this will reset all your preferences too");
							end
						end
						subStack1 = {};
						subStack1, subStack1ParamStack = iStableMaster:BubbleSortTableAndParamtableByParamtable(subStack2,subStack1ParamStack,iStableMaster:GetSortingValue("Family","Direction"));
						for j=1, #subStack1 do  -- fill the parameters into the sortstacktrace using a look up function

							local temp = iStableMaster:FindValueFromKey(subStack1,SortStackTrace[j]["Index"]);  
							SortStackTrace[j][i] = subStack1ParamStack[temp]*-iStableMaster:GetSortingValue("Family","Direction");
						end
					elseif sortpriority[i] == "Diets" then						
						for j=1, #subStack1 do  -- fill the parameters into the sortstacktrace using a look up function
							local dietList = {GetStablePetFoodTypes(stack1[j])};
							local temp = iStableMaster:StringKeyTableLengthI(dietList); 
							SortStackTrace[j][i] = temp;
						end
					elseif sortpriority[i] == "Favourites" then
						for j = 1,#subStack1 do 	
							if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["favourite"]) then
								SortStackTrace[j][i] = 1;
							elseif(not iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["favourite"]) then					
								SortStackTrace[j][i] = 0;
							end	
						end
					elseif sortpriority[i] == "Exotic" then
						for j = 1,#subStack1 do 	
							if(iStableMaster:IsExotic(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["family"])) then
								SortStackTrace[j][i] = 1;
							elseif(false == iStableMaster:IsExotic(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..subStack1[j]]["PetInfo"]["family"])) then
								SortStackTrace[j][i] = 0;
							end	
						end	
					elseif sortpriority[i] == "Renamed" then
						for j = 1,#subStack1 do 	
							if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[j]]["PetInfo"]["name"] ~= iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[j]]["PetInfo"]["family"]) then
								SortStackTrace[j][i] = 1;
							elseif(false == iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[j]]["PetInfo"]["name"] ~= iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[j]]["PetInfo"]["family"]) then
								SortStackTrace[j][i] = 0;
							end	
						end
					elseif sortpriority[i] == "Rarity" then
						if DebugMessageLimiter == 1 then 
							iStableMaster:Print("|cfff88c00Attention:|cffffffff Sorting of "..sortpriority[i].." are not yet implemented");		
						end
					elseif sortpriority[i] == "ActiveSlots" then
						for j = 1,#subStack1 do
							if(stack1[j] <= GlobalActiveSlotLoopValue) then
								SortStackTrace[j][i] = 1;
							elseif(stack1[j] > GlobalActiveSlotLoopValue) then
								SortStackTrace[j][i] = 0;
							end	
						end
					elseif sortpriority[i] == "AnimalCompanion" then
						lTalents = {};
						local lConfigID = C_ClassTalents.GetActiveConfigID();
						local lConfigInfo = C_Traits.GetConfigInfo(lConfigID);
						local lTreeIDs = lConfigInfo["treeIDs"];
						for i = 1, #lTreeIDs do
							for _, lNodeID in pairs(C_Traits.GetTreeNodes(lTreeIDs[i])) do
								local lNodeInfo = C_Traits.GetNodeInfo(lConfigID, lNodeID);
								local activeEntry = lNodeInfo.activeEntry;
								local activeRank = lNodeInfo.activeRank;
								if ( activeEntry and activeRank > 0 ) then
									local activeEntryID = activeEntry.entryID;
									local lEntryInfo = C_Traits.GetEntryInfo(lConfigID,activeEntryID);
									local lDefinitionID = lEntryInfo["definitionID"];
									local lDefinitionInfo = C_Traits.GetDefinitionInfo(lDefinitionID);
									local spellID = lDefinitionInfo["spellID"];
									local spellName = GetSpellInfo(spellID);
									lTalents[spellName] = activeRank;
								end
							end
						end
						for j = 1,#subStack1 do 	
							local hasAnimalCompanionTalent  = iStableMaster:HasTalent("Animal Companion");
							if(stack1[j] == 6 and hasAnimalCompanionTalent == true and GlobalSpecialization == "Beast Mastery") then -- need to add condition that slot 6 is actually an animal companion slot!
								SortStackTrace[j][i] = 1;
							elseif(stack1[j] ~= 6 or (hasAnimalCompanionTalent ~= true or GlobalSpecialization ~= "Beast Mastery")) then
								SortStackTrace[j][i] = 0;
							end	
						end		
					end
				end
				-- This should take care of all iterations of Sort, as long as the SubStack 1 has been correctly set it should add the weights, here and then we sort the final thing based on the weights.
				if(subStack1 == {}) then 
					if DebugMessageLimiter == 1 then 
						iStableMaster:Print("|cc224488f DEBUG: ".."|ccff2222fWarning:|cffffffff There is no subStack1 Saved for layer: "..i);
					end
				else
				end
			until true; -- this runs just once.
			subStack8[i] = #subStack1;
			for j = 1, #subStack1 do
				if (input == nil or input == "" or input == "N/A" ) and i == 0 then
					tableOfStringsToPrint[i][j] = {[1]="Sort layer: "..i,[2]="PetSlot: "..j,[3]="value: "..0, [4] = i,[5]=j,[6]=0};
				elseif (not (input == nil or input == "" or input == "N/A" ) ) and i ~= 0 then
					tableOfStringsToPrint[i][j] = {[1]="Sort layer: "..i,[2]="PetSlot: "..iStableMaster:FindValueFromKey(subStack1,SortStackTrace[j]["Index"]),[3]="value: "..SortStackTrace[j][i], [4] = i,[5]=iStableMaster:FindValueFromKey(subStack1,SortStackTrace[j]["Index"]),[6]=SortStackTrace[j][i]};
				end
			end
			--SortStackTrace[j][i]										==> Values
			--SortStackTrace[j]["Index"]								==> Index of j in sorted stack
			--iStableMaster:FindValueFromKey(subStack1,SortStackTrace[j]["Index"]);	==> Value of subStack1[j]'s indexed PetSlot
		end ---- sort loop ending
		for i = 1, #subStack1 do
			stringOut[i] = {[0]={},[1]={},[2]={},[3]={},[4]={},[5]={},[6]={},[7]={}};
		end
		lcount = 0;
		for n = 0, 3 do
			for j = 0, 3 do
				for i = 1, #subStack1 do
					if (tableOfStringsToPrint[j][i] ~= nil) then
						if (tableOfStringsToPrint[j][i][5] == j) then		
							stringOut[i][n][1] = tableOfStringsToPrint[n][i][1]
							stringOut[i][n][2] = tableOfStringsToPrint[n][i][2]
							stringOut[i][n][3] = tableOfStringsToPrint[n][i][3]
							stringOut[i][n][4] = tableOfStringsToPrint[n][i][4]
							stringOut[i][n][5] = tableOfStringsToPrint[n][i][5]
							stringOut[i][n][6] = tableOfStringsToPrint[n][i][6]
							stringOut[i][n][7] = tableOfStringsToPrint[n][i][7]
							lcount = lcount+1;
						end
					end
				end
			end
		end
		for i = 1, #stringOut do
			for j=0,3 do
				if (stringOut[i][j][1] ~= nil) then
					--print(stringOut[i][j][1],"\n",stringOut[i][j][2],stringOut[i][j][3])
				end
			end
		end
		--- new atttempt of a column by sort iteration to rows of index print table print to console stack
		iColoumnByjRows = {};	
		for j = 1, iStableMaster:StringKeyTableLengthI(subStack1) do
			iColoumnByjRows[j] = {};
			if(tableOfStringsToPrint[0][j] ~= nil) then
				iColoumnByjRows[j][0] = tableOfStringsToPrint[0][j];
			else
				iColoumnByjRows[j][0] = {}
				iColoumnByjRows[j][0][1] = "N/A";
			end
			if(tableOfStringsToPrint[1][j] ~= nil) then
				iColoumnByjRows[j][1] = tableOfStringsToPrint[1][j];
			else
				iColoumnByjRows[j][1] = {}
				iColoumnByjRows[j][1][1] = "N/A";
			end
			if(tableOfStringsToPrint[2][j] ~= nil) then
				iColoumnByjRows[j][2] = tableOfStringsToPrint[2][j];
			else
				iColoumnByjRows[j][2] = {}
				iColoumnByjRows[j][2][1] = "N/A";
			end
			if(tableOfStringsToPrint[3][j] ~= nil) then
				iColoumnByjRows[j][3] = tableOfStringsToPrint[3][j];
			else
				iColoumnByjRows[j][3] = {}
				iColoumnByjRows[j][3][1] = "N/A";
			end
		end
		printTostack = {};
		printTostack = iStableMaster:BubbleSortBySeveralParameters(stack1,SortStackTrace,1);
		stack1 = {};
		stack1 = printTostack;
		local maxSizeY = ((#stack1)*(iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"]+4));
		iStableMaster.ScrollFrameArrElem["ScrollElement0"]:SetSize((StablesRightFrame.ScrollFrame:GetWidth()),maxSizeY);		
	end
	-- sort end
	
	-- join stacks
	local numberOfVisibleElements = #stack1;
	do
		if(flip)then -- add empty either at top or bottom
			for i = 1,#stack1 do -- Add the filtered and sorted elements to the Empty stack
				stack0[#stack0+1] = stack1[i];
			end
			for i = 1, #stack0 do
				stack2[#stack2+1] = stack0[i];
			end
		else

			for i = 1, #stack0 do -- Add the Empty to the filtered and sorted elements stack
				stack1[#stack1+1] = stack0[i];
				iStableMaster.ScrollFrameArrElem["ScrollElement"..stack0[i]]:Hide();
			end
			for i = 1, #stack1 do
				stack2[#stack2+1] = stack1[i];
				_G["ScrollElement"..i]:Hide(); -- the frame elements get generated twice, this line removes the duplicates that screw with the scroll frame size!
			end
		end
		for i = 1, #stack3 do -- Join the outfiltered and hidden elements with the visible and sorted stack
			iStableMaster.ScrollFrameArrElem["ScrollElement"..stack3[i]]:Hide();
		end
	end
	--join stacks end

	--MoveAllElements Into Place
	do
		local hasTalent = iStableMaster:HasTalent("Animal Companion");
		local animalCompanionAtTop = false
		local animalCompanionAtBottom = false
		local activeSlotsAtTop = false
		local activeSlotsAtBottom = false;
		local numOfAvailableActiveSlots = iStableMaster:HowManyCallPets();
		local seen = 0;
		local checkLocigDebug = false; -- Set to true if bugs with missing labels in the separator to debug

		for i = 1, #stack1 do
			-- we check for out filtered active pets and reduce the numOfAvailableActiveSlots based on this
			if (iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["Slot"] < numOfAvailableActiveSlots+1 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack1[i]]["PetInfo"]["name"] ~= "N/A") then
				seen = seen + 1;
				--print(seen);
			end
			if(seen == numOfAvailableActiveSlots) then
				break;
			end
		end
		numOfAvailableActiveSlots = seen;
		for i = 1, #stack2 do
			local j = stack2[i];
			if(j ~= nil) then
				if(i == 1) then
					k = ElementSizeY*(i-1);
				else
					k = ElementSizeY*(i-1);
				end
				if(iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:IsVisible()) then 
					if i == 1 and j == 6 and hasTalent then 
						animalCompanionAtTop = true;
					end
					if i == 1 and j == 1 and hasTalent then 
						animalCompanionAtBottom = true;
					end
					if(not hasTalent) then
						animalCompanionAtBottom = false;
						animalCompanionAtTop = false;
					end
					if i < numOfAvailableActiveSlots+1 and j < numOfAvailableActiveSlots+1 then
						activeSlotsAtTop = true;
					end
					if j < numOfAvailableActiveSlots+1 and i > numOfAvailableActiveSlots+1 then 
						activeSlotsAtTop = false;			
					end
					if  i <= numOfAvailableActiveSlots+1 and j <= numOfAvailableActiveSlots+1 and hasTalent then
						activeSlotsAtBottom = true;
					end
					if i > numOfAvailableActiveSlots+1 and j < numOfAvailableActiveSlots+1 then 
						activeSlotsAtBottom = false;
					end
					if numOfAvailableActiveSlots == 1 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[1]]["PetInfo"]["Slot"] ~= 6 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[1]]["PetInfo"]["Slot"] < 6 then
						activeSlotsAtTop = true;
						if hasTalent then 
							animalCompanionAtBottom = true;
						end
					elseif numOfAvailableActiveSlots == 1 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[1]]["PetInfo"]["Slot"] == 6 then
						activeSlotsAtBottom = true;
						if hasTalent then 
							animalCompanionAtTop = true;
						end
					end
					if numOfAvailableActiveSlots == 1 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[1]]["PetInfo"]["Slot"] == 6 
						and  numOfAvailableActiveSlots == 1 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[2]]["PetInfo"]["Slot"] <= 5 then
							animalCompanionAtTop = true;			
							activeSlotsAtBottom = true;
							activeSlotsAtTop = true;
							animalCompanionAtBottom = false;

						elseif numOfAvailableActiveSlots == 1 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[1]]["PetInfo"]["Slot"] == 6 
							and numOfAvailableActiveSlots == 1 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[2]]["PetInfo"]["Slot"] > 6 then
								animalCompanionAtTop = true;			
								activeSlotsAtBottom = false;
								activeSlotsAtTop = false;
								animalCompanionAtBottom = false;
						elseif numOfAvailableActiveSlots == 2 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[1]]["PetInfo"]["Slot"] == 6 
							and numOfAvailableActiveSlots == 2 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[2]]["PetInfo"]["Slot"] <= 5
								and numOfAvailableActiveSlots == 2 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[3]]["PetInfo"]["Slot"] <= 5 then
									animalCompanionAtTop = true;			
									activeSlotsAtBottom = false;
									activeSlotsAtTop = true;
									animalCompanionAtBottom = false;
						elseif numOfAvailableActiveSlots == 2 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[1]]["PetInfo"]["Slot"] == 6 
							and numOfAvailableActiveSlots == 2 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[2]]["PetInfo"]["Slot"] > 6
								and numOfAvailableActiveSlots == 2 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..stack2[3]]["PetInfo"]["Slot"] > 6 then
									animalCompanionAtTop = true;			
									activeSlotsAtBottom = false;
									activeSlotsAtTop = false;
									animalCompanionAtBottom = false;
						end


				end
			end
		end
		if(not iStableMaster.ScrollFrameArrElem["ScrollElement"..6]:IsVisible() ) then 
			animalCompanionAtBottom = false;
			animalCompanionAtTop = false;
		end
		--print("anTop:",animalCompanionAtTop,"anBot:",animalCompanionAtBottom,"actTop:",activeSlotsAtTop,"actBot:",activeSlotsAtBottom,"numOfCallPets: "..numOfAvailableActiveSlots)
		if iStableMaster.PetScrollFrameSeparator.first == nil then 
			iStableMaster.PetScrollFrameSeparator.first = iStableMaster.ScrollFrameArrElem["ScrollElement"..0]:CreateFontString(nil,"OVERLAY","GameFontNormal");
			iStableMaster.PetScrollFrameSeparator.first:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,0);
			iStableMaster.PetScrollFrameSeparator.first:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElement0"]:GetWidth(),16);
		end
		if iStableMaster.PetScrollFrameSeparator.second == nil then 
			iStableMaster.PetScrollFrameSeparator.second = iStableMaster.ScrollFrameArrElem["ScrollElement"..0]:CreateFontString(nil,"OVERLAY","GameFontNormal");
			iStableMaster.PetScrollFrameSeparator.second:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,0);
			iStableMaster.PetScrollFrameSeparator.second:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElement0"]:GetWidth(),16);
		end
		if iStableMaster.PetScrollFrameSeparator.third == nil then 
			iStableMaster.PetScrollFrameSeparator.third = iStableMaster.ScrollFrameArrElem["ScrollElement"..0]:CreateFontString(nil,"OVERLAY","GameFontNormal");
			iStableMaster.PetScrollFrameSeparator.third:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,0);
			iStableMaster.PetScrollFrameSeparator.third:SetSize(iStableMaster.ScrollFrameArrElem["ScrollElement0"]:GetWidth(),16);
		end
		iStableMaster.PetScrollFrameSeparator.first:SetText("");
		iStableMaster.PetScrollFrameSeparator.second:SetText("");
		iStableMaster.PetScrollFrameSeparator.third:SetText("");
		iStableMaster.PetScrollFrameSeparator.first:SetJustifyH("CENTER");
		iStableMaster.PetScrollFrameSeparator.second:SetJustifyH("CENTER");
		iStableMaster.PetScrollFrameSeparator.third:SetJustifyH("CENTER");
		-- if active top and AC top then first = Animal Companion
		if animalCompanionAtTop and activeSlotsAtTop then
			if(checkLocigDebug)then print("1"); end
			iStableMaster.PetScrollFrameSeparator.first:SetText("Animal Companion");
			-- Second = Active Slots
			iStableMaster.PetScrollFrameSeparator.second:SetText("Active Slots");
			iStableMaster.PetScrollFrameSeparator.second:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(2-1)-24);
			-- Third = Stable Slots
			iStableMaster.PetScrollFrameSeparator.third:SetText("Stable Slots");
			iStableMaster.PetScrollFrameSeparator.third:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(numOfAvailableActiveSlots+1)-48);
		end
		-- if active top and AC Bot then first = Active Slots
		-- Second = Animal Companion
		-- Third = Stable Slots
		-- if AC top and active Bot then first = Animal Companion
		-- Second = Active Slots
		-- Third = Stable Slots
		-- if AC top and Active neither then first = Animal Companion
		if animalCompanionAtTop and ( (not activeSlotsAtTop) and (not activeSlotsAtBot)) then
			iStableMaster.PetScrollFrameSeparator.first:SetText("Animal Companion");
			-- Second = Stable Slots
			iStableMaster.PetScrollFrameSeparator.second:SetText("Stable Slots");
			if(checkLocigDebug)then print("2"); end
			iStableMaster.PetScrollFrameSeparator.second:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(2-1)-24);
		end
		-- if animal companion is false in both, then it must be with the stable, and first must be stables
		if ((not animalCompanionAtTop) and (not animalCompanionAtBot) and activeSlotsAtBot) then
			iStableMaster.PetScrollFrameSeparator.first:SetText("Stable Slots");
			iStableMaster.PetScrollFrameSeparator.second:SetText("Active Slots");
			if(checkLocigDebug)then print("3"); end
			iStableMaster.PetScrollFrameSeparator.second:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(numberOfVisibleElements-numOfAvailableActiveSlots-1)-24);
		end
		if ((not animalCompanionAtTop) and (not animalCompanionAtBot) and activeSlotsAtTop and (not activeSlotsAtBot)) then
			iStableMaster.PetScrollFrameSeparator.first:SetText("Active Slots");
			iStableMaster.PetScrollFrameSeparator.second:SetText("Stable Slots");
			if(checkLocigDebug)then print("4"); end
			iStableMaster.PetScrollFrameSeparator.second:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(numOfAvailableActiveSlots)-24);
		end
		if (not animalCompanionAtTop and not animalCompanionAtBot and not activeSlotsAtTop and not activeSlotsAtBot ) then
			if(iStableMaster:GetFilterValue("ActiveSlots")) then
				iStableMaster.PetScrollFrameSeparator.first:SetText("Active and Stabled Slots");
			else
				iStableMaster.PetScrollFrameSeparator.first:SetText("Stabled Slots");
			end
			if(checkLocigDebug)then print("5"); end
		end
		if animalCompanionAtBottom and activeSlotsAtTop and not animalCompanionAtTop and not activeSlotsAtBottom then
			iStableMaster.PetScrollFrameSeparator.first:SetText("Active Slots");	
			-- Second = Active Slots
			iStableMaster.PetScrollFrameSeparator.second:SetText("Animal Companion");
			iStableMaster.PetScrollFrameSeparator.second:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(2-1)-24);
			-- Third = Stable Slots
			iStableMaster.PetScrollFrameSeparator.third:SetText("Stable Slots");
			iStableMaster.PetScrollFrameSeparator.third:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(numOfAvailableActiveSlots+1)-48);
			if(checkLocigDebug)then print("6"); end
		elseif ( animalCompanionAtTop == false and animalCompanionAtBottom and activeSlotsAtTop and activeSlotsAtBottom and iStableMaster:GetSortingValue("AnySort") == false ) then
			iStableMaster.PetScrollFrameSeparator.first:SetText("Active Slots");
			-- Second = Active Slots
			iStableMaster.PetScrollFrameSeparator.second:SetText("Animal Companion");
			iStableMaster.PetScrollFrameSeparator.second:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(numOfAvailableActiveSlots)-24);
			-- Third = Stable Slots
			iStableMaster.PetScrollFrameSeparator.third:SetText("Stable Slots");
			iStableMaster.PetScrollFrameSeparator.third:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(numOfAvailableActiveSlots+1)-48);
			if(checkLocigDebug)then print("7"); end
		end
		-- ANCHORS AND VISIBILITY should be handled by the same place as the spacing.
		for i = 1, #stack2 do
			local j = stack2[i];
			if(j ~= nil) then
				iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:ClearAllPoints();
				if(i == 1) then
					k = ElementSizeY*(i-1);
				else
					k = ElementSizeY*(i-1);
				end
				if(iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:IsVisible()) then
					if animalCompanionAtTop and activeSlotsAtBottom then
						if i == 1 then
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16);
							-- set "Animal Companion" label here and make it visible if hidden
							-- set "Active Pets" label here and make it visible if hidden
							-- set "Stabled Pets" label here and make it visible if hidden
						elseif i <= numOfAvailableActiveSlots+1 then
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-24);
						else
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-48)
						end
					elseif animalCompanionAtBottom and activeSlotsAtTop and not animalCompanionAtTop and not activeSlotsAtBottom then
						if i == 1 then
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16);
						elseif i == 2 then
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-(ElementSizeY*(numOfAvailableActiveSlots+1)));
						else
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-48)
						end
					elseif ( animalCompanionAtTop == false and animalCompanionAtBottom and activeSlotsAtTop and activeSlotsAtBottom and iStableMaster:GetSortingValue("AnySort") == false ) then
						if j < 6 then
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16);
						elseif j == 6 then
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-(ElementSizeY*(numOfAvailableActiveSlots+1)));
						else
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-48)
						end
					elseif animalCompanionAtBottom and activeSlotsAtTop then
						if j <= numOfAvailableActiveSlots then
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16);
						elseif j == numOfAvailableActiveSlots+1 then
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-24);
							-- set "Animal Companion" label here and make it visible if hidden
							if(hasTalent) then else end
							-- set "Active Pets" label here and make it visible if hidden
							-- set "Stabled Pets" label here and make it visible if hidden



						else
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-48)
						end
					elseif animalCompanionAtTop then
						if i == 1 then
							-- set "Animal Companion" label here and make it visible if hidden
							-- set "Active Pets" label here and make it visible if hidden
							-- set "Stabled Pets" label here and make it visible if hidden
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16);
						else
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-24)
						end
					elseif activeSlotsAtTop and (not animalCompanionAtTop) and (not animalCompanionAtBot)then
						if i <= numOfAvailableActiveSlots then
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16);
						else
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-24)
						end
					elseif activeSlotsAtTop then
						if i <= numOfAvailableActiveSlots+1 then
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16);
						else
							iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-24)
						end

					else
						iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16);
					end
					if(animalCompanionAtTop == true and			
						activeSlotsAtBottom == false and
							activeSlotsAtTop == true and
								animalCompanionAtBottom == false) then 

									iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:ClearAllPoints();
									if j == 6 then
										iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16);
									elseif j < 6 then
										iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-24)
									else
										iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint("TOPLEFT", iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT", 4,-ElementSizeY*(i-1)-16-48)
									end
								end
				else
					iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:Show();
					iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:SetPoint(point,iStableMaster.ScrollFrameArrElem["ScrollElement"..0],"TOPLEFT",0,0);
					iStableMaster.ScrollFrameArrElem["ScrollElement"..j]:Hide();
				end
			else
				-- do nothing
			end
		end
	end
	--MoveAllElements Into Place End

	local maxSizeY = ((numberOfVisibleElements)*(iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"]+4))-(((numberOfVisibleElements)-2)*4);
	local minSizeY = (iStableMaster.ScrollFrameArrElem["ScrollElementSizeY"]+4)*10;
	if(maxSizeY > minSizeY) then
		iStableMaster.ScrollFrameArrElem["ScrollElement0"]:SetSize((StablesRightFrame.ScrollFrame:GetWidth()),maxSizeY+8);
	end
	DebugMessageLimiter = DebugMessageLimiter+1;
	if DebugMessageLimiter > 6 then
		DebugMessageLimiter = 1;
	end
end-- The ultimate filtering and sorting algorithm for the AddOn. Should be made more "Generic"/dynamic such that it can be used on other things also, and doesn't "die" during a rework.
function iStableMaster:UpdateFilterSpecs(bool)
	if( iStableMaster:GetFilterValue("AnyFilter")) then
		--MoveHiddenSpecsToBottomOfScroll(bool);
		--HideNonFilterSpecs(bool);
		iStableMaster:MasterFilterSort("",not bool);


	end

end-- WE USE THIS ONE! We need to establish why they exist by name and aren't generic  That is this one and iStableMaster:UpdateFilterDiets
function iStableMaster:UpdateFilterDiets(bool)
	if( iStableMaster:GetFilterValue("AnyFilter")) then
		--MoveHiddenDietsToBottomOfScroll(bool);
		--HideNonFilterDiets(bool);
		iStableMaster:MasterFilterSort("",not bool);


	end

end-- PROBABLY WE ALSO USE THIS ONE!  We need to establish why they exist by name and aren't generic That is this one and iStableMaster:UpdateFilterSpecs
-------------------------------------------------------------------------------------


----------------------------------------------------
--           Crude String Sorting in use          --
----------------------------------------------------
function iStableMaster:NameSortAZ(tableIn)


	local inputstack = {};
	local l_tempStack = {}
	local l_names ={}
	--l_tempStack.length = iStableMaster:StringKeyTableLengthI(l_tempStack)+1;

	for j=1,#tableIn do
		inputstack[j] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..tableIn[j]]["PetInfo"]["name"];
		--print(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..tableIn[j]]["PetInfo"]["name"], j);
	end
	local unsafeSortedStack = iStableMaster:AlphabeticalSort(inputstack);
	for j=1,#tableIn do
		for jj=1,#tableIn do
			--print(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..tableIn[jj]]["PetInfo"]["name"], unsafeSortedStack[jj]);
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..tableIn[jj]]["PetInfo"]["name"] == unsafeSortedStack[j])then
				local seen = false;
				for k=1,#l_tempStack do 
					if l_tempStack[k] == tableIn[jj] then
						seen = true;
					end
				end
				if(seen == false) then 
					--print(jj,tableIn[jj]);
					l_tempStack[#l_tempStack+1] = tableIn[jj];
					--l_tempStack.length =l_tempStack.length.length +1;
					break;
				end
			end
		end
	end
	--for j=1,#l_tempStack do

	--print("Stak out: "..l_tempStack[j], "Unstable Sorted stack"..unsafeSortedStack[j]);
	--end
	for i=1,#l_tempStack do
		l_names[i] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..l_tempStack[i]]["PetInfo"]["name"];
		--print(l_names[i]);
	end


	return l_tempStack,l_names;
	--return unsafeSortedStack;
end
function iStableMaster:NameSortZA(tableIn)
	local inputstack = {};
	local l_tempStack = {};
	local l_names = {};
	--l_tempStack.length = iStableMaster:StringKeyTableLengthI(l_tempStack)+1;
	for j=#tableIn,1,-1 do

		inputstack[#inputstack+1] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..tableIn[j]]["PetInfo"]["name"];
		--print(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..tableIn[j]]["PetInfo"]["name"], j);
	end
	local unsafeSortedStack = iStableMaster:AlphabeticalSort(inputstack);
	for j=1,#tableIn do
		for jj=1,#tableIn do
			--print(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..tableIn[jj]]["PetInfo"]["name"], unsafeSortedStack[jj]);
			if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..tableIn[jj]]["PetInfo"]["name"] == unsafeSortedStack[j])then
				local seen = false;
				for k=1,#l_tempStack do 
					if l_tempStack[k] == tableIn[jj] then
						seen = true;
					end
				end
				if(seen == false) then 
					--print(jj,tableIn[jj]);
					l_tempStack[#l_tempStack+1] = tableIn[jj];
					--l_tempStack.length =l_tempStack.length.length +1;
					break;
				end
			end
		end
	end
	--for j=1,#l_tempStack do
	--print("Stak out: "..l_tempStack[j], "Unstable Sorted stack"..unsafeSortedStack[j]);
	--end
	local flipstack = {};
	for j=#l_tempStack,1,-1 do
		flipstack[#flipstack+1] = l_tempStack[j];
	end
	for i=1,#flipstack do
		l_names[i] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..flipstack[i]]["PetInfo"]["name"];
		--print(l_names[i]);
	end
	return flipstack, l_names;
	--return unsafeSortedStack;
end
function iStableMaster:AlphabeticalSort(input)
	local buffer = {}
	for i=1,#input do

		buffer[i] = input[i];
	end

	table.sort(buffer)
	return buffer;
	--print(table.concat(buffer));
end
----------------------------------------------------
--         Crude String Sorting in use END        --
----------------------------------------------------
--############################################################--
--		EVERYTHING SORTING AND FILTERING IMPLEMENTATION END   --
--############################################################--  



----------------------------------------------------
--    Sophisticated Generic Sorting functions     --
----------------------------------------------------
function iStableMaster:BubbleSortBySeveralParameters(TableToBeSorted,TraceTable,dir)

	l_TableToBeSorted = TableToBeSorted; 
	l_TraceTable = TraceTable;

	if dir == nil or 1 then 
		for i=1,#l_TableToBeSorted do
			for j=1,#l_TableToBeSorted-1 do
				--for i=1,iStableMaster:StringKeyTableLengthI(l_TableToBeSorted) do
				--	for j=1,iStableMaster:StringKeyTableLengthI(l_TableToBeSorted)-1 do			

				for k=0,3 do
					if l_TraceTable[j][k] == nil then
						l_TraceTable[j][k] = 0;

					end
					if l_TraceTable[j+1][k] == nil then
						l_TraceTable[j+1][k] = 0;

					end

				end

				--print("j="..j,"l_TraceTable["..j.."].0="..l_TraceTable[j][0],"l_TraceTable["..(j+1).."].0="..l_TraceTable[j+1][0]);
				--print("j="..j,"l_TraceTable["..j.."].1="..l_TraceTable[j][1],"l_TraceTable["..(j+1).."].1="..l_TraceTable[j+1][1]);
				--print("j="..j,"l_TraceTable["..j.."].2="..l_TraceTable[j][2],"l_TraceTable["..(j+1).."].2="..l_TraceTable[j+1][2]);
				--print("j="..j,"l_TraceTable["..j.."].3="..l_TraceTable[j][3],"l_TraceTable["..(j+1).."].3="..l_TraceTable[j+1][3]);


				local swap = {};
				if l_TraceTable[j][0] == l_TraceTable[j+1][0] then
					if l_TraceTable[j][1] == l_TraceTable[j+1][1] then
						if l_TraceTable[j][2] == l_TraceTable[j+1][2] then
							if l_TraceTable[j][3] == l_TraceTable[j+1][3] then
								swap = l_TraceTable[j];
								l_TraceTable[j] = l_TraceTable[j+1];
								l_TraceTable[j+1] = swap;
								l_TableToBeSorted[j] = l_TableToBeSorted[j+1]
								l_TableToBeSorted[j+1] = swap["Index"];

							elseif l_TraceTable[j][3] < l_TraceTable[j+1][3] then
								swap = l_TraceTable[j];
								l_TraceTable[j] = l_TraceTable[j+1];
								l_TraceTable[j+1] = swap;
								l_TableToBeSorted[j] = l_TableToBeSorted[j+1]
								l_TableToBeSorted[j+1] = swap["Index"];

							end
						elseif l_TraceTable[j][2] < l_TraceTable[j+1][2] then
							swap = l_TraceTable[j];
							l_TraceTable[j] = l_TraceTable[j+1];
							l_TraceTable[j+1] = swap;
							l_TableToBeSorted[j] = l_TableToBeSorted[j+1]
							l_TableToBeSorted[j+1] = swap["Index"];

						end
					elseif l_TraceTable[j][1] < l_TraceTable[j+1][1] then
						swap = l_TraceTable[j];
						l_TraceTable[j] = l_TraceTable[j+1];
						l_TraceTable[j+1] = swap;
						l_TableToBeSorted[j] = l_TableToBeSorted[j+1]
						l_TableToBeSorted[j+1] = swap["Index"];
					end
				elseif l_TraceTable[j][0] < l_TraceTable[j+1][0] then
					swap = l_TraceTable[j];
					l_TraceTable[j] = l_TraceTable[j+1];
					l_TraceTable[j+1] = swap;
					l_TableToBeSorted[j] = l_TableToBeSorted[j+1]
					--print(swap.Index);											
					l_TableToBeSorted[j+1] = swap["Index"];

				end

			end
		end
	else
		for i=1,#l_TableToBeSorted do
			for j=1,#l_TableToBeSorted-1 do 
				local swap = {};
				local swapIndex = {};
				if l_TraceTable[j][0] == l_TraceTable[j+1][0] then
					if l_TraceTable[j][1] == l_TraceTable[j+1][1] then
						if l_TraceTable[j][2] == l_TraceTable[j+1][2] then
							if l_TraceTable[j][3] == l_TraceTable[j+1][3] then
								swap = l_TraceTable[j];
								l_TraceTable[j] = l_TraceTable[j+1];
								l_TraceTable[j+1] = swap;
								l_TableToBeSorted[j] = l_TableToBeSorted[j+1]
								l_TableToBeSorted[j+1] = swap["Index"];

							elseif l_TraceTable[j][3] > l_TraceTable[j+1][3] then
								swap = l_TraceTable[j];
								l_TraceTable[j] = l_TraceTable[j+1];
								l_TraceTable[j+1] = swap;
								l_TableToBeSorted[j] = l_TableToBeSorted[j+1]
								l_TableToBeSorted[j+1] = swap["Index"];

							end
						elseif l_TraceTable[j][2] > l_TraceTable[j+1][2] then
							swap = l_TraceTable[j];
							l_TraceTable[j] = l_TraceTable[j+1];
							l_TraceTable[j+1] = swap;
							l_TableToBeSorted[j] = l_TableToBeSorted[j+1]
							l_TableToBeSorted[j+1] = swap["Index"];

						end
					elseif l_TraceTable[j][1] > l_TraceTable[j+1][1] then
						swap = l_TraceTable[j];
						l_TraceTable[j] = l_TraceTable[j+1];
						l_TraceTable[j+1] = swap;
						l_TableToBeSorted[j] = l_TableToBeSorted[j+1]
						l_TableToBeSorted[j+1] = swap["Index"];
					end
				elseif l_TraceTable[j][0] > l_TraceTable[j+1][0] then
					swap = l_TraceTable[j];
					l_TraceTable[j] = l_TraceTable[j+1];
					l_TraceTable[j+1] = swap;
					l_TableToBeSorted[j] = l_TableToBeSorted[j+1]
					l_TableToBeSorted[j+1] = swap["Index"];

				end


			end
		end

	end


	
	return l_TableToBeSorted;
end --KEY TO SORTING
function iStableMaster:BubbleSortTableAndParamtableByParamtable(tableToSort,equivalentParamTable,inverse) 
	if not #tableToSort == #equivalentParamTable then
		return;
	end
	local l_tableToSort = tableToSort;
	local l_equivalentParamTable = equivalentParamTable;
	--print(equivalentPramTable[1]);

	local flip = inverse;

	if flip == nil then
		inverse = 1;
	end
	
	
	if inverse > 0 then
		for i=1,#l_tableToSort do
			for j=1,#l_tableToSort-1 do 
				local swap;
				local swapE;
				--print("compare j: "..l_equivalentParamTable[j].." With j+1: ", l_equivalentParamTable[j+1]);
				if(l_equivalentParamTable[j] < l_equivalentParamTable[j+1]) then
					--swap
					swap = l_tableToSort[j];
					l_tableToSort[j] = l_tableToSort[j+1];
					l_tableToSort[j+1] = swap;



					swapE = l_equivalentParamTable[j];
					l_equivalentParamTable[j] = l_equivalentParamTable[j+1];
					l_equivalentParamTable[j+1] = swapE;





				end


			end


		end

	elseif inverse == nil or inverse < 0 then

		for i=1,#l_tableToSort do
			for j=1,#l_tableToSort-1 do 
				local swap;
				local swapE;
				--print("compare j: "..l_equivalentParamTable[j].." With j+1: ", l_equivalentParamTable[j+1]);
				if(l_equivalentParamTable[j] > l_equivalentParamTable[j+1]) then
					--swap
					swap = l_tableToSort[j];
					l_tableToSort[j] = l_tableToSort[j+1];
					l_tableToSort[j+1] = swap;



					swapE = l_equivalentParamTable[j];
					l_equivalentParamTable[j] = l_equivalentParamTable[j+1];
					l_equivalentParamTable[j+1] = swapE;





				end


			end


		end
	end
	for i=1,#l_tableToSort do
		--print("Params sorted: "..l_equivalentParamTable[i], "TableSorted: "..l_tableToSort[i]);
	end
	return l_tableToSort, l_equivalentParamTable;
end--KEY TO SORTING
-------------------------------------------------------
--	 Sophisticated Generic Sorting functions END	 --
-------------------------------------------------------

---------------------------------------------------------------------------------------------------- FILTER AND SORT FRONTEND IMPLEMENTATION SECTION ------------------------------------------------------------------------------------------

----------------------------------------
--	FILTER SORT IMPLEMENTATION BLOCK  --
----------------------------------------
-- FILTERS AND SORTS MAINFRAME HANDLERS
function iStableMaster:ToggleFiltersFrame() 
	if CardContainerFrame:IsShown() then
		CardContainerFrame:Hide();
		StablesFilterSortFrame:Show();
		if (CollectionsJournal:GetAttribute("UIPanelLayout-width") ~= 1000) and (iStableMasterOptionsDB.Layout == "Compact") then
			CollectionsJournal:SetAttribute("UIPanelLayout-width", 1000);
			CollectionsJournal:SetWidth(1000);
		else
			--nothing
		end
	else
		StablesFilterSortFrame:Hide();
		CardContainerFrame:Show();
		if (CollectionsJournal:GetAttribute("UIPanelLayout-width") == 1000) and (iStableMasterOptionsDB.Layout == "Compact") then
			CollectionsJournal:SetAttribute("UIPanelLayout-width", 720);
			CollectionsJournal:SetWidth(720);
		else
			--nothing
		end
	end
end
function iStableMaster:TempHideFiltersFrame() 
	if CardContainerFrame:IsShown() then
		CardContainerFrame:Hide();
		StablesFilterSortFrame:Show();
		if (CollectionsJournal:GetAttribute("UIPanelLayout-width") ~= 1000) and (iStableMasterOptionsDB.Layout == "Compact") then
			CollectionsJournal:SetAttribute("UIPanelLayout-width", 1000);
			CollectionsJournal:SetWidth(1000);
		else
			--nothing
		end
	else
		StablesFilterSortFrame:Hide();
		CardContainerFrame:Show();
		if (CollectionsJournal:GetAttribute("UIPanelLayout-width") == 1000) and (iStableMasterOptionsDB.Layout == "Compact") then
			CollectionsJournal:SetAttribute("UIPanelLayout-width", 720);
			CollectionsJournal:SetWidth(720);
		else
			--nothing
		end
	end
end
-- FILTERS AND SORTS INITIALIZATION AND IMPLEMENTATIONS
function iStableMaster:FilterSortFrameOnLoad()
	FilterScrollLoaded = false;
	-- FILTERS
	StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild = CreateFrame("Frame","$parentScrollChild",StablesFilterSortFrameFilterScrollFrame.FSScrollFrame, BackdropTemplateMixin and "BackdropTemplate");
	StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild:SetAllPoints();
	StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild:SetSize(200,200);
	--print(StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild:GetPoint());
	StablesFilterSortFrameFilterScrollFrame.FSScrollFrame:SetScrollChild(StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild);
	StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild:SetSize(StablesFilterSortFrameFilterScrollFrame.FSScrollFrame:GetWidth(),StablesFilterSortFrameFilterScrollFrame.FSScrollFrame:GetHeight());
	
	iStableMaster.filtertemplateinuse = "FilterButtonTemplate";
	if( iStableMasterOptionsDB.FilterSortTemplatesFilterScrollElements == "Default" or nil) then-- any setting that controls this in the options
		--iStableMaster.filtertemplateinuse = "IconFilterButtonTemplate";
		iStableMaster.filtertemplateinuse =	"IconWMFilterButtonTemplate"
	elseif(iStableMasterOptionsDB.FilterSortTemplatesFilterScrollElements == "Compact") then
		iStableMaster.filtertemplateinuse = "FilterButtonTemplate";
	end
	local indexList = {Family = 1,Specialization = 2,FamAbilities = 3,Diets = 4,Others = 5}
	

	-- FAMILY	
	iStableMaster:SetExpandableFilterButtonFamilies(indexList["Family"]);
	-- SPECIALIZATION					
	iStableMaster:SetExpandableFilterButtonSpecializations(indexList["Specialization"]);
	--FamilyAbilities:
	iStableMaster:SetExpandableFilterButtonFamilyAbilities(indexList["FamAbilities"]);
	-- DIETS	
	iStableMaster:SetExpandableFilterButtonDiets(indexList["Diets"]);
	-- OTHER:
	iStableMaster:SetExpandableFilterButtonOthers(indexList["Others"]);

	
	-- update the size of the scroll child based on the height of the elements expanded or not:
	iStableMaster:UpdateHeightFilterScrollFrameChild();
	-- Sets the On Load Value of the checkmarks:
	iStableMaster:CheckStatusOfAllFamilyFiltersCheckButton(indexList["Family"])
	iStableMaster:CheckStatusOfAllSpecsFiltersCheckButton(indexList["Specialization"])
	iStableMaster:CheckStatusOfAllFamilyAbilitiesFiltersCheckButton(indexList["FamAbilities"])
	iStableMaster:CheckStatusOfAllDietsFiltersCheckButton(indexList["Diets"])
	iStableMaster:CheckStatusOfAllOtherFiltersCheckButton(indexList["Others"])
	-- now its time to Set the Filters On/Off Button
	StablesFilterSortFrameFilterScrollFrameCheckbox:HookScript("OnClick", function() 
		StablesFilterSortFrameFilterScrollFrameCheckbox:SetChecked(not iStableMaster:GetFilterValue("AnyFilter"));
		iStableMaster:SetFilterValue("AnyFilter", not iStableMaster:GetFilterValue("AnyFilter"));
		iStableMaster:UpdateScrollListMainCall();
	end);
	-- set the On Load Value of the checkmark for Filters On/Off
	StablesFilterSortFrameFilterScrollFrameCheckbox:SetChecked(iStableMaster:GetFilterValue("AnyFilter"));
	-- SORTS
	StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild = CreateFrame("Frame","$parentScrollChild",StablesFilterSortFrameSortsScrollFrame.FSScrollFrame, BackdropTemplateMixin and "BackdropTemplate");
	StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild:SetAllPoints();
	StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild:SetSize(200,200);
	--print(StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild:GetPoint());
	StablesFilterSortFrameSortsScrollFrame.FSScrollFrame:SetScrollChild(StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild);
	StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild:SetSize(StablesFilterSortFrameSortsScrollFrame.FSScrollFrame:GetWidth(),StablesFilterSortFrameSortsScrollFrame.FSScrollFrame:GetHeight());
	SortsScrollElementsArr = {};
	-- Primary Sorts
	SortsScrollElementsArr[1] = CreateFrame("Frame","SortsScrollElementsNo"..1,StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild,"SortsScrollElementTemplate");
	SortsScrollElementsArr[1]:SetPoint("TOPLEFT",StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild,"TOPLEFT",0,0);
	PrimarySortElements = {};
	_G["SortsScrollElementsNo1HeaderExpandButton"].Text:SetText("Primary");
	for i=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do
		PrimarySortElements[i] = CreateFrame("Frame","PrimarySortsElement: "..i,SortsScrollElementsArr[1].Span,"SortsButtonTemplate");
		PrimarySortElements[i]:ClearAllPoints();
		-- we set the text here first for the selected sort option on the collapsable button header
		SortsScrollElementsArr[1].header.expandbtn.SelectedText:SetText("["..iStableMaster:SpaceAdderForString((iStableMasterDB.ActiveSorts.CurrentSort.primary or "none")).."]");
		SortsScrollElementsArr[1].header.expandbtn.SelectedText:SetTextColor(0,0.753,0);
		if i == 1 then
			PrimarySortElements[i]:SetPoint("TOPLEFT",SortsScrollElementsArr[1].Span,"TOPLEFT",0,-16);
			PrimarySortElements[i]:SetPoint("TOPRIGHT",SortsScrollElementsArr[1].Span,"TOPRIGHT",0,-16);
			PrimarySortElements[i]:SetPoint("BOTTOMRIGHT",SortsScrollElementsArr[1].Span,"TOPRIGHT",0,-48);
			PrimarySortElements[i]:SetHeight(32);
		else
			PrimarySortElements[i]:SetPoint("TOPLEFT",PrimarySortElements[i-1],"BOTTOMLEFT",0,-3);
			PrimarySortElements[i]:SetPoint("TOPRIGHT",PrimarySortElements[i-1],"BOTTOMRIGHT",0,-3);
			PrimarySortElements[i]:SetHeight(32);
		end
		PrimarySortElements[i]:SetBackdrop(nil);
		PrimarySortElements[i].FilterLabel:SetText(iStableMaster:SpaceAdderForString(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
		PrimarySortElements[i].FilterLabel:SetWidth(100-32);
		PrimarySortElements[i]:SetWidth(80);
		SortsScrollElementsArr[1].MaxHeight = ((3+PrimarySortElements[i]:GetHeight())*(i+2));
		SortsScrollElementsArr[1].Span:SetHeight(SortsScrollElementsArr[1].MaxHeight);
		_G["PrimarySortsElement: "..i.."Checkbox"]:SetChecked((iStableMasterDB.ActiveSorts.CurrentSort.primary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i])));
		_G["PrimarySortsElement: "..i.."Checkbox"]:HookScript("OnClick",function()
			-- we set the text here first for the selected sort option on the collapsable button header
			SortsScrollElementsArr[1].header.expandbtn.SelectedText:SetText("["..iStableMaster:SpaceAdderForString(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]).."]");
			for j=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do 
				if j~= i then
					_G["PrimarySortsElement: "..j.."Checkbox"]:SetChecked(false);
				else
					_G["PrimarySortsElement: "..j.."Checkbox"]:SetChecked(true);
				end
			end
			iStableMaster:SetSortPriority(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i],nil,nil)
			iStableMaster:UpdateScrollListMainCall();
		end);
		_G["PrimarySortsElement: "..i]:SetScript("OnMouseUp",function()
			-- we set the text here first for the selected sort option on the collapsable button header
			SortsScrollElementsArr[1].header.expandbtn.SelectedText:SetText("["..iStableMaster:SpaceAdderForString(iStableMaster:SpaceAdderForString(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i])).."]");
			for j=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do 									
				if j~= i then
					_G["PrimarySortsElement: "..j.."Checkbox"]:SetChecked(false);
				else
					_G["PrimarySortsElement: "..j.."Checkbox"]:SetChecked(true);
				end
			end
			iStableMaster:SetSortPriority(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i],nil,nil)
			iStableMaster:UpdateScrollListMainCall();
		end);
	end
	-- Secondary Sorts
	SortsScrollElementsArr[2] = CreateFrame("Frame","SortsScrollElementsNo"..2,StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild,"SortsScrollElementTemplate");
	SortsScrollElementsArr[2]:SetPoint("TOPLEFT",SortsScrollElementsArr[1],"BOTTOMLEFT",0,0);
	SortsScrollElementsArr[2]:SetPoint("TOPRIGHT",SortsScrollElementsArr[1],"BOTTOMRIGHT",0,-3);
	SecondarySortElements = {};
	_G["SortsScrollElementsNo2HeaderExpandButton"].Text:SetText("Secondary");
	for i=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do
		SecondarySortElements[i] = CreateFrame("Frame","SecondarySortsElement: "..i,SortsScrollElementsArr[2].Span,"SortsButtonTemplate");
		SecondarySortElements[i]:ClearAllPoints();
		-- we set the text here first for the selected sort option on the collapsable button header
		SortsScrollElementsArr[2].header.expandbtn.SelectedText:SetText("["..iStableMaster:SpaceAdderForString((iStableMasterDB.ActiveSorts.CurrentSort.secondary or "none")).."]");
		SortsScrollElementsArr[2].header.expandbtn.SelectedText:SetTextColor(0,0.753,0);
		if i == 1 then
			SecondarySortElements[i]:SetPoint("TOPLEFT",SortsScrollElementsArr[2].Span,"TOPLEFT",0,-16);
			SecondarySortElements[i]:SetPoint("TOPRIGHT",SortsScrollElementsArr[2].Span,"TOPRIGHT",0,-16);
			SecondarySortElements[i]:SetPoint("BOTTOMRIGHT",SortsScrollElementsArr[2].Span,"TOPRIGHT",0,-48);
			SecondarySortElements[i]:SetHeight(32);
		else
			SecondarySortElements[i]:SetPoint("TOPLEFT",SecondarySortElements[i-1],"BOTTOMLEFT",0,-3);
			SecondarySortElements[i]:SetPoint("TOPRIGHT",SecondarySortElements[i-1],"BOTTOMRIGHT",0,-3);
			SecondarySortElements[i]:SetHeight(32);
		end
		SecondarySortElements[i]:SetBackdrop(nil);
		SecondarySortElements[i].FilterLabel:SetText(iStableMaster:SpaceAdderForString(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
		SecondarySortElements[i].FilterLabel:SetWidth(100-32);
		SecondarySortElements[i]:SetWidth(80);
		SortsScrollElementsArr[2].MaxHeight = ((3+SecondarySortElements[i]:GetHeight())*(i+2));
		SortsScrollElementsArr[2].Span:SetHeight(SortsScrollElementsArr[2].MaxHeight);
		_G["SecondarySortsElement: "..i.."Checkbox"]:SetChecked((iStableMasterDB.ActiveSorts.CurrentSort.secondary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i])));
		_G["SecondarySortsElement: "..i.."Checkbox"]:HookScript("OnClick",function()
			-- we set the text here first for the selected sort option on the collapsable button header
			SortsScrollElementsArr[2].header.expandbtn.SelectedText:SetText("["..iStableMaster:SpaceAdderForString(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]).."]");
			for j=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do
				if j~= i then
					_G["SecondarySortsElement: "..j.."Checkbox"]:SetChecked(false);
				else
					_G["SecondarySortsElement: "..j.."Checkbox"]:SetChecked(true);
				end
			end
			iStableMaster:SetSortPriority(nil,iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i],nil)
			iStableMaster:UpdateScrollListMainCall();
		end);
		_G["SecondarySortsElement: "..i]:SetScript("OnMouseUp",function()
			-- we set the text here first for the selected sort option on the collapsable button header
			SortsScrollElementsArr[2].header.expandbtn.SelectedText:SetText("["..iStableMaster:SpaceAdderForString(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]).."]");
			for j=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do 
				if j~= i then
					_G["SecondarySortsElement: "..j.."Checkbox"]:SetChecked(false);
				else
					_G["SecondarySortsElement: "..j.."Checkbox"]:SetChecked(true);
				end
			end
			iStableMaster:SetSortPriority(nil,iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i],nil)
			iStableMaster:UpdateScrollListMainCall();
		end);
	end
	-- Tertiary Sorts
	SortsScrollElementsArr[3] = CreateFrame("Frame","SortsScrollElementsNo"..3,StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild,"SortsScrollElementTemplate");
	SortsScrollElementsArr[3]:SetPoint("TOPLEFT",SortsScrollElementsArr[2],"BOTTOMLEFT",0,0);
	SortsScrollElementsArr[3]:SetPoint("TOPRIGHT",SortsScrollElementsArr[2],"BOTTOMRIGHT",0,-3);
	TertiarySortElements = {};
	_G["SortsScrollElementsNo3HeaderExpandButton"].Text:SetText("Tertiary");
	for i=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do
		TertiarySortElements[i] = CreateFrame("Frame","TertiarySortsElement: "..i,SortsScrollElementsArr[3].Span,"SortsButtonTemplate");
		TertiarySortElements[i]:ClearAllPoints();
		-- we set the text here first for the selected sort option on the collapsable button header
		SortsScrollElementsArr[3].header.expandbtn.SelectedText:SetText("["..iStableMaster:SpaceAdderForString((iStableMasterDB.ActiveSorts.CurrentSort.tertiary or "none")).."]");
		SortsScrollElementsArr[3].header.expandbtn.SelectedText:SetTextColor(0,0.753,0);
		if i == 1 then
			TertiarySortElements[i]:SetPoint("TOPLEFT",SortsScrollElementsArr[3].Span,"TOPLEFT",0,-16);
			TertiarySortElements[i]:SetPoint("TOPRIGHT",SortsScrollElementsArr[3].Span,"TOPRIGHT",0,-16);
			TertiarySortElements[i]:SetPoint("BOTTOMRIGHT",SortsScrollElementsArr[3].Span,"TOPRIGHT",0,-48);
			TertiarySortElements[i]:SetHeight(32);
		else
			TertiarySortElements[i]:SetPoint("TOPLEFT",TertiarySortElements[i-1],"BOTTOMLEFT",0,-3);
			TertiarySortElements[i]:SetPoint("TOPRIGHT",TertiarySortElements[i-1],"BOTTOMRIGHT",0,-3);
			TertiarySortElements[i]:SetHeight(32);
		end
		TertiarySortElements[i]:SetBackdrop(nil);
		TertiarySortElements[i].FilterLabel:SetText(iStableMaster:SpaceAdderForString(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
		TertiarySortElements[i].FilterLabel:SetWidth(100-32);
		TertiarySortElements[i]:SetWidth(80);
		SortsScrollElementsArr[3].MaxHeight = ((3+TertiarySortElements[i]:GetHeight())*(i+2));
		SortsScrollElementsArr[3].Span:SetHeight(SortsScrollElementsArr[3].MaxHeight);
		_G["TertiarySortsElement: "..i.."Checkbox"]:SetChecked((iStableMasterDB.ActiveSorts.CurrentSort.tertiary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i])));
		_G["TertiarySortsElement: "..i.."Checkbox"]:HookScript("OnClick",function()
			-- we set the text here first for the selected sort option on the collapsable button header
			SortsScrollElementsArr[3].header.expandbtn.SelectedText:SetText("["..iStableMaster:SpaceAdderForString(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]).."]");
			for j=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do 
				if j~= i then
					_G["TertiarySortsElement: "..j.."Checkbox"]:SetChecked(false);
				else
					_G["TertiarySortsElement: "..j.."Checkbox"]:SetChecked(true);
				end
			end
			iStableMaster:SetSortPriority(nil,nil,iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i])
			iStableMaster:UpdateScrollListMainCall();
		end);
		_G["TertiarySortsElement: "..i]:SetScript("OnMouseUp",function()
			-- we set the text here first for the selected sort option on the collapsable button header
			SortsScrollElementsArr[3].header.expandbtn.SelectedText:SetText("["..iStableMaster:SpaceAdderForString(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]).."]");
			for j=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do 
				if j~= i then
					_G["TertiarySortsElement: "..j.."Checkbox"]:SetChecked(false);
				else
					_G["TertiarySortsElement: "..j.."Checkbox"]:SetChecked(true);
				end
			end
			iStableMaster:SetSortPriority(nil,nil,iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i])
			iStableMaster:UpdateScrollListMainCall();
		end);					
	end
	-- update the size of the scroll child based on the height of the elements expanded or not:
	iStableMaster:UpdateHeightSortsScrollFrameChild();
	-- now its time to Set the Sorts On/Off Button
	StablesFilterSortFrameSortsScrollFrameCheckbox:HookScript("OnClick", function() 
		StablesFilterSortFrameSortsScrollFrameCheckbox:SetChecked(not iStableMaster:GetSortingValue("AnySort"));
		iStableMaster:SetSortingValue("AnySort", not iStableMaster:GetSortingValue("AnySort"));
		iStableMaster:UpdateScrollListMainCall();
	end);
	-- set the On Load Value of the checkmark for Filters On/Off
	StablesFilterSortFrameSortsScrollFrameCheckbox:SetChecked(iStableMaster:GetSortingValue("AnySort"));
	FilterScrollLoaded = true;
end
function iStableMaster:UpdateHeightFilterScrollFrameChild()
	-- First we initialize the required max heights to a single height
	-- We can help ourselves by doing this dynamically
	local accumulatedMaxHeight = 0;
	for i = 1, iStableMaster:StringKeyTableLengthI(iStableMaster.FilterScrollElementsArr) do
		accumulatedMaxHeight = accumulatedMaxHeight+iStableMaster.FilterScrollElementsArr[i].MaxHeight;
	end
	StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild:SetHeight(accumulatedMaxHeight);
	-- we can prep ourselves for the changing heights by doing the same to make this dynamic as well
	local accumulatedHeight = 0;
	for i = 1, iStableMaster:StringKeyTableLengthI(iStableMaster.FilterScrollElementsArr) do
		accumulatedHeight = accumulatedHeight+iStableMaster.FilterScrollElementsArr[i]:GetHeight();
	end
	-- then we loop over all the expandables to apply a height change when a change in height should happen on click
	for i=1,iStableMaster:StringKeyTableLengthI(iStableMaster.FilterScrollElementsArr) do				
		_G["FilterScrollElementsNo"..i.."HeaderExpandButton"]:HookScript("OnClick",
			function()
				StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild:SetHeight(accumulatedHeight);
				--StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild:SetHeight(iStableMaster.FilterScrollElementsArr[1]:GetHeight()+iStableMaster.FilterScrollElementsArr[2]:GetHeight()+iStableMaster.FilterScrollElementsArr[3]:GetHeight()+iStableMaster.FilterScrollElementsArr[4]:GetHeight());
			end);
	end
	-- after we set the onclick we want to make sure that it also resizes on time on load, so we do not have to click it first before the functionality kicks in
	StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild:SetHeight(accumulatedHeight);
end
function iStableMaster:UpdateHeightSortsScrollFrameChild()
	-- First we initialize the required max heights to a single height	
	-- We can help ourselves by doing this dynamically
	local accumulatedMaxHeight = 0;
	for i = 1, iStableMaster:StringKeyTableLengthI(SortsScrollElementsArr) do
		accumulatedMaxHeight = accumulatedMaxHeight+SortsScrollElementsArr[i].MaxHeight;
	end
	StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild:SetHeight(accumulatedMaxHeight);
	-- we can prep ourselves for the changing heights by doing the same to make this dynamic as well
	local accumulatedHeight = 0;
	for i = 1, iStableMaster:StringKeyTableLengthI(SortsScrollElementsArr) do
		accumulatedHeight = accumulatedHeight+SortsScrollElementsArr[i]:GetHeight();
	end
	-- then we loop over all the expandables to apply a height change when a change in height should happen on click
	for i=1,iStableMaster:StringKeyTableLengthI(SortsScrollElementsArr) do				
		_G["SortsScrollElementsNo"..i.."HeaderExpandButton"]:HookScript("OnClick",
			function() 
				StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild:SetHeight(accumulatedHeight);
			end);
	end
	-- after we set the onClick we want to make sure that it also resizes on time on load, so we do not have to click it first before the functionality kicks in
	StablesFilterSortFrameSortsScrollFrame.FSScrollFrame.scrollChild:SetHeight(accumulatedHeight);
end
function iStableMaster:SetAllFamilyFilters(boolean) 
	for i = 1, iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex) do
		if boolean == nil then
			iStableMaster:Print("WARNING:: A critical value has been detected aborting function to protect SavedVariables.");
			return;
		end
		iStableMaster:SetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[i],boolean);
		_G["FamilyFiltersElement: "..i.."Checkbox"]:SetChecked(boolean)
	end
	iStableMaster:UpdateScrollListMainCall();
end
function iStableMaster:SetAllSpecFilters(boolean)
	for i = 1, 3 do
		if boolean == nil then
			iStableMaster:Print("WARNING:: A critical value has been detected aborting function to protect SavedVariables.");
			return;
		end
		iStableMaster:SetFilterValue(tostring(select(2,GetSpecializationInfo(i, false , true))),boolean);
		_G["SpecializationFiltersElement: "..i.."Checkbox"]:SetChecked(boolean)
	end
	iStableMaster:UpdateScrollListMainCall();
end
function iStableMaster:SetAllDietsFilters(boolean)
	for i = 1, iStableMaster:StringKeyTableLengthI(listOfFoods) do
		if boolean == nil then
			iStableMaster:Print("WARNING:: A critical value has been detected aborting function to protect SavedVariables.");
			return;
		end
		iStableMaster:SetFilterValue(listOfFoods[i],boolean);
		_G["DietFiltersElement: "..i.."Checkbox"]:SetChecked(boolean)
	end
	iStableMaster:UpdateScrollListMainCall();
end
function iStableMaster:SetAllFamilyAbilitiesFilters(boolean) 
	for i = 1, iStableMaster:StringKeyTableLengthI(iStableMaster.listOfFamilyAbilityTypes) do
		if boolean == nil then
			iStableMaster:Print("WARNING:: A critical value has been detected aborting function to protect SavedVariables.");
			return;
		end
		iStableMaster:SetFilterValue(iStableMaster.listOfFamilyAbilityTypes[i],boolean);
		_G["FamilyAbilitiesFiltersElement: "..i.."Checkbox"]:SetChecked(boolean)
	end
	iStableMaster:UpdateScrollListMainCall();
end
function iStableMaster:SetAllOtherFilters(boolean) 
	for i = 1, iStableMaster:StringKeyTableLengthI(listOfOthers) do
		if boolean == nil then
			iStableMaster:Print("WARNING:: A critical value has been detected aborting function to protect SavedVariables.");
			return;
		end
		iStableMaster:SetFilterValue(listOfOthers[i],boolean);
		_G["OtherFiltersElement: "..i.."Checkbox"]:SetChecked(boolean)
	end
	iStableMaster:UpdateScrollListMainCall();
end
function iStableMaster:CheckStatusOfAllFamilyFiltersCheckButton(index)
	
	if(_G["FilterScrollElementsNo"..index]:IsVisible() ~= true and FilterScrollLoaded) then
		return;
	end 
	local trend = iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[1]))
	for i = 2, iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex) do
		if(iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[i])) ~= trend) then
			_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:SetChecked(false);
			return;
		end
	end
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:SetChecked(trend);
	--print(trend);
end
function iStableMaster:CheckStatusOfAllSpecsFiltersCheckButton(index)
	if(_G["FilterScrollElementsNo"..index]:IsVisible() ~= true and FilterScrollLoaded) then
		return;
	end 
	local trend = iStableMaster:GetFilterValue(tostring(select(2,GetSpecializationInfo(1, false , true))))
	for i = 2, 3 do
		if(iStableMaster:GetFilterValue(tostring(select(2,GetSpecializationInfo(i, false , true)))) ~= trend) then
			_G["FilterScrollElementsNo2HeaderExpandButton"].CheckBox:SetChecked(false);
			return;
		end
	end
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:SetChecked(trend);
	--print(trend);
end
function iStableMaster:CheckStatusOfAllDietsFiltersCheckButton(index)
	if(_G["FilterScrollElementsNo"..index]:IsVisible() ~= true and FilterScrollLoaded) then
		return;
	end 
	local trend = iStableMaster:GetFilterValue(tostring(listOfFoods[1]))
	for i = 2, iStableMaster:StringKeyTableLengthI(listOfFoods) do
		if(iStableMaster:GetFilterValue(tostring(listOfFoods[i])) ~= trend) then
			_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:SetChecked(false);
			return;
		end
	end
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:SetChecked(trend);
	--print(trend);
end
function iStableMaster:CheckStatusOfAllFamilyAbilitiesFiltersCheckButton(index)
	if(_G["FilterScrollElementsNo"..index]:IsVisible() ~= true and FilterScrollLoaded) then
		return;
	end 
	local trend = iStableMaster:GetFilterValue(tostring(iStableMaster.listOfFamilyAbilityTypes[1]))
	for i = 2, iStableMaster:StringKeyTableLengthI(iStableMaster.listOfFamilyAbilityTypes) do
		if(iStableMaster:GetFilterValue(tostring(iStableMaster.listOfFamilyAbilityTypes[i])) ~= trend) then
			_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:SetChecked(false);
			return;
		end
	end
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:SetChecked(trend);
	--print(trend);
end
function iStableMaster:CheckStatusOfAllOtherFiltersCheckButton(index)
	if(_G["FilterScrollElementsNo"..index]:IsVisible() ~= true and FilterScrollLoaded) then
		return;
	end 
	local trend = iStableMaster:GetFilterValue(tostring(listOfOthers[1]))
	for i = 2, iStableMaster:StringKeyTableLengthI(listOfOthers) do
		if(iStableMaster:GetFilterValue(tostring(listOfOthers[i])) ~= trend) then
			_G["FilterScrollElementsNo5HeaderExpandButton"].CheckBox:SetChecked(false);
			return;
		end
	end
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:SetChecked(trend);
	--print(trend);
end
function iStableMaster:CompleteFilterSearch(input) -- NOT COMPLETED YET
	local listOfPetSpecs = {"Ferocity","Tenacity","Cunning"};
	-- collapse all spans here
	-- NEXT we check which spans should expand:
	if(tContains(iStableMasterDB.PetFamilyNamesByIndex,input)) then 
		-- expand this span
	elseif(tContains(listOfFoods,input)) then 
		-- expand this span
	elseif(tContains(listOfPetSpecs,input)) then 
		-- expand this span
	elseif(tContains(listOfOther,input)) then 
		-- expand this span
	else
		-- in case the match is not exact we do a brute force search, before giving up:
		for i=1, iStableMaster:StringKeyTableLengthI(l_DB_Families) do
			-- We use a string.Find for each entry by i and checks if it has a match, and if it does we expand the span.
			-- Perhaps this is what should be done regardless of the elseif code above. Since we want to scroll to this filter.

		end
		
		for i=1, iStableMaster:StringKeyTableLengthI(listOfFoods) do


		end

		for i=1, iStableMaster:StringKeyTableLengthI(listOfPetSpecs) do


		end

		for i=1, iStableMaster:StringKeyTableLengthI(listOfOther) do


		end


	end
	
	

end
function iStableMaster:TestFilterTrend(input)
	if( type(input) == "string") then 
		t = {tostring(select(2,GetSpecializationInfo(1, false , true))),tostring(select(2,GetSpecializationInfo(2, false , true))),tostring(select(2,GetSpecializationInfo(3, false , true)))}
	else
		t = input
	end
	local trend = iStableMaster:GetFilterValue(tostring(t[1]))
	for i = 2, iStableMaster:StringKeyTableLengthI(t) do
		if(iStableMaster:GetFilterValue(tostring(t[i])) ~= trend) then
			return false;
		end
		return trend;
	end
end
function iStableMaster:FindKeyByTableAndValue(table,value)
	for k, v in pairs(table) do
		if(tContains(table,value)) then
			return table[k];
		end
	end
end
function iStableMaster:SetExpandableFilterButtonFamilies(index) 

	hooksecurefunc(iStableMaster,"UpdateScrollListMainCall",function() iStableMaster:CheckStatusOfAllFamilyFiltersCheckButton(index) end);
	iStableMaster.FilterScrollElementsArr[index] = CreateFrame("Frame","FilterScrollElementsNo"..index,StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild,"FilterScrollElementTemplate");
	if(index == 1) then 
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPLEFT",StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild,"TOPLEFT",0,0);
	else
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPLEFT",iStableMaster.FilterScrollElementsArr[index-1],"BOTTOMLEFT",0,0);
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPRIGHT",iStableMaster.FilterScrollElementsArr[index-1],"BOTTOMRIGHT",0,-3);
	end
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].Text:SetText("Families");
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked = iStableMaster:TestFilterTrend(iStableMasterDB.PetFamilyNamesByIndex);
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:SetChecked(_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked);
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:HookScript("OnClick",function()
		_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked = not _G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked;		
		iStableMaster:SetAllFamilyFilters(_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked)
	end);
	for i=1,iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex) do
		iStableMaster.FamilyFiltersElements[i] = CreateFrame("Frame","FamilyFiltersElement: "..i,iStableMaster.FilterScrollElementsArr[index].Span,iStableMaster.filtertemplateinuse);	
		iStableMaster.FamilyFiltersElements[i]:ClearAllPoints();
		if i == 1 then
			iStableMaster.FamilyFiltersElements[i]:SetPoint("TOPLEFT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPLEFT",0,-16);
			iStableMaster.FamilyFiltersElements[i]:SetPoint("TOPRIGHT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPRIGHT",0,-16);
			iStableMaster.FamilyFiltersElements[i]:SetPoint("BOTTOMRIGHT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPRIGHT",0,-48);
			iStableMaster.FamilyFiltersElements[i]:SetHeight(32);
		else
			iStableMaster.FamilyFiltersElements[i]:SetPoint("TOPLEFT",iStableMaster.FamilyFiltersElements[i-1],"BOTTOMLEFT",0,-3);
			iStableMaster.FamilyFiltersElements[i]:SetPoint("TOPRIGHT",iStableMaster.FamilyFiltersElements[i-1],"BOTTOMRIGHT",0,-3);
			iStableMaster.FamilyFiltersElements[i]:SetHeight(32);
		end
		iStableMaster.FamilyFiltersElements[i]:SetBackdrop(nil);
		iStableMaster.FamilyFiltersElements[i].FilterLabel:SetText(iStableMasterDB.PetFamilyNamesByIndex[i]);
		iStableMaster.FamilyFiltersElements[i].FilterLabel:SetWidth(100-32);
		iStableMaster.FamilyFiltersElements[i]:SetWidth(80);
		iStableMaster.FilterScrollElementsArr[index].MaxHeight = ((3+iStableMaster.FamilyFiltersElements[i]:GetHeight())*(i+2));
		iStableMaster.FilterScrollElementsArr[index].Span:SetHeight(iStableMaster.FilterScrollElementsArr[index].MaxHeight);
		_G["FamilyFiltersElement: "..i.."Checkbox"]:SetChecked(iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[i])));
		_G["FamilyFiltersElement: "..i.."Checkbox"]:HookScript("OnClick",function()
			_G["FamilyFiltersElement: "..i.."Checkbox"]:SetChecked(not iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[i])));
			iStableMaster:SetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[i],not iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[i])));
			iStableMaster:UpdateScrollListMainCall();
		end);
		_G["FamilyFiltersElement: "..i]:SetScript("OnMouseUp",function()
			_G["FamilyFiltersElement: "..i.."Checkbox"]:SetChecked(not iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[i])));
			iStableMaster:SetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[i],not iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[i])));
			iStableMaster:UpdateScrollListMainCall();
		end);
		if _G["FamilyFiltersElement: "..i].icon ~= nil then 
			_G["FamilyFiltersElement: "..i].icon:SetTexture(iStableMasterDB["FamilyIconsByFamilyID"][i]);
		end
	end
end
function iStableMaster:SetExpandableFilterButtonSpecializations(index)
	iStableMaster.FilterScrollElementsArr[index] = CreateFrame("Frame","FilterScrollElementsNo"..index,StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild,"FilterScrollElementTemplate");
	if(index == 1) then 
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPLEFT",StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild,"TOPLEFT",0,0);
	else
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPLEFT",iStableMaster.FilterScrollElementsArr[index-1],"BOTTOMLEFT",0,0);
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPRIGHT",iStableMaster.FilterScrollElementsArr[index-1],"BOTTOMRIGHT",0,-3);
	end
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].Text:SetText("Specializations");
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].Text:SetFontObject("GameFontNormalSmall");
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked = iStableMaster:TestFilterTrend("talents");
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:HookScript("OnClick",function()
		_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked = not _G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked;		
		iStableMaster:SetAllSpecFilters(_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked)
	end);
	for i=1,3 do
		iStableMaster.SpecializationFiltersElements[i] = CreateFrame("Frame","SpecializationFiltersElement: "..i,iStableMaster.FilterScrollElementsArr[index].Span,iStableMaster.filtertemplateinuse);	
		iStableMaster.SpecializationFiltersElements[i]:ClearAllPoints();
		if i == 1 then
			iStableMaster.SpecializationFiltersElements[i]:SetPoint("TOPLEFT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPLEFT",0,-16);
			iStableMaster.SpecializationFiltersElements[i]:SetPoint("TOPRIGHT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPRIGHT",0,-16);
			iStableMaster.SpecializationFiltersElements[i]:SetPoint("BOTTOMRIGHT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPRIGHT",0,-48);
			iStableMaster.SpecializationFiltersElements[i]:SetHeight(32);
		else
			iStableMaster.SpecializationFiltersElements[i]:SetPoint("TOPLEFT",iStableMaster.SpecializationFiltersElements[i-1],"BOTTOMLEFT",0,-3);
			iStableMaster.SpecializationFiltersElements[i]:SetPoint("TOPRIGHT",iStableMaster.SpecializationFiltersElements[i-1],"BOTTOMRIGHT",0,-3);
			iStableMaster.SpecializationFiltersElements[i]:SetHeight(32);
		end
		iStableMaster.SpecializationFiltersElements[i]:SetBackdrop(nil);
		iStableMaster.SpecializationFiltersElements[i].FilterLabel:SetText(select(2,GetSpecializationInfo(i, false , true)));
		iStableMaster.SpecializationFiltersElements[i].FilterLabel:SetWidth(100-32);
		iStableMaster.SpecializationFiltersElements[i]:SetWidth(80);
		iStableMaster.FilterScrollElementsArr[index].MaxHeight = ((3+iStableMaster.SpecializationFiltersElements[i]:GetHeight())*(i+2));
		iStableMaster.FilterScrollElementsArr[index].Span:SetHeight(iStableMaster.FilterScrollElementsArr[index].MaxHeight);
		_G["SpecializationFiltersElement: "..i.."Checkbox"]:SetChecked(iStableMaster:GetFilterValue(tostring(select(2,GetSpecializationInfo(i, false , true)))));
		_G["SpecializationFiltersElement: "..i.."Checkbox"]:HookScript("OnClick",function()
			_G["SpecializationFiltersElement: "..i.."Checkbox"]:SetChecked(not iStableMaster:GetFilterValue(tostring(select(2,GetSpecializationInfo(i, false , true)))));
			iStableMaster:SetFilterValue(tostring(select(2,GetSpecializationInfo(i, false , true))),not iStableMaster:GetFilterValue(tostring(select(2,GetSpecializationInfo(i, false , true)))));
			iStableMaster:UpdateScrollListMainCall();
		end);
		_G["SpecializationFiltersElement: "..i]:SetScript("OnMouseUp",function()
			_G["SpecializationFiltersElement: "..i.."Checkbox"]:SetChecked(not iStableMaster:GetFilterValue(tostring(select(2,GetSpecializationInfo(i, false , true)))));
			iStableMaster:SetFilterValue(tostring(select(2,GetSpecializationInfo(i, false , true))),not iStableMaster:GetFilterValue(tostring(select(2,GetSpecializationInfo(i, false , true)))));
			iStableMaster:UpdateScrollListMainCall();
		end);
		if _G["SpecializationFiltersElement: "..i].icon ~= nil then 
			_G["SpecializationFiltersElement: "..i].icon:SetTexture(select(4,GetSpecializationInfo(i,false,true)));
		end
	end
	hooksecurefunc(iStableMaster,"UpdateScrollListMainCall",function() iStableMaster:CheckStatusOfAllSpecsFiltersCheckButton(index) end);
end
function iStableMaster:SetExpandableFilterButtonDiets(index)
listOfFoods = {"Bread", "Cheese","Fish","Fruit","Fungus","Meat","Mechanical Bits","Raw Fish","Raw Meat"}		
	iStableMaster.FilterScrollElementsArr[index] = CreateFrame("Frame","FilterScrollElementsNo"..index,StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild,"FilterScrollElementTemplate");
	if(index == 1) then 
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPLEFT",StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild,"TOPLEFT",0,0);
	else
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPLEFT",iStableMaster.FilterScrollElementsArr[index-1],"BOTTOMLEFT",0,0);
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPRIGHT",iStableMaster.FilterScrollElementsArr[index-1],"BOTTOMRIGHT",0,-3);
	end
	
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].Text:SetText("Diet");
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked = iStableMaster:TestFilterTrend(listOfFoods);
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:HookScript("OnClick",function()
		_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked = not _G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked;		
		iStableMaster:SetAllDietsFilters(_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked)
	end);
	for i = 1,9 do
		iStableMaster.DietFiltersElements[i] = CreateFrame("Frame","DietFiltersElement: "..i,iStableMaster.FilterScrollElementsArr[index].Span,iStableMaster.filtertemplateinuse);	
		iStableMaster.DietFiltersElements[i]:ClearAllPoints();
		if i == 1 then
			iStableMaster.DietFiltersElements[i]:SetPoint("TOPLEFT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPLEFT",0,-16);
			iStableMaster.DietFiltersElements[i]:SetPoint("TOPRIGHT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPRIGHT",0,-16);
			iStableMaster.DietFiltersElements[i]:SetPoint("BOTTOMRIGHT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPRIGHT",0,-48);
			iStableMaster.DietFiltersElements[i]:SetHeight(32);
		else
			iStableMaster.DietFiltersElements[i]:SetPoint("TOPLEFT",iStableMaster.DietFiltersElements[i-1],"BOTTOMLEFT",0,-3);
			iStableMaster.DietFiltersElements[i]:SetPoint("TOPRIGHT",iStableMaster.DietFiltersElements[i-1],"BOTTOMRIGHT",0,-3);
			iStableMaster.DietFiltersElements[i]:SetHeight(32);
		end
		iStableMaster.DietFiltersElements[i]:SetBackdrop(nil);
		iStableMaster.DietFiltersElements[i].FilterLabel:SetText(listOfFoods[i]);
		iStableMaster.DietFiltersElements[i].FilterLabel:SetWidth(100-32);
		iStableMaster.DietFiltersElements[i]:SetWidth(80);
		iStableMaster.FilterScrollElementsArr[index].MaxHeight = ((3+iStableMaster.DietFiltersElements[i]:GetHeight())*(i+2));
		iStableMaster.FilterScrollElementsArr[index].Span:SetHeight(iStableMaster.FilterScrollElementsArr[index].MaxHeight);
		_G["DietFiltersElement: "..i.."Checkbox"]:SetChecked(iStableMaster:GetFilterValue(tostring(listOfFoods[i])));
		_G["DietFiltersElement: "..i.."Checkbox"]:HookScript("OnClick",function()
			_G["DietFiltersElement: "..i.."Checkbox"]:SetChecked(not iStableMaster:GetFilterValue(tostring(listOfFoods[i])));
			iStableMaster:SetFilterValue(listOfFoods[i],not iStableMaster:GetFilterValue(tostring(listOfFoods[i])));
			iStableMaster:UpdateScrollListMainCall();
		end);

		_G["DietFiltersElement: "..i]:SetScript("OnMouseUp",function()

			_G["DietFiltersElement: "..i.."Checkbox"]:SetChecked(not iStableMaster:GetFilterValue(tostring(listOfFoods[i])));
			iStableMaster:SetFilterValue(listOfFoods[i],not iStableMaster:GetFilterValue(tostring(listOfFoods[i])));
			iStableMaster:UpdateScrollListMainCall();
		end);
		if _G["DietFiltersElement: "..i].icon ~= nil then 
			_G["DietFiltersElement: "..i].icon:SetTexture(iStableMasterDB["DietIconsByIndex"][i]);
		end 

	end
	hooksecurefunc(iStableMaster,"UpdateScrollListMainCall",function() iStableMaster:CheckStatusOfAllDietsFiltersCheckButton(index) end);
end
function iStableMaster:SetExpandableFilterButtonFamilyAbilities(index)	
	local iStableMaster = iStableMaster or {}
	iStableMaster.listOfFamilyAbilityTypes = {"Defense","BonusFamilyAbilities","Trick"}
	iStableMaster.listOfFamilyAbilityTypeIcons = {132110,"communities-icon-addgroupplus",236202}
	
	iStableMaster.FilterScrollElementsArr[index] = CreateFrame("Frame","FilterScrollElementsNo"..index,StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild,"FilterScrollElementTemplate");
	if(index == 1) then 
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPLEFT",StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild,"TOPLEFT",0,0);
	else
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPLEFT",iStableMaster.FilterScrollElementsArr[index-1],"BOTTOMLEFT",0,0);
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPRIGHT",iStableMaster.FilterScrollElementsArr[index-1],"BOTTOMRIGHT",0,-3);
	end
	
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].Text:SetText("Ability Types");
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].Text:SetFontObject("GameFontNormalSmall");
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked = iStableMaster:TestFilterTrend(iStableMaster.listOfFamilyAbilityTypes);

	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:SetChecked(_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked);
	_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].CheckBox:HookScript("OnClick",function()
		_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked = not _G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked;		
		iStableMaster:SetAllFamilyAbilitiesFilters(_G["FilterScrollElementsNo"..index.."HeaderExpandButton"].checked)
	end);
	for i=1,iStableMaster:StringKeyTableLengthI(iStableMaster.listOfFamilyAbilityTypes) do
		iStableMaster.FamilyAbilitiesFiltersElements[i] = CreateFrame("Frame","FamilyAbilitiesFiltersElement: "..i,iStableMaster.FilterScrollElementsArr[index].Span,iStableMaster.filtertemplateinuse);	
		iStableMaster.FamilyAbilitiesFiltersElements[i]:ClearAllPoints();
		if i == 1 then
			iStableMaster.FamilyAbilitiesFiltersElements[i]:SetPoint("TOPLEFT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPLEFT",0,-16);
			iStableMaster.FamilyAbilitiesFiltersElements[i]:SetPoint("TOPRIGHT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPRIGHT",0,-16);
			iStableMaster.FamilyAbilitiesFiltersElements[i]:SetPoint("BOTTOMRIGHT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPRIGHT",0,-48);
			iStableMaster.FamilyAbilitiesFiltersElements[i]:SetHeight(32);
		else
			iStableMaster.FamilyAbilitiesFiltersElements[i]:SetPoint("TOPLEFT",iStableMaster.FamilyAbilitiesFiltersElements[i-1],"BOTTOMLEFT",0,-3);
			iStableMaster.FamilyAbilitiesFiltersElements[i]:SetPoint("TOPRIGHT",iStableMaster.FamilyAbilitiesFiltersElements[i-1],"BOTTOMRIGHT",0,-3);
			iStableMaster.FamilyAbilitiesFiltersElements[i]:SetHeight(32);
		end
		iStableMaster.FamilyAbilitiesFiltersElements[i]:SetBackdrop(nil);
		iStableMaster.FamilyAbilitiesFiltersElements[i].FilterLabel:SetText(iStableMaster:SpaceAdderForString(iStableMaster.listOfFamilyAbilityTypes[i]));
		iStableMaster.FamilyAbilitiesFiltersElements[i].FilterLabel:SetWidth(100-32);
		iStableMaster.FamilyAbilitiesFiltersElements[i]:SetWidth(80);
		iStableMaster.FilterScrollElementsArr[index].MaxHeight = ((3+iStableMaster.FamilyAbilitiesFiltersElements[i]:GetHeight())*(i+2));
		iStableMaster.FilterScrollElementsArr[index].Span:SetHeight(iStableMaster.FilterScrollElementsArr[index].MaxHeight);
		_G["FamilyAbilitiesFiltersElement: "..i.."Checkbox"]:SetChecked(iStableMaster:GetFilterValue(tostring(iStableMaster.listOfFamilyAbilityTypes[i])));
		_G["FamilyAbilitiesFiltersElement: "..i.."Checkbox"]:HookScript("OnClick",function()
			_G["FamilyAbilitiesFiltersElement: "..i.."Checkbox"]:SetChecked(not iStableMaster:GetFilterValue(tostring(iStableMaster.listOfFamilyAbilityTypes[i])));
			iStableMaster:SetFilterValue(iStableMaster.listOfFamilyAbilityTypes[i],not iStableMaster:GetFilterValue(tostring(iStableMaster.listOfFamilyAbilityTypes[i])));
			iStableMaster:UpdateScrollListMainCall();
		end);
		_G["FamilyAbilitiesFiltersElement: "..i]:SetScript("OnMouseUp",function()
			_G["FamilyAbilitiesFiltersElement: "..i.."Checkbox"]:SetChecked(not iStableMaster:GetFilterValue(tostring(iStableMaster.listOfFamilyAbilityTypes[i])));
			iStableMaster:SetFilterValue(iStableMaster.listOfFamilyAbilityTypes[i],not iStableMaster:GetFilterValue(tostring(iStableMaster.listOfFamilyAbilityTypes[i])));
			iStableMaster:UpdateScrollListMainCall();
		end);
		
		if _G["FamilyAbilitiesFiltersElement: "..i].icon ~= nil then 
			--print(type(iStableMaster.listOfFamilyAbilityTypeIcons[i]));
			if(type(iStableMaster.listOfFamilyAbilityTypeIcons[i]) == "number")then
				_G["FamilyAbilitiesFiltersElement: "..i].icon:SetTexture(iStableMaster.listOfFamilyAbilityTypeIcons[i]);
			else
				_G["FamilyAbilitiesFiltersElement: "..i].icon:SetAtlas(iStableMaster.listOfFamilyAbilityTypeIcons[i]);
			end
		end
	end
	hooksecurefunc(iStableMaster,"UpdateScrollListMainCall",function() iStableMaster:CheckStatusOfAllFamilyAbilitiesFiltersCheckButton(index) end);

end
function iStableMaster:SetExpandableFilterButtonOthers(index)
	listOfOthers = {"ActiveSlots","Named","Favourite", "Rarity", "Exotic"}
	iStableMaster.FilterScrollElementsArr[index] = CreateFrame("Frame","FilterScrollElementsNo"..index,StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild,"FilterScrollElementTemplate");
	if(index == 1) then 
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPLEFT",StablesFilterSortFrameFilterScrollFrame.FSScrollFrame.scrollChild,"TOPLEFT",0,0);
	else
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPLEFT",iStableMaster.FilterScrollElementsArr[index-1],"BOTTOMLEFT",0,0);
	iStableMaster.FilterScrollElementsArr[index]:SetPoint("TOPRIGHT",iStableMaster.FilterScrollElementsArr[index-1],"BOTTOMRIGHT",0,-3);
	end
	
	_G["FilterScrollElementsNo5HeaderExpandButton"].Text:SetText("Other");
	_G["FilterScrollElementsNo5HeaderExpandButton"].checked = iStableMaster:TestFilterTrend(listOfOthers);
	_G["FilterScrollElementsNo5HeaderExpandButton"].CheckBox:HookScript("OnClick",function()
		_G["FilterScrollElementsNo5HeaderExpandButton"].checked = not _G["FilterScrollElementsNo5HeaderExpandButton"].checked;		
		iStableMaster:SetAllOtherFilters(_G["FilterScrollElementsNo5HeaderExpandButton"].checked)
	end);
	for i = 1,#listOfOthers do
		iStableMaster.OtherFiltersElements[i] = CreateFrame("Frame","OtherFiltersElement: "..i,iStableMaster.FilterScrollElementsArr[index].Span,iStableMaster.filtertemplateinuse);	
		iStableMaster.OtherFiltersElements[i]:ClearAllPoints();
		if i == 1 then
			iStableMaster.OtherFiltersElements[i]:SetPoint("TOPLEFT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPLEFT",0,-16);
			iStableMaster.OtherFiltersElements[i]:SetPoint("TOPRIGHT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPRIGHT",0,-16);
			iStableMaster.OtherFiltersElements[i]:SetPoint("BOTTOMRIGHT",iStableMaster.FilterScrollElementsArr[index].Span,"TOPRIGHT",0,-48);
			iStableMaster.OtherFiltersElements[i]:SetHeight(32);
		else
			iStableMaster.OtherFiltersElements[i]:SetPoint("TOPLEFT",iStableMaster.OtherFiltersElements[i-1],"BOTTOMLEFT",0,-3);
			iStableMaster.OtherFiltersElements[i]:SetPoint("TOPRIGHT",iStableMaster.OtherFiltersElements[i-1],"BOTTOMRIGHT",0,-3);
			iStableMaster.OtherFiltersElements[i]:SetHeight(32);
		end
		iStableMaster.OtherFiltersElements[i]:SetBackdrop(nil);
		iStableMaster.OtherFiltersElements[i].FilterLabel:SetText(iStableMaster:SpaceAdderForString(listOfOthers[i]));
		iStableMaster.OtherFiltersElements[i].FilterLabel:SetWidth(100-32);
		iStableMaster.OtherFiltersElements[i]:SetWidth(80);
		iStableMaster.FilterScrollElementsArr[index].MaxHeight = ((3+iStableMaster.OtherFiltersElements[i]:GetHeight())*(i+2));
		iStableMaster.FilterScrollElementsArr[index].Span:SetHeight(iStableMaster.FilterScrollElementsArr[index].MaxHeight);
		_G["OtherFiltersElement: "..i.."Checkbox"]:SetChecked(iStableMaster:GetFilterValue(listOfOthers[i]));
		_G["OtherFiltersElement: "..i.."Checkbox"]:HookScript("OnClick",function()
			_G["OtherFiltersElement: "..i.."Checkbox"]:SetChecked(not iStableMaster:GetFilterValue(listOfOthers[i]));
			iStableMaster:SetFilterValue(listOfOthers[i],not iStableMaster:GetFilterValue(listOfOthers[i]));
			iStableMaster:UpdateScrollListMainCall();
		end);
		_G["OtherFiltersElement: "..i]:SetScript("OnMouseUp",function()
			_G["OtherFiltersElement: "..i.."Checkbox"]:SetChecked(not iStableMaster:GetFilterValue(tostring(listOfOthers[i])));
			iStableMaster:SetFilterValue(listOfOthers[i],not iStableMaster:GetFilterValue(tostring(listOfOthers[i])));
			iStableMaster:UpdateScrollListMainCall();
		end);
		if _G["OtherFiltersElement: "..i].icon ~= nil then 
			_G["OtherFiltersElement: "..i].icon:SetTexture(iStableMasterDB["OtherFilterIconsByIndex"][i]);
			if i ==4 then
				_G["OtherFiltersElement: "..i].icon:SetDesaturated(1)
				_G["OtherFiltersElement: "..i].icon:SetVertexColor(0.84,0.90,0.91,1);
				_G["OtherFiltersElement: "..i].icon:SetAlpha(1);
			end
		end
	end
hooksecurefunc(iStableMaster,"UpdateScrollListMainCall",function() iStableMaster:CheckStatusOfAllOtherFiltersCheckButton(index) end);
end
-------------------------------------------
--	FILTER SORT IMPLEMENTATION BLOCK END --
-------------------------------------------


----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------- END OF DOCUMENT ISH ------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------
-- DEPRECATED FUNCTIONS
-------------------------------------------------------------------------------
--#######################################
-------------------------------------------------------------------------------
-- DEPRECATED FUNCTIONS END
-------------------------------------------------------------------------------

-------------------------------------------------------------------------------- PARKED CODE CURRENTLY NOT IN USE BUT PLANNED TO RETURN ------------------------------------------------------------------------------------------
function StablesCollectionSortDropDown_Initialize(self, level)
	
	local info = UIDropDownMenu_CreateInfo();
	info.keepShownOnClick = true;	
	
	--	level = level or 1;
	
	--	if (level == 1) then
	--     for key, subarray in pairs(Test1_Data) do
	--       local info = UIDropDownMenu_CreateInfo();
	--       info.hasArrow = true; -- creates submenu
	--       info.notCheckable = true;
	--       info.text = key;
	--       info.value = {
	--         ["Level1_Key"] = key;
	--       };
	--       UIDropDownMenu_AddButton(info, level);
	--     end -- for key, subarray
	--   end -- if level 1

	--local fampagesnum = 1;
	--local famperpagesnum = 1;
	local nestingcheck = false;
	if(level ~= nil) then

		if(level > 1) then
			nestingcheck = (level == UIDROPDOWNMENU_MENU_VALUE["sublayer"] and UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 1);
			--print(nestingcheck,level, UIDROPDOWNMENU_MENU_VALUE["sublayer"], UIDROPDOWNMENU_MENU_VALUE["SubLevel"]);
		end
	end

	

	if level == 1 then
		

		info.text = "Sort ON/OFF";
		info.func = 	function(_, _, _, value)
			--C_PetJournal.SetFilterChecked(LE_PET_JOURNAL_FILTER_COLLECTED, value);
			iStableMaster:SetSortingValue("AnySort", value);
			iStableMaster:UpdateScrollListMainCall();

		end
		info.checked = iStableMaster:GetSortingValue("AnySort");--C_PetJournal.IsFilterChecked(LE_PET_JOURNAL_FILTER_COLLECTED);
		info.isNotRadio = true;
		UIDropDownMenu_AddButton(info, level);

		info.disabled = nil;

		--info.text = NOT_COLLECTED;
		--info.func = 	function(_, _, _, value)
		--					--C_PetJournal.SetFilterChecked(LE_PET_JOURNAL_FILTER_NOT_COLLECTED, value);
		--				end
		--info.checked = true;--C_PetJournal.IsFilterChecked(LE_PET_JOURNAL_FILTER_NOT_COLLECTED);
		--info.isNotRadio = true;
		--UIDropDownMenu_AddButton(info, level);

		info.checked = 	nil;
		info.isNotRadio = nil;
		info.func =  nil;
		info.hasArrow = true;
		info.notCheckable = true;

		info.text = "Primary Sort";
		info.value = {["SubLevel"] = 1, ["sublayer"] = 1};
		UIDropDownMenu_AddButton(info, level);

		info.text = "Secondary Sort";
		info.value = {["SubLevel"] = 2, ["sublayer"] = 1};
		UIDropDownMenu_AddButton(info, level);

		info.text = "Tertiary Sort";
		info.value = {["SubLevel"] = 3, ["sublayer"] = 1};
		UIDropDownMenu_AddButton(info, level);

	elseif (level == 2 or nestingcheck) then
		for i = 1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do
			local direction = " - Ascending";
			
			if UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 3 then
				info.checked = (iStableMasterDB.ActiveSorts.CurrentSort.tertiary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
				--info.func = UIDropDownMenu_Refresh(_G["DropDownList2Menu"],UIDROPDOWNMENU_MENU_VALUE,UIDROPDOWNMENU_MENU_VALUE["SubLevel"]);

				--for j=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do

				--	_G["DropDownList"..2 .."Button"..j].checked = false;

				--end


				
			elseif UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 2 then 
				info.checked = (iStableMasterDB.ActiveSorts.CurrentSort.secondary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
			elseif UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 1 then 
				info.checked = (iStableMasterDB.ActiveSorts.CurrentSort.primary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
			else
			end
			info.func = function(_, _, _, value) 
				local sortpriority = {};
				--	if type(iStableMaster:GetSortPriority(1,2,3)) == "table" then
				--		sortpriority = iStableMaster:GetSortPriority(1,2,3);
				--print(iStableMaster:GetSortPriority(1));
				--		elseif type(iStableMaster:GetSortPriority(1,2,3)) == "boolean" then 
				--print ("Bool DO SOMETHING!")
				--			sortpriority = {};


				if iStableMasterDB["ActiveSorts"]["CurrentSort"].primary == 0 then
					--						sortpriority[#sortpriority+1] = "ActiveSlots";
				else
					--						sortpriority[#sortpriority+1] = iStableMasterDB["ActiveSorts"]["CurrentSort"].primary;
				end

				if iStableMasterDB["ActiveSorts"]["CurrentSort"].secondary == 0 then
					--					sortpriority[#sortpriority+1] = "Family";
				else
					--					sortpriority[#sortpriority+1] = iStableMasterDB["ActiveSorts"]["CurrentSort"].secondary;

				end


				if(iStableMasterDB["ActiveSorts"]["CurrentSort"].tertiary == 0) then
					--				sortpriority[#sortpriority+1] = "Name";
				else
					--		sortpriority[#sortpriority+1] = iStableMasterDB["ActiveSorts"]["CurrentSort"].tertiary;
				end

				--	else

				--		end
				--print(type( iStableMaster:GetSortPriority(1,2,3) ), #sortpriority);
				--	print(sortpriority[1],sortpriority[2],sortpriority[3]);
				if(UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 1) then
					--	iStableMaster:SetSortPriority(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i],sortpriority[2],sortpriority[3]);
					iStableMaster:SetSortPriority(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i],nil,nil)
				elseif(UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 2)then
					--		iStableMaster:SetSortPriority(sortpriority[1],iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i],sortpriority[3]);
					iStableMaster:SetSortPriority(nil,iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i],nil)
				elseif(UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 3)then
					--		iStableMaster:SetSortPriority(sortpriority[1],sortpriority[2],iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]);
					iStableMaster:SetSortPriority(nil,nil,iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i])
				end
				


				iStableMaster:MasterFilterSort();
				--_G["DropDownList"..2]:Hide();


				--info.func = function(info) ---- this works but also mess up sorting!
				--			iStableMaster:SetSortDirection(iStableMasterDB["ActiveSorts"].ReverseLookUpIndex[i], iStableMaster:GetSortDirection(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i])*-1);
				--end

				info.isNotRadio = false;
				--iStableMaster:Print("|cc224488f DEBUG: |cffffffff".. iStableMaster:GetSortPriority(1,2,3)[UIDROPDOWNMENU_MENU_VALUE["SubLevel"]]);--iStableMaster:GetSortingValue(iStableMaster:GetSortPriority(UIDROPDOWNMENU_MENU_VALUE["SubLevel"])), "Comparing to:", iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]);

				--if iStableMaster:GetSortPriority(UIDROPDOWNMENU_MENU_VALUE["SubLevel"]) ~= "String" then
				--info.checked = false;
				--	else
				--info.func = iStableMaster:UpdateSortDropDownInfo(UIDROPDOWNMENU_MENU_VALUE,info);
				--for j=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do 
				--	if j == i then 
				if UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 3 then
					info.checked = (iStableMasterDB.ActiveSorts.CurrentSort.tertiary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
					--info.func = UIDropDownMenu_Refresh(_G["DropDownList2Menu"],UIDROPDOWNMENU_MENU_VALUE,UIDROPDOWNMENU_MENU_VALUE["SubLevel"]);
					


					

				elseif UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 2 then 
					info.checked = (iStableMasterDB.ActiveSorts.CurrentSort.secondary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
				elseif UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 1 then 
					info.checked = (iStableMasterDB.ActiveSorts.CurrentSort.primary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
				else
				end
				for j=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do
					if UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 1 then
						if((iStableMasterDB.ActiveSorts.CurrentSort.primary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][j]))) then 
							_G["DropDownList"..2 .."Button"..j.."Check"]:Show();
							_G["DropDownList"..2 .."Button"..j.."UnCheck"]:Hide();
						else
							_G["DropDownList"..2 .."Button"..j.."Check"]:Hide();
							_G["DropDownList"..2 .."Button"..j.."UnCheck"]:Show();
						end
					end
					
					if UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 2 then
						if((iStableMasterDB.ActiveSorts.CurrentSort.secondary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][j]))) then 
							_G["DropDownList"..2 .."Button"..j.."Check"]:Show();
							_G["DropDownList"..2 .."Button"..j.."UnCheck"]:Hide();
						else
							_G["DropDownList"..2 .."Button"..j.."Check"]:Hide();
							_G["DropDownList"..2 .."Button"..j.."UnCheck"]:Show();
						end
					end
					
					if UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 3 then
						if((iStableMasterDB.ActiveSorts.CurrentSort.tertiary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][j]))) then 
							_G["DropDownList"..2 .."Button"..j.."Check"]:Show();
							_G["DropDownList"..2 .."Button"..j.."UnCheck"]:Hide();
						else
							_G["DropDownList"..2 .."Button"..j.."Check"]:Hide();
							_G["DropDownList"..2 .."Button"..j.."UnCheck"]:Show();
						end
					end
				end
			end;

			--	end
			--end
			
			--info.checked = ((iStableMaster:GetSortPriority(1,2,3)[UIDROPDOWNMENU_MENU_VALUE["SubLevel"]]) == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
			--	end
			
			if iStableMaster:GetSortDirection(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]) == 0 then
				direction = " - No Direction";
			elseif(iStableMaster:GetSortDirection(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]) < 0) then
				direction = " - Descending";
			end
			info.text = iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]..direction;
			
			info.hasArrow = false;
			info.notCheckable = false;
			
			UIDropDownMenu_AddButton(info, level);
		end	
	end
end
function StablesCollectionFilterDropDown_Initialize(self, level)
	
	local info = UIDropDownMenu_CreateInfo();
	info.keepShownOnClick = true;	
	
	--	level = level or 1;
	
	--	if (level == 1) then
	--     for key, subarray in pairs(Test1_Data) do
	--       local info = UIDropDownMenu_CreateInfo();
	--       info.hasArrow = true; -- creates submenu
	--       info.notCheckable = true;
	--       info.text = key;
	--       info.value = {
	--         ["Level1_Key"] = key;
	--       };
	--       UIDropDownMenu_AddButton(info, level);
	--     end -- for key, subarray
	--   end -- if level 1

	--local fampagesnum = 1;
	--local famperpagesnum = 1;
	local nestingcheck = false;
	if(level ~= nil) then

		if(level > 1) then
			nestingcheck = (level == UIDROPDOWNMENU_MENU_VALUE["sublayer"] and UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 1);
			--print(nestingcheck,level, UIDROPDOWNMENU_MENU_VALUE["sublayer"], UIDROPDOWNMENU_MENU_VALUE["SubLevel"]);
		end
	end

	

	if level == 1 then
		

		info.text = "Filters ON/OFF";
		info.func = 	function(_, _, _, value)
			--C_PetJournal.SetFilterChecked(LE_PET_JOURNAL_FILTER_COLLECTED, value);
			iStableMaster:SetFilterValue("AnyFilter", value);
			iStableMaster:UpdateScrollListMainCall();

		end
		info.checked = iStableMaster:GetFilterValue("AnyFilter");--C_PetJournal.IsFilterChecked(LE_PET_JOURNAL_FILTER_COLLECTED);
		info.isNotRadio = true;
		UIDropDownMenu_AddButton(info, level);

		info.disabled = nil;

		--info.text = NOT_COLLECTED;
		--info.func = 	function(_, _, _, value)
		--					--C_PetJournal.SetFilterChecked(LE_PET_JOURNAL_FILTER_NOT_COLLECTED, value);
		--				end
		--info.checked = true;--C_PetJournal.IsFilterChecked(LE_PET_JOURNAL_FILTER_NOT_COLLECTED);
		--info.isNotRadio = true;
		--UIDropDownMenu_AddButton(info, level);

		info.checked = 	nil;
		info.isNotRadio = nil;
		info.func =  nil;
		info.hasArrow = true;
		info.notCheckable = true;

		info.text = "Families";
		info.value = {["SubLevel"] = 1, ["sublayer"] = 1};
		UIDropDownMenu_AddButton(info, level);

		info.text = "Specialization";
		info.value = {["SubLevel"] = 2, ["sublayer"] = 1};
		UIDropDownMenu_AddButton(info, level);

		info.text = "Diet";
		info.value = {["SubLevel"] = 3, ["sublayer"] = 1};
		UIDropDownMenu_AddButton(info, level);

		info.text = "Other";
		info.value = {["SubLevel"] = 4, ["sublayer"] = 1};
		UIDropDownMenu_AddButton(info, level);

	elseif (level == 2 or nestingcheck) then
		if (UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 1 )then
			if(UIDROPDOWNMENU_MENU_VALUE["sublayer"] == 1) then
				info.hasArrow = false;
				info.isNotRadio = true;
				info.notCheckable = true;

				info.text = CHECK_ALL;
				info.func = function()
					--local layer = UIDROPDOWNMENU_MENU_VALUE["sublayer"];
					local k = 1;
					--for j = 1, 19 or select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) do
					repeat
						--print(famperpagesnum);


						k = k + 1;
						local trimstart = 2;
						--if(select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) < 19 ) then
						--trimstart = 1;
						--end
						local fexist = _G["DropDownList2".."Button"..k+trimstart+1 .."Check"] or false;
						--print(k+trimstart,(fexist == false or "nil"))


						_G["DropDownList2".."Button"..k+trimstart .."Check"]:Show();
						_G["DropDownList2".."Button"..k+trimstart .."UnCheck"]:Hide();
						iStableMaster:SetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[20+k], true);
						_G["DropDownList2".."Button"..k+trimstart].checked = true;--iStableMaster:GetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[20+k]);
						--print("DropDownList2".."Button"..k+trimstart)
					until (fexist == false) 
					iStableMaster:UpdateScrollListMainCall();

					--end
					--C_PetJournal.SetAllPetTypesChecked(true);
					--UIDropDownMenu_Refresh(PetJournalFilterDropDown, 1, 2);
				end
				UIDropDownMenu_AddButton(info, level);

				info.text = UNCHECK_ALL;
				info.func = function()
					--C_PetJournal.SetAllPetTypesChecked(false);
					--UIDropDownMenu_Refresh(PetJournalFilterDropDown, 1, 2);
					--local layer = UIDROPDOWNMENU_MENU_VALUE["sublayer"];
					local k = 1;
					--for j = 1, 19 or select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) do
					repeat
						--print(famperpagesnum);


						k = k + 1;
						--print(k)
						local trimstart = 2;
						local fexist = _G["DropDownList2".."Button"..k+trimstart+1 .."Check"] or false;
						--if(select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) < 19 ) then
						--trimstart = 1;
						--end




						_G["DropDownList2".."Button"..k+trimstart .."Check"]:Hide();
						_G["DropDownList2".."Button"..k+trimstart .."UnCheck"]:Show();
						iStableMaster:SetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[20+k], false);
						_G["DropDownList2".."Button"..k+trimstart].checked = false;--iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[20+k]));
						--print("DropDownList2".."Button"..k+trimstart,_G["DropDownList2".."Button"..k+trimstart].checked);
					until (fexist == false) 
					iStableMaster:UpdateScrollListMainCall();

					--end
				end
				UIDropDownMenu_AddButton(info, level);
				


				info.notCheckable = false;


				local numTypes = 59;--C_PetJournal.GetNumPetTypes();
				local ownedFamilies = {}; -- should be moved to somewhere more general
				ownedFamilies.length = iStableMaster:StringKeyTableLengthI(ownedFamilies);

				for j=1,iStableMaster.ScrollFrameArrElem.length-1 do
					local seen = true; -- bit turned on its head but it filters out not opts in
					local limit
					if(ownedFamilies.length < 2)then
						limit = 1;
					else
						limit = ownedFamilies.length-1;
					end 
					for i=1,limit do
						if(ownedFamilies.length > 0 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"] ~= "N/A")then
							if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"] ~= ownedFamilies[i])then
								--if(iStableMasterDB.PetFamilyNamesByIndex[i] ~= ownedFamilies[i])then


								seen = false;

							end


						elseif(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"] ~= "N/A") then
							ownedFamilies.length = ownedFamilies.length+1;
							ownedFamilies[ownedFamilies.length] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"];
							--print(ownedFamilies[ownedFamilies.length]);
						end
					end	
					if(not seen) then
						ownedFamilies.length = ownedFamilies.length+1;
						ownedFamilies[ownedFamilies.length] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"];

					end
				end



				--			local Level1_Key = UIDROPDOWNMENU_MENU_VALUE["SubLevel"];
				--			subarray = Test1_Data[Level1_Key];

				--			for key, subsubarray in pairs(subarray) do
				--				local info = UIDropDownMenu_CreateInfo();
				--				info.hasArrow = false; -- no submenues this time
				--				info.notCheckable = true;
				--				info.text = subsubarray["name"];
				----				use info.func to set a function to be called at "click"
				--			    info.value = {
				--				["Level1_Key"] = Level1_Key;
				--				["Sublevel_Key"] = key;
				--				};
				--			UIDropDownMenu_AddButton(info, level);
				--			end
				--for i = famperpagesnum or 1,ownedFamilies.length-1 do
				for i = famperpagesnum or 1, (UIDROPDOWNMENU_MENU_VALUE["sublayer"] * 10) * 2.0 or iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1 do
					local addbuttonlevel = 1 + select(1,math.modf(i/20));



					if (mod(i,20)==0) then
						local info = UIDropDownMenu_CreateInfo();
						info.text = (famperpagesnum or 21).."-"..i*2 - 1
						info.hasArrow = true;
						info.notCheckable = true;
						--info.func = function() fampagesnum = nil; famperpagesnum = nil; end;
						info.checked = nil;
						if(fampagesnum == nil) then fampagesnum = i; end
						fampagesnum = fampagesnum+1;
						--famperpagesnum = i+1;		
						info.value = {["SubLevel"] = 1;	["sublayer"] =  addbuttonlevel +1;	};

						info.checked = 	nil;
						info.isNotRadio = nil;
						info.func =  nil;
						info.hasArrow = true;
						info.notCheckable = true;
						--print(addbuttonlevel, info.value["SubLevel"], info.value["sublayer"], level);
						UIDropDownMenu_AddButton(info,level);
						break;			
					end

					--info.notCheckable = false;
					--info.hasArrow = false;				
					----info.text = ownedFamilies[i];				
					--info.text = iStableMasterDB.PetFamilyNamesByIndex[i];
					--info.func = function(_, _, _, value) end
					--info.checked = function() return false;	end

					--UIDropDownMenu_AddButton(info,level);				

				end
				for i = famperpagesnum or 1, (UIDROPDOWNMENU_MENU_VALUE["sublayer"] * 10) * 2.0 or iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1 do
					local addbuttonlevel = 1 + select(1,math.modf(i/20));
					info.notCheckable = false;
					info.hasArrow = false;				
					--info.text = ownedFamilies[i];				
					info.text = iStableMasterDB.PetFamilyNamesByIndex[i];
					info.func = function(_, _, _, value)

						iStableMaster:SetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[i]), value);
						iStableMaster:UpdateScrollListMainCall();

					end
					info.checked = iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[i]));


					UIDropDownMenu_AddButton(info,level);				

				end
			elseif(UIDROPDOWNMENU_MENU_VALUE["sublayer"] >= 2) then
				--print(UIDROPDOWNMENU_MENU_VALUE["sublayer"]);
				info.hasArrow = false;
				info.isNotRadio = true;
				info.notCheckable = true;
				info.text = CHECK_ALL;
				info.func = function()
					--								local layer = UIDROPDOWNMENU_MENU_VALUE["sublayer"];
					--								local k = 1;
					--									for j = 1, 19 or select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) do

					--									--print(famperpagesnum);


					--									k = k + 1;
					--									local trimstart = 2;
					--									if(select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) < 19 ) then
					--									trimstart = 1;
					--									end

					--									iStableMaster:SetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[layer*10+j]), true);
					--									iStableMaster:UpdateScrollListMainCall();

					--									_G["DropDownList"..layer .."Button"..k+trimstart .."Check"]:Show();
					--									_G["DropDownList"..layer .."Button"..k+trimstart .."UnCheck"]:Hide();
					--									_G["DropDownList"..layer .."Button"..k+trimstart].checked = iStableMaster:GetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[layer*10+j]);
					--									end
					--C_PetJournal.SetAllPetTypesChecked(true);
					--UIDropDownMenu_Refresh(PetJournalFilterDropDown, 1, 2);
					lexist = (_G["DropDownList4"] or false);

					local listNum = 0;
					if((lexist:IsShown() or false) ~= false) then 
						listNum = 4;
					else 
						listNum = 3;
					end 

					local k = 1;
					--for j = 1, 19 or select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) do
					repeat
						--print(famperpagesnum);


						k = k + 1;
						--										print(k)
						local trimstart = 2;
						if (listNum== 4) then 
							trimstart = 1;
						end
						local fexist = _G["DropDownList"..listNum.."Button"..k+trimstart+1 .."Check"] or false;
						--if(select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) < 19 ) then
						--trimstart = 1;
						--end




						_G["DropDownList"..listNum.."Button"..k+trimstart .."Check"]:Show();
						_G["DropDownList"..listNum.."Button"..k+trimstart .."UnCheck"]:Hide();
						iStableMaster:SetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[(listNum*10)+k], true);
						_G["DropDownList"..listNum.."Button"..k+trimstart].checked = iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[(listNum*10)+k]));
						--									print("DropDownList"..listNum.."Button"..k+trimstart,_G["DropDownList"..listNum.."Button"..k+trimstart].checked);
					until (fexist == false) 
					iStableMaster:UpdateScrollListMainCall();
				end
				UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_VALUE["sublayer"]);

				info.text = UNCHECK_ALL;
				info.func = function()
					--								local layer = UIDROPDOWNMENU_MENU_VALUE["sublayer"];
					--								local k = 1;
					--									for j = 1, 19 or select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) do

					--									--print(famperpagesnum);


					--									k = k + 1;
					--									local trimstart = 2;
					--									if(select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) < 19 ) then
					--									trimstart = 1;
					--									end

					--									iStableMaster:SetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[layer*10+j], false);
					--									iStableMaster:UpdateScrollListMainCall();

					--									_G["DropDownList"..layer .."Button"..k+trimstart .."Check"]:Hide();
					--									_G["DropDownList"..layer .."Button"..k+trimstart .."UnCheck"]:Show();
					--									_G["DropDownList"..layer .."Button"..k+trimstart].checked = iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[layer*10+j]));
					--									end
					lexist = (_G["DropDownList4"] or false);



					local listNum = 0;
					if((lexist:IsShown() or false) ~= false) then 
						listNum = 4;
					else 
						listNum = 3;
					end 

					local k = 1;
					--for j = 1, 19 or select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) do
					repeat
						--print(famperpagesnum);


						k = k + 1;
						--	print(k, listNum)
						local trimstart = 2;
						if (listNum == 4) then 
							trimstart = 1;
						end

						local fexist = _G["DropDownList"..listNum.."Button"..k+trimstart+1 .."Check"] or false;
						--if(select(1,math.modf((iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1)/layer)) < 19 ) then
						--trimstart = 1;
						--end



						_G["DropDownList"..listNum.."Button"..k+trimstart .."Check"]:Hide();
						_G["DropDownList"..listNum.."Button"..k+trimstart .."UnCheck"]:Show();
						iStableMaster:SetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[(listNum*10)+k], false);
						_G["DropDownList"..listNum.."Button"..k+trimstart].checked = iStableMaster:GetFilterValue(tostring(iStableMasterDB.PetFamilyNamesByIndex[(listNum*10)+k]));

						--print("DropDownList"..listNum.."Button"..k+trimstart,_G["DropDownList"..listNum.."Button"..k+trimstart].checked);
					until (fexist == false) 
					iStableMaster:UpdateScrollListMainCall();

					--C_PetJournal.SetAllPetTypesChecked(false);
					--UIDropDownMenu_Refresh(PetJournalFilterDropDown, 1, 2);
				end
				UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_VALUE["sublayer"]);
				


				info.notCheckable = false;


				local numTypes = 59;--C_PetJournal.GetNumPetTypes();
				local ownedFamilies = {}; -- should be moved to somewhere more general
				ownedFamilies.length = iStableMaster:StringKeyTableLengthI(ownedFamilies);

				for j=1,iStableMaster.ScrollFrameArrElem.length-1 do
					local seen = true; -- bit turned on its head but it filters out not opts in
					local limit
					if(ownedFamilies.length < 2)then
						limit = 1;
					else
						limit = ownedFamilies.length-1;
					end 
					for i=1,limit do
						if(ownedFamilies.length > 0 and iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"] ~= "N/A")then
							if(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"] ~= ownedFamilies[i])then
								--if(iStableMasterDB.PetFamilyNamesByIndex[i] ~= ownedFamilies[i])then


								seen = false;

							end


						elseif(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"] ~= "N/A") then
							ownedFamilies.length = ownedFamilies.length+1;
							ownedFamilies[ownedFamilies.length] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"];
							--print(ownedFamilies[ownedFamilies.length]);
						end
					end	
					if(not seen) then
						ownedFamilies.length = ownedFamilies.length+1;
						ownedFamilies[ownedFamilies.length] = iStableMaster.ScrollFrameArrElem["ScrollElementChild"..j]["PetInfo"]["family"];

					end
				end



				--			local Level1_Key = UIDROPDOWNMENU_MENU_VALUE["SubLevel"];
				--			subarray = Test1_Data[Level1_Key];

				--			for key, subsubarray in pairs(subarray) do
				--				local info = UIDropDownMenu_CreateInfo();
				--				info.hasArrow = false; -- no submenues this time
				--				info.notCheckable = true;
				--				info.text = subsubarray["name"];
				----				use info.func to set a function to be called at "click"
				--			    info.value = {
				--				["Level1_Key"] = Level1_Key;
				--				["Sublevel_Key"] = key;
				--				};
				--			UIDropDownMenu_AddButton(info, level);
				--			end
				--for i = famperpagesnum or 1,ownedFamilies.length-1 do
				for i = ((UIDROPDOWNMENU_MENU_VALUE["sublayer"]-2) * 10)* 2.0 + 1, ((UIDROPDOWNMENU_MENU_VALUE["sublayer"]-1) * 10  ) *2.0 or iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1 do
					local addbuttonlevel = 2 + select(1,math.modf(i/20));
					info.notCheckable = false;
					info.hasArrow = false;				
					--info.text = ownedFamilies[i];				
					info.text = iStableMasterDB.PetFamilyNamesByIndex[i];
					info.func = function(_, _, _, value) 

						iStableMaster:SetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[i], value);
						iStableMaster:UpdateScrollListMainCall();

					end
					info.checked = iStableMaster:GetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[i]);

					local lastIndex = 19;
					if(iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1 < i+19) then
						lastIndex = iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex)-1;
					else
						lastIndex = i+19;

					end	
					if(i == lastIndex + 1)then
						break;
					end
					--UIDropDownMenu_AddButton(info,UIDROPDOWNMENU_MENU_VALUE["sublayer"]);		

					if (mod(i,20)==0) then

						local info = UIDropDownMenu_CreateInfo();


						info.text = ((((UIDROPDOWNMENU_MENU_VALUE["sublayer"]-1) * 10) *2.0 or 1)).."-"..(lastIndex+1);
						info.hasArrow = true;
						info.notCheckable = true;
						--info.func = function() fampagesnum = nil; famperpagesnum = nil; end;
						info.checked = nil;
						if(fampagesnum == nil) then fampagesnum = i; end
						fampagesnum = fampagesnum+1;
						--famperpagesnum = i+1;		
						info.value = {["SubLevel"] = 1;	["sublayer"] = addbuttonlevel;	};

						info.checked = 	nil;
						info.isNotRadio = nil;
						info.func =  nil;
						info.hasArrow = true;
						info.notCheckable = true;
						--print(addbuttonlevel, info.value["SubLevel"], info.value["sublayer"], level);
						UIDropDownMenu_AddButton(info,level);
						break;			
					end



				end
			end
			for i = ((UIDROPDOWNMENU_MENU_VALUE["sublayer"]-2) * 10)* 2.0 + 1, ((UIDROPDOWNMENU_MENU_VALUE["sublayer"]-1) * 10  ) *2.0 or iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex) do


				local addbuttonlevel = 2 + select(1,math.modf(i/20));
				info.notCheckable = false;
				info.hasArrow = false;				
				--info.text = ownedFamilies[i];				
				info.text = iStableMasterDB.PetFamilyNamesByIndex[i];
				info.func = function(_, _, _, value)

					iStableMaster:SetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[i], value);
					iStableMaster:UpdateScrollListMainCall();

				end
				info.checked = iStableMaster:GetFilterValue(iStableMasterDB.PetFamilyNamesByIndex[i]);
				
				local lastIndex = 19;
				if(iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex) < i+19) then
					lastIndex = iStableMaster:StringKeyTableLengthI(iStableMasterDB.PetFamilyNamesByIndex);
				else
					lastIndex = i+19;

				end	
				if(i == lastIndex + 1)then
					break;
				end
				if (mod(i,20)==0) then
					
					local info = UIDropDownMenu_CreateInfo();
					

					--info.text = (((UIDROPDOWNMENU_MENU_VALUE["sublayer"]-1) * 10) *2.0 or 1).."-"..lastIndex;
					info.hasArrow = true;
					info.notCheckable = true;
					--info.func = function() fampagesnum = nil; famperpagesnum = nil; end;
					info.checked = nil;
					if(fampagesnum == nil) then fampagesnum = i; end
					fampagesnum = fampagesnum+1;
					--famperpagesnum = i+1;		
					info.value = {["SubLevel"] = 1;	["sublayer"] = addbuttonlevel;	};

					info.checked = 	nil;
					info.isNotRadio = nil;
					info.func =  nil;
					info.hasArrow = true;
					info.notCheckable = true;
					--print(addbuttonlevel, info.value["SubLevel"], info.value["sublayer"], level);
					--UIDropDownMenu_AddButton(info,level);
					break;			
				end
				
				if( info.text ~= nil) then
					UIDropDownMenu_AddButton(info,UIDROPDOWNMENU_MENU_VALUE["sublayer"]);
				end
			end


		elseif UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 2 then
			info.hasArrow = false;
			info.isNotRadio = true;
			info.notCheckable = true;

			info.text = CHECK_ALL;
			info.func = function()
				--C_PetJournal.SetAllPetSourcesChecked(true);
				--UIDropDownMenu_Refresh(PetJournalFilterDropDown, 2, 2);
				local numSources = 3;
				for i=1,numSources do
					local specString = ""..select(2,GetSpecializationInfo(i, false , true));
					--print(specString);
					iStableMaster:SetFilterValue(specString, true);
					iStableMaster:UpdateScrollListMainCall();
					_G["DropDownList"..2 .."Button"..i+2 .."Check"]:Show();
					_G["DropDownList"..2 .."Button"..i+2 .."UnCheck"]:Hide();
					local specString = ""..select(2,GetSpecializationInfo(i, false , true));
					_G["DropDownList"..2 .."Button"..i+2].checked = iStableMaster:GetFilterValue(specString);
				end


				--UIDropDownMenu_Refresh(StablesRightFrameFilterBtnFilterDropDown,2,2);

			end
			UIDropDownMenu_AddButton(info, level);

			info.text = UNCHECK_ALL;
			info.func = function()
				local numSources = 3;
				for i=1,numSources do
					local specString = ""..select(2,GetSpecializationInfo(i, false , true));
					--print(specString);
					_G["DropDownList"..2 .."Button"..i+2 .."Check"]:Hide();
					_G["DropDownList"..2 .."Button"..i+2 .."UnCheck"]:Show();
					iStableMaster:SetFilterValue(specString, false);
					iStableMaster:UpdateScrollListMainCall();
					local specString = ""..select(2,GetSpecializationInfo(i, false , true));
					_G["DropDownList"..2 .."Button"..i+2].checked = iStableMaster:GetFilterValue(specString);
				end


				--UIDropDownMenu_Refresh(StablesRightFrameFilterBtnFilterDropDown,2,2);
				--C_PetJournal.SetAllPetSourcesChecked(false);
				--UIDropDownMenu_Refresh(PetJournalFilterDropDown, 2, 2);
			end
			UIDropDownMenu_AddButton(info, level);

			info.notCheckable = false;
			local numSources = 3; --C_PetJournal.GetNumPetSources();
			for i=1,numSources do
				info.text = select(2,GetSpecializationInfo(i, false , true));

				info.func = function(_, _, _, value)
					local specString = ""..select(2,GetSpecializationInfo(i, false , true));
					--print(specString);
					iStableMaster:SetFilterValue(specString, value);
					iStableMaster:UpdateScrollListMainCall();



					--C_PetJournal.SetPetSourceChecked(i, value);
				end
				local specString = ""..select(2,GetSpecializationInfo(i, false , true));
				info.checked = iStableMaster:GetFilterValue(specString);
				



				UIDropDownMenu_AddButton(info, level);
			end
		elseif UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 3 then
			info.hasArrow = false;
			info.isNotRadio = true;
			info.notCheckable = true;
			info.keepShownOnClick = true;
			local listOfFoods = {"Bread", "Meat", "Raw Meat","Fish","Raw Fish","Fungus","Mechanical Bits","Fruit","Cheese"}
			info.text = CHECK_ALL;
			info.func = function(value)


				for i=1,#listOfFoods  do
					--print(specString);

					local buttonDBref = listOfFoods[i];
					--print(tostring(buttonDBref));
					_G["DropDownList"..2 .."Button"..i+2 .."Check"]:Show();
					_G["DropDownList"..2 .."Button"..i+2 .."UnCheck"]:Hide();
					iStableMaster:SetFilterValue(buttonDBref, true);
					iStableMaster:UpdateScrollListMainCall();
					_G["DropDownList"..2 .."Button"..i+2].checked = iStableMaster:GetFilterValue(buttonDBref);
				end
			end
			UIDropDownMenu_AddButton(info, level);

			info.text = UNCHECK_ALL;
			info.func = function()

				for i=1,#listOfFoods do
					--print(specString);

					local buttonDBref = listOfFoods[i];
					_G["DropDownList"..2 .."Button"..i+2 .."Check"]:Hide();
					_G["DropDownList"..2 .."Button"..i+2 .."UnCheck"]:Show();
					iStableMaster:SetFilterValue(buttonDBref, false);
					iStableMaster:UpdateScrollListMainCall();
					_G["DropDownList"..2 .."Button"..i+2].checked = iStableMaster:GetFilterValue(buttonDBref);
				end
			end
			UIDropDownMenu_AddButton(info, level);


			info.notCheckable = false;
			for i=1,#listOfFoods do
				info.text = listOfFoods[i];
				info.func = function(_,_,_,value)

					iStableMaster:SetFilterValue(listOfFoods[i],value);
					iStableMaster:UpdateScrollListMainCall();
				end
				info.checked = iStableMaster:GetFilterValue(listOfFoods[i]);
				UIDropDownMenu_AddButton(info, level);

			end

			info.text = "Bread";
			info.func = function(value)

				iStableMaster:SetFilterValue("Bread", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Bread");
			UIDropDownMenu_AddButton(info, level);

			info.text = "Meat";
			info.func = function(value)

				iStableMaster:SetFilterValue("Meat", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Meat");			
			UIDropDownMenu_AddButton(info, level);

			info.text = "Raw Meat";
			info.func = function(value)

				iStableMaster:SetFilterValue("Raw Meat", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Raw Meat");
			UIDropDownMenu_AddButton(info, level);

			info.text = "Fish";
			info.func = function(value)

				iStableMaster:SetFilterValue("Fish", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Fish");
			UIDropDownMenu_AddButton(info, level);

			info.text = "Raw Fish";
			info.func = function(value)

				iStableMaster:SetFilterValue("Raw Fish", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Raw Fish");
			UIDropDownMenu_AddButton(info, level);
			info.text = "Fungi";
			info.func = function(value)

				iStableMaster:SetFilterValue("Fungi", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Fungi");
			UIDropDownMenu_AddButton(info, level);
			info.text = "Mechanical Bits";
			info.func = function(value)

				iStableMaster:SetFilterValue("Mechanical Bits", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Mechanical Bits");
			UIDropDownMenu_AddButton(info, level);
			info.text = "Fruit";
			info.func = function(value)

				iStableMaster:SetFilterValue("Fruit", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Fruit");
			UIDropDownMenu_AddButton(info, level);
			info.text = "Cheese";
			info.func = function(value)

				iStableMaster:SetFilterValue("Cheese", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Cheese");
			UIDropDownMenu_AddButton(info, level);

		elseif UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 4 then
			info.hasArrow = false;
			info.isNotRadio = true;
			info.notCheckable = true;
			info.keepShownOnClick = true;
			local listOfOthers = {"Named","Favourite", "Rarity", "Exotic"}
			info.text = CHECK_ALL;
			info.func = function()

				iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"] = true;
				_G["DropDownList"..2 .."Button"..3].checked = iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"];
				_G["DropDownList"..2 .."Button"..3 .."Check"]:Show();
				_G["DropDownList"..2 .."Button"..3 .."UnCheck"]:Hide();
				for i=1,#listOfOthers do
					--print(specString);

					local buttonDBref = listOfOthers[i];
					_G["DropDownList"..2 .."Button"..i+3 .."Check"]:Show();
					_G["DropDownList"..2 .."Button"..i+3 .."UnCheck"]:Hide();
					iStableMaster:SetFilterValue(buttonDBref, true);
					iStableMaster:UpdateScrollListMainCall();
					_G["DropDownList"..2 .."Button"..i+3].checked = iStableMaster:GetFilterValue(tostring(buttonDBref));
				end
			end
			UIDropDownMenu_AddButton(info, level);

			info.text = UNCHECK_ALL;
			info.func = function()


				iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"] = false;
				_G["DropDownList"..2 .."Button"..3].checked = iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"];
				_G["DropDownList"..2 .."Button"..3 .."Check"]:Hide();
				_G["DropDownList"..2 .."Button"..3 .."UnCheck"]:Show();
				for i=1,#listOfOthers do
					--print(specString);


					local buttonDBref = listOfOthers[i];
					_G["DropDownList"..2 .."Button"..i+3 .."Check"]:Hide();
					_G["DropDownList"..2 .."Button"..i+3 .."UnCheck"]:Show();
					iStableMaster:SetFilterValue(buttonDBref, false);
					iStableMaster:UpdateScrollListMainCall();
					_G["DropDownList"..2 .."Button"..i+3].checked = iStableMaster:GetFilterValue(tostring(buttonDBref));

				end
			end
			UIDropDownMenu_AddButton(info, level);
			
			info.notCheckable = false;



			info.text = "ActiveSlots";
			info.func = function(value)
				iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"] = not iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"];
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMasterOptionsDB["ScrollList"]["ShowActiveSlots"];
			UIDropDownMenu_AddButton(info, level);

			for i=1, #listOfOthers do
				if(listOfOthers[i] == "Named") then

					info.text = "Re-named";
				else
					info.text = listOfOthers[i];
				end

				info.func = function(_,_,_,value)

					iStableMaster:SetFilterValue(listOfOthers[i], value);
					iStableMaster:UpdateScrollListMainCall();
				end
				info.checked = iStableMaster:GetFilterValue(listOfOthers[i]);
				UIDropDownMenu_AddButton(info, level);
			end


			info.text = "Renamed";
			info.func = function(value)

				iStableMaster:SetFilterValue("Named", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Named");
			UIDropDownMenu_AddButton(info, level);

			info.text = "Favourite";
			info.func = function(value)

				iStableMaster:SetFilterValue("Favourite", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Favourite");
			UIDropDownMenu_AddButton(info, level);

			info.text = "Rarity";
			info.func = function(value)

				iStableMaster:SetFilterValue("Rarity", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Rarity");
			UIDropDownMenu_AddButton(info, level);

			info.text = "Exotic";
			info.func = function(value)

				iStableMaster:SetFilterValue("Exotic", value);
				iStableMaster:UpdateScrollListMainCall();
			end
			info.checked = iStableMaster:GetFilterValue("Exotic");
			UIDropDownMenu_AddButton(info, level);
		end
	end
end
function iStableMaster:UpdateSortDropDownInfo(value,info)
	for i=1, iStableMaster:StringKeyTableLengthI(iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"]) do 
		if UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 3 then
			info.checked = (iStableMasterDB.ActiveSorts.CurrentSort.tertiary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
		elseif UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 2 then 
			info.checked = (iStableMasterDB.ActiveSorts.CurrentSort.secondary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
		elseif UIDROPDOWNMENU_MENU_VALUE["SubLevel"] == 1 then 
			info.checked = (iStableMasterDB.ActiveSorts.CurrentSort.primary == (iStableMasterDB["ActiveSorts"]["ReverseLookUpIndex"][i]));
		else
		end 
	end
end
