local _, core               = ...;
local WC_arrEventRefresh    = {};
local WC_arrCriteriaRefresh = {};
g_guideSelected             = { ["WC"] = "", ["WCC"] = ""};
g_pageSelected              = { ["WC"] = "", ["WCC"] = ""};
local g_pinsActivated       = { ["WC"] = {}, ["WCC"] = {} };
local HBD_Pins              = LibStub("HereBeDragons-Pins-2.0");
local AceSerializer         = LibStub("AceSerializer-3.0");
WCC_MAX_PAGE_GUIDE          = 7;

-------- PETS --------
function WC_Lib.ClearFilterPets()
	if (_G["PetJournalSearchBox"] ~= nil and _G["PetJournalSearchBox"]:GetText() ~= "") then
		C_PetJournal.ClearSearchFilter();
	end
	if not C_PetJournal.IsFilterChecked(LE_PET_JOURNAL_FILTER_COLLECTED)     then C_PetJournal.SetFilterChecked(LE_PET_JOURNAL_FILTER_COLLECTED,     true) end
	if not C_PetJournal.IsFilterChecked(LE_PET_JOURNAL_FILTER_NOT_COLLECTED) then C_PetJournal.SetFilterChecked(LE_PET_JOURNAL_FILTER_NOT_COLLECTED, true) end
	for i = 1, C_PetJournal.GetNumPetTypes() do
		if not C_PetJournal.IsPetTypeChecked(i) then
			C_PetJournal.SetPetTypeFilter(i, true);
		end
	end
	for i = 1, C_PetJournal.GetNumPetSources() do
		if not C_PetJournal.IsPetSourceChecked(i) then
			C_PetJournal.SetPetSourceChecked(i, true);
		end
	end
end

function WC_Lib.getPetInfoById(idPet)
	WC_Lib.ClearFilterPets();
	for i = 1, C_PetJournal.GetNumPets() do
		local tmp = {C_PetJournal.GetPetInfoByIndex(i)};
		if (tmp[11] == tonumber(idPet)) then
			return unpack({tmp, i});
		end
	end
	return nil;
end

-------- HF --------
local function printCriteriaHF(hfID)
	local streturn = "";
	for i = 1, GetAchievementNumCriteria(hfID) do
		local getCriteria = {GetAchievementCriteriaInfo(hfID, i)}
		if (getCriteria[3] == true) then
			streturn = streturn.."|cff00ff00"..getCriteria[1]..'|r\n';
		else
			streturn = streturn..getCriteria[1]..'\n';
		end
	end
	return streturn;
end
core.libs.printCriteriaHF = printCriteriaHF;

--- COLOR ITEM ---
function WC_Lib.nameItemInColor(itemInfo, mode) -- 1 Tout; 2 Only icon; 3 Only text
	local ret = itemInfo[1];
	if (itemInfo[3] == 0) then
		ret = "|cFF9d9d9d["..itemInfo[1].."]|r";
	elseif (itemInfo[3] == 1) then
		ret = "|cFFffffff["..itemInfo[1].."]|r";
	elseif (itemInfo[3] == 2) then
		ret = "|cFF1eff00["..itemInfo[1].."]|r";
	elseif (itemInfo[3] == 3) then
		ret = "|cFF0070dd["..itemInfo[1].."]|r";
	elseif (itemInfo[3] == 4) then
		ret = "|cFFa335ee["..itemInfo[1].."]|r";
	elseif (itemInfo[3] == 5) then
		ret = "|cFFff8000["..itemInfo[1].."]|r";
	elseif (itemInfo[3] == 6) then
		ret = "|cFFe6cc80["..itemInfo[1].."]|r";
	elseif (itemInfo[3] == 7 or itemInfo[3] == 8) then
		ret = "|cFF00ccff["..itemInfo[1].."]|r";
	end
	if (itemInfo[4] ~= nil) then
		if (mode == 1) then
			ret = "|T"..itemInfo[4]..":16|t "..ret;
		elseif (mode == 2) then
			ret = "|T"..itemInfo[4]..":16|t";
		end
	end
	return ret;
end

function WC_Lib.RefreshNPCDroppedLoot(loot)
	local str = "|cffffffff"..core.L["DroppedBy"].."|r";
	for i = 1, #loot do
		local strDropPercent = "";
		if (loot[i].dropPercent ~= "" and loot[i].dropPercent ~= nil) then
			strDropPercent = "("..loot[i].dropPercent.."%)";
		end
		str = str..loot[i].nameNPC.." "..strDropPercent;
		if (i ~= #loot) then
			str = str.."|cffffffff, |r";
		end
	end
	str = str.."|cffffffff.|r";
	return str;
end

function WC_Lib.RefreshNPCVendor(names)
	local str = "|cffffffff"..core.L["SoldBy"].."|r";
	for i = 1, #names do
		str = str..names[i];
		if (i ~= #names) then
			str = str.."|cffffffff, |r";
		end
	end
	str = str.."|cffffffff.|r";
	return str;
end

function WC_Lib.RefreshCompoCreate(create, profession)
	local str = "|cffffffff"..core.L["CreatedBy"].."|r";
	if (profession ~= nil and profession ~= "none") then
		str = str.."|cFFF5CC00["..profession.."]|r |cffffffff-|r ";
	end
	for i = 1, #create do
		local compo = "";
		local item = Item:CreateFromItemID(tonumber(create[i].idItem));
		item:ContinueOnItemLoad(function()
			compo = {GetItemInfo(create[i].idItem)};
		end)
		if (compo == "") then
			str = str.."Loading";
		else
			local sortCompo = {};
			sortCompo[1] = compo[1];
			sortCompo[2] = compo[2];
			sortCompo[3] = compo[3];
			sortCompo[4] = compo[10];
			str = str..WC_Lib.nameItemInColor(sortCompo, 1);
		end
		str = str.." |cffffffff("..create[i].nbNeed..")|r";
		if (i ~= #create) then
			str = str.."|cffffffff,|r ";
		end
	end
	str = str.."|cffffffff.|r";
	return str;
end

local function heightBgTask(arrTask)
	local height = 0;
	for i = 1, #arrTask do
		height = 40*i;
	end
	return height;
end
core.libs.heightBgTask = heightBgTask;

local function centerListObjectX(nb, nbmax, tailleImg)
	local x = 0;
	x =  (nb - 1) * tailleImg - nbmax * tailleImg / 2;
	return x;
end
core.libs.centerListObjectX = centerListObjectX;

function WC_Lib.centerListObjectXByWidth(nb, nbmax, width, tailleImg)
	local x = 0;
	x = (width - tailleImg * nbmax) / (nbmax + 1) * nb + tailleImg * (nb - 1);
	return x;
end

function WC_Lib.ScrollFrame_OnMouseWheel(self, delta)
	local speed               = 50;
	local verticalScrollRange = self:GetVerticalScrollRange();
	
	if self.wheelSpeed  then speed = self.wheelSpeed end
	if self.scrollRange then verticalScrollRange = self.scrollRange end
	
	local newValue = self:GetVerticalScroll() - (delta * speed);
	
	if (newValue < 0) then
		newValue = 0;
	elseif (newValue > verticalScrollRange) then
		newValue = verticalScrollRange;
	end
	self:SetVerticalScroll(newValue);
end

-- ===== DIVERS =====
local function checkIdInArrayEvent(taskType, id)
	for i = 1, #WC_arrEventRefresh do
		if (WC_arrEventRefresh[i][2] == taskType and WC_arrEventRefresh[i][3] == id) then
			return WC_arrEventRefresh[i][1];
		end
	end
	return nil;
end

function WC_Lib.AddingInEventRefresh(addingArray)
	local bOK = true;
	for i = 1, #WC_arrEventRefresh do
		if (WC_arrEventRefresh[i][2] == addingArray[2] and WC_arrEventRefresh[i][3] == addingArray[3]) then
			bOK = false;
		end
	end
	if (bOK == true) then
		table.insert(WC_arrEventRefresh, addingArray);
	end
end

function WC_Lib.SetAppearanceToModel(modelFrame, sourceID)
	modelFrame:TryOn(sourceID);
end

function WC_Lib.findInArray(array, value, option)
	for i = 1, #array do
		if not option then
			if (array[i] == value) then
				return i
			end
		else
			if (array[i][option] == value) then
				return i
			end
		end
	end
	return -1;
end

function WC_Lib.GetGuideByID(id, addon)
	if (addon == "WCC") then
		for i = 1, #YourGuides do
			if (YourGuides[i].idGuide == id) then
				return YourGuides[i];
			end
		end
		return nil;
	elseif (addon == "WC") then
		for i = 1, #WC_Guides do
			if (WC_Guides[i].idGuide == id) then
				return WC_Guides[i];
			end
		end
		return nil;
	end
end

function WC_Lib.GetIndexGuideByID(id, addon)
	if (addon == "WCC") then
		for i = 1, #YourGuides do
			if (YourGuides[i].idGuide == id) then
				return i;
			end
		end
		return nil;
	elseif (addon == "WC") then
		for i = 1, #WC_Guides do
			if (WC_Guides[i].idGuide == id) then
				return i;
			end
		end
		return nil;
	end
end

function WC_Lib.GetPosGuideByID(id, addon)
	if (addon == "WCC") then
		for i = 1, #ListGuides do
			if (ListGuides[i] == id) then
				return i;
			end
		end
		return nil;
	elseif (addon == "WC") then
		for i = 1, #WC_ListGuides do
			if (WC_ListGuides[i] == id) then
				return i;
			end
		end
		return nil;
	end
end

-- ====== EVENT WC ======
function OnRefreshingGuides(idGuide)
	WC_Lib.RefreshCollectionContent(idGuide, "WC", true);
end

local canRefreshHiddenQuest = true;
local function RefreshingGuidesWithHiddenQuest()
	local _, finished = IsAddOnLoaded("WoWChallenger");
	if (finished == true) then
		local second = 0;
		for i = 1, #WC_arrCriteriaRefresh do
			local idGuide = WC_arrCriteriaRefresh[i];
			if (_G["WC_BasicFrames"] ~= nil and g_guideSelected["WC"] == idGuide) then
				core.cpgn.WC_wait(second, OnRefreshingGuides, idGuide);
				second = second + 0.25;
			end
		end
		canRefreshHiddenQuest = true;
	end
end

local WC_refreshHiddenQuest = CreateFrame("Frame");
WC_refreshHiddenQuest:RegisterEvent("CRITERIA_UPDATE");
WC_refreshHiddenQuest:SetScript("OnEvent", function(self, event, ...)
	if (canRefreshHiddenQuest == true) then
		core.cpgn.WC_wait(2, RefreshingGuidesWithHiddenQuest);
	end
	canRefreshHiddenQuest = false;
end)

local WC_refreshQuest = CreateFrame("Frame");
WC_refreshQuest:RegisterEvent("QUEST_TURNED_IN");
WC_refreshQuest:RegisterEvent("QUEST_AUTOCOMPLETE");
WC_refreshQuest:SetScript("OnEvent", function(self, event, questID, ...)
	local _, finished = IsAddOnLoaded("WoWChallenger");
	if (finished == true) then
		if (questID ~= nil) then
			local idGuide = checkIdInArrayEvent("quest", tostring(questID));
			if (_G["WC_BasicFrames"] ~= nil and g_guideSelected["WC"] == idGuide) then
				core.cpgn.WC_wait(1, WC_Lib.RefreshCollectionContent, idGuide, "WC", true);
			end
		end
	end
end)

local WC_refreshHF = CreateFrame("Frame");
WC_refreshHF:RegisterEvent("ACHIEVEMENT_EARNED");
WC_refreshHF:SetScript("OnEvent", function(self, event, achievementID, ...)
	local _, finished = IsAddOnLoaded("WoWChallenger");
	if (finished == true and achievementID ~= nil) then
		local idGuide = checkIdInArrayEvent("hf", tostring(achievementID));
		if (idGuide ~= nil) then
			core.cpgn.WC_wait(1, WC_Lib.RefreshListCollections, "WC");
			if (_G["WC_BasicFrames"] ~= nil and g_guideSelected["WC"] == idGuide) then
				core.cpgn.WC_wait(1, WC_Lib.RefreshCollectionContent, idGuide, "WC", true);
			end
		end
	end
end)

local WC_refreshMounts = CreateFrame("Frame");
WC_refreshMounts:RegisterEvent("NEW_MOUNT_ADDED");
WC_refreshMounts:SetScript("OnEvent", function(self, event, mountID, ...)
	local _, finished = IsAddOnLoaded("WoWChallenger");
	if (finished == true and mountID ~= nil) then
		local idGuide = checkIdInArrayEvent("mounts", tostring(mountID));
		if (idGuide ~= nil) then
			core.cpgn.WC_wait(1, WC_Lib.RefreshListCollections, "WC");
			if (_G["WC_BasicFrames"] ~= nil and g_guideSelected["WC"] == idGuide) then
				core.cpgn.WC_wait(1, WC_Lib.RefreshCollectionContent, idGuide, "WC", true);
			end
		end
	end
end)

local WC_refreshPets = CreateFrame("Frame");
WC_refreshPets:RegisterEvent("NEW_PET_ADDED");
WC_refreshPets:SetScript("OnEvent", function(self, event, battlePetGUID, ...)
	local _, finished = IsAddOnLoaded("WoWChallenger");
	if (finished == true and battlePetGUID ~= nil) then
		local idPet = select(11, C_PetJournal.GetPetInfoByPetID(battlePetGUID));
		local idGuide = checkIdInArrayEvent("pets", tostring(idPet));
		if (idGuide ~= nil) then
			core.cpgn.WC_wait(1, WC_Lib.RefreshListCollections, "WC");
			if (_G["WC_BasicFrames"] ~= nil and g_guideSelected["WC"] == idGuide) then
				core.cpgn.WC_wait(1, WC_Lib.RefreshCollectionContent, idGuide, "WC", true);
			end
		end
	end
end)

local WC_refreshTransmog = CreateFrame("Frame");
WC_refreshTransmog:RegisterEvent("TRANSMOG_COLLECTION_SOURCE_ADDED");
WC_refreshTransmog:SetScript("OnEvent", function(self, event, itemModifiedAppearanceID)
	local _, finished = IsAddOnLoaded("WoWChallenger");
	if (finished == true and itemModifiedAppearanceID ~= nil) then
		local idGuide = checkIdInArrayEvent("transmogs", tostring(itemModifiedAppearanceID));
		if (idGuide ~= nil) then
			core.cpgn.WC_wait(1, WC_Lib.RefreshListCollections, "WC");
			if (_G["WC_BasicFrames"] ~= nil and g_guideSelected["WC"] == idGuide) then
				core.cpgn.WC_wait(1, WC_Lib.RefreshCollectionContent, idGuide, "WC", true);
			end
		end
	end
end)
-- ====== END EVENT WC ======

-- ===== DIALOG =====
StaticPopupDialogs["DeleteCollection"] = {
	text = core.L["Voulez-vous supprimer"].." |cFFF5CC00%s|r ?\nID: |cff00c8ff%s|r",
	button1 = core.L["Oui"],
	button2 = core.L["Non"],
	OnAccept = function(self)
		WC_Lib.DeleteCollection(self.idGuide, self.addon)
	end,
	hideOnEscape = false,
	whileDead = true,
}

StaticPopupDialogs["WC_OKDialog"] = {
	text = "%s",
	button1 = "Ok",
	hideOnEscape = true,
	whileDead = true,
}

StaticPopupDialogs["WC_ConfirmDialog"] = {
	text = "%s",
	button1 = core.L["Confirmer"],
	button2 = core.L["Annuler"],
	OnAccept = function(self)
		self.func();
	end,
	hideOnEscape = false,
	whileDead = true,
}

-- ===== TOOLTIP =====
WC_Lib.OnLeave = function(self, motion)
	GameTooltip:Hide()
end

function WC_Lib.setStringProgressionGuides(onlyNumber)
	local nbCollected = 0;
	for i = 1, #WC_ListGuides do
		local infoGuide = WC_Lib.GetGuideByID(WC_ListGuides[i], "WC");
		if (WC_Lib.checkIfGuideIsDone(infoGuide.category, infoGuide.id, infoGuide.Model.modID) == true) then
			nbCollected = nbCollected + 1;
		end
	end
	local color = "|cffffffff";
	if (nbCollected == 0) then
		color = "|cffff0000";
	elseif (nbCollected == #WC_ListGuides) then
		color = "|cff00ff00";
	end
	
	if onlyNumber then return nbCollected.."/"..#WC_ListGuides end
	
	return core.L["Collections"]..core.L["2points"]..color..nbCollected.."/"..#WC_ListGuides.."|r";
end

WC_Lib.OnEnterIconItem = function(self, motion)
	if (self.itemLink ~= 0) then
		GameTooltip:SetOwner(self, "ANCHOR_LEFT", 0, 0);
		if (self.itemLink ~= nil) then
			GameTooltip:SetHyperlink(self.itemLink)
		else
			GameTooltip:AddLine("|cffff0000Loading...|r");
		end
		GameTooltip:Show();
	end
end

WC_Lib.OnEnterTask = function(self, motion)
	GameTooltip:SetOwner(self, "ANCHOR_TOP", 0, 5);
	if (self.taskInfo.taskType == "hf" and self.taskInfo.idHF ~= "") then
		local info = {GetAchievementInfo(self.taskInfo.idHF)};
		if (info[4] == true) then
			if (info[14] ~= "") then
				GameTooltip:AddLine(core.L["AcheveBy"].." "..info[14], 0, 1, 0);
			else
				GameTooltip:AddLine(core.L["Acheve"], 0, 1, 0);
			end
		else
			GameTooltip:AddLine(core.L["NoAcheve"], 0.5, 0.5, 0.5);
		end
		GameTooltip:AddLine(info[8], 1, 1, 1);
		if (GetAchievementNumCriteria(self.taskInfo.idHF) ~= 0) then
			GameTooltip:AddLine(core.libs.printCriteriaHF(info[1]));
		end
	elseif (self.taskInfo.taskType == "quest") then
		local completed = C_QuestLog.IsQuestFlaggedCompleted(self.taskInfo.idQuest);
		if (completed == true) then
			GameTooltip:AddLine(core.L["Acheve"], 0, 1, 0);
		else
			GameTooltip:AddLine(core.L["NoAcheve"], 0.5, 0.5, 0.5);
		end
		if (self.taskInfo.tooltipText ~= nil and self.taskInfo.tooltipText ~= "") then
			GameTooltip:AddLine(self.taskInfo.tooltipText, 1, 1, 1);
		else
			GameTooltip:AddLine(WC_Lib.GetObjectivesQuest(self.taskInfo.idQuest), 1, 1, 1);
		end
	elseif (self.taskInfo.taskType == "custom") then
		if (self.isDone == true) then
			GameTooltip:AddLine(core.L["Acheve"], 0, 1, 0);
		else
			GameTooltip:AddLine(core.L["NoAcheve"], 0.5, 0.5, 0.5);
		end
		GameTooltip:AddLine(self.taskInfo.tooltipText, 1, 1, 1, true);
		if (self.addon == "WC") then
			GameTooltip:AddLine(" ");
			if (self.isDone == true) then
				GameTooltip:AddLine(core.L["PutNotComplete"], 0.6, 0.6, 0.6);
			else
				GameTooltip:AddLine(core.L["PutComplete"], 0, 0.8, 0);
			end
		end
	elseif (self.taskInfo.taskType == "need") then
		if (self.isDone == true) then
			GameTooltip:AddLine(core.L["Acheve"], 0, 1, 0);
		else
			GameTooltip:AddLine(core.L["NoAcheve"], 0.5, 0.5, 0.5);
		end
		GameTooltip:AddLine(core.L["Obtenir"]..tostring(self.taskInfo.nbRequired).." "..WC_Lib.nameItemInColor(self.taskInfo.itemInfo, 1)..".", 1, 1, 1);
		GameTooltip:AddLine(" ");
		local count = GetItemCount(self.taskInfo.idItem)
		if (count >= tonumber(self.taskInfo.nbRequired)) then
			GameTooltip:AddLine(core.L["HaveItem"]..count.."/"..self.taskInfo.nbRequired.." "..WC_Lib.nameItemInColor(self.taskInfo.itemInfo, 2), 0, 1, 0);		
		else
			GameTooltip:AddLine(core.L["HaveItem"]..count.."/"..self.taskInfo.nbRequired.." "..WC_Lib.nameItemInColor(self.taskInfo.itemInfo, 2), 1, 1, 1);
		end
		if (self.taskInfo.obtentionType == "loot") then
			GameTooltip:AddLine(WC_Lib.RefreshNPCDroppedLoot(self.taskInfo.obtention_loot), 1, 0.82, 0, true);
		elseif (self.taskInfo.obtentionType == "vendor") then
			GameTooltip:AddLine(WC_Lib.RefreshNPCVendor(self.taskInfo.obtention_vendor), 1, 0.82, 0, true);
			elseif (self.taskInfo.obtentionType == "create") then
			GameTooltip:AddLine(WC_Lib.RefreshCompoCreate(self.taskInfo.obtention_create, self.taskInfo.obtention_profession), 1, 1, 1, true);
		elseif (self.taskInfo.obtentionType == "quest") then
			GameTooltip:AddLine("|cffffffff"..core.L["FinishQuest"].."|r"..self.taskInfo.obtention_titleQuest.."|cffffffff.|r", 1, 0.82, 0, true);
		elseif (self.taskInfo.obtentionType == "hf") then
			GameTooltip:AddLine("|cffffffff"..core.L["FinishHF"].."|r"..self.taskInfo.obtention_titleHF.."|cffffffff.|r", 1, 0.82, 0, true);
		end
		if (self.addon == "WC" and self.taskInfo.validationType == "manual") then
			GameTooltip:AddLine(" ");
			if (self.isDone == true) then
				GameTooltip:AddLine(core.L["PutNotComplete"], 0.6, 0.6, 0.6);
			else
				GameTooltip:AddLine(core.L["PutComplete"], 0, 0.8, 0);
			end
		end
	end
	
	if (self.addon == "WCC") then
		GameTooltip:AddLine(" ");
		GameTooltip:AddLine("<"..core.L["Cliquer pour modifier"]..">", 0, 1, 0);
	end
	GameTooltip:Show();
end
WC_Lib.OnEnterIconHelp = function(self, motion)
	GameTooltip:SetOwner(self, "ANCHOR_LEFT", 0, 0);
	if (self.important == true) then
		GameTooltip:AddLine("|c00FF7F00"..core.L["HelpImportant"].."|r");
	else
		GameTooltip:AddLine(core.L["Aide"]);
	end
	GameTooltip:AddLine(self.helpDesc, 1, 1, 1, true);
	GameTooltip:Show();
end

WC_Lib.OnEnterBtnShowMap = function(self, motion)
	GameTooltip:SetOwner(self, "ANCHOR_TOP");
	if WC_Lib.isPinActivated(self.idGuide, self.idPage, self.idRens, self.addon) then
		GameTooltip:AddLine(core.L["Cacher sur la carte"]);
	else
		GameTooltip:AddLine(core.L["Afficher sur la carte"]);
	end
	local strZone      = "";
	local oldArrIDZone = {};
	for i = 1, #self.pins do
		if (WC_Lib.findInArray(oldArrIDZone, self.pins[i].IDZone) == -1) then
			if (strZone == "") then
				strZone = WC_Lib.GetShowMapStr(self.pins[i].IDZone);
			else
				strZone = strZone..", "..WC_Lib.GetShowMapStr(self.pins[i].IDZone);
			end
			table.insert(oldArrIDZone, self.pins[i].IDZone);
		end
	end
	if (strZone == "") then
		GameTooltip:AddLine(self.title);
	elseif (self.title == "") then
		GameTooltip:AddLine(strZone, 1, 1, 1);
	else
		GameTooltip:AddLine(self.title..", |cffffffff"..strZone.."|r");
	end
	GameTooltip:Show();
end

WC_Lib.tooltip_iconCollection = function(self, motion)
	GameTooltip:SetOwner(self, self.anchor or "ANCHOR_LEFT", 0, 0);
	local settings = self.guide;
	if (settings ~= nil) then
		GameTooltip:AddLine(settings.info[1], 1, 1, 1);
		if (settings.info[2] ~= nil and settings.info[2] ~= "" and settings.info[2] == true) then
			GameTooltip:AddDoubleLine("|cff00ff00"..core.L["MountCollected"].."|r", core.L["Difficult"][settings.difficulty]);
		else
			GameTooltip:AddDoubleLine("|cffff0000"..core.L["MountNotCollected"].."|r", core.L["Difficult"][settings.difficulty]);
		end
		if (settings.info[3] ~= nil and settings.info[3] ~= "") then
			GameTooltip:AddLine("\""..settings.info[3].."\"", 1, 0.82, 0, true);
		end
		if (settings.info[4] ~= nil and settings.info[4] ~= "") then
			GameTooltip:AddLine(settings.info[4], 1, 1, 1);
		end
		local classStr = "";
		if (settings.class ~= nil) then
			for i = 1, #settings.class do
				if (i == 1) then
					classStr = classStr..core.L["ClassesList"][settings.class[i]];
				else
					classStr = classStr.."|cffffffff,|r "..core.L["ClassesList"][settings.class[i]];	
				end
			end
		end
		if (classStr ~= "" and #settings.class < 12) then
			GameTooltip:AddLine(core.L["Classes"]..core.L["2points"]..classStr, 1, 0.82, 0, true);
		end
		
		if (settings.expansion ~= "" and settings.expansion ~= nil) then
			GameTooltip:AddLine(core.L["Expansion"]..core.L["2points"].."|cffffffff"..settings.expansion.."|r");
		end
	else
		GameTooltip:AddLine(core.L["Informations manquantes"], 1, 0, 0);
	end
	GameTooltip:Show();
end

-- ===== ROTATION MODEL 3D =====
function LeftButtonOnUpdate(self, elapsed)
	local x = GetCursorPosition();
	local newX = x - self.cursorX;
	local facing = self:GetFacing();
	self:SetFacing(facing + newX/100);
	self.cursorX = x;
end

function WC_Lib.ModelOnMouseDown(self,button)
	if button == "LeftButton" then
		self.cursorX = GetCursorPosition();
		self:SetScript("OnUpdate", LeftButtonOnUpdate)
	end
end

function WC_Lib.ModelOnMouseUp(self, button)
	self:SetScript("OnUpdate", nil)
end

function WC_Lib.ModelOnMouseWheel(self, delta)
	local max = 10;
    local min = 0.1;
    self.camDistance = math.min(math.max(self.camDistance-delta*0.15,min),max);
    self:SetCamDistanceScale(self.camDistance);
end


-- ===== VALIDATION TASK/STEP/PAGE =====
local function checkIfExistsDoneTask(value)
	if (value == nil) then
		value = {};
	end
end

local function ToggleDoneTask(self)
	if (WC_arrIsDone[self.allIdFromTask[1]] == nil) then
		WC_arrIsDone[self.allIdFromTask[1]] = {};
	end
	if (WC_arrIsDone[self.allIdFromTask[1]][self.allIdFromTask[2]] == nil) then
		WC_arrIsDone[self.allIdFromTask[1]][self.allIdFromTask[2]] = {};
	end
	if (WC_arrIsDone[self.allIdFromTask[1]][self.allIdFromTask[2]][self.allIdFromTask[3]] == nil) then
		WC_arrIsDone[self.allIdFromTask[1]][self.allIdFromTask[2]][self.allIdFromTask[3]] = {};
	end
	if (WC_arrIsDone[self.allIdFromTask[1]][self.allIdFromTask[2]][self.allIdFromTask[3]][self.allIdFromTask[4]] == nil) then
		WC_arrIsDone[self.allIdFromTask[1]][self.allIdFromTask[2]][self.allIdFromTask[3]][self.allIdFromTask[4]] = true;
	else
		WC_arrIsDone[self.allIdFromTask[1]][self.allIdFromTask[2]][self.allIdFromTask[3]][self.allIdFromTask[4]] = not WC_arrIsDone[self.allIdFromTask[1]][self.allIdFromTask[2]][self.allIdFromTask[3]][self.allIdFromTask[4]];
	end
	WC_Lib.RefreshCollectionContent(self.allIdFromTask[1], "WC", true);
	WC_Lib.OnEnterTask(self);
end

local function WC_arrIsDoneExists(allIdFromTask)
	if (WC_arrIsDone[allIdFromTask[1]] ~= nil) then
		if (WC_arrIsDone[allIdFromTask[1]][allIdFromTask[2]] ~= nil) then
			if (WC_arrIsDone[allIdFromTask[1]][allIdFromTask[2]][allIdFromTask[3]] ~= nil) then
				if (WC_arrIsDone[allIdFromTask[1]][allIdFromTask[2]][allIdFromTask[3]][allIdFromTask[4]] ~= nil) then
					return true;
				end
			end
		end		
	end
	return false;
end

local function isDoneTask(task, allIdFromTask)
	if (task ~= nil) then
		if (task["taskType"] == "custom") then
			local isNotNil = WC_arrIsDoneExists(allIdFromTask);
			if (isNotNil == true) then
				return WC_arrIsDone[allIdFromTask[1]][allIdFromTask[2]][allIdFromTask[3]][allIdFromTask[4]];
			end
		elseif (task["taskType"] == "hf") then
			local  ret = select(4, GetAchievementInfo(tonumber(task["idHF"])));
			return ret;
		elseif (task["taskType"] == "quest") then
			local  ret = C_QuestLog.IsQuestFlaggedCompleted(tonumber(task["idQuest"]));
			return ret;
		elseif (task["taskType"] == "need") then
			local idValidation = tonumber(task["validationId"]);
			if (task["validationType"] == "manual") then
				local isNotNil = WC_arrIsDoneExists(allIdFromTask);
				if (isNotNil == true) then
					return WC_arrIsDone[allIdFromTask[1]][allIdFromTask[2]][allIdFromTask[3]][allIdFromTask[4]];
				end
				return false;
			elseif (task["validationType"] == "hf") then
				local  ret = select(4, GetAchievementInfo(idValidation));
				return ret;
			elseif (task["validationType"] == "quest") then
				return C_QuestLog.IsQuestFlaggedCompleted(idValidation);
			elseif (task["validationType"] == "mounts") then
				local  ret = select(11, C_MountJournal.GetMountInfoByID(idValidation));
				return ret;
			elseif (task["validationType"] == "pets") then
				local ret   = WC_Lib.getPetInfoById(idValidation);
				return ret[3];
			elseif (task["validationType"] == "transmogs") then
				local  ret = C_TransmogCollection.PlayerHasTransmog(idValidation, task["validationModId"]);
				return ret;
			end
		end
	end
	return false;
end

local function isDoneStep(step, allIdFromTask)
	if (step ~= nil and step.task ~= nil) then
		for i = 1, #step.task do
			allIdFromTask[4] = i;
			if (isDoneTask(step.task[i], allIdFromTask) == false) then
				return false;
			end
		end
		return true;
	end
	return false;
end

local function isDonePage(page, allIdFromTask)
	if (page ~= nil and page.step ~= nil) then
		for i = 1, #page.step do
			allIdFromTask[3] = i;
			if (isDoneStep(page.step[i], allIdFromTask) == false) then
				return false;
			end
		end
		return true;
	end
	return false;
end
-- ===== END validation task/step/page =====


function WC_Lib.GetInfoHFCriteria(hfID, mode) -- mode: 0 = only nbDone ; 1 = only string Crit ; 2 = string Crit + color done
	local stret = "";
	local nbDone = 0;
	for i = 1, GetAchievementNumCriteria(hfID) do
		local getCriteria = {GetAchievementCriteriaInfo(hfID, i)}
		if (getCriteria[3] == true and mode ~= 1) then
			nbDone = nbDone + 1;
			stret = stret.."|cff00ff00"..getCriteria[1]..'|r\n';
		else
			stret = stret..getCriteria[1]..'\n';
		end
	end
	if (mode == 0) then
		return nbDone;
	end
	return stret;
	
end

function WC_Lib.DeleteCollection(idGuide, addon)
	local tmp = nil;
	local tmpColl = nil;
	local itmp = 1;
	if (addon == "WCC") then
		for i = 1, #ListGuides do
			if (idGuide == ListGuides[i]) then
				if (idGuide == g_guideSelected[addon] and _G[addon.."_BasicFrames"]) then
					_G[addon.."_BasicFrames"]:Hide();
				end
				_G[addon.."_GuidesCollection"..idGuide]:Hide();
				_G[addon.."_GuidesCollection"..idGuide]:ClearAllPoints();
				table.remove(ListGuides, i)
				table.remove(YourGuides, WC_Lib.GetIndexGuideByID(idGuide, addon))
				break;
			end
		end
	elseif (addon == "WC") then
		for i = 1, #WC_ListGuides do
			if (idGuide == WC_ListGuides[i]) then
				if (idGuide == g_guideSelected[addon] and _G[addon.."_BasicFrames"]) then
					_G[addon.."_BasicFrames"]:Hide();
				end				
				_G[addon.."_GuidesCollection"..idGuide]:Hide();
				_G[addon.."_GuidesCollection"..idGuide]:ClearAllPoints();
				table.remove(WC_ListGuides, i)
				table.remove(WC_Guides, WC_Lib.GetIndexGuideByID(idGuide, addon))
				break;
			end
		end
	end
	WC_Lib.RefreshListCollections(addon);
end

function WC_Lib.SetProgressButton(icon, idBtn, isDone, isSelected, addon)--(parent, icon, isDone, isSelected, addon)
	local iconFrame   = _G[addon.."_BasicFrames"].goalIconFrame;
	if idBtn > 0 then
		iconFrame = _G[addon.."_PageBtn"..idBtn]
	end
	iconFrame:SetBackdrop({bgFile = icon or "Interface\\ICONS\\inv_misc_questionmark"});
	iconFrame.greenCheck:Hide();
	iconFrame.lockIcon:Hide();
	if (addon == "WC") then
		if (isDone == 1 or isDone == true) then
			iconFrame.lockIcon:Hide();
			iconFrame.greenCheck:Show();
		elseif (isDone == 2 and idBtn ~= 0) then
			iconFrame.greenCheck:Hide();
			iconFrame.lockIcon:Show();
		end
	end
	if (isSelected == true) then
		iconFrame.selected:Show();
	else
		iconFrame.selected:Hide();
	end
end

function CollectionPage_OnClick(self)
	local guide = WC_Lib.GetGuideByID(self.idGuide, self.addon);
	if (string.find(self:GetName(), "Goal")) then
		CollectionPageFrame_Hide_All(self.addon, guide);
		WC_Lib.SetProgressButton(self, guide.icon, guide["info"][2], true, self.addon);
	else
		CollectionPageFrame_Hide_All(self.addon, guide);
		WC_Lib.SetProgressButton(self, guide["page"][self.id].icon, self.isDone, true, self.addon);
		local parentName = self.addon.."_CollectionFrame"..self.idGuide.."_PageChapter"..self.id.."_Btn_Content";
		if (_G[parentName.."_Rens1"] == nil) then
			WC_Lib.RefreshAllRens(guide["page"][self.id], _G[parentName], self.addon);
		end
	end
	self.isSelected = true;
	PlaySound("83", "sfx");
	self.content:Show();
end

function WC_Lib.RefreshProgressBarHFGoal(idHF, addon)
	local criteriaDone = 0;
	local nbCriteria = 0;
	if (idHF ~= "") then
		criteriaDone = WC_Lib.GetInfoHFCriteria(idHF, 0);
		nbCriteria = GetAchievementNumCriteria(idHF);
	else
		criteriaDone = "??";
		nbCriteria = "??";
	end
	
	if (nbCriteria == 0) then
		local _, _, _, completed = GetAchievementInfo(idHF);
		if (completed == true) then
			criteriaDone = 1;
		else
			criteriaDone = 0;
		end
		nbCriteria = 1;
	end
	local progressFrame = _G[addon.."_BasicFrames"].goal_content.hfContent.progressFrame;
	if (criteriaDone == "??" or nbCriteria == "??") then
		progressFrame.progressBar.fillFrame:SetSize(0, 15);
	else
		local percent = criteriaDone * 100 / nbCriteria;
		local width = (progressFrame.progressBar:GetWidth()-3) * percent / 100;
		if width <= 0 then width = 0.5 end
		progressFrame.progressBar.fillFrame:SetSize(width, 15);
		progressFrame:SetScript("OnLeave", WC_Lib.OnLeave);
		progressFrame:SetScript("OnEnter", function (self, motion)
			GameTooltip:SetOwner(self, "ANCHOR_TOP", 0, 0);
			GameTooltip:AddLine(core.L["Progression de votre personnage"]);
			GameTooltip:AddLine(WC_Lib.GetInfoHFCriteria(idHF, 2), 1, 1, 1);
			GameTooltip:Show();
			end);
	end
	progressFrame.progressBar.text:SetText(criteriaDone.."/"..nbCriteria);
end

function WC_Lib.RensNext_OnClick(self)
	if (self:GetParent():GetID() + 1 <= self:GetParent().rensCount) then
		for i = 1, self:GetParent().rensCount do
			self:GetParent():Hide();
		end
		local minus = string.len(self:GetParent():GetID());
		_G[self:GetParent():GetName():sub(1, -1 - minus)..(self:GetParent():GetID() + 1)]:Show();
		PlaySound("605", "sfx", true);
	end
end

function WC_Lib.RensPrev_OnClick(self)
	if (self:GetParent():GetID() - 1 >= 1) then
		for i = 1, self:GetParent().rensCount do
			self:GetParent():Hide();
		end
		local minus = string.len(self:GetParent():GetID());
		_G[self:GetParent():GetName():sub(1, -1 - minus)..(self:GetParent():GetID() - 1)]:Show();
		PlaySound("605", "sfx", true);
	end
end

function WC_Lib.GetShowMapStr(IDZone)
	local ret = "";
	local infoMap    = C_Map.GetMapInfo(tonumber(IDZone));
	local parentZone = "";
	if (infoMap ~= nil) then
		if (infoMap.parentMapID ~= 0) then
			parentZone = " ("..C_Map.GetMapInfo(infoMap.parentMapID).name..")";
		end
		if (ret == "") then
			ret = infoMap.name..parentZone;
		else
			ret = ret..", "..infoMap.name..parentZone;
		end
	else
		ret = ret..", |cffff0000"..core.L["Erreur Zone ID"]..core.L["2points"]..IDZone.."|r";
	end
	return ret;
end

local OnEnterPinsOnMap = function(self, motion)
	GameTooltip:SetOwner(self, "ANCHOR_TOP");
	if (self.infoPin.IsEntry) then
		GameTooltip:AddLine(self.title.." ("..core.L["Entrance"]..")");	
	else
		GameTooltip:AddLine(self.title);	
	end
	GameTooltip:AddLine("|cffffffff"..WC_Lib.GetShowMapStr(self.infoPin.IDZone).."|r ("..tostring(self.infoPin.posX)..", "..tostring(self.infoPin.posY)..")");
	GameTooltip:Show();
end

function WC_Lib.isPinActivated(idGuide, idPage, idRens, addon)
	for i = 1, #g_pinsActivated[addon] do
		if (g_pinsActivated[addon][i] and
			g_pinsActivated[addon][i].idGuide == idGuide and
			g_pinsActivated[addon][i].idPage  == idPage and
			g_pinsActivated[addon][i].idRens  == idRens) then
			return true;
		end
	end
	return false;
end

function WC_Lib.DisablePin(idGuide, idPage, idRens, addon)
	for i = 1, #g_pinsActivated[addon] do
		if (g_pinsActivated[addon][i] and
			g_pinsActivated[addon][i].idGuide == idGuide and
			g_pinsActivated[addon][i].idPage  == idPage and
			g_pinsActivated[addon][i].idRens  == idRens) then
			table.remove(g_pinsActivated[addon], i);
		end
	end
end

function WC_Lib.ShowMap_OnClick(self)
	local pinsRef = _G["WC_Pins"..self.idGuide..self.idPage..self.idRens];
	if not pinsRef then
		pinsRef = CreateFrame("Frame", "WC_Pins"..self.idGuide..self.idPage..self.idRens, nil);
	end
	if not WC_Lib.isPinActivated(self.idGuide, self.idPage, self.idRens, self.addon) then
		table.insert(g_pinsActivated[self.addon], {idGuide = self.idGuide, idPage = self.idPage, idRens = self.idRens});
		self:SetNormalTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin_selected");
		self:SetPushedTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin_selected");
		self:SetHighlightTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin_selected");
		for i = 1, #self.pins do		
			local pinWorldMap   = CreateFrame("Button", "WoWChallengerPin", WorldMapFrame)
			pinWorldMap.title   = self.title;
			pinWorldMap.infoPin = self.pins[i];
			pinWorldMap:SetWidth(45)
			pinWorldMap:SetHeight(45)
			pinWorldMap:EnableMouse(true)
			pinWorldMap:SetFrameLevel(WorldMapFrame:GetFrameLevel() + 2);
			pinWorldMap:SetNormalTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
			pinWorldMap:SetPushedTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
			pinWorldMap:SetHighlightTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
			pinWorldMap:SetScript("OnEnter", OnEnterPinsOnMap);
			pinWorldMap:SetScript("OnLeave", WC_Lib.OnLeave);
			
			pinWorldMap.texture = pinWorldMap:CreateTexture(nil, "BACKGROUND")
			pinWorldMap.texture:SetSize(25, 25);
			pinWorldMap.texture:SetPoint("CENTER", pinWorldMap, "CENTER");
			if (self.category == "NPC" and self.displayID ~= "") then
				SetPortraitTextureFromCreatureDisplayID(pinWorldMap.texture, self.displayID);
			else
				pinWorldMap.texture:SetTexture(134269)
			end
			
			local pinMinimap   = CreateFrame("Button", "WoWChallengerPin", MinimapCluster)
			pinMinimap.title   = self.title;
			pinMinimap.infoPin = self.pins[i];
			pinMinimap:SetWidth(35)
			pinMinimap:SetHeight(35)
			pinMinimap:EnableMouse(true)
			pinMinimap:SetFrameLevel(MinimapCluster:GetFrameLevel() + 2);
			pinMinimap:SetNormalTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
			pinMinimap:SetPushedTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
			pinMinimap:SetHighlightTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
			pinMinimap:SetScript("OnEnter", OnEnterPinsOnMap);
			pinMinimap:SetScript("OnLeave", WC_Lib.OnLeave);
			
			pinMinimap.texture = pinMinimap:CreateTexture(nil, "BACKGROUND")
			pinMinimap.texture:SetSize(18, 18);
			pinMinimap.texture:SetPoint("CENTER", pinMinimap, "CENTER");
			if (self.category == "NPC" and self.displayID ~= "") then
				SetPortraitTextureFromCreatureDisplayID(pinMinimap.texture, self.displayID);
			else
				pinMinimap.texture:SetTexture(134269);
			end

			HBD_Pins:AddWorldMapIconMap(pinsRef, pinWorldMap, tonumber(self.pins[i].IDZone), tonumber(self.pins[i].posX/100), tonumber(self.pins[i].posY/100), HBD_PINS_WORLDMAP_SHOW_WORLD);
			HBD_Pins:AddMinimapIconMap(pinsRef, pinMinimap, tonumber(self.pins[i].IDZone), tonumber(self.pins[i].posX/100), tonumber(self.pins[i].posY/100), false, true)
		end
	else
		WC_Lib.DisablePin(self.idGuide, self.idPage, self.idRens, self.addon);
		self:SetNormalTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
		self:SetPushedTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
		self:SetHighlightTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
		HBD_Pins:RemoveAllWorldMapIcons(pinsRef);
		HBD_Pins:RemoveAllMinimapIcons(pinsRef); -- bug remove tous les points (car même frame)
	end
	WC_Lib.OnEnterBtnShowMap(self);
	PlaySound("83", "sfx");
end

function WC_Lib.GetObjectivesQuest(idQuest)
	local ret = "";
	local objectives = C_QuestLog.GetQuestObjectives(idQuest);
	if (objectives ~= nil) then
		for i = 1, #objectives do
			local text = objectives[i].text;
			if (objectives[i].finished == true) then
				text = "|cff00ff00"..text.."|r";
			end
			if (ret == "") then
				ret = text;
			else
				ret = ret.."\n"..text;
			end
		end
	else
		ret = core.L["DescQuest"]
	end
	return ret;
end

function WC_Lib.CreateBasicFrames(addon)
	local frameParent = _G["WoWChallengerFrameCollections"];
	local posY        = 0;
	if (addon == "WCC") then
		frameParent = _G["WoWChallengerCreatorFrame"];
		posY = 2.5;
	end
	
	local basicFrames = CreateFrame("Frame", addon.."_BasicFrames", frameParent, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames:SetSize(555,450);
	basicFrames:SetPoint("BOTTOMRIGHT", frameParent, "BOTTOMRIGHT", -2, posY);
	basicFrames:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/challenges/bg_step_challenge",
								edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
								tile = false, edgeSize = 16, 
								insets = { left = 3, right = 0, top = 0, bottom = 0 }});
	
	basicFrames.title = basicFrames:CreateFontString(nil, "OVERLAY", nil, basicFrames);
	if GetLocale() == "ruRU" then
		basicFrames.title:SetFont("Interface\\AddOns\\WoWChallenger\\fonts\\FRIZQT__CYR.TTF", 20, "OUTLINE");
	else
		basicFrames.title:SetFont("Fonts\\FRIZQT__.TTF", 20, "OUTLINE");
	end
	basicFrames.title:SetPoint("TOP", basicFrames, "TOP", 0, -15);
	basicFrames.title:SetSize(basicFrames:GetWidth(), 0);
	
	basicFrames.infoBtn = CreateFrame("Button", nil, basicFrames);
	basicFrames.infoBtn:SetSize(40, 40);
	basicFrames.infoBtn:SetPoint("TOPRIGHT", basicFrames, "TOPRIGHT", -20, -8);
	basicFrames.infoBtn:SetNormalTexture("Interface/COMMON/help-i");
	basicFrames.infoBtn:SetScript("OnEnter", function(self)
		GameTooltip:SetOwner(self, "ANCHOR_TOP", 0, 7);
		GameTooltip:AddLine(self.info.name, 1, 1, 1);
		GameTooltip:AddLine(core.L["ID Guide"]..core.L["2points"].."|cff00c8ff"..self.info.id.."|r");
		GameTooltip:AddLine(core.L["Version"]..core.L["2points"].."|cffffffff"..self.info.version.."|r");
		GameTooltip:AddLine(core.L["Créé par"]..core.L["2points"].."|cffffffff"..self.info.createBy.."|r");
		GameTooltip:AddLine(core.L["Langue"]..core.L["2points"].."|cffffffff"..self.info.lang.."|r");
		GameTooltip:Show();
	end);
	basicFrames.infoBtn:SetScript("OnLeave", WC_Lib.OnLeave);
	basicFrames.infoBtn:Hide();

	basicFrames.editBtn = CreateFrame("Button", nil, basicFrames);
	basicFrames.editBtn:SetSize(22, 22);
	basicFrames.editBtn:SetPoint("TOPRIGHT", basicFrames, "TOPRIGHT", -25, -15);
	basicFrames.editBtn:SetNormalTexture("Interface/WorldMap/Gear_64Grey");
	basicFrames.editBtn:SetHighlightTexture("Interface/Buttons/UI-Common-MouseHilight");
	basicFrames.editBtn:SetScript("OnClick", function(self) WCCreator_Lib.ShowMainParamGuide(self) end);
	basicFrames.editBtn:SetScript("OnEnter", function(self)	GameTooltip:SetOwner(self, "ANCHOR_RIGHT", 0, 0);
												GameTooltip:AddLine(core.L["Paramètres"]);
												GameTooltip:Show(); end);
	basicFrames.editBtn:SetScript("OnLeave", WC_Lib.OnLeave);
	basicFrames.editBtn:Hide();
	
	basicFrames.bar_page = CreateFrame("Frame", nil, basicFrames, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames.bar_page:SetSize(548, 55);
	basicFrames.bar_page:SetPoint("TOP", basicFrames, "TOP", -10, -60);
	basicFrames.bar_page:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/mounts/fond_progress_page"});	
	
	-- ICONS PAGES --
	for i = 1, WCC_MAX_PAGE_GUIDE do
		local pageBtn = CreateFrame("Button", addon.."_PageBtn"..i, basicFrames.bar_page, BackdropTemplateMixin and "BackdropTemplate");
		pageBtn:SetSize(36, 36);
		pageBtn:SetBackdrop({bgFile = "Interface\\ICONS\\inv_misc_questionmark"});
		pageBtn:SetPoint("CENTER");
		pageBtn:SetScript("OnLeave", WC_Lib.OnLeave);
		pageBtn:SetScript("OnEnter", function(self)
			GameTooltip:SetOwner(self, "ANCHOR_TOP", 0, 3);
			if (self.addon == "WCC") then
				GameTooltip:AddLine(core.L["Chapter"]..i);
				GameTooltip:AddLine("<"..core.L["Clique droit pour modifier"]..">", 0, 1, 0);
			else
				if (self.isDone == 2) then
					GameTooltip:AddLine(core.L["Chapter"]..i.." ("..core.L["Lock"]..")", 0.5, 0.5, 0.5);
				elseif (self.isDone == true or self.isDone == 1) then
					GameTooltip:AddLine(core.L["Chapter"]..i, 0, 1, 0);
				else
					GameTooltip:AddLine(core.L["Chapter"]..i);
				end
			end
			GameTooltip:Show();
		end);		
		pageBtn:RegisterForClicks("LeftButtonUp", "RightButtonDown");
		pageBtn.contextMenu = CreateFrame("Frame", nil, pageBtn, "UIDropDownMenuTemplate");
		pageBtn:SetScript("OnClick", function (self, button, down)
			if (button == "LeftButton") then
				if (self.isDonePrev == false and self.addon == "WC") then
					return;
				else
					WC_Lib.CollectionPage_OnClick(self);
				end
			elseif (button == "RightButton" and self.addon == "WCC") then
				WCCreator_Lib.structures.PageMenu.frameOwner = self;
				if (self.nbPage == 1) then
					WCCreator_Lib.structures.PageMenu.info[4].disabled = true;
				else
					WCCreator_Lib.structures.PageMenu.info[4].disabled = false;
				end	
				if (self.nbPage == WCC_MAX_PAGE_GUIDE) then
					WCCreator_Lib.structures.PageMenu.info[2].disabled = true;
					WCCreator_Lib.structures.PageMenu.info[3].disabled = true;
				else
					WCCreator_Lib.structures.PageMenu.info[2].disabled = false;
					WCCreator_Lib.structures.PageMenu.info[3].disabled = false;
				end
				EasyMenu(WCCreator_Lib.structures.PageMenu.info, pageBtn.contextMenu, pageBtn, 0 , 0, "MENU")
				PlaySound("83", "sfx");
			end
		end);
		
		pageBtn.greenCheck = CreateFrame("Frame", nil, pageBtn, BackdropTemplateMixin and "BackdropTemplate");
		pageBtn.greenCheck:SetSize(35, 35);
		pageBtn.greenCheck:SetPoint("CENTER", pageBtn, "CENTER");
		pageBtn.greenCheck:SetFrameLevel(pageBtn:GetFrameLevel() + 1);
		pageBtn.greenCheck:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/greenCheck"});
			
		pageBtn.lockIcon = CreateFrame("Frame", nil, pageBtn, BackdropTemplateMixin and "BackdropTemplate");
		pageBtn.lockIcon:SetPoint("CENTER", pageBtn, "CENTER");
		pageBtn.lockIcon:SetFrameLevel(pageBtn:GetFrameLevel() + 1);
		pageBtn.lockIcon:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/challenges/lockIconStep"});
		pageBtn.lockIcon:SetSize(22, 22);
		pageBtn.lockIcon:Hide();
		
		pageBtn.selected = CreateFrame("Frame", nil, pageBtn, BackdropTemplateMixin and "BackdropTemplate");
		pageBtn.selected:SetSize(pageBtn:GetWidth(), pageBtn:GetHeight()+1);
		pageBtn.selected:SetPoint("CENTER", pageBtn, "CENTER");
		pageBtn.selected:SetFrameLevel(pageBtn.greenCheck:GetFrameLevel() + 1);
		pageBtn.selected:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/CheckButtonHilight"});
		
		local arrow = CreateFrame("Frame", addon.."_PageArrow"..i, basicFrames.bar_page, BackdropTemplateMixin and "BackdropTemplate");
		arrow:SetSize(16, 32);
		arrow:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/mounts/arrowRight"});
		arrow:SetPoint("CENTER");
	end
	
	-- ICON GOAL --
	basicFrames.goalIconFrame = CreateFrame("Button", nil, basicFrames, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames.goalIconFrame:SetSize(50, 50);
	basicFrames.goalIconFrame:SetFrameLevel(basicFrames.bar_page:GetFrameLevel() + 1);
	basicFrames.goalIconFrame:SetPoint("RIGHT", basicFrames.bar_page, "RIGHT", -5, -2);
	basicFrames.goalIconFrame:SetScript("OnEnter", WC_Lib.tooltip_iconCollection);
	basicFrames.goalIconFrame:SetScript("OnLeave", WC_Lib.OnLeave);
	basicFrames.goalIconFrame.anchor = "ANCHOR_RIGHT";
	basicFrames.goalIconFrame:SetScript("OnClick", WC_Lib.CollectionPageGoal_OnClick);
	
	basicFrames.goalIconFrame.bg = CreateFrame("Frame", nil, basicFrames.goalIconFrame, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames.goalIconFrame.bg:SetSize(58, 58);
	basicFrames.goalIconFrame.bg:SetPoint("CENTER", basicFrames.goalIconFrame, "CENTER");
	basicFrames.goalIconFrame.bg:SetFrameLevel(basicFrames.goalIconFrame:GetFrameLevel() + 1);
	basicFrames.goalIconFrame.bg:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/bg_goal"});
	
	basicFrames.goalIconFrame.greenCheck = CreateFrame("Frame", nil, basicFrames.goalIconFrame, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames.goalIconFrame.greenCheck:SetPoint("CENTER", basicFrames.goalIconFrame, "CENTER");
	basicFrames.goalIconFrame.greenCheck:SetFrameLevel(basicFrames.goalIconFrame:GetFrameLevel() + 1);
	basicFrames.goalIconFrame.greenCheck:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/greenCheck"});
	basicFrames.goalIconFrame.greenCheck:SetSize(48, 48);
	
	basicFrames.goalIconFrame.lockIcon = CreateFrame("Frame", nil, basicFrames.goalIconFrame, BackdropTemplateMixin and "BackdropTemplate");
	
	basicFrames.goalIconFrame.selected = CreateFrame("Frame", nil, basicFrames.goalIconFrame, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames.goalIconFrame.selected:SetSize(45, 47);
	basicFrames.goalIconFrame.selected:SetPoint("CENTER", basicFrames.goalIconFrame, "CENTER", 0, 2);
	basicFrames.goalIconFrame.selected:SetFrameLevel(basicFrames.goalIconFrame.greenCheck:GetFrameLevel() + 1);
	basicFrames.goalIconFrame.selected:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/CheckButtonHilight"});
	
	-- GOAL CONTENT --
	basicFrames.goal_content = CreateFrame("Frame", nil, basicFrames);
	basicFrames.goal_content:SetSize(544, 333);
	basicFrames.goal_content:SetPoint("BOTTOM", basicFrames, "BOTTOM", 0, 3);	
	
		-- MOUNTS/PETS/TRANMOGS CONTENT --
	basicFrames.goal_content.modelFrame = CreateFrame("DressUpModel", nil, basicFrames.goal_content, BackdropTemplateMixin and "BackdropTemplate")
	basicFrames.goal_content.modelFrame:SetSize(525,330);
	basicFrames.goal_content.modelFrame:SetPoint("TOPLEFT");
	basicFrames.goal_content.modelFrame:SetBackdrop({ bgFile = "Interface/AddOns/WoWChallenger/images/mounts/bg_mounts"});
	basicFrames.goal_content.modelFrame:SetFrameLevel(6);	
	basicFrames.goal_content.modelFrame:SetKeepModelOnHide(true);
	basicFrames.goal_content.modelFrame.cursorX = 0;
	basicFrames.goal_content.modelFrame:SetScript("OnMouseWheel", WC_Lib.ModelOnMouseWheel);
	basicFrames.goal_content.modelFrame:SetScript("OnMouseDown", WC_Lib.ModelOnMouseDown);
	basicFrames.goal_content.modelFrame:SetScript("OnMouseUp", WC_Lib.ModelOnMouseUp);
	
	basicFrames.goal_content.modelFrame.SavePosModel = CreateFrame("Button", nil, basicFrames.goal_content.modelFrame, "UIPanelButtonTemplate");
	basicFrames.goal_content.modelFrame.SavePosModel:SetSize(140, 25);
	basicFrames.goal_content.modelFrame.SavePosModel:SetText(core.L["Enregistrer position"]);
	basicFrames.goal_content.modelFrame.SavePosModel:SetFrameLevel(basicFrames.goal_content.modelFrame:GetFrameLevel() + 1);
	basicFrames.goal_content.modelFrame.SavePosModel:SetPoint("TOPLEFT", basicFrames.goal_content.modelFrame, "TOPLEFT", 5, -5);
	basicFrames.goal_content.modelFrame.SavePosModel:SetScript("OnClick", function(self)
		local model = self:GetParent();
		self.guide.Model.camDist  = model.camDistance;
		self.guide.Model.rotation = model:GetFacing();
		WCCreator_Lib.UpdateVersionGuide(self.guide, nil);
	end);
		
		-- HF CONTENT --
	basicFrames.goal_content.hfContent = CreateFrame("Frame", nil, basicFrames.goal_content, BackdropTemplateMixin and "BackdropTemplate")
	basicFrames.goal_content.hfContent:SetSize(525,330);
	basicFrames.goal_content.hfContent:SetPoint("TOPLEFT");
	basicFrames.goal_content.hfContent:SetBackdrop({ bgFile = "Interface/ACHIEVEMENTFRAME/UI-Achievement-Parchment-Horizontal"});
		
	basicFrames.goal_content.hfContent.desc = basicFrames.goal_content.hfContent:CreateFontString(nil, "OVERLAY", nil, basicFrames.goal_content.hfContent);
	basicFrames.goal_content.hfContent.desc:SetFontObject("GameFontHighlight");
	basicFrames.goal_content.hfContent.desc:SetSize(basicFrames.goal_content.hfContent:GetWidth()-20, 0);
	basicFrames.goal_content.hfContent.desc:SetPoint("TOP", basicFrames.goal_content.hfContent, "TOP", 0, -15);
	
	basicFrames.goal_content.hfContent.progressFrame = CreateFrame("Frame", nil, basicFrames.goal_content.hfContent);	
	basicFrames.goal_content.hfContent.progressFrame:SetSize(175, 30);		
	basicFrames.goal_content.hfContent.progressFrame:SetPoint("CENTER", basicFrames.goal_content.hfContent, "CENTER", 0, 20);
	
	basicFrames.goal_content.hfContent.progressFrame.title = basicFrames.goal_content.hfContent.progressFrame:CreateFontString(nil, "OVERLAY", nil, basicFrames.goal_content.hfContent.progressFrame);
	basicFrames.goal_content.hfContent.progressFrame.title:SetFontObject("GameFontWhite");
	basicFrames.goal_content.hfContent.progressFrame.title:SetPoint("TOPLEFT", basicFrames.goal_content.hfContent.progressFrame, "TOPLEFT", 2, 0);
	basicFrames.goal_content.hfContent.progressFrame.title:SetText(core.L["Progression"]);
		
	basicFrames.goal_content.hfContent.progressFrame.progressBar = CreateFrame("Frame", nil, basicFrames.goal_content.hfContent.progressFrame, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames.goal_content.hfContent.progressFrame.progressBar:SetSize(175, 18);
	basicFrames.goal_content.hfContent.progressFrame.progressBar:SetPoint("BOTTOM");
	basicFrames.goal_content.hfContent.progressFrame.progressBar:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/hf_progressBar"});
	
	basicFrames.goal_content.hfContent.progressFrame.progressBar.fillFrame = CreateFrame("Frame", nil, basicFrames.goal_content.hfContent.progressFrame.progressBar, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames.goal_content.hfContent.progressFrame.progressBar.fillFrame:SetPoint("LEFT", basicFrames.goal_content.hfContent.progressFrame.progressBar, "LEFT", 1, 0);
	basicFrames.goal_content.hfContent.progressFrame.progressBar.fillFrame:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/hf_progressBar_Fill"});

	basicFrames.goal_content.hfContent.progressFrame.progressBar.text = basicFrames.goal_content.hfContent.progressFrame.progressBar.fillFrame:CreateFontString(nil, "OVERLAY", nil, basicFrames.goal_content.hfContent.progressFrame.progressBar.fillFrame);
	basicFrames.goal_content.hfContent.progressFrame.progressBar.text:SetFontObject("GameFontHighlightSmall");
	basicFrames.goal_content.hfContent.progressFrame.progressBar.text:SetPoint("CENTER", basicFrames.goal_content.hfContent.progressFrame.progressBar, "CENTER");

	
	basicFrames.goal_content.hfContent.icon = CreateFrame("Frame", nil, basicFrames.goal_content.hfContent, BackdropTemplateMixin and "BackdropTemplate")
	basicFrames.goal_content.hfContent.icon:SetSize(75,75);
	basicFrames.goal_content.hfContent.icon:SetPoint("RIGHT", basicFrames.goal_content.hfContent.progressFrame, "LEFT", -10, 0);
	basicFrames.goal_content.hfContent.icon.portrait = CreateFrame("Frame", nil, basicFrames.goal_content.hfContent, BackdropTemplateMixin and "BackdropTemplate")
	basicFrames.goal_content.hfContent.icon.portrait:SetSize(168,168);
	basicFrames.goal_content.hfContent.icon.portrait:SetFrameLevel(basicFrames.goal_content.hfContent.icon:GetFrameLevel()+1);
	basicFrames.goal_content.hfContent.icon.portrait:SetPoint("TOPLEFT", basicFrames.goal_content.hfContent.icon, "TOPLEFT", -9, 10);
	basicFrames.goal_content.hfContent.icon.portrait:SetBackdrop({ bgFile = "Interface/ACHIEVEMENTFRAME/UI-Achievement-IconFrame"});
	
	basicFrames.goal_content.hfContent.iconPointAchiev = CreateFrame("Frame", nil, basicFrames.goal_content.hfContent, BackdropTemplateMixin and "BackdropTemplate")
	basicFrames.goal_content.hfContent.iconPointAchiev:SetSize(85,85);
	basicFrames.goal_content.hfContent.iconPointAchiev:SetPoint("LEFT", basicFrames.goal_content.hfContent.progressFrame, "RIGHT");
	basicFrames.goal_content.hfContent.iconPointAchiev:SetBackdrop({ bgFile = "Interface/AddOns/WoWChallenger/images/collections/page_goal_achievement_icon"});
	basicFrames.goal_content.hfContent.iconPointAchiev.nbPoint = basicFrames.goal_content.hfContent.iconPointAchiev:CreateFontString(nil, "OVERLAY", nil, basicFrames.goal_content.hfContent.iconPointAchiev);
	basicFrames.goal_content.hfContent.iconPointAchiev.nbPoint:SetFontObject("GameFontHighlightLarge");
	basicFrames.goal_content.hfContent.iconPointAchiev.nbPoint:SetPoint("CENTER");
	
	basicFrames.goal_content.hfContent.bgReward = CreateFrame("Frame", nil, basicFrames.goal_content.hfContent, BackdropTemplateMixin and "BackdropTemplate")
	basicFrames.goal_content.hfContent.bgReward:SetSize(basicFrames.goal_content.hfContent:GetWidth(),30);
	basicFrames.goal_content.hfContent.bgReward:SetPoint("TOP", basicFrames.goal_content.hfContent.progressFrame, "BOTTOM", 80, -35);
	basicFrames.goal_content.hfContent.bgReward:SetBackdrop({ bgFile = "Interface/ACHIEVEMENTFRAME/UI-Achievement-Reward-Background"});
	basicFrames.goal_content.hfContent.bgReward.text = basicFrames.goal_content.hfContent.bgReward:CreateFontString(nil, "OVERLAY", nil, basicFrames.goal_content.hfContent.bgReward);
	basicFrames.goal_content.hfContent.bgReward.text:SetFontObject("GameFontNormalSmall");
	basicFrames.goal_content.hfContent.bgReward.text:SetPoint("CENTER", basicFrames.goal_content.hfContent.bgReward, "CENTER", -80, 7);
	
	basicFrames.goal_content.hfContent:Hide();
		-- END HF CONTENT --
	
	basicFrames.goal_content.nextBtn = CreateFrame("Button", nil, basicFrames.goal_content, "UIPanelButtonTemplate");
	basicFrames.goal_content.nextBtn:SetSize(120, 25);
	basicFrames.goal_content.nextBtn:SetText(core.L["Next"]);
	basicFrames.goal_content.nextBtn:SetFrameLevel(basicFrames.goal_content.modelFrame:GetFrameLevel() + 1);
	basicFrames.goal_content.nextBtn:SetPoint("BOTTOM", basicFrames.goal_content, "BOTTOM", 0, 20);
	basicFrames.goal_content.nextBtn:SetScript("OnClick", function(self)
													_G[self.addon.."_PageBtn1"]:Click();
												end);
	basicFrames.goal_content.edge = CreateFrame("Frame", nil, basicFrames.goal_content, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames.goal_content.edge:SetSize(545, 340);
	basicFrames.goal_content.edge:SetPoint("BOTTOM", basicFrames.goal_content, "BOTTOM", -6, 0);
	basicFrames.goal_content.edge:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/challenges/edge_character_pct"});
	basicFrames.goal_content.edge:SetFrameLevel(basicFrames.goal_content.modelFrame:GetFrameLevel() + 1);
	
	basicFrames.goal_content:Hide();
	-- END GOAL CONTENT --
	
	-- PAGE CONTENT --
	basicFrames.page_content = CreateFrame("Frame", nil, basicFrames);
	basicFrames.page_content:SetSize(544, 333);
	basicFrames.page_content:SetPoint("BOTTOM", basicFrames, "BOTTOM", 0, 3);
		-- RENS CONTENT --
	basicFrames.page_content.rensZone = CreateFrame("Frame", nil, basicFrames.page_content, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames.page_content.rensZone:SetSize(235, 335);
	basicFrames.page_content.rensZone:SetPoint("BOTTOMLEFT", basicFrames.page_content, "BOTTOMLEFT", -4, 0);
	basicFrames.page_content.rensZone:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/bgBrown",
							edgeFile = "Interface/FriendsFrame/UI-Toast-Border", 
							tile = false, edgeSize = 16, 
							insets = { left = 7, right = 5, top = 5, bottom = 6 }});
							
	basicFrames.page_content.rensZone.rensContent = CreateFrame("DressUpModel", nil, basicFrames.page_content.rensZone, BackdropTemplateMixin and "BackdropTemplate");
	basicFrames.page_content.rensZone.rensContent:SetSize(basicFrames.page_content.rensZone:GetWidth()-15, basicFrames.page_content.rensZone:GetHeight()-15);
	basicFrames.page_content.rensZone.rensContent:SetPoint("CENTER");

	basicFrames.page_content.rensZone.rensContent:SetCamDistanceScale(1);
	basicFrames.page_content.rensZone.rensContent.cursorX = 0;
	basicFrames.page_content.rensZone.rensContent.camDistance = 1;
	basicFrames.page_content.rensZone.rensContent:SetScript("OnMouseWheel", WC_Lib.ModelOnMouseWheel);
	basicFrames.page_content.rensZone.rensContent:SetScript("OnMouseDown", WC_Lib.ModelOnMouseDown)
	basicFrames.page_content.rensZone.rensContent:SetScript("OnMouseUp", WC_Lib.ModelOnMouseUp)		
	basicFrames.page_content.rensZone.rensContent:SetScript("OnShow", function(self)
		if (self.displayID ~= "") then
			if (self.category == "ENV") then
				self:SetModel(tonumber(self.displayID));
			elseif (self.category == "NPC") then
				self:SetDisplayInfo(self.displayID);
			elseif (self.category == "ZONE") then
				self:ClearModel();
			end
		else
			self:ClearModel();
		end
	end)
	
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn = CreateFrame("Button", nil, basicFrames.page_content.rensZone.rensContent);
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn:SetSize(50, 50);
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn:SetPoint("TOPRIGHT", basicFrames.page_content.rensZone.rensContent, "TOPRIGHT", 5, 5);
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn:SetNormalTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn:SetPushedTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn:SetHighlightTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");		
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn.texture = basicFrames.page_content.rensZone.rensContent.showOnMapBtn:CreateTexture(nil, "BACKGROUND")
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn.texture:SetSize(25, 25);
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn.texture:SetPoint("CENTER", basicFrames.page_content.rensZone.rensContent.showOnMapBtn, "CENTER");
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn:SetScript("OnEnter", WC_Lib.OnEnterBtnShowMap);
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn:SetScript("OnLeave", WC_Lib.OnLeave);
	basicFrames.page_content.rensZone.rensContent.showOnMapBtn:SetScript("OnClick", WC_Lib.ShowMap_OnClick);
	basicFrames.page_content.rensZone.rensContent.stepAssignedText = basicFrames.page_content.rensZone.rensContent:CreateFontString(nil, "OVERLAY", nil);
	basicFrames.page_content.rensZone.rensContent.stepAssignedText:SetFontObject("GameFontWhite");
	basicFrames.page_content.rensZone.rensContent.stepAssignedText:SetPoint("TOPLEFT", basicFrames.page_content.rensZone.rensContent, "TOPLEFT", 8, -8);
	basicFrames.page_content.rensZone.rensContent.title = basicFrames.page_content.rensZone.rensContent:CreateFontString(nil, "OVERLAY", nil);
	basicFrames.page_content.rensZone.rensContent.title:SetFontObject("GameFontNormalLarge");
	basicFrames.page_content.rensZone.rensContent.title:SetPoint("BOTTOM", basicFrames.page_content.rensZone.rensContent, "BOTTOM", 0, 40);
	basicFrames.page_content.rensZone.rensContent.title:SetSize(basicFrames.page_content.rensZone.rensContent:GetWidth(), 0);
	
	basicFrames.page_content.rensZone.rensContent.buttonL = CreateFrame("Button", nil, basicFrames.page_content.rensZone.rensContent);
	basicFrames.page_content.rensZone.rensContent.buttonL:SetSize(32, 32);
	basicFrames.page_content.rensZone.rensContent.buttonL:SetPoint("BOTTOM", basicFrames.page_content.rensZone.rensContent, "BOTTOM", -40, 5);
	basicFrames.page_content.rensZone.rensContent.buttonL:SetScript("OnClick", function(self) WC_Lib.RefreshRens(self.id - 1, self.arrRens, self.addon, self.idGuide, self.idPage) end);

	basicFrames.page_content.rensZone.rensContent.buttonR = CreateFrame("Button", nil, basicFrames.page_content.rensZone.rensContent);
	basicFrames.page_content.rensZone.rensContent.buttonR:SetSize(32, 32);
	basicFrames.page_content.rensZone.rensContent.buttonR:SetPoint("BOTTOM", basicFrames.page_content.rensZone.rensContent, "BOTTOM", 40, 5);
	basicFrames.page_content.rensZone.rensContent.buttonR:SetScript("OnClick", function(self) WC_Lib.RefreshRens(self.id + 1, self.arrRens, self.addon, self.idGuide, self.idPage) end);
	
	basicFrames.page_content.rensZone.rensContent.pageText = basicFrames.page_content.rensZone.rensContent:CreateFontString(nil, "OVERLAY", nil);
	basicFrames.page_content.rensZone.rensContent.pageText:SetFontObject("GameFontHighlight");
	basicFrames.page_content.rensZone.rensContent.pageText:SetPoint("BOTTOM", basicFrames.page_content.rensZone.rensContent, "BOTTOM", 0, 15);
	
		-- BUTTONS ADD RENS
	basicFrames.page_content.rensZone.rensContent.AddBtn = CreateFrame("Button", nil, basicFrames.page_content.rensZone.rensContent);
	basicFrames.page_content.rensZone.rensContent.AddBtn:SetSize(24, 24);
	basicFrames.page_content.rensZone.rensContent.AddBtn.bIsNew = true;
	basicFrames.page_content.rensZone.rensContent.AddBtn:SetPoint("BOTTOMRIGHT", basicFrames.page_content.rensZone.rensContent, "BOTTOMRIGHT", -20, 9);
	basicFrames.page_content.rensZone.rensContent.AddBtn:SetNormalTexture("Interface/GuildBankFrame/UI-GuildBankFrame-NewTab");
	basicFrames.page_content.rensZone.rensContent.AddBtn:SetHighlightTexture("Interface/GuildBankFrame/UI-GuildBankFrame-NewTab");
	basicFrames.page_content.rensZone.rensContent.AddBtn:SetScript("OnClick", function(self) WCCreator_Lib.ToggleSettingsRens(self) end);
	basicFrames.page_content.rensZone.rensContent.AddBtn:SetScript("OnLeave", WC_Lib.OnLeave);
	basicFrames.page_content.rensZone.rensContent.AddBtn:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, "ANCHOR_RIGHT", 0, 0);
																		GameTooltip:AddLine(core.L["Ajouter un cadre"]);
																		GameTooltip:Show();
																	end);
	
		-- BUTTONS EDIT RENS
	basicFrames.page_content.rensZone.rensContent.EditBtn        = CreateFrame("Button", nil, basicFrames.page_content.rensZone.rensContent);
	basicFrames.page_content.rensZone.rensContent.EditBtn:SetSize(24, 24);
	basicFrames.page_content.rensZone.rensContent.EditBtn.bIsNew = false;
	basicFrames.page_content.rensZone.rensContent.EditBtn:SetPoint("BOTTOMLEFT", basicFrames.page_content.rensZone.rensContent, "BOTTOMLEFT", 20, 9);
	basicFrames.page_content.rensZone.rensContent.EditBtn:SetNormalTexture("Interface/WorldMap/Gear_64Grey");
	basicFrames.page_content.rensZone.rensContent.EditBtn:SetHighlightTexture("Interface/Buttons/UI-Common-MouseHilight");
	basicFrames.page_content.rensZone.rensContent.EditBtn:SetScript("OnClick", function(self) WCCreator_Lib.ToggleSettingsRens(self) end);
	basicFrames.page_content.rensZone.rensContent.EditBtn:SetScript("OnLeave", WC_Lib.OnLeave);
	basicFrames.page_content.rensZone.rensContent.EditBtn:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, "ANCHOR_RIGHT", 0, 0);
																		GameTooltip:AddLine(core.L["Editer le cadre"]);
																		GameTooltip:Show();
																	end);
	
		-- STEP CONTENT --
	basicFrames.page_content.ScrollStep = CreateFrame("ScrollFrame",  nil, basicFrames.page_content, "UIPanelScrollFrameTemplate");
	basicFrames.page_content.ScrollStep:SetSize(315, 335);
	basicFrames.page_content.ScrollStep:SetPoint("BOTTOMRIGHT", basicFrames.page_content, "BOTTOMRIGHT");
	basicFrames.page_content.ScrollStep:SetClipsChildren(true);
	basicFrames.page_content.ScrollStep.ScrollBar:ClearAllPoints();
	basicFrames.page_content.ScrollStep.ScrollBar:SetPoint("TOPRIGHT", basicFrames.page_content.ScrollStep, "TOPRIGHT", -1, -18);
	basicFrames.page_content.ScrollStep.ScrollBar:SetPoint("BOTTOMRIGHT", basicFrames.page_content.ScrollStep, "BOTTOMRIGHT", -1, 18);
	basicFrames.page_content.ScrollStep.child = CreateFrame("Frame", nil, basicFrames.page_content.ScrollStep);
	basicFrames.page_content.ScrollStep.child:SetSize(315, 332);
	basicFrames.page_content.ScrollStep:SetScrollChild(basicFrames.page_content.ScrollStep.child);
	basicFrames.page_content.ScrollStep:SetScript("OnMouseWheel", WC_Lib.ScrollFrame_OnMouseWheel);
	
	basicFrames.page_content.btnNewStep = CreateFrame("Button", nil, basicFrames.page_content.ScrollStep.child, "UIPanelButtonTemplate");
	basicFrames.page_content.btnNewStep:SetSize(256, 27);
	basicFrames.page_content.btnNewStep:SetText(core.L["Nouvel étape"]);
	basicFrames.page_content.btnNewStep:SetScript("OnClick", function(self)
		local newStep = {help = "", important = false, task = { {taskType = "custom", title = core.L["Titre quête"], tooltipText = core.L["Description quête"]}} };
		table.insert(self.arrSteps, newStep);
		WC_Lib.RefreshPageSteps(self.arrSteps, "WCC", self.idGuide, self.idPage);
		WCCreator_Lib.UpdateVersionGuide(nil, self.idGuide);
	end);
	
	basicFrames.page_content:Hide();
end


------ ONCLICK EVENT ------
function WC_Lib.CollectionPage_OnClick(self)
	local basicFrames = _G[self.addon.."_BasicFrames"];
	basicFrames.goal_content:Hide();
	basicFrames.page_content:Show();
	local guide = WC_Lib.GetGuideByID(self.idGuide, self.addon);
	if (g_pageSelected[self.addon] ~= self.id) then
		basicFrames.page_content.ScrollStep:SetVerticalScroll(0);
		WC_Lib.RefreshRens(1, guide.page[self.id].rens, self.addon, guide.idGuide, self.id);
		WC_Lib.RefreshPageSteps(guide.page[self.id].step, self.addon, guide.idGuide, self.id);		
	end
	WC_Lib.SetProgressButton(guide.icon, 0, guide.info[2], false, self.addon);
	g_pageSelected[self.addon] = self.id;
	WC_Lib.RefreshAllBtnPageCollection(guide, self.addon);
	PlaySound("83", "sfx");
end

function WC_Lib.CollectionPageGoal_OnClick(self)
	if not self.guide then return end;
	
	local basicFrames = _G[self.addon.."_BasicFrames"];
	basicFrames.page_content:Hide();
	basicFrames.goal_content:Show();
	if (g_pageSelected[self.addon] ~= "" and self.guide.page[g_pageSelected[self.addon]]) then
		WC_Lib.SetProgressButton(self.guide.page[g_pageSelected[self.addon]].icon, g_pageSelected[self.addon], _G[self.addon.."_PageBtn"..g_pageSelected[self.addon]].isDone, false, self.addon);
		g_pageSelected[self.addon] = "";
	end
	if (g_guideSelected[self.addon] ~= self.guide.idGuide) then
		local hfFrame    = basicFrames.goal_content.hfContent;
		local modelFrame = basicFrames.goal_content.modelFrame;
		if (self.guide.category == "hf") then
			modelFrame:Hide();
			hfFrame.desc:SetText(self.guide["info"][3]);
			hfFrame.icon:SetBackdrop({ bgFile = self.guide.icon});
			WC_Lib.RefreshProgressBarHFGoal(self.guide.id, self.addon);
			if (self.guide.id ~= "") then
				local _, _, points, _,_,_,_,_,_,_, rewardText = GetAchievementInfo(self.guide.id);
				hfFrame.iconPointAchiev.nbPoint:SetText(points);
				hfFrame.bgReward.text:SetText(rewardText);
				if (rewardText == "") then
					hfFrame.bgReward:Hide();
				end
			else
				hfFrame.iconPointAchiev.nbPoint:SetText("??");
				hfFrame.bgReward.text:SetText("");
				hfFrame.bgReward:Hide();
			end
			hfFrame:Show();
		else
			hfFrame:Hide();		
			if (self.guide.Model.id ~= "") then
				if (self.guide.category == "transmogs") then
					modelFrame:SetUnit("player");
					if (self.guide.Model.bOnPlayer ~= nil and self.guide.Model.bOnPlayer == true) then
						modelFrame:Undress();
						local _, sourceID = C_TransmogCollection.GetItemInfo(self.guide.Model.id, self.guide.Model.modID)
						local displayID = sourceID or "item:"..self.guide.Model.id;
						WC_wait(0.5, WC_Lib.SetAppearanceToModel, modelFrame, displayID);
					else
						modelFrame:SetItem(self.guide.Model.id, self.guide.Model.modID);
					end
				else
					modelFrame:SetDisplayInfo(self.guide.Model.id);
				end
				modelFrame:SetFacing(self.guide.Model.rotation);
			end			
			modelFrame:SetCamDistanceScale(self.guide.Model.camDist);
			modelFrame.camDistance = self.guide.Model.camDist;
			modelFrame:Show();
		end
	end
	WC_Lib.SetProgressButton(self.guide.icon, 0, self.guide["info"][2], true, self.addon);
	PlaySound("83", "sfx");
end
----- END ONCLICK EVENT -----

function WC_Lib.CreateTask(id, addon, frameParent)
	local parentName = frameParent:GetParent():GetName();
	local taskFrame  = CreateFrame("Button", parentName.."_Task"..id, frameParent);
	taskFrame:SetSize(frameParent:GetWidth(), 40);
	taskFrame:SetScript("OnLeave", WC_Lib.OnLeave);
	taskFrame:SetScript("OnEnter", WC_Lib.OnEnterTask);
	if (id == 1) then
		taskFrame:SetPoint("TOPLEFT", frameParent, "TOPLEFT", 0, -5);
	else
		taskFrame:SetPoint("LEFT", _G[parentName.."_Task"..id - 1], "LEFT", 0, -40);
	end
	
	taskFrame.title = taskFrame:CreateFontString(nil, "OVERLAY", nil, taskFrame);
	taskFrame.title:SetJustifyH("LEFT");
	taskFrame.title:SetSize(frameParent:GetWidth()-15, 0);
	taskFrame.title:SetPoint("LEFT", taskFrame, "LEFT", 25, 0);
	taskFrame.title:SetFontObject("GameFontHighlightLarge");
	taskFrame.checkIcon = CreateFrame("Frame", nil, taskFrame, BackdropTemplateMixin and "BackdropTemplate");
	taskFrame.checkIcon:SetSize(32, 32);
	taskFrame.checkIcon:SetPoint("LEFT", taskFrame, "LEFT", -3, 0);
	taskFrame.checkIcon:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/challenges/greenCheckButton"});

	taskFrame.itemIcon = CreateFrame("Frame", nil, taskFrame, BackdropTemplateMixin and "BackdropTemplate");
	taskFrame.itemIcon:SetSize(22, 22);
	taskFrame.itemIcon:SetPoint("LEFT", taskFrame, "LEFT", 25, 0);
	taskFrame.itemIcon:SetScript("OnEnter", WC_Lib.OnEnterIconItem);
	taskFrame.itemIcon:SetScript("OnLeave", WC_Lib.OnLeave);

	return taskFrame;
end

function WC_Lib.RefreshStepTasks(arrTasks, addon, idGuide, idPage, idStep, isDonePrevStep)
	local j = 1;
	for i = 1, #arrTasks do
		local taskFrame   = _G[addon.."_Step"..idStep.."_Task"..i];
		local currentTask = arrTasks[i];
		local isDone      = isDoneTask(currentTask, {idGuide, idPage, idStep, i});
		
		---- CREATE TASK IF NOT EXIST ----
		if not taskFrame then
			taskFrame = WC_Lib.CreateTask(i, addon, _G[addon.."_Step"..idStep].taskBg);
		end
		
		---- VALUES ----
		taskFrame.addon         = addon;
		taskFrame.isDone        = isDone;
		taskFrame.taskInfo      = currentTask;
		taskFrame.arrTasks      = arrTasks;
		taskFrame.allIdFromTask = {idGuide, idPage, idStep, i};
		
		
		taskFrame.checkIcon:Hide();
		taskFrame.title:SetFontObject("GameFontHighlightLarge");
		
		if (currentTask.taskType == "need") then
			taskFrame.itemIcon:SetBackdrop({bgFile = currentTask.itemInfo[4] or 134400});
			taskFrame.itemIcon.itemLink = currentTask.itemInfo[2] or 0;
			taskFrame.itemIcon:Show();
			taskFrame.title:SetPoint("LEFT", taskFrame, "LEFT", 50, 0);
			taskFrame.title:SetText("x"..tostring(currentTask.nbRequired)..core.L["Required"]);			
		else
			taskFrame.itemIcon:Hide();
			taskFrame.title:SetPoint("LEFT", taskFrame, "LEFT", 25, 0);
			taskFrame.title:SetText(currentTask.title);
		end
		
		if (addon == "WC") then
			if (isDone == true) then
				taskFrame.checkIcon:Show();
				taskFrame.title:SetFontObject("GameFontGreenLarge");
			end
			if (currentTask.validationType == "manual") then
				taskFrame:SetScript("OnClick", ToggleDoneTask);
			elseif (currentTask.validationType == "transmogs") then
				local _, sourceID = C_TransmogCollection.GetItemInfo(currentTask.validationId, currentTask.validationModId);
				WC_Lib.AddingInEventRefresh({idGuide, currentTask.validationType, tostring(sourceID)});
			else
				WC_Lib.AddingInEventRefresh({idGuide, currentTask.validationType, currentTask.validationId});
				if (currentTask.validationType == "quest" and currentTask.bAutoRefresh ~= nil and currentTask.bAutoRefresh ~= false
				and	WC_Lib.findInArray(WC_arrCriteriaRefresh, idGuide) == -1) then
					table.insert(WC_arrCriteriaRefresh, idGuide);
				end
			end
			if (currentTask.taskType == "custom") then
				taskFrame:SetScript("OnClick", ToggleDoneTask);
			elseif (currentTask.taskType == "hf") then
				WC_Lib.AddingInEventRefresh({idGuide, currentTask.taskType, currentTask.idHF});
			elseif (currentTask.taskType == "quest") then
				WC_Lib.AddingInEventRefresh({idGuide, currentTask.taskType, currentTask.idQuest});
				if (currentTask.bAutoRefresh ~= nil and currentTask.bAutoRefresh ~= false and WC_Lib.findInArray(WC_arrCriteriaRefresh, idGuide) == -1) then
					table.insert(WC_arrCriteriaRefresh, idGuide);
				end
			end
			
			if (isDonePrevStep == false) then
				taskFrame:Hide();
			else
				taskFrame:Show();
			end
		else
			taskFrame:SetScript("OnClick", WCCreator_Lib.ToggleSettingsTask);
			taskFrame:Show();
		end		
		j = j + 1;
	end

	--HIDE LES ETAPES EN TROP
	for j = j, 666 do
		if (_G[addon.."_Step"..idStep.."_Task"..j] == nil) then
			j = 667;
			break;
		else
			_G[addon.."_Step"..idStep.."_Task"..j]:Hide();
		end
	end
end

function WC_Lib.CreateStep(id, arrSteps, addon)
	local parent      = _G[addon.."_BasicFrames"].page_content.ScrollStep.child;
	local stepFrame   = CreateFrame("Frame", addon.."_Step"..id, parent);
	local currentStep = arrSteps[id];

	---- HEADER AND BG PART ----
	stepFrame.title = CreateFrame("Frame", nil, stepFrame, BackdropTemplateMixin and "BackdropTemplate");
	stepFrame.title:SetSize(256, 32);
	stepFrame.title:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/challenges/step_title_bg"});
	stepFrame.title.text = stepFrame.title:CreateFontString(nil, "OVERLAY", nil);
	stepFrame.title.text:SetFontObject("GameFontWhite");
	stepFrame.title.text:SetPoint("LEFT", stepFrame.title, "LEFT", 10, 0);
	if (id == 1) then
		stepFrame.title:SetPoint("TOP", parent, "TOP", -8, -10);
	else
		stepFrame.title:SetPoint("BOTTOM", _G[addon.."_Step"..(id - 1)].taskBg, "BOTTOM", 0, -40);
	end	
	
	stepFrame.title.iconHelp = CreateFrame("Frame", nil, stepFrame.title, BackdropTemplateMixin and "BackdropTemplate");
	stepFrame.title.iconHelp:SetPoint("RIGHT", stepFrame.title, "RIGHT", -5, 0);
	stepFrame.title.iconHelp:SetSize(20, 20);
	stepFrame.title.iconHelp:SetScript("OnEnter", WC_Lib.OnEnterIconHelp);
	stepFrame.title.iconHelp:SetScript("OnLeave", WC_Lib.OnLeave);

	stepFrame.taskBg = CreateFrame("Frame", nil, stepFrame, BackdropTemplateMixin and "BackdropTemplate");
	stepFrame.taskBg:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/challenges/step_task_bg"});
	stepFrame.taskBg:SetPoint("TOP", stepFrame.title, "BOTTOM", 0, 5);
	---- END header and bg part ----
	
	---- LOCK PART ----
	stepFrame.lockStepText = stepFrame.taskBg:CreateFontString(nil, "OVERLAY", nil);
	stepFrame.lockStepText:SetFontObject("GameFontHighlight");
	stepFrame.lockStepText:SetText(core.L["EtapeLock"]);
	stepFrame.lockStepText:SetPoint("LEFT", stepFrame.taskBg, "LEFT", 25, 0);
	stepFrame.lockStepText:SetJustifyH("LEFT");
	stepFrame.lockStepText:SetSize(stepFrame:GetWidth(), 0);
	stepFrame.title.iconLock = CreateFrame("Frame", nil, stepFrame.title, BackdropTemplateMixin and "BackdropTemplate");
	stepFrame.title.iconLock:SetPoint("RIGHT", stepFrame.title, "RIGHT", -5, 0);
	stepFrame.title.iconLock:SetSize(20, 20);
	stepFrame.title.iconLock:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/challenges/lockIconStep"});
	stepFrame.title.iconLock:SetScript("OnEnter", function(self, motion)
		GameTooltip:SetOwner(self, "ANCHOR_LEFT", 0, 0);
		GameTooltip:AddLine(core.L["Lock"], 0.5, 0.5, 0.5);
		GameTooltip:Show();
	end);
	stepFrame.title.iconLock:SetScript("OnLeave", WC_Lib.OnLeave);
	---- END lock part ----
	
	---- WCC BTN ----
	stepFrame.btnEditStep = CreateFrame("Button", nil, stepFrame);
	stepFrame.btnEditStep:SetSize(20, 20);
	stepFrame.btnEditStep.idStep = id;
	stepFrame.btnEditStep:SetPoint("RIGHT", stepFrame.title, "RIGHT", -5, 0);
	stepFrame.btnEditStep:SetNormalTexture("Interface/WorldMap/Gear_64Grey");
	stepFrame.btnEditStep:SetHighlightTexture("Interface/Buttons/UI-Common-MouseHilight");
	stepFrame.btnEditStep:SetScript("OnClick", function(self) WCCreator_Lib.ToggleSettingsStep(self) end);
	stepFrame.btnEditStep:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, "ANCHOR_RIGHT", 0, 0);
												GameTooltip:AddLine(core.L["Modifier l'étape"]);
												GameTooltip:Show(); end);
	stepFrame.btnEditStep:SetScript("OnLeave", WC_Lib.OnLeave);
	
	stepFrame.btn_arrowDown = CreateFrame("Button", nil, stepFrame);
	stepFrame.btn_arrowDown:SetSize(22, 22);
	stepFrame.btn_arrowDown:SetPoint("RIGHT", stepFrame.btnEditStep, "LEFT", 0, 0);
	stepFrame.btn_arrowDown:SetNormalTexture("Interface/Buttons/UI-Panel-ExpandButton-Up");
	stepFrame.btn_arrowDown:SetHighlightTexture("Interface/Buttons/UI-Panel-MinimizeButton-Highlight");
	stepFrame.btn_arrowDown:SetPushedTexture("Interface/Buttons/UI-Panel-ExpandButton-Down");
	stepFrame.btn_arrowDown:SetScript("OnClick", function(self)
		if (self.id < #self.arrSteps) then
			self.arrSteps[self.id], self.arrSteps[self.id + 1] = self.arrSteps[self.id + 1], self.arrSteps[self.id];
			WC_Lib.RefreshPageSteps(self.arrSteps, "WCC", self.idGuide, self.idPage);
			WCCreator_Lib.UpdateVersionGuide(nil, self.idGuide);
			PlaySound("123", "sfx");
		end
	end);

	stepFrame.btn_arrowUp = CreateFrame("Button", nil, stepFrame);
	stepFrame.btn_arrowUp:SetSize(22, 22);
	stepFrame.btn_arrowUp:SetPoint("RIGHT", stepFrame.btn_arrowDown, "LEFT", 0, 0);
	stepFrame.btn_arrowUp:SetNormalTexture("Interface/Buttons/UI-Panel-CollapseButton-Up");
	stepFrame.btn_arrowUp:SetHighlightTexture("Interface/Buttons/UI-Panel-MinimizeButton-Highlight");
	stepFrame.btn_arrowUp:SetPushedTexture("Interface/Buttons/UI-Panel-CollapseButton-Down");
	stepFrame.btn_arrowUp:SetScript("OnClick", function(self)
		if (self.id > 1) then
			self.arrSteps[self.id], self.arrSteps[self.id - 1] = self.arrSteps[self.id - 1], self.arrSteps[self.id];
			WC_Lib.RefreshPageSteps(self.arrSteps, "WCC", self.idGuide, self.idPage);
			WCCreator_Lib.UpdateVersionGuide(nil, self.idGuide);
			PlaySound("123", "sfx");
		end
	end);	
	return stepFrame;
end

function WC_Lib.RefreshPageSteps(arrSteps, addon, idGuide, idPage)
	local newStepBtn = _G[addon.."_BasicFrames"].page_content.btnNewStep;
	local j = 1;
	for i = 1, #arrSteps do
		local stepFrame   = _G[addon.."_Step"..i];
		local currentStep = arrSteps[i];
		local isDone      = isDoneStep(currentStep, {idGuide, idPage, i});
		local isDonePrev  = true;
		if (i > 1) then
			for k = 1, i-1 do
				if (isDoneStep(arrSteps[k], {idGuide, idPage, k}) == false) then
					isDonePrev = false;
				end
			end
		end
		---- CREATE STEP IF NOT EXIST ----
		if not stepFrame then
			stepFrame = WC_Lib.CreateStep(i, arrSteps, addon);
		end
		
		---- VALUES ----
		stepFrame.title.iconHelp.helpDesc  = currentStep.help;
		stepFrame.title.iconHelp.important = currentStep.important;
		
		stepFrame.btnEditStep.idPage   = idPage;
		stepFrame.btnEditStep.idGuide  = idGuide;
		stepFrame.btnEditStep.arrSteps = arrSteps;
		stepFrame.btn_arrowDown.id       = i;
		stepFrame.btn_arrowDown.idPage   = idPage;
		stepFrame.btn_arrowDown.idGuide  = idGuide;
		stepFrame.btn_arrowDown.arrSteps = arrSteps;
		stepFrame.btn_arrowUp.id       = i;
		stepFrame.btn_arrowUp.idPage   = idPage;
		stepFrame.btn_arrowUp.idGuide  = idGuide;
		stepFrame.btn_arrowUp.arrSteps = arrSteps;		
		
		---- SHOW/HIDE/POSITION ----
		stepFrame.taskBg:SetSize(252, core.libs.heightBgTask(currentStep.task)+10);
		if (isDone == true and isDonePrev == true) then
			stepFrame.title.text:SetText(core.L["Etape"].." "..i.."/"..#arrSteps..core.L["2points"]..core.L["Acheve"]);
		else
			stepFrame.title.text:SetText(core.L["Etape"].." "..i.."/"..#arrSteps..core.L["2points"]);
		end
		if (currentStep.important == true) then
			stepFrame.title.iconHelp:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/challenges/helpIconStep2"});
		else
			stepFrame.title.iconHelp:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/challenges/helpIconStep"});
		end
		if (currentStep.help ~= nil and currentStep.help ~= "") then
			stepFrame.title.iconHelp:Show();
		else
			stepFrame.title.iconHelp:Hide();
		end		
		
		if (addon == "WC") then
			stepFrame.btnEditStep:Hide();
			stepFrame.btn_arrowUp:Hide();
			stepFrame.btn_arrowDown:Hide();
			if (isDonePrev == false) then
				stepFrame.lockStepText:Show();
				stepFrame.title.iconLock:Show();
				stepFrame.taskBg:SetSize(252, 50);
				stepFrame.title.iconHelp:Hide();
			else
				stepFrame.lockStepText:Hide();
				stepFrame.title.iconLock:Hide();
			end
		else
			stepFrame.lockStepText:Hide();
			stepFrame.title.iconLock:Hide();
			stepFrame.btnEditStep:Show();
			stepFrame.btn_arrowUp:Show();
			stepFrame.btn_arrowDown:Show();
			stepFrame.title.iconHelp:SetPoint("RIGHT", stepFrame.btn_arrowUp, "LEFT", 0, 0);
		end
		WC_Lib.RefreshStepTasks(currentStep.task, addon, idGuide, idPage, i, isDonePrev);
		stepFrame:Show();		
		j = j + 1;
	end
	--HIDE LES ETAPES EN TROP
	for j = j, 666 do
		if (_G[addon.."_Step"..j] == nil) then
			j = 667;
			break;
		else
			_G[addon.."_Step"..j]:Hide();
		end
	end
	if (addon == "WCC") then	
		newStepBtn.idGuide  = idGuide;
		newStepBtn.idPage   = idPage;
		newStepBtn.arrSteps = arrSteps;
		newStepBtn:SetPoint("TOP", _G[addon.."_Step"..#arrSteps].taskBg, "BOTTOM", 0, -10);
		newStepBtn:Show();
	else
		newStepBtn:Hide();
	end
end

function WC_Lib.RefreshRens(id, arrRens, addon, idGuide, idPage)
	local rens = arrRens[id];
	if not rens then return end;

	local rensFrame = _G[addon.."_BasicFrames"].page_content.rensZone.rensContent;
	-- TEXT --
	rensFrame.title:SetText(rens.title);
	rensFrame.pageText:SetText(id.."/"..#arrRens);
	rensFrame.stepAssignedText:SetText(core.L["Etape"].." "..tostring(rens.stepAssigned));
	if (rens.stepAssigned ~= "") then
		rensFrame.stepAssignedText:Show();
	else
		rensFrame.stepAssignedText:Hide();
	end
	
	-- ONMAP BUTTON --
	rensFrame.showOnMapBtn.title     = rens.title;
	rensFrame.showOnMapBtn.pins      = rens.onMap.pins;
	rensFrame.showOnMapBtn.displayID = rens.displayID;
	rensFrame.showOnMapBtn.category  = rens.category;
	rensFrame.showOnMapBtn.idRens    = id;
	rensFrame.showOnMapBtn.idGuide   = idGuide;
	rensFrame.showOnMapBtn.idPage    = idPage;
	rensFrame.showOnMapBtn.addon     = addon;
	if (rens.category == "ZONE") then
		rensFrame:SetBackdrop({bgFile = "Interface/ARCHEOLOGY/ArchRare-TheInnKeepersDaughter",
								insets = { left = -70, right = -70, top = 0, bottom = 0 }});
		rensFrame.showOnMapBtn.texture:SetTexture(134269);
	else
		rensFrame:SetBackdrop({bgFile = ""});
		rensFrame:SetFacing(0.5);
		rensFrame:SetCamDistanceScale(1);
		rensFrame.cursorX = 0;
		rensFrame.camDistance = 1;
		if (rens.category == "NPC") then
			if (rens.displayID ~= "") then
				SetPortraitTextureFromCreatureDisplayID(rensFrame.showOnMapBtn.texture, rens.displayID);
			else
				rensFrame.showOnMapBtn.texture:SetTexture(134269);
			end
		elseif (rens.category == "ENV") then
			rensFrame.showOnMapBtn.texture:SetTexture(134269);
		end
	end
	if WC_Lib.isPinActivated(idGuide, idPage, id, addon) then
		rensFrame.showOnMapBtn:SetNormalTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin_selected");
		rensFrame.showOnMapBtn:SetPushedTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin_selected");
		rensFrame.showOnMapBtn:SetHighlightTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin_selected");
	else
		rensFrame.showOnMapBtn:SetNormalTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
		rensFrame.showOnMapBtn:SetPushedTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
		rensFrame.showOnMapBtn:SetHighlightTexture("Interface/AddOns/WoWChallenger/images/collections/portrait_pin");
	end
	if (#rens.onMap.pins > 0) then
		rensFrame.showOnMapBtn:Show();
	else
		rensFrame.showOnMapBtn:Hide();
	end
	
	-- MODEL --
	rensFrame.displayID = rens.displayID;
	rensFrame.category  = rens.category;
	if (rens.displayID ~= "") then
		if (rens.category == "ENV") then
			rensFrame:SetModel(tonumber(rens.displayID));
		elseif (rens.category == "NPC") then
			rensFrame:SetDisplayInfo(rens.displayID);
		elseif (rens.category == "ZONE") then
			rensFrame:ClearModel();
		end
	else
		rensFrame:ClearModel();
	end
	
	-- BUTTON CHANGING RENS -- 
	rensFrame.buttonL.id      = id;
	rensFrame.buttonL.arrRens = arrRens;
	rensFrame.buttonL.addon   = addon;
	rensFrame.buttonL.idGuide = idGuide;
	rensFrame.buttonL.idPage  = idPage;
	rensFrame.buttonR.id      = id;
	rensFrame.buttonR.arrRens = arrRens;
	rensFrame.buttonR.addon   = addon;
	rensFrame.buttonR.idGuide = idGuide;
	rensFrame.buttonR.idPage  = idPage;
	if (id == 1) then
		rensFrame.buttonL:SetNormalTexture("Interface/Buttons/UI-SpellbookIcon-PrevPage-Disabled");
		rensFrame.buttonL:SetPushedTexture("Interface/Buttons/UI-SpellbookIcon-PrevPage-Disabled");
		rensFrame.buttonL:SetHighlightTexture("");
	else
		rensFrame.buttonL:SetNormalTexture("Interface/Buttons/UI-SpellbookIcon-PrevPage-Up");
		rensFrame.buttonL:SetPushedTexture("Interface/Buttons/UI-SpellbookIcon-PrevPage-Down");
		rensFrame.buttonL:SetHighlightTexture("Interface/Buttons/UI-Common-MouseHilight");
	end
	if (id == #arrRens) then
		rensFrame.buttonR:SetNormalTexture("Interface/Buttons/UI-SpellbookIcon-NextPage-Disabled");
		rensFrame.buttonR:SetPushedTexture("Interface/Buttons/UI-SpellbookIcon-NextPage-Disabled");
		rensFrame.buttonR:SetHighlightTexture("");
	else
		rensFrame.buttonR:SetNormalTexture("Interface/Buttons/UI-SpellbookIcon-NextPage-Up");
		rensFrame.buttonR:SetPushedTexture("Interface/Buttons/UI-SpellbookIcon-NextPage-Down");
		rensFrame.buttonR:SetHighlightTexture("Interface/Buttons/UI-Common-MouseHilight");
	end
	
	-- ADD/EDIT BTN --
	if (addon == "WCC") then
		rensFrame.AddBtn:Show();
		rensFrame.EditBtn:Show();
	else
		rensFrame.AddBtn:Hide();
		rensFrame.EditBtn:Hide();
	end
	rensFrame.AddBtn.idRens   = id;
	rensFrame.AddBtn.idPage   = idPage;
	rensFrame.AddBtn.idGuide  = idGuide;
	rensFrame.AddBtn.arrRens  = arrRens;
	rensFrame.EditBtn.idRens  = id;
	rensFrame.EditBtn.idPage  = idPage;
	rensFrame.EditBtn.idGuide = idGuide;
	rensFrame.EditBtn.arrRens = arrRens;

	PlaySound("605", "sfx", true);
end

function WC_Lib.RefreshAllBtnPageCollection(infoGuide, addon)
	local basicFrames = _G[addon.."_BasicFrames"];
	local j = 1;
	for i = 1, #infoGuide.page do
		local currentPage = infoGuide.page[i];
		local pageBtn     = _G[addon.."_PageBtn"..i];
		local arrow       = _G[addon.."_PageArrow"..i];
		local isDone      = isDonePage(currentPage, {infoGuide.idGuide, i});
		local isDonePrev  = true;
		local isSelected  = g_pageSelected[addon] == i;
		if (i > 1) then
			isDonePrev = isDonePage(infoGuide.page[i - 1], {infoGuide.idGuide, i - 1});
			if _G[addon.."_PageBtn"..i - 1].lockIcon:IsShown() then isDonePrev = false; end
			if (isDonePrev == false) then
				isDone = 2;
			end
		end
		pageBtn.addon      = addon;
		pageBtn.isDone     = isDone;
		pageBtn.isDonePrev = isDonePrev;
		pageBtn.nbPage     = #infoGuide.page;
		pageBtn.idGuide    = infoGuide.idGuide;
		pageBtn.id         = i;
		
		pageBtn:SetPoint("TOPLEFT", basicFrames.bar_page, "TOPLEFT",	WC_Lib.centerListObjectXByWidth((i*2)-1, #(infoGuide.page)*2, 470, 36)+30, -10);
		pageBtn:Show();
		arrow:SetPoint("TOPLEFT", basicFrames.bar_page, "TOPLEFT", WC_Lib.centerListObjectXByWidth((i*2), #(infoGuide.page)*2, 470, 36)+35, -13);
		arrow:Show();
		WC_Lib.SetProgressButton(currentPage.icon, i, isDone, isSelected, addon);
		
		if (addon == "WCC") then
			pageBtn.func_iconSelect = function (self)
				PlaySound("83", "sfx");
				currentPage.icon = self.iconSelected;
				pageBtn:SetBackdrop({bgFile = self.iconSelected});
				_G["WCC_ListIconSelectorFrameIcon"]:Hide();
				WCCreator_Lib.UpdateVersionGuide(nil, infoGuide.idGuide);
			end
		end
		
		j = j + 1;
	end
	for j = j, WCC_MAX_PAGE_GUIDE do
		_G[addon.."_PageBtn"..j]:Hide();
		_G[addon.."_PageArrow"..j]:Hide();
	end
end

function WC_Lib.RefreshCollectionContent(idGuide, addon, isRefresh)	
	if not _G[addon.."_BasicFrames"] then
		WC_Lib.CreateBasicFrames(addon);
	end
	
	local guide = WC_Lib.GetGuideByID(idGuide, addon);	
	if guide then
		local basicFrames = _G[addon.."_BasicFrames"];
		basicFrames.title:SetText(guide["info"][1]);
		basicFrames.goalIconFrame.guide                        = guide;
		basicFrames.goalIconFrame.addon                        = addon;
		basicFrames.goal_content.nextBtn.addon                 = addon;		
		basicFrames.editBtn.idGuide                              = idGuide;
		basicFrames.goal_content.modelFrame.SavePosModel.guide = guide;
		basicFrames.infoBtn.info = {
			name     = guide.info[1],
			id       = guide.idGuide,
			version  = guide.av_settings.version,
			createBy = guide.av_settings.createBy,
			lang     = core.L["LangSTR"][guide.lang[1]]
		};
		if (addon == "WC") then
			basicFrames.editBtn:Hide();
			basicFrames.infoBtn:Show();
			basicFrames.goal_content.modelFrame.SavePosModel:Hide();
		elseif(addon == "WCC") then
			basicFrames.infoBtn:Hide();
			basicFrames.editBtn:Show();
			basicFrames.goal_content.modelFrame.SavePosModel:Show();
		end
		WC_Lib.RefreshAllBtnPageCollection(guide, addon);
		if not isRefresh then
			basicFrames.goalIconFrame:Click();
		else
			if (g_pageSelected[addon] ~= "") then
				WC_Lib.RefreshPageSteps(guide.page[tonumber(g_pageSelected[addon])].step, addon, idGuide, g_pageSelected[addon]);
			end
		end		
		_G[addon.."_BasicFrames"]:Show();
	end
end

function WC_Lib.UnselectCurrentGuide(addon, bJustHide)
	if (g_guideSelected[addon] ~= "") then
		if (bJustHide == false) then
			_G[addon.."_GuidesCollection"..g_guideSelected[addon].."_Btn"]:SetNormalTexture("Interface/AddOns/WoWChallenger/images/mounts/button_mount");
			_G[addon.."_GuidesCollection"..g_guideSelected[addon].."_Btn"]:SetHighlightTexture("Interface/AddOns/WoWChallenger/images/mounts/button_highlight_mount");
		end
	end
end

function WC_Lib.CollectionBtn_OnClick(self)
	PlaySound("83", "sfx");
	if _G["WCC_MainParamGuide"] then _G["WCC_MainParamGuide"]:Hide() end;
	WC_Lib.UnselectCurrentGuide(self.addon, false);
	self:SetNormalTexture("Interface/AddOns/WoWChallenger/images/mounts/button_clicked_mount");
	WC_Lib.RefreshCollectionContent(self.idGuide, self.addon);
	g_guideSelected[self.addon] = self.idGuide;
end

local function SearchingGuides(value, name)
	local n = name:lower();
	local v = value:lower();
	n = string.gsub(n, "%(", "")
	v = string.gsub(v, "%(", "")
	if (n:find(v) ~= nil) then
		return true;
	end
	return false;
end

local function FilterDifficulty(filter, value1, value2, idGuide, prevGuide, addon, pos)
	if (filter == true and value1 == value2) then
		if (pos == 1) then
			_G[addon.."_GuidesCollection"..idGuide]:SetPoint("TOPLEFT", _G[addon.."_GuidesListScrollChild"], "TOPLEFT", 0, -15);
		else
			_G[addon.."_GuidesCollection"..idGuide]:SetPoint("TOP", _G[prevGuide], "BOTTOM", 0, -2);
		end
		_G[addon.."_GuidesCollection"..idGuide]:Show();
	end
end

local function FilterType(filters, infoGuide, prevGuide, addon, pos)
	if (filters[3] == true and infoGuide.category == "hf") then
		FilterDifficulty(filters[7], infoGuide.difficulty, 1, infoGuide.idGuide, prevGuide, addon, pos);
		FilterDifficulty(filters[8], infoGuide.difficulty, 2, infoGuide.idGuide, prevGuide, addon, pos);
		FilterDifficulty(filters[9], infoGuide.difficulty, 3, infoGuide.idGuide, prevGuide, addon, pos);
	end
	if (filters[4] == true and infoGuide.category == "mounts") then
		FilterDifficulty(filters[7], infoGuide.difficulty, 1, infoGuide.idGuide, prevGuide, addon, pos);
		FilterDifficulty(filters[8], infoGuide.difficulty, 2, infoGuide.idGuide, prevGuide, addon, pos);
		FilterDifficulty(filters[9], infoGuide.difficulty, 3, infoGuide.idGuide, prevGuide, addon, pos);
	end
	if (filters[5] == true and infoGuide.category == "pets") then
		FilterDifficulty(filters[7], infoGuide.difficulty, 1, infoGuide.idGuide, prevGuide, addon, pos);
		FilterDifficulty(filters[8], infoGuide.difficulty, 2, infoGuide.idGuide, prevGuide, addon, pos);
		FilterDifficulty(filters[9], infoGuide.difficulty, 3, infoGuide.idGuide, prevGuide, addon, pos);
	end
	if (filters[6] == true and infoGuide.category == "transmogs") then
		FilterDifficulty(filters[7], infoGuide.difficulty, 1, infoGuide.idGuide, prevGuide, addon, pos);
		FilterDifficulty(filters[8], infoGuide.difficulty, 2, infoGuide.idGuide, prevGuide, addon, pos);
		FilterDifficulty(filters[9], infoGuide.difficulty, 3, infoGuide.idGuide, prevGuide, addon, pos);
	end
end

local function FilterFaction(filters, infoGuide, prevGuide, addon, pos)
	if (filters[10] == true and infoGuide.faction == 1) then
		FilterType(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[11] == true and infoGuide.faction == 2) then
		FilterType(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[12] == true and infoGuide.faction == 3) then
		FilterType(filters, infoGuide, prevGuide, addon, pos);
	end
end

local function FilterExpansion(filters, infoGuide, prevGuide, addon, pos)
	if (infoGuide.expansion == "") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[13] == true and infoGuide.expansion == "Classic") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[14] == true and infoGuide.expansion == "Burning Crusade") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[15] == true and infoGuide.expansion == "Wrath of the Lich King") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[16] == true and infoGuide.expansion == "Cataclysm") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[17] == true and infoGuide.expansion == "Mist of Pandaria") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[18] == true and infoGuide.expansion == "Warlords of Draenor") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[19] == true and infoGuide.expansion == "Legion") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[20] == true and infoGuide.expansion == "Battle for Azeroth") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[21] == true and infoGuide.expansion == "Shadowlands") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
	if (filters[22] == true and infoGuide.expansion == "Dragonflight") then
		FilterFaction(filters, infoGuide, prevGuide, addon, pos);
	end
end

function WC_Lib.DisplayGuidesByFilter(addon)
	local currList = nil;
	local filters  = nil;
	if (addon == "WCC") then
		currList = ListGuides;
		filters  = WCCreator_Lib.structures.CurrentFilters;
	elseif (addon == "WC") then
		currList = WC_ListGuides;
		filters  = WC_Lib.structures.CurrentFilters;
	end
	local pos       = 1;
	local prevGuide = "";
	for i = 1, #currList do
		local infoGuide = WC_Lib.GetGuideByID(currList[i], addon);
		if (_G[addon.."_GuidesCollection"..infoGuide.idGuide] ~= nil) then
			_G[addon.."_GuidesCollection"..infoGuide.idGuide]:Hide();
			_G[addon.."_GuidesCollection"..infoGuide.idGuide]:ClearAllPoints();
			if (filters[1] == true) then
				if (WC_Lib.checkIfGuideIsDone(infoGuide.category, infoGuide.id, infoGuide.Model.modID) == true) then
					FilterExpansion(filters, infoGuide, prevGuide, addon, pos);
				end
			end
			if (filters[2] == true) then
				if (WC_Lib.checkIfGuideIsDone(infoGuide.category, infoGuide.id, infoGuide.Model.modID) == false) then
					FilterExpansion(filters, infoGuide, prevGuide, addon, pos);
				end
			end
			local textFilter = _G[addon.."_EditBoxFilterGuides"]:GetText();
			if (textFilter ~= nil and textFilter ~= "" and SearchingGuides(textFilter, infoGuide["info"][1]) == false) then
				_G[addon.."_GuidesCollection"..infoGuide.idGuide]:Hide();
				_G[addon.."_GuidesCollection"..infoGuide.idGuide]:ClearAllPoints();
			end
			if (_G[addon.."_GuidesCollection"..infoGuide.idGuide]:IsShown()) then
				prevGuide = addon.."_GuidesCollection"..infoGuide.idGuide;
				pos = pos + 1;
			end
		end
	end
end


function WC_Lib.MoveWCCGuides()
	for i = 1, #ListGuides do
		local infoGuide = WC_Lib.GetGuideByID(ListGuides[i], "WCC");
		if (infoGuide ~= nil) then
			local btn = _G["WCC_GuidesCollection"..infoGuide.idGuide];
			if (btn ~= nil) then
				btn:ClearAllPoints();
				if (i == 1) then
					btn:SetPoint("TOPLEFT", _G["WCC_GuidesListScrollChild"], "TOPLEFT", 0, -15);
				else
					btn:SetPoint("TOP", _G["WCC_GuidesCollection"..ListGuides[i - 1]], "BOTTOM", 0, -2);
				end
			end
		end
	end
end

function WC_Lib.RefreshListCollections(addon)
	if (addon == "WCC") then
		for i = 1, #ListGuides do
			local infoGuide = WC_Lib.GetGuideByID(ListGuides[i], addon);
			if (infoGuide ~= nil) then
				local btn = WC_Lib.CreateBtnCollection(infoGuide, _G["WCC_GuidesListScrollChild"], "WCC_GuidesCollection"..infoGuide.idGuide);
				if (btn ~= nil) then
					btn:ClearAllPoints();
					if (i == 1) then
						btn:SetPoint("TOPLEFT", _G["WCC_GuidesListScrollChild"], "TOPLEFT", 0, -15);
					else
						btn:SetPoint("TOP", _G["WCC_GuidesCollection"..ListGuides[i - 1]], "BOTTOM", 0, -2);
					end
				end
			end
		end
		_G["WCC_GuidesListCollectedText"]:SetText(#ListGuides);
	elseif (addon == "WC") then
		local nbCollected = 0;
		for i = 1, #WC_ListGuides do
			local infoGuide = WC_Lib.GetGuideByID(WC_ListGuides[i], addon);
			if (WC_Lib.checkIfGuideIsDone(infoGuide.category, infoGuide.id, infoGuide.Model.modID) == true) then
				nbCollected = nbCollected + 1;
			end
			if (infoGuide ~= nil) then
				local btn = WC_Lib.CreateBtnCollection(infoGuide, _G["WC_GuidesListScrollChild"], "WC_GuidesCollection"..infoGuide.idGuide);
				if (btn ~= nil) then
					btn:ClearAllPoints();
					if (i == 1) then
						btn:SetPoint("TOPLEFT", _G["WC_GuidesListScrollChild"], "TOPLEFT", 0, -15);
					else
						btn:SetPoint("TOP", _G["WC_GuidesCollection"..WC_ListGuides[i - 1]], "BOTTOM", 0, -2);
					end
				end
			end
		end
		_G["WC_GuidesListCollectedText"]:SetText(nbCollected.."/"..#WC_ListGuides);
	end
end

function WC_Lib.MoveUpCollectionGuide(self)
	local posCollection = -1;
	if (self.addon == "WCC") then
		for i = 1, #ListGuides do
			if (self.idGuide == ListGuides[i]) then
				posCollection = i;
				break;
			end
		end
		if (posCollection > 1) then
			local tmp = ListGuides[posCollection - 1];
			ListGuides[posCollection - 1] = ListGuides[posCollection];
			ListGuides[posCollection] = tmp;
		end
	elseif (self.addon == "WC") then
		for i = 1, #WC_ListGuides do
			if (self.idGuide == WC_ListGuides[i]) then
				posCollection = i;
				break;
			end
		end
		if (posCollection > 1) then
			local tmp = WC_ListGuides[posCollection - 1];
			WC_ListGuides[posCollection - 1] = WC_ListGuides[posCollection];
			WC_ListGuides[posCollection] = tmp;
		end
	end
	WC_Lib.MoveWCCGuides();
end

function WC_Lib.MoveDownCollectionGuide(self)
	local posCollection = -1;
	if (self.addon == "WCC") then
		for i = 1, #ListGuides do
			if (self.idGuide == ListGuides[i]) then
				posCollection = i;
				break;
			end
		end
		if (posCollection < #ListGuides and posCollection ~= -1) then
			local tmp = ListGuides[posCollection + 1];
			ListGuides[posCollection + 1] = ListGuides[posCollection];
			ListGuides[posCollection] = tmp;
		end
	elseif (self.addon == "WC") then
		for i = 1, #WC_ListGuides do
			if (self.idGuide == WC_ListGuides[i]) then
				posCollection = i;
				break;
			end
		end
		if (posCollection < #WC_ListGuides and posCollection ~= -1) then
			local tmp = WC_ListGuides[posCollection + 1];
			WC_ListGuides[posCollection + 1] = WC_ListGuides[posCollection];
			WC_ListGuides[posCollection] = tmp;
		end
	end
	WC_Lib.MoveWCCGuides();
end

-- ===== FILTER COLLECTION =====
function WC_Lib.CreateHeaderGuideList(parent, addon)
	local mainFrame = CreateFrame("Frame", nil, parent, BackdropTemplateMixin and "BackdropTemplate");
	mainFrame:SetSize(parent:GetWidth()+6, 65);
	mainFrame:SetPoint("TOP", parent, "TOP", 0, 4);
	mainFrame:SetBackdrop({bgFile = "Interface/FrameGeneral/UI-Background-Rock",
									tile = false,
									insets = { left = 8, right = 6, top = 8, bottom = 5 }
									});

	mainFrame.textBox = CreateFrame("EditBox", nil, mainFrame, "InputBoxTemplate");
	mainFrame.textBox:SetSize(160, 30);
	mainFrame.textBox:Disable();
	mainFrame.textBox:SetPoint("TOP", mainFrame, "TOP", 27, -7);
	mainFrame.textBox.collectionsText = mainFrame.textBox:CreateFontString(nil, "OVERLAY", nil, mainFrame.textBox);
	mainFrame.textBox.collectionsText:SetFontObject("GameFontNormalSmall");
	if (addon == "WC") then
		mainFrame.textBox.collectionsText:SetText(core.L["MountCollected"]);
	elseif (addon == "WCC") then
		mainFrame.textBox.collectionsText:SetText(core.L["Guide(s)"]);
	end
	mainFrame.textBox.collectionsText:SetPoint("LEFT");
	mainFrame.textBox.nbCollectionsText = mainFrame.textBox:CreateFontString(addon.."_GuidesListCollectedText", "OVERLAY", nil, mainFrame.textBox);
	mainFrame.textBox.nbCollectionsText:SetFontObject("GameFontWhiteSmall");
	mainFrame.textBox.nbCollectionsText:SetJustifyH("RIGHT");
	mainFrame.textBox.nbCollectionsText:SetPoint("RIGHT", mainFrame.textBox, "RIGHT", -5, 0);

	mainFrame.searchBox = CreateFrame("EditBox", addon.."_EditBoxFilterGuides", mainFrame, "SearchBoxTemplate");
	mainFrame.searchBox:SetWidth(150);
	mainFrame.searchBox:SetHeight(20);
	mainFrame.searchBox:SetPoint("BOTTOMLEFT", mainFrame, "BOTTOMLEFT", 12, 7);
	mainFrame.searchBox:HookScript("OnTextChanged", function(self)
		WC_Lib.DisplayGuidesByFilter(addon);
	end);
	
	mainFrame.FilterBtn = CreateFrame("Button", nil, mainFrame, "UIMenuButtonStretchTemplate");
	mainFrame.FilterBtn.contextMenu = CreateFrame("Frame", nil, mainFrame.FilterBtn, "UIDropDownMenuTemplate");
	mainFrame.FilterBtn:SetWidth(86);
	mainFrame.FilterBtn:SetHeight(21);
	mainFrame.FilterBtn:SetText(core.L["Filtrer"]);
	mainFrame.FilterBtn:SetPoint("LEFT", mainFrame.searchBox, "RIGHT", -2, 0);
	mainFrame.FilterBtn:SetScript("OnClick", function()
		if (addon == "WCC") then
			WCCreator_Lib.structures.WCCFilterMenu.frameOwner = self;
			EasyMenu(WCCreator_Lib.structures.WCCFilterMenu.info, mainFrame.FilterBtn.contextMenu, mainFrame.FilterBtn, 0 , 0, "MENU")
		elseif (addon == "WC") then
			WC_Lib.structures.WCFilterMenu.frameOwner = self;
			EasyMenu(WC_Lib.structures.WCFilterMenu.info, mainFrame.FilterBtn.contextMenu, mainFrame.FilterBtn, 0 , 0, "MENU")
		end
		PlaySound("83", "sfx");
	end)

	return mainFrame;
end

-- ===== BUTTON COLLECTION =====
function WC_Lib.CreateBtnCollection(infoCollection, parent, frameName)
	infoCollection.info[2] = WC_Lib.checkIfGuideIsDone(infoCollection.category, infoCollection.id, infoCollection.Model.modID);
	if (_G[frameName] == nil) then
		local addonID = frameName:sub(1, 3);
		if (addonID == "WC_") then
			addonID = "WC";
		end
		
		local mainFrame = CreateFrame("Frame", frameName, parent);	
		mainFrame:SetSize(175, 45);
		
		local icon = CreateFrame("Frame", frameName.."_Icon", mainFrame, BackdropTemplateMixin and "BackdropTemplate");
		icon.guide = infoCollection;
		icon:SetSize(45, 45);
		icon:SetPoint("LEFT", mainFrame, "LEFT", 4, 10);
		icon:SetBackdrop({bgFile = infoCollection.icon});
		icon:SetScript("OnEnter", WC_Lib.tooltip_iconCollection);
		icon:SetScript("OnLeave", WC_Lib.OnLeave);
		
		local btn = CreateFrame("Button",  frameName.."_Btn", mainFrame);
		btn:SetSize(175, 45);
		btn:SetPoint("LEFT", icon, "RIGHT", 0, 0);
		btn.idGuide   = infoCollection.idGuide;
		btn.addon     = addonID;
		btn.nameGuide = infoCollection.info[1];
		btn:SetNormalTexture("Interface/AddOns/WoWChallenger/images/mounts/button_mount");
		btn:SetHighlightTexture("Interface/AddOns/WoWChallenger/images/mounts/button_highlight_mount");
		if (addonID == "WCC") then
			btn:SetScript("OnLeave", function(self) _G[mainFrame:GetName().."_arrowUp"]:Hide(); _G[mainFrame:GetName().."_arrowDown"]:Hide();  end);
			btn:SetScript("OnEnter", function(self) _G[mainFrame:GetName().."_arrowUp"]:Show(); _G[mainFrame:GetName().."_arrowDown"]:Show();  end);	
		end
		btn:RegisterForClicks("LeftButtonUp", "RightButtonDown");
		btn.contextMenu = CreateFrame("Frame", nil, btn, "UIDropDownMenuTemplate");
		btn:SetScript("OnClick", function (self, button, down)
			if (button == "LeftButton") then
				WC_Lib.CollectionBtn_OnClick(self);
			elseif (button == "RightButton") then
				if (self.addon == "WCC") then
					WCCreator_Lib.structures.WCCGuideMenu.frameOwner = self;
					EasyMenu(WCCreator_Lib.structures.WCCGuideMenu.info, btn.contextMenu, btn, 0 , 0, "MENU")
				elseif (self.addon == "WC") then
					WC_Lib.structures.WCGuideMenu.frameOwner = self;
					EasyMenu(WC_Lib.structures.WCGuideMenu.info, btn.contextMenu, btn, 0 , 0, "MENU")
				end
				PlaySound("83", "sfx");
			end
		end);
		
		btn.btn_arrowUp = CreateFrame("Button", frameName.."_arrowUp", btn);
		btn.btn_arrowUp:SetSize(25, 25);
		btn.btn_arrowUp:SetPoint("TOPRIGHT", btn, "TOPRIGHT", -20, 2);
		btn.btn_arrowUp:SetNormalTexture("Interface/Buttons/UI-Panel-CollapseButton-Up");
		btn.btn_arrowUp:SetHighlightTexture("Interface/Buttons/UI-Panel-MinimizeButton-Highlight");
		btn.btn_arrowUp:SetPushedTexture("Interface/Buttons/UI-Panel-CollapseButton-Down");
		btn.btn_arrowUp.idGuide = infoCollection.idGuide;
		btn.btn_arrowUp.addon = addonID;
		btn.btn_arrowUp:SetScript("OnClick", WC_Lib.MoveUpCollectionGuide);
		btn.btn_arrowUp:Hide();
		btn.btn_arrowUp:SetScript("OnEnter", function(self) _G[mainFrame:GetName().."_arrowUp"]:Show(); _G[mainFrame:GetName().."_arrowDown"]:Show(); end);
		btn.btn_arrowUp:SetScript("OnLeave", function(self) _G[mainFrame:GetName().."_arrowUp"]:Hide(); _G[mainFrame:GetName().."_arrowDown"]:Hide(); end);
		
		btn.btn_arrowDown = CreateFrame("Button",  frameName.."_arrowDown", btn);
		btn.btn_arrowDown:SetSize(25, 25);
		btn.btn_arrowDown:SetPoint("TOPRIGHT", btn, "TOPRIGHT", 2, 2);
		btn.btn_arrowDown:SetNormalTexture("Interface/Buttons/UI-Panel-ExpandButton-Up");
		btn.btn_arrowDown:SetHighlightTexture("Interface/Buttons/UI-Panel-MinimizeButton-Highlight");
		btn.btn_arrowDown:SetPushedTexture("Interface/Buttons/UI-Panel-ExpandButton-Down");
		btn.btn_arrowDown.idGuide = infoCollection.idGuide;
		btn.btn_arrowDown.addon = addonID;
		btn.btn_arrowDown:SetScript("OnClick", WC_Lib.MoveDownCollectionGuide);
		btn.btn_arrowDown:Hide();
		btn.btn_arrowDown:SetScript("OnEnter", function(self) _G[mainFrame:GetName().."_arrowUp"]:Show(); _G[mainFrame:GetName().."_arrowDown"]:Show();  end);
		btn.btn_arrowDown:SetScript("OnLeave", function(self) _G[mainFrame:GetName().."_arrowUp"]:Hide(); _G[mainFrame:GetName().."_arrowDown"]:Hide();  end);

		btn.bg_faction = CreateFrame("Frame", frameName.."_Faction", btn, BackdropTemplateMixin and "BackdropTemplate");
		btn.bg_faction:SetSize(57, 57);
		btn.bg_faction:SetPoint("RIGHT", btn, "RIGHT", 5, 0);
		if (infoCollection.faction == 1) then
			btn.bg_faction:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/mounts/button_bg_Alliance"});
		elseif (infoCollection.faction == 2) then
			btn.bg_faction:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/mounts/button_bg_Horde"});
		else
			btn.bg_faction:SetBackdrop({bgFile = ""});
		end
		
		btn.bg_category = CreateFrame("Frame", frameName.."_Category", btn, BackdropTemplateMixin and "BackdropTemplate");
		btn.bg_category:SetSize(22, 22);
		btn.bg_category:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", 0, 2);
		btn.bg_category:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/"..infoCollection.category.."_category"});

		btn.name = btn:CreateFontString(frameName.."_Name", "OVERLAY", nil, btn);
		btn.name:SetSize(btn:GetWidth()-20, 0);
		if (infoCollection.info[2] == true) then
			btn.name:SetFontObject("GameFontGreen");
		else
			btn.name:SetFontObject("GameFontNormal");
		end
		btn.name:SetText(infoCollection.info[1]);
		btn.name:SetJustifyH("LEFT");
		btn.name:SetPoint("LEFT", btn, "LEFT", 10, 0);
		if (addonID == "WC") then
			local id = infoCollection.id;
			if (infoCollection.category == "transmogs") then
				_, id = C_TransmogCollection.GetItemInfo(infoCollection.id, infoCollection.Model.modID);
			end
			WC_Lib.AddingInEventRefresh({infoCollection.idGuide, infoCollection.category, tostring(id)});
		end
		return mainFrame;
	else
		_G[frameName.."_Icon"]:SetBackdrop({bgFile = infoCollection.icon});
		_G[frameName.."_Icon"].guide = infoCollection;
		_G[frameName.."_Faction"]:SetBackdrop({bgFile = infoCollection.icon});
		if (infoCollection.faction == 1) then
			_G[frameName.."_Faction"]:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/mounts/button_bg_Alliance"});
		elseif (infoCollection.faction == 2) then
			_G[frameName.."_Faction"]:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/mounts/button_bg_Horde"});
		else
			_G[frameName.."_Faction"]:SetBackdrop({bgFile = ""});
		end
		_G[frameName.."_Category"]:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/collections/"..infoCollection.category.."_category"});
		if (infoCollection.info[2] == true) then
			_G[frameName.."_Name"]:SetFontObject("GameFontGreen");
		else
			_G[frameName.."_Name"]:SetFontObject("GameFontNormal");
		end
		_G[frameName.."_Name"]:SetText(infoCollection.info[1]);
		_G[frameName]:Show();
		return _G[frameName];
	end
end

----- EXPORT FUNCTIONS -----
function WC_Lib.TransformEnterLetter(str, bExport)
	local ret = "";
	if (bExport == true) then
		ret = string.gsub(str, "|n",   "?ETR");
		ret = string.gsub(ret, "|cFF", "?qcS");
		ret = string.gsub(ret, "|r",   "?qcE");
		ret = string.gsub(ret, "|T",   "?TiS");
		ret = string.gsub(ret, "|t",   "?TiE");
		ret = string.gsub(ret, '"',    '\\"');
		ret = string.gsub(ret, 'Interface\\ICONS\\', 'Interface\\\\ICONS\\\\');
	else
		ret = string.gsub(str, "?ETR", "|n");
		ret = string.gsub(ret, "?qcS", "|cFF");
		ret = string.gsub(ret, "?qcE", "|r");
		ret = string.gsub(ret, "?TiS", "|T");
		ret = string.gsub(ret, "?TiE", "|t");
		ret = string.gsub(ret, '\\"',  '"');
		ret = string.gsub(ret, 'Interface\\\\ICONS\\\\', 'Interface\\ICONS\\');
	end
	return ret;
end

local function SortGuide(guide)
	local ret = {};
	
	--- Main values ---
	ret.expansion   = guide.expansion;
	ret.id          = guide.id;
	ret.idGuide     = guide.idGuide;
	ret.av_settings = guide.av_settings;
	ret.difficulty  = guide.difficulty;
	ret.lang        = guide.lang;
	ret.info        = guide.info;
	ret.faction     = guide.faction;
	ret.class       = guide.class;
	ret.Model       = guide.Model;
	ret.icon        = guide.icon;
	ret.category    = guide.category;

	--- inside page values ---
	local current_page = {};
	for i = 1, #guide.page do
		current_page[i] = {};
		current_page[i].step = {};
		current_page[i].icon = guide.page[i].icon;
		current_page[i].rens = guide.page[i].rens;
		for j = 1, #guide.page[i].step do
			current_page[i].step[j] = {};
			current_page[i].step[j].help      = guide.page[i].step[j].help;
			current_page[i].step[j].important = guide.page[i].step[j].important;
			current_page[i].step[j].task      = {};
			for k = 1, #guide.page[i].step[j].task do
				local currentTask = guide.page[i].step[j].task[k];
				local sortCurrTask    = {};
				sortCurrTask.taskType = currentTask.taskType;
				if (currentTask.taskType == "custom") then
					sortCurrTask.title       = currentTask.title;
					sortCurrTask.tooltipText = currentTask.tooltipText;
				elseif (currentTask.taskType == "hf") then
					sortCurrTask.title = currentTask.title;
					sortCurrTask.idHF  = currentTask.idHF;
				elseif (currentTask.taskType == "quest") then
					sortCurrTask.idQuest = currentTask.idQuest;
					sortCurrTask.title   = currentTask.title;
					if (currentTask.bForceQuest == true) then
						sortCurrTask.tooltipText  = currentTask.tooltipText;
					end
					if (currentTask.bAutoRefresh ~= nil) then
						sortCurrTask.bAutoRefresh = currentTask.bAutoRefresh;
					end
				elseif (currentTask.taskType == "need") then
					sortCurrTask.nbRequired     = currentTask.nbRequired;
					sortCurrTask.idItem         = currentTask.idItem;
					sortCurrTask.itemInfo       = currentTask.itemInfo;
					sortCurrTask.itemInfo[2]    = string.match(currentTask.itemInfo[2], "item[%-?%d:]+");
					sortCurrTask.obtentionType  = currentTask.obtentionType;
					sortCurrTask.validationType = currentTask.validationType;
					if (currentTask.validationType ~= "manual") then
						sortCurrTask.validationId = currentTask.validationId;
					end
					if (currentTask.validationType == "quest" and currentTask.bAutoRefresh ~= nil) then
						sortCurrTask.bAutoRefresh = currentTask.bAutoRefresh;
					end
					if (currentTask.validationType == "transmogs") then
						sortCurrTask.validationModId = currentTask.validationModId;
					end
					if (currentTask.obtentionType == "loot") then
						sortCurrTask.obtention_loot = currentTask.obtention_loot;
					elseif (currentTask.obtentionType == "vendor") then
						sortCurrTask.obtention_vendor = currentTask.obtention_vendor;
					elseif (currentTask.obtentionType == "create") then
						sortCurrTask.obtention_create     = currentTask.obtention_create;
						sortCurrTask.obtention_profession = currentTask.obtention_profession;
					elseif (currentTask.obtentionType == "quest") then
						sortCurrTask.obtention_titleQuest = currentTask.obtention_titleQuest;
						sortCurrTask.obtention_IdQuest = currentTask.obtention_IdQuest;
					elseif (currentTask.obtentionType == "hf") then
						sortCurrTask.obtention_titleHF = currentTask.obtention_titleHF;
						sortCurrTask.obtention_IdHF = currentTask.obtention_IdHF;
					end
				end
				current_page[i].step[j].task[k] = sortCurrTask;
			end
		end
	end
	ret.page = current_page;
	
	return ret;
end

function WC_Lib.ShowPopupExport(idGuide, addon)
	local guide           = WC_Lib.GetGuideByID(idGuide, addon);
	local sortedGuide     = SortGuide(guide);
	local serialize_guide = AceSerializer:Serialize(sortedGuide);
	serialize_guide = WC_Lib.TransformEnterLetter(serialize_guide, true);
	if (_G["WC_PopupExportGuide"] == nil) then
		local PopupExport = CreateFrame("Frame", "WC_PopupExportGuide", UIParent, BackdropTemplateMixin and "BackdropTemplate");
		PopupExport:SetSize(550, 350);
		PopupExport:SetFrameLevel(519);
		PopupExport:SetMovable(true);
		PopupExport:EnableMouse(true);
		PopupExport:RegisterForDrag("LeftButton");
		PopupExport:SetScript("OnDragStart", PopupExport.StartMoving);
		PopupExport:SetScript("OnDragStop", PopupExport.StopMovingOrSizing);
		PopupExport:SetPoint("CENTER", UIParent, "CENTER");
		PopupExport:SetBackdrop({bgFile = "Interface/Collections/CollectionsBackgroundTile",
								edgeFile = "Interface/FriendsFrame/UI-Toast-Border",
								edgeSize = 16,
								insets = { left = 7, right = 5, top = 5, bottom = 6 }});
								
		PopupExport.close = CreateFrame("Button", nil, PopupExport, "UIPanelCloseButton");
		PopupExport.close:SetSize(25, 25);
		PopupExport.close:SetPoint("TOPRIGHT", PopupExport, "TOPRIGHT", -5, -5);
		PopupExport.close:SetFrameLevel(PopupExport:GetFrameLevel() + 1);
		PopupExport.close:SetScript("OnClick", function(self)
			PopupExport:Hide();
			PlaySound("854", "sfx");
		end);
		
		PopupExport.title = PopupExport:CreateFontString(nil, "OVERLAY", nil, PopupExport);
		PopupExport.title:SetFontObject("GameFontHighlightLarge");
		PopupExport.title:SetSize(PopupExport:GetWidth(), 0);
		PopupExport.title:SetPoint("TOP", PopupExport, "TOP", 0, -13);

		
		PopupExport.editBox = CreateFrame("Button", nil, PopupExport, BackdropTemplateMixin and "BackdropTemplate");
		PopupExport.editBox:SetSize(460, 225);
		PopupExport.editBox:SetPoint("BOTTOM", PopupExport, "BOTTOM", 0, 40);
		PopupExport.editBox:SetScript("OnClick", function(self) self.multiline:SetFocus() end);
		PopupExport.editBox:SetBackdrop({bgFile = [[Interface\GLUES\COMMON\Glue-Tooltip-Background]],
								edgeFile = [[Interface\GLUES\COMMON\TextPanel-Border]],
								edgeSize = 14,
								insets = {left = 5, right = 1, top = 1, bottom = 4},
													});
													
		PopupExport.text = PopupExport:CreateFontString(nil, "OVERLAY", nil, PopupExport);
		PopupExport.text:SetFontObject("GameFontNormal");
		PopupExport.text:SetText(core.L["Partagez votre guide avec vos amis en copiant le code ci-dessous."]);
		PopupExport.text:SetSize(PopupExport.editBox:GetWidth(), 0);
		PopupExport.text:SetPoint("BOTTOMLEFT", PopupExport.editBox, "TOPLEFT", 0, 25);
		PopupExport.Warningtext = PopupExport:CreateFontString(nil, "OVERLAY", nil, PopupExport);
		PopupExport.Warningtext:SetFontObject("GameFontRedSmall");
		PopupExport.Warningtext:SetText(core.L["Attention, modifier ce code peut entraîner un dysfonctionnement de l'addon lors de l'importation."]);
		PopupExport.Warningtext:SetSize(PopupExport.editBox:GetWidth(), 0);
		PopupExport.Warningtext:SetPoint("TOP", PopupExport.text, "BOTTOM", 0, -5);
		
		local scroll = CreateFrame("ScrollFrame", nil, PopupExport.editBox, "UIPanelScrollFrameTemplate");
		scroll:SetSize(PopupExport.editBox:GetWidth()-20, PopupExport.editBox:GetHeight()-15);
		scroll:SetPoint("CENTER", PopupExport.editBox, "CENTER", -4, 0);
		
		PopupExport.editBox.multiline = CreateFrame("EditBox", nil, editBox);
		PopupExport.editBox.multiline:SetMultiLine(true);
		PopupExport.editBox.multiline:SetAutoFocus(true);
		PopupExport.editBox.multiline:SetFontObject("GameFontWhite");
		PopupExport.editBox.multiline:SetWidth(435);
		
		scroll:SetScrollChild(PopupExport.editBox.multiline);
		
		PopupExport.btnImportToWC = CreateFrame("Button", nil, PopupExport, "UIPanelButtonTemplate");
		PopupExport.btnImportToWC:SetSize(200, 25);
		PopupExport.btnImportToWC:SetText(core.L["Importer sur WoW Challenger"]);
		PopupExport.btnImportToWC:SetPoint("BOTTOM", PopupExport, "BOTTOM", 0, 10);
		PopupExport.btnImportToWC:SetScript("OnClick", function(self)
														WC_Lib.BeforeImportGuide(PopupExport.editBox.multiline:GetText())
														_G["WC_PopupExportGuide"]:Hide();
													end);
	end
	if (addon == "WCC") then
		_G["WC_PopupExportGuide"].btnImportToWC:Show();
	else
		_G["WC_PopupExportGuide"].btnImportToWC:Hide();
	end
	_G["WC_PopupExportGuide"].title:SetText(core.L["Exporter"].." |cFFF5CC00["..guide["info"][1].."]|r");	
	_G["WC_PopupExportGuide"].editBox.multiline:SetText(serialize_guide);
	_G["WC_PopupExportGuide"].editBox.multiline:HighlightText();
	_G["WC_PopupExportGuide"]:Show();
	PlaySound("681", "sfx");
end