--=============================================
---
--- GoldCounter (GoldCounter.lua) by Hexiatröhm
---
--=============================================

local format  = string.format
local floor   = math.floor
local upper   = string.upper
local tremove = table.remove
local len 	  = string.len

--- Global Data
SLASH_GC1, SLASH_GC2 = "/gc", "/goldcounter"

GC_WOW_isRetail, GC_WOW_isVanilla, GC_WOW_isPandaria, GC_WOW_isBCAnniv = false, false, false, false
GC_Version = ""
GC_Flavor = ""
GC_LastLoginDate  = 0
GC_LastLoginTime  = ""
GC_LastLogoutDate = 0
GC_LastLogoutTime = ""
GC_PlayerName, GC_PlayerRealm, GC_PlayerNormName, GC_PlayerNormRealm = "", "", "", ""
GC_PlayerClassEN, GC_PlayerClassLocale, GC_PlayerClassIndex = "?", "?", 0
GC_PlayerFaction, GC_PlayerFactionLocale = "", ""
GC_PlayerLevel = 0
GC_PlayerItemLevel = 0
GC_MaxPlayerLevel = 120
GC_PlayerXP, GC_LastXP = 0, 0
GC_CharGender = 0
GC_PlayerRaceLocalized, GC_PlayerRaceEN = "", ""
GC_PlayerGuildName = nil
GC_Job1, GC_Job1Icon, GC_Job1SkillLevel, GC_Job1MaxSkillLevel = nil, nil, 0, 0
GC_Job2, GC_Job2Icon, GC_Job2SkillLevel, GC_Job2MaxSkillLevel = nil, nil, 0, 0

GC_LoginMoneyInit = 0
GC_CurrentFunds = 0
GC_PreviousMoney = 0
GC_MaxHistoryRec = 28 -- 4 weeks
GC_MinHistoryRec = 7 -- 1 week
GC_DefaultHistoryRec = 14 -- 2 weeks

GC_WarnVersionDone = false
GC_ProfileButtonChecked = 1
GC_ToggleSwitch = false
GC_Reset_EraseDB_Checked, GC_Reset_EraseAllProfiles_Checked = false, false
GC_CurrentDate = 0
GC_Roster_PlayersNum_Event = 0
GC_Beacon = false
GC_Beacon_LastName = ""
GC_Total_Tooltip = 0

GC_MM_Plus_OverallScore = 0
GC_MM_Plus_HighestKeyLevel = 0
GC_MM_Plus_HighestKeyDungeonName = ""
GC_MM_Plus_RetryCount = 0
GC_MM_Plus_TimerPending = false
GC_MM_Plus_HighestKeyLevel_Backup = 0
GC_MM_Plus_HighestKeyDungeonName_Backup = ""
GC_MM_Plus_UsingBackup = false

GC_BorderColor1 = { }
GC_BorderColor2 = { }

--- Saved Variable
MySavedMoney = nil
MySavedMoneyHistory = { }
My_GC_Settings = { }
My_GC_Settings_Local = { }
My_GC_Profile = { }
My_GC_CharMoneyDB = { }
GC_MyDailyData = { }
---

GC_Events_Data = {
	IsMercOpen = false,
	BankFrame_Open = false,
	GuildBankFrame_Open = false,
	Auctioneer_Open = false,
	MailBox_Open = false,
	isLootOpenHasMoney = false,
	TransmoMerc_Open = false,
	Profession_Open = false,
}

---------------------------------------------------
--- Data Tables
		
GC_MyMoney = {	
		["Gold"]		= "0",
		["Silver"]		= "00",
		["Copper"]		= "00",
		["Sign"]		= " ",
		["Color"]		= "|cffFFFFFF",
		["NoColor"]		= "|cffE0E0E0",
		["PosColor"]	= "|cff00ff00",
		["NegColor"]	= "|cffff0000",
}

GC_Gear_Durability = { 
		["Equipped_Stuff"]     = "??",
		["Equipped_Weapons"]   = "??",
		["Color_State_LOW"]    = "|cfff00000",
		["Color_State_MEDIUM"] = "|cfff0f000",
		["Color_State_GOOD"]   = "|cff00f000",
}

GC_CounterFonts_List = {
		
		"MailFont_Large",
		"SystemFont_Outline",
		"Game13Font",
		"Game15Font",
		"Game18Font",
		"Game12Font_o1",
		"Game13Font_o1",
		"Game15Font_o1",
		"FriendsFont_Large",
		"NumberFont_Shadow_Med",
		"NumberFont_Outline_Med",
		"NumberFont_Outline_Large",
		"Fancy16Font",
		"Fancy18Font",
		"QuestFont_Shadow_Huge",
		"QuestFont_Outline_Huge",
		"Erika",
		"Erika_B",
		"SicretMono_Regular",
		"SicretMono_Medium",
		"Xanmono",
		"Hack",
		"Targa",
		"WhiteRabbit",
		"Makisupa",
		"JetBrains",
		}

---------------------------------------------------
--- Libraries Functions
GCLDB   = LibStub:GetLibrary("LibDataBroker-1.1")
GCLibDD = LibStub:GetLibrary("LibUIDropDownMenu-4.0")
GC_Icon = LibStub("LibDBIcon-1.0")

GC_Icon_DataObj = GCLDB:NewDataObject("GOLDCOUNTER", {
	type = "launcher",
	text = "GoldCounter",
	label = "GC_MiniMapButtonLabel",
	icon = "Interface\\Icons\\Inv_misc_coin_01",
	OnClick = function( self, button ) GC_MiniMapButton_OnClick( self, button ) end,
	OnEnter = function(self) GC_MiniMapButton_OnEnter(self) end,
	OnLeave = function() GC_MinimapButtonTooltip:Hide() end,
})

GC_Icon_DB = {
	profile = {
		minimap = {
			hide = false
		}
	}
}

---------------------------------------------------

--- Startup OnLoad
function GoldCounter_OnLoad()

	----------------------
	--- Register Event ---
	----------------------
	GoldCounter_MainFrame:RegisterEvent( "ADDON_LOADED" )
	GoldCounter_MainFrame:RegisterEvent( "PLAYER_ENTERING_WORLD" )
	GoldCounter_MainFrame:RegisterEvent( "PLAYER_LEAVING_WORLD" )
	GoldCounter_MainFrame:RegisterEvent( "PLAYER_MONEY" )
	GoldCounter_MainFrame:RegisterEvent( "PLAYER_LEVEL_UP" )
	GoldCounter_MainFrame:RegisterEvent( "CHAT_MSG_ADDON" )
	GoldCounter_MainFrame:RegisterEvent( "PLAYER_REGEN_ENABLED" )
	GoldCounter_MainFrame:RegisterEvent( "PLAYER_REGEN_DISABLED" )
	GoldCounter_MainFrame:RegisterEvent( "PLAYER_XP_UPDATE" )
	GoldCounter_MainFrame:RegisterEvent( "PLAYER_UPDATE_RESTING" )
	GoldCounter_MainFrame:RegisterEvent( "UPDATE_EXHAUSTION" )
	GoldCounter_MainFrame:RegisterEvent( "ZONE_CHANGED" )
	GoldCounter_MainFrame:RegisterEvent( "ZONE_CHANGED_INDOORS" )
	GoldCounter_MainFrame:RegisterEvent( "ZONE_CHANGED_NEW_AREA" )
	GoldCounter_MainFrame:RegisterEvent( "LOOT_OPENED" )
	GoldCounter_MainFrame:RegisterEvent( "GUILD_ROSTER_UPDATE" )
	GoldCounter_MainFrame:RegisterEvent( "GROUP_ROSTER_UPDATE" )
	GoldCounter_MainFrame:RegisterEvent( "PLAYER_INTERACTION_MANAGER_FRAME_SHOW" )
	GoldCounter_MainFrame:RegisterEvent( "PLAYER_INTERACTION_MANAGER_FRAME_HIDE" )
	GoldCounter_MainFrame:RegisterEvent( "QUEST_TURNED_IN" )
	GoldCounter_MainFrame:RegisterEvent( "SCENARIO_COMPLETED" )
	GoldCounter_MainFrame:RegisterEvent( "LFG_COMPLETION_REWARD")
	GoldCounter_MainFrame:RegisterEvent( "BOSS_KILL" )
	GoldCounter_MainFrame:RegisterEvent( "SKILL_LINES_CHANGED")
	GoldCounter_MainFrame:RegisterEvent( "CHALLENGE_MODE_COMPLETED")
	----------------------
end

--------------------------------------------------------------------------------------------------------------

function GoldCounter_OnEvent( self, event, arg1, arg2, arg3, arg4 )

	--- Addon Loaded ------------
	if event == "ADDON_LOADED" and arg1 == "GoldCounter" then

	-----------------------------------------------
	--- DATA INIT
	-----------------------------------------------

	GC_Version = C_AddOns.GetAddOnMetadata("GoldCounter", "Version")

	-----------------------------------------------
	--- Set localized texts
	GC_SetLocaleText()
	GC_SetOptionsPanelText()
	-----------------------------------------------

	GC_WOW_isRetail, GC_WOW_isPandaria, GC_WOW_isBCAnniv, GC_WOW_isVanilla = false, false, false, false

	--- Determine WOW Expansion
	if WOW_PROJECT_ID == 1 then

		GC_WOW_isRetail = true      -- Retail
		GC_Flavor = ""
		GC_MaxPlayerLevel = 90

	elseif WOW_PROJECT_ID == 19 then

		GC_WOW_isPandaria = true    -- Pandaria
		GC_Flavor = "( Pandaria )"
		GC_MaxPlayerLevel = 90

	elseif WOW_PROJECT_ID == 5 then

		GC_WOW_isBCAnniv = true    -- BC Anniversary
		GC_Flavor = "( Burning Crusade )"
		GC_MaxPlayerLevel = 70

	elseif WOW_PROJECT_ID == 2 then

		GC_WOW_isVanilla = true     -- Vanilla
		GC_Flavor = "( Vanilla )"
		GC_MaxPlayerLevel = 60
	else

	GC_WOW_isVanilla = true     -- Unknown ??
	GC_Flavor = "( ? )"
	GC_MaxPlayerLevel = 120
	end

	---  Is it connection or Reload ? ------------ (self, event, isLogin, isReload)
	elseif event == "PLAYER_ENTERING_WORLD" and ( arg1 or arg2 ) then 

	GC_ResetButton:SetMotionScriptsWhileDisabled( true ) --- Reset button always shows tooltip

	-------------------------------------------
	--- Minimap button register
	GC_Icon:Register( "GOLDCOUNTER", GC_Icon_DataObj , GC_Icon_DB.profile.minimap )
	--- Check and apply Addon Settings
	GC_SetAddonOptions()
	--- Create and Set DropdownList and menus defaults
	GC_Create_DDM()
	-------------------------------------------

	----------------------------
	--- Check if Version Update
	----------------------------
	if GC_CheckNewVersion( My_GC_Settings_Local.GC_Version, GC_Version ) then GC_UpdatedVersion()
	end

	DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r "..GC_Version.." "..GC_Locale_Text.LOADED_MSG.."! "..GC_Flavor )
	My_GC_Settings_Local.GC_Version = GC_Version
	----------------------------

	-------------------------------------------
	--- Check Last Login Date and Time
	GC_CurrentDate = tonumber( date("%y%m%d") )

	GC_LastLoginDate  = My_GC_Settings_Local.LastLoginDate
	GC_LastLoginTime  = My_GC_Settings_Local.LastLoginTime
	My_GC_Settings_Local.LastLoginDate = GC_CurrentDate
	My_GC_Settings_Local.LastLoginTime = date("%H:%M:%S")
	
	--- Logout date and time for commandline reference only
	GC_LastLogoutDate = My_GC_Settings_Local.LastLogoutDate
	GC_LastLogoutTime  = My_GC_Settings_Local.LastLogoutTime
	
	-------------------------------------------
	--- Counter Init
	GC_CurrentFunds 	= GetMoney() -- Store current funds
	GC_LoginMoneyInit	= GC_CurrentFunds
	GC_PreviousMoney 	= GC_CurrentFunds
	-------------------------------------------

	----------------------------
	--- Global Login References
	----------------------------
	My_GC_Settings.Addon			= "GoldCounter"
	My_GC_Settings.Version			= GC_Version
	My_GC_Settings.LastConnectDate	= GC_CurrentDate
	My_GC_Settings.LastConnectTime	= My_GC_Settings_Local.LastLoginTime
	----------------------------

	-------------------------------------------
	--- If SaveVar doesn't exist - First time Init
	if not MySavedMoney then
		MySavedMoney = 0
	else
		GC_LoginMoneyInit = GC_LoginMoneyInit - MySavedMoney -- if saved value then modify balance
	end

	GoldCounter_Update()
	-------------------------------------------

	-------------------------------------------
	--- Daily Reset -- Check for today
	if ( My_GC_Settings_Local.LastResetDate < GC_CurrentDate ) then 

		GC_MyDailyData.DailyCount = 0
		GC_MyDailyData.Instance_MoneyLoot = 0
		GC_MyDailyData.Money_Loot = 0
		GC_MyDailyData.Merchant_Money = 0
		GC_MyDailyData.Auctioneer = 0
		GC_MyDailyData.MailBoxIncome = 0
		GC_MyDailyData.QuestXP = 0
		GC_MyDailyData.Merchant_Transmo = 0
		GC_MyDailyData.TaxiCost = 0
		GC_MyDailyData.Craftsmanship = 0
		
		if ( My_GC_Settings_Local.DailyReset == true and MySavedMoney ~= 0 ) then
			GoldCounter_Reset( true ) --- AutoReset = true
		end
	end

	My_GC_Settings_Local.LastResetDate = GC_CurrentDate

	---
	local ServerRespond = GC_GetPlayerData()
	if not ServerRespond then
		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r ".."|cffffa500" ..GC_Locale_Text.ERROR_MSG1.."|r" )
	end
	---

	GC_BuildCharDB()

	-------------------------------------------
	--- Register Addon Messages system
	C_ChatInfo.RegisterAddonMessagePrefix( "GOLDCOUNTER" )
	-------------------------------------------

	-------------------------------------------
	--- Send Addon Version to Guild for checkup
	if IsInGuild() then
		C_ChatInfo.SendAddonMessage( "GOLDCOUNTER", "LOGIN1-"..GC_Version, "GUILD" )
	end
	-------------------------------------------

	-------------------------------------------
	--- First Start do action
	-------------------------------------------
	if not My_GC_Settings_Local.FirstStartDone then

		GC_FirstStart()
		--- To Do Tutorial Tooltips
		--- My_GC_Settings_Local.FirstStartDone = true
	end
	-------------------------------------------

	-------------------------------------------------------------
	--- Is it receiving addon message ?
	elseif event == "CHAT_MSG_ADDON" then

		GC_GetAddonMessage( arg1, arg2, arg3, arg4 )

	-------------------------------------------------------------
	--- Is it Interaction with NPC ?
	elseif event == "PLAYER_INTERACTION_MANAGER_FRAME_SHOW" then
		--print(arg1)
		if arg1 == 5 or arg1 == 12 or arg1 == 53 then

			--- Merchant
			GC_Events_Data.IsMercOpen = true

		elseif arg1 == 8 or arg1 == 68 then

			--- Bank
			GC_Events_Data.BankFrame_Open = true

		elseif arg1 == 10 then

			--- GuildBank
			GC_Events_Data.GuildBankFrame_Open = true

		elseif arg1 == 17 then

			--- Mail
			GC_Events_Data.MailBox_Open = true

		elseif arg1 == 24 then

			--- Transmo
			GC_Events_Data.TransmoMerc_Open = true

		elseif arg1 == 21 then

			--- Auctioneer
			GC_Events_Data.Auctioneer_Open = true

		elseif arg1 == 59 or arg1 == 60 then
		
			GC_Events_Data.Profession_Open = true

		end
	-------------------------------------------------------------
	elseif event == "PLAYER_INTERACTION_MANAGER_FRAME_HIDE" then

		if arg1 == 5 or arg1 == 12 or arg1 == 53 then

			GC_Events_Data.IsMercOpen = false

		elseif arg1 == 8 or arg1 == 68 then -- 68 = Bataillon

			GC_Events_Data.BankFrame_Open = false

		elseif arg1 == 10 then

			GC_Events_Data.GuildBankFrame_Open = false

		elseif arg1 == 17 then

			GC_Events_Data.MailBox_Open = false

		elseif arg1 == 24 then

			GC_Events_Data.TransmoMerc_Open = false

		elseif arg1 == 21 then

			GC_Events_Data.Auctioneer_Open = false

		elseif arg1 == 59 or arg1 == 60 then
		
			GC_Events_Data.Profession_Open = false

		end

	--- Check Item Level
	GC_PlayerItemLevel = GC_GetPlayerItemLevel()
	GoldCounterCharPanel_Build() -- Update Lines Panel and Total money

	-------------------------------------------------------------
	--- Is delve/dungeon Over ?
	elseif event == "SCENARIO_COMPLETED" or event == "LFG_COMPLETION_REWARD" or event == "BOSS_KILL" then

		--- End of fighting not detected when delve/dungeon is done
		GC_CheckFighting()

	-------------------------------------------------------------
	--- Is MM+ done ?
	elseif event == "CHALLENGE_MODE_COMPLETED" then
	
	GC_MM_Plus_Infos()

	------------------------------------------------------------- GC_MM_Plus_BestLevel = 0
	--- Is lootbox open ?
	elseif event == "LOOT_OPENED" then

			GC_Events_Data.isLootOpenHasMoney = false

		--- Is there money in the lootbox
		for i = 1, GetNumLootItems() do

			if GetLootSlotType(i) == Enum.LootSlotType.Money then 

			GC_Events_Data.isLootOpenHasMoney = true

			end
		end

	-------------------------------------------------------------
	--- Is it money update ?
	elseif event == "PLAYER_MONEY" then

		GC_PLAYER_MONEY()

	-------------------------------------------------------------
	elseif event == "QUEST_TURNED_IN" then
	
		local WonXP = arg2 or 0
		-- local WonGold = arg3 or 0

		GC_MyDailyData.QuestXP = GC_MyDailyData.QuestXP + WonXP

	elseif event == "GUILD_ROSTER_UPDATE" then

		--- Send Version to guild at login or when someone login in guild
		--- Event will trigger only if in guild

		GC_PlayerGuildName = GetGuildInfo("player")
		C_ChatInfo.SendAddonMessage( "GOLDCOUNTER", "LOGIN1-"..GC_Version, "GUILD" )

	-------------------------------------------------------------
	elseif event == "GROUP_ROSTER_UPDATE" then

		local _, instanceType = IsInInstance()
		local isParty = GetNumGroupMembers()

		if GC_Roster_PlayersNum_Event == isParty then return end

		if instanceType == "pvp" then

			C_ChatInfo.SendAddonMessage( "GOLDCOUNTER", "LOGIN1-"..GC_Version, "BATTLEGROUND" )
		
		elseif instanceType == "raid" then

			C_ChatInfo.SendAddonMessage( "GOLDCOUNTER", "LOGIN1-"..GC_Version, "RAID" )

		elseif isParty > 1 then
			C_ChatInfo.SendAddonMessage( "GOLDCOUNTER", "LOGIN1-"..GC_Version, "PARTY" )
			C_ChatInfo.SendAddonMessage( "GOLDCOUNTER", "LOGIN1-"..GC_Version, "INSTANCE_CHAT" )
		end

		--- If same number of players then no messages
		GC_Roster_PlayersNum_Event = isParty

	-------------------------------------------------------------
	--- Combat started
	elseif event == "PLAYER_REGEN_DISABLED" then

		if ( My_GC_Settings_Local.HideInCombat == true and GC_ToggleSwitch == false ) then

		GoldCounter_MainFrame:Hide()

		end

		--- Check if Fighting and start Animation
		StopLoop2()
		GC_CheckFighting()

	-------------------------------------------------------------
	--- Combat stopped
	elseif event == "PLAYER_REGEN_ENABLED" then

		--- Stop Animation
		StopLoop1()

		if ( My_GC_Settings_Local.HideInCombat == true and GC_ToggleSwitch == false ) then

			GoldCounter_MainFrame:Show()

		end

		--- Check if Resting and start Animation
		GC_CheckResting()

	-------------------------------------------------------------
	--- Rest points updated or entering rest area
	elseif event == "UPDATE_EXHAUSTION" or event == "PLAYER_UPDATE_RESTING" then
	
		--- Check if Resting and start Animation
		GC_CheckResting()

		if ( GoldCounter_CharCard:IsShown() ) then
			GoldCounter_CharCard:Hide()
			GC_CardInit()
			GoldCounter_CharCard:Show()
		end

	-------------------------------------------------------------
	elseif event == "PLAYER_XP_UPDATE" then

		local CharXP = UnitXP("player")
		local WonXP = CharXP - GC_PlayerXP

		if ( WonXP > 0 ) then
			GC_LastXP = WonXP
			GC_PlayerXP = CharXP
		end

		if ( GoldCounter_CharCard:IsShown() ) then
			GoldCounter_CharCard:Hide()
			GC_CardInit()
			GoldCounter_CharCard:Show()
		end

	-------------------------------------------------------------
	elseif event == "ZONE_CHANGED" or event == "ZONE_CHANGED_INDOORS" or event == "ZONE_CHANGED_NEW_AREA" then

			--- Check Item Level
			GC_PlayerItemLevel = GC_GetPlayerItemLevel()
			GC_GetJobsData()
			GoldCounterCharPanel_Build()

			--- Check if Resting or Fighting and start Animation
			GC_CheckResting()
			GC_CheckFighting()

	-------------------------------------------------------------
	elseif event == "PLAYER_LEVEL_UP" then

		GC_PlayerLevel = arg1
		GoldCounterCharPanel_Build() -- Update Lines Panel and Total money

	elseif event == "SKILL_LINES_CHANGED" then
	
	GC_GetJobsData()
	
	elseif event == "PLAYER_LEAVING_WORLD" then

		GC_BuildCharDB() --- Save and update recent data to DB
		
		My_GC_Settings_Local.LastLogoutDate = tonumber( date("%y%m%d") )
		My_GC_Settings_Local.LastLogoutTime = date("%H:%M:%S")

	end
 
end

function GC_GetPlayerData()

	local ServerRespond = true

	GC_PlayerName			= UnitName( "player" ) or "?NoName?"
	GC_CharGender 			= UnitSex("player") or "?NG?"
	GC_PlayerRaceLocalized, GC_PlayerRaceEN = UnitRace("player")
	
	GC_PlayerXP				= UnitXP("player") or 0 -- Base
	GC_PlayerLevel			= UnitLevel("player") or 0
	GC_PlayerItemLevel		= GC_GetPlayerItemLevel() or "?NoIL?" -- Get Initial ItemLevel

	GC_PlayerClassLocale, GC_PlayerClassEN, GC_PlayerClassIndex = UnitClass( "player" )
	GC_PlayerFaction, GC_PlayerFactionLocale = UnitFactionGroup( "player" )

	GC_PlayerRealm			= GetRealmName() or "?NoRealm?"
	GC_PlayerNormRealm		= GetNormalizedRealmName() or "?NoNormRealm?"
	GC_PlayerNormName 		= GC_PlayerName.."-"..GC_PlayerNormRealm

	--- Professions
	GC_GetJobsData()

	--- MM+
	GC_MM_Plus_Infos()

	--- Check Up
	if GC_PlayerName == "?NoName?" or GC_CharGender == "?NG?" or not GC_PlayerRaceLocalized or not GC_PlayerRaceEN then ServerRespond = false end
	if GC_PlayerLevel == 0 then ServerRespond = false end
	
	if not GC_PlayerRaceLocalized then GC_PlayerRaceLocalized = "?NoRaceLoc?" ServerRespond = false end
	if not GC_PlayerRaceEN then GC_PlayerRaceEN = "?NoRaceEN?" ServerRespond = false end
	if not GC_PlayerClassLocale then GC_PlayerClassLocale = "?NoClassLoc?" ServerRespond = false end
	if not GC_PlayerClassEN then GC_PlayerClassEN = "?NoClassEN?" ServerRespond = false end
	if not GC_PlayerClassIndex then GC_PlayerClassIndex = "?NoClassIndex?" ServerRespond = false end
	if not GC_PlayerFaction then GC_PlayerFaction = "?NoFaction?" ServerRespond = false end
	if not GC_PlayerFactionLocale then GC_PlayerFactionLocale = "?NoFactionLoc?" ServerRespond = false end

	return ServerRespond
end

function GC_BuildCharDB()

	---------------------------------
	--- Update Characters Database
	---------------------------------

	local CharFound = false
	local Idx = 0

		--- Is there already a DB
		if #My_GC_CharMoneyDB > 0 then

			--- Search if character exists and update
			for Idx = 1, #My_GC_CharMoneyDB do

				if My_GC_CharMoneyDB[Idx].NormName == GC_PlayerNormName then
				
					My_GC_CharMoneyDB[Idx].Balance			  	= MySavedMoney
					My_GC_CharMoneyDB[Idx].Funds				= GC_CurrentFunds
					My_GC_CharMoneyDB[Idx].Class				= GC_PlayerClassEN
					My_GC_CharMoneyDB[Idx].ClassLocale		  	= GC_PlayerClassLocale
					My_GC_CharMoneyDB[Idx].ClassIndex			= GC_PlayerClassIndex
					My_GC_CharMoneyDB[Idx].Level				= GC_PlayerLevel
					My_GC_CharMoneyDB[Idx].Faction			  	= GC_PlayerFaction
					My_GC_CharMoneyDB[Idx].FactionLocale		= GC_PlayerFactionLocale
					My_GC_CharMoneyDB[Idx].ItemLevel			= GC_PlayerItemLevel
					My_GC_CharMoneyDB[Idx].GuildName			= GC_PlayerGuildName
					My_GC_CharMoneyDB[Idx].Job1				  	= GC_Job1
					My_GC_CharMoneyDB[Idx].Job1Icon			  	= GC_Job1Icon
					My_GC_CharMoneyDB[Idx].Job1SkillLevel		= GC_Job1SkillLevel
					My_GC_CharMoneyDB[Idx].Job1MaxSkillLevel	= GC_Job1MaxSkillLevel
					My_GC_CharMoneyDB[Idx].Job2				  	= GC_Job2
					My_GC_CharMoneyDB[Idx].Job2Icon			  	= GC_Job2Icon
					My_GC_CharMoneyDB[Idx].Job2SkillLevel		= GC_Job2SkillLevel
					My_GC_CharMoneyDB[Idx].Job2MaxSkillLevel	= GC_Job2MaxSkillLevel

					-- Secure MM+ data
					if GC_WOW_isRetail then
						if GC_MM_Plus_OverallScore > 0 then

						My_GC_CharMoneyDB[Idx].MM_Plus_OverallScore = GC_MM_Plus_OverallScore

							if GC_MM_Plus_HighestKeyLevel == 0 and My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel_Backup
							and My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel_Backup > 0 then

							My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel			= My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel_Backup
							My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName	= My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName_Backup
							GC_MM_Plus_HighestKeyLevel								= My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel_Backup
							GC_MM_Plus_HighestKeyDungeonName						= My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName_Backup
							
							GC_MM_Plus_UsingBackup = true

							elseif GC_MM_Plus_HighestKeyLevel > 0 and not GC_MM_Plus_UsingBackup then
							My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel				= GC_MM_Plus_HighestKeyLevel
							My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName		= GC_MM_Plus_HighestKeyDungeonName
							My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel_Backup		= GC_MM_Plus_HighestKeyLevel_Backup -- Backup
							My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName_Backup	= GC_MM_Plus_HighestKeyDungeonName_Backup -- Backup

							end

						else -- In case of new season or not playing MM+ -> Reset MM+ data
							My_GC_CharMoneyDB[Idx].MM_Plus_OverallScore 				= 0
							My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel				= 0
							My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName		= ""
							My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel_Backup		= 0
							My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName_Backup	= ""
						end
					end
					------------------

					CharFound = true
				end

					if CharFound then break end
			end

		end

		if #My_GC_CharMoneyDB > 0 and not CharFound then -- DB exists but current character not found
			Idx = #My_GC_CharMoneyDB + 1 -- Add New character
			My_GC_CharMoneyDB[Idx] = {}
		elseif #My_GC_CharMoneyDB == 0 then -- No DB, create new one
			Idx = 1
			My_GC_CharMoneyDB = {} 
			My_GC_CharMoneyDB[Idx] = {}
		else
			return
		end

			My_GC_CharMoneyDB[Idx].NormName				= GC_PlayerNormName
			My_GC_CharMoneyDB[Idx].Name					= GC_PlayerName
			My_GC_CharMoneyDB[Idx].Realm				= GC_PlayerRealm
			My_GC_CharMoneyDB[Idx].Balance				= MySavedMoney
			My_GC_CharMoneyDB[Idx].Funds				= GC_CurrentFunds
			My_GC_CharMoneyDB[Idx].Class				= GC_PlayerClassEN
			My_GC_CharMoneyDB[Idx].ClassLocale			= GC_PlayerClassLocale
			My_GC_CharMoneyDB[Idx].ClassIndex			= GC_PlayerClassIndex
			My_GC_CharMoneyDB[Idx].Level				= GC_PlayerLevel
			My_GC_CharMoneyDB[Idx].Faction				= GC_PlayerFaction
			My_GC_CharMoneyDB[Idx].FactionLocale		= GC_PlayerFactionLocale
			My_GC_CharMoneyDB[Idx].ItemLevel			= GC_PlayerItemLevel
			My_GC_CharMoneyDB[Idx].GuildName			= GC_PlayerGuildName
			My_GC_CharMoneyDB[Idx].Job1					= GC_Job1
			My_GC_CharMoneyDB[Idx].Job1Icon				= GC_Job1Icon
			My_GC_CharMoneyDB[Idx].Job1SkillLevel		= GC_Job1SkillLevel
			My_GC_CharMoneyDB[Idx].Job1MaxSkillLevel	= GC_Job1MaxSkillLevel
			My_GC_CharMoneyDB[Idx].Job2					= GC_Job2
			My_GC_CharMoneyDB[Idx].Job2Icon				= GC_Job2Icon
			My_GC_CharMoneyDB[Idx].Job2SkillLevel		= GC_Job2SkillLevel
			My_GC_CharMoneyDB[Idx].Job2MaxSkillLevel	= GC_Job2MaxSkillLevel

			if GC_WOW_isRetail then
				if GC_MM_Plus_OverallScore > 0 then
						
				My_GC_CharMoneyDB[Idx].MM_Plus_OverallScore	= GC_MM_Plus_OverallScore

					if GC_MM_Plus_HighestKeyLevel > 0 then
					My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel				= GC_MM_Plus_HighestKeyLevel
					My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName		= GC_MM_Plus_HighestKeyDungeonName
					My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel_Backup		= GC_MM_Plus_HighestKeyLevel_Backup  -- Backup
					My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName_Backup	= GC_MM_Plus_HighestKeyDungeonName_Backup -- Backup
					end

				else -- In case of new season or not playing MM
					My_GC_CharMoneyDB[Idx].MM_Plus_OverallScore 				= 0
					My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel				= 0
					My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName		= ""
					My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyLevel_Backup		= 0
					My_GC_CharMoneyDB[Idx].MM_Plus_HighestKeyDungeonName_Backup	= ""
				end
			end
end
--------------------------------------------------------------------------------------------------------------

function GC_ClearSelectCharDB()

	local i = GC_CharIndexToDelete
	local LastName

	if i ~= -1 then -- Delete one character
	
		LastName = My_GC_CharMoneyDB[i].NormName

		tremove( My_GC_CharMoneyDB, i )

	GoldCounterCharPanel_Build() -- Update Lines Panel and Total money

	DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r |cff00FFFF"..LastName.."|r "..GC_Locale_Text.CHAT_DB_SELECTERASED )
	GC_PlaySFX( 3 )

	else -- Clear full database
	
	GC_ClearCharDB()
	end

	GCLibDD:UIDropDownMenu_SetText( GC_CharDB_DropDownList, GC_Locale_Text.OPTIONSPANELTXT_CHOOSECHAR )
	GC_Options_ClearDB_Button:Disable()

	--- Close menus on Classics
	if not GC_WOW_isRetail then

		if L_UIDROPDOWNMENU_OPEN_MENU then
			GCLibDD:ToggleDropDownMenu( nil, nil, GC_CharDB_DropDownList )
		end

	end

end

function GC_ClearCharDB()

	My_GC_CharMoneyDB = {} -- Clear Database

	GC_BuildCharDB() -- Rebuild Database with only current char
	GoldCounterCharPanel_Build() -- Update Lines Panel and Total money
	
	DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r "..GC_Locale_Text.CHAT_DB_ERASED )

	GC_PlaySFX( 3 )
end

function GoldCounter_SetHistoryList()

	local _, frameY = GoldCounter_MainFrame:GetCenter()
	local _, screenY = UIParent:GetCenter()
	local AnchorPoint, AnchorPointY = "", 0
	
	if frameY > screenY then
		AnchorPoint = "ANCHOR_BOTTOM"
		AnchorPointY = -6
	else
		AnchorPoint = "ANCHOR_TOP"
		AnchorPointY = 6
	end
	
	GoldCounter_Custom_Tooltip:Hide()
	GoldCounter_Custom_Tooltip:ClearLines()
	GoldCounter_Custom_Tooltip:SetOwner( _G["GC_ResetButton"], AnchorPoint, 0, AnchorPointY )
	
	--- Title ---
	GoldCounter_Custom_TooltipTextLeft1:SetFontObject( Fancy12Font )
	GoldCounter_Custom_Tooltip:AddLine( GC_Locale_Text.TOOLTIP_INFOS_HISTORY.." - "..GC_PlayerName, nil, nil, nil, false )

	--- Add space ---
	GoldCounter_Custom_Tooltip:AddLine( " ", 0, 0, 0, false )

	--- Local vars
	local amount = 0
	local amountNum = 0
	local sign = " "
	local FundString = ""
	local Balance = 0
	local HistListIndex = 2
	local CustDate = ""
	local WeekGain = 0
	local Data1, Data2, Str = "", "", ""
	---

	if My_GC_Settings_Local.MaxHistoryRec > 1 then
	
		------------------------------------------------
		--- Write Data from Max to before first entry
		for i = My_GC_Settings_Local.MaxHistoryRec, 2, -1 do
		
			if ( MySavedMoneyHistory[i].date and MySavedMoneyHistory[i].date ~= "*" ) then

				amount = MySavedMoneyHistory[i].amount
				sign = MySavedMoneyHistory[i].sign

				--- Compatibility with older version
				if type(amount) == "string" then amount = tonumber(amount) or 0 sign = " " end
				---

					Data1 = sign 
					Data2 = tostring(amount)
					Str = Data1..Data2
					amountNum = tonumber( Str )
					Balance = Balance + amountNum

				FundString = GC_MoneyCoinsTextures( sign, amount, false )

				HistListIndex = HistListIndex + 1
				_G["GoldCounter_Custom_TooltipTextLeft"..HistListIndex]:SetFontObject( GameFontWhiteTiny ) 
				_G["GoldCounter_Custom_TooltipTextRight"..HistListIndex]:SetFont("Interface\\AddOns\\GoldCounter\\Fonts\\JetBrainsMonoNL-SemiBold.ttf", 10, "")

				CustDate = GC_TranslateDate( MySavedMoneyHistory[i].date )
				GoldCounter_Custom_Tooltip:AddDoubleLine( CustDate, FundString, 1, 1, 1, false )
			end
		end
		------------------------------------------------
	end

	if ( MySavedMoneyHistory[1] and MySavedMoneyHistory[1].date and MySavedMoneyHistory[1].date ~= "*" ) then

			amount = MySavedMoneyHistory[1].amount
			sign = MySavedMoneyHistory[1].sign
 
				--- Compatibility with older version
				if type(amount) == "string" then amount = tonumber(amount) or 0 end

					Data1 = sign 
					Data2 = tostring(amount)
					Str = Data1..Data2
					amountNum = tonumber( Str )
					Balance = Balance + amountNum

			FundString = GC_MoneyCoinsTextures( sign, amount, false )

		HistListIndex = HistListIndex + 1
		_G["GoldCounter_Custom_TooltipTextLeft"..HistListIndex]:SetFontObject( GameFontWhiteTiny )
		_G["GoldCounter_Custom_TooltipTextRight"..HistListIndex]:SetFont("Interface\\AddOns\\GoldCounter\\Fonts\\JetBrainsMonoNL-SemiBold.ttf", 10, "")

		CustDate = GC_TranslateDate( MySavedMoneyHistory[1].date )
		GoldCounter_Custom_Tooltip:AddDoubleLine( CustDate, FundString, 1, 1, 0, false )

		--- Add space ---
		HistListIndex = HistListIndex + 1
		GoldCounter_Custom_Tooltip:AddLine( " ", 0, 0, 0, false )

			--- Calculate by week
			for i = 1, 7, 1 do

				if MySavedMoneyHistory[i] and MySavedMoneyHistory[i].amount and MySavedMoneyHistory[i].amount ~= "*" then
					Data1 = MySavedMoneyHistory[i].sign 
					Data2 = MySavedMoneyHistory[i].amount
					Str = Data1..Data2
					amountNum = tonumber( Str )
					WeekGain = WeekGain + amountNum
				end

			end

			local WeekGain_TextureString = GC_MoneyCoinsTextures( nil, WeekGain, false )
			local TOTAL = GC_MoneyCoinsTextures( nil, Balance, false )
			------------

		HistListIndex = HistListIndex + 1
		_G["GoldCounter_Custom_TooltipTextLeft"..HistListIndex]:SetFontObject( GameFontWhiteTiny )
		_G["GoldCounter_Custom_TooltipTextRight"..HistListIndex]:SetFont("Interface\\AddOns\\GoldCounter\\Fonts\\JetBrainsMonoNL-SemiBold.ttf", 10, "")
		GoldCounter_Custom_Tooltip:AddDoubleLine( GC_Locale_Text.TOOLTIP_INFOS_WEEKLY, WeekGain_TextureString, nil, nil, nil, false )

		HistListIndex = HistListIndex + 1
		_G["GoldCounter_Custom_TooltipTextLeft"..HistListIndex]:SetFontObject( GameFontWhiteTiny )
		_G["GoldCounter_Custom_TooltipTextRight"..HistListIndex]:SetFont("Interface\\AddOns\\GoldCounter\\Fonts\\JetBrainsMonoNL-SemiBold.ttf", 10, "")
		GoldCounter_Custom_Tooltip:AddDoubleLine( GC_Locale_Text.TOOLTIP_INFOS_TOTAL, TOTAL, nil, nil, nil, false )

	else
		HistListIndex = HistListIndex + 1
		_G["GoldCounter_Custom_TooltipTextLeft"..HistListIndex]:SetFontObject( GameFontWhiteTiny )
		GoldCounter_Custom_Tooltip:AddLine( GC_Locale_Text.TOOLTIP_INFOS_NOHIST, 0.4, 0.4, 0.4, false )
	end

	if ( GC_ResetButton:IsEnabled() ) then

	--- Add space ---
	HistListIndex = HistListIndex + 1
	GoldCounter_Custom_Tooltip:AddLine( " ", 0, 0, 0, false )

	--- Click Reset Message ---
	HistListIndex = HistListIndex + 1
	_G["GoldCounter_Custom_TooltipTextLeft".. HistListIndex]:SetFontObject( GameFontWhiteTiny )
	GoldCounter_Custom_Tooltip:AddLine( GC_Locale_Text.TOOLTIP_RESET, 1, 1, 1, false )
	end

end

function GC_SaveProfile()

	My_GC_Profile[GC_ProfileButtonChecked] = { }  --- Création

	My_GC_Profile[GC_ProfileButtonChecked].Scale				= My_GC_Settings_Local.Scale
	My_GC_Profile[GC_ProfileButtonChecked].TransView			= My_GC_Settings_Local.TransView
	My_GC_Profile[GC_ProfileButtonChecked].TransView_SW			= My_GC_Settings_Local.TransView_SW
	My_GC_Profile[GC_ProfileButtonChecked].ShowGoldOnly			= My_GC_Settings_Local.ShowGoldOnly
	My_GC_Profile[GC_ProfileButtonChecked].ShowGoldOnly_SW		= My_GC_Settings_Local.ShowGoldOnly_SW
	My_GC_Profile[GC_ProfileButtonChecked].UseShiftToDrag		= My_GC_Settings_Local.UseShiftToDrag
	My_GC_Profile[GC_ProfileButtonChecked].UseShiftToDrag_SW	= My_GC_Settings_Local.UseShiftToDrag_SW
	My_GC_Profile[GC_ProfileButtonChecked].DailyReset			= My_GC_Settings_Local.DailyReset
	My_GC_Profile[GC_ProfileButtonChecked].DailyReset_SW		= My_GC_Settings_Local.DailyReset_SW
	My_GC_Profile[GC_ProfileButtonChecked].HideInCombat			= My_GC_Settings_Local.HideInCombat
	My_GC_Profile[GC_ProfileButtonChecked].HideInCombat_SW		= My_GC_Settings_Local.HideInCombat_SW
	My_GC_Profile[GC_ProfileButtonChecked].MaxHistoryRec		= My_GC_Settings_Local.MaxHistoryRec
	My_GC_Profile[GC_ProfileButtonChecked].Font					= My_GC_Settings_Local.Font
	My_GC_Profile[GC_ProfileButtonChecked].UserDateFormat		= My_GC_Settings_Local.UserDateFormat
	My_GC_Profile[GC_ProfileButtonChecked].Thousand_Delimiter	= My_GC_Settings_Local.Thousand_Delimiter
	My_GC_Profile[GC_ProfileButtonChecked].MinimapButtonUse		= My_GC_Settings_Local.MinimapButtonUse
	My_GC_Profile[GC_ProfileButtonChecked].MinimapButtonUse_SW	= My_GC_Settings_Local.MinimapButtonUse_SW
	My_GC_Profile[GC_ProfileButtonChecked].MinimapButtonPos		= GC_Icon_DB.profile.minimap.minimapPos
	My_GC_Profile[GC_ProfileButtonChecked].IconsFlash			= My_GC_Settings_Local.IconsFlash
	My_GC_Profile[GC_ProfileButtonChecked].IconsFlash_SW		= My_GC_Settings_Local.IconsFlash_SW
	My_GC_Profile[GC_ProfileButtonChecked].CheckBank			= My_GC_Settings_Local.CheckBank
	My_GC_Profile[GC_ProfileButtonChecked].CheckBank_SW			= My_GC_Settings_Local.CheckBank_SW
	My_GC_Profile[GC_ProfileButtonChecked].SortServerOnTop		= My_GC_Settings_Local.SortServerOnTop
	My_GC_Profile[GC_ProfileButtonChecked].SortServerOnTop_SW	= My_GC_Settings_Local.SortServerOnTop_SW
	My_GC_Profile[GC_ProfileButtonChecked].HideHistory			= My_GC_Settings_Local.HideHistory
	My_GC_Profile[GC_ProfileButtonChecked].HideHistory_SW		= My_GC_Settings_Local.HideHistory_SW

	My_GC_Profile[GC_ProfileButtonChecked].Name					= GC_PlayerName
	My_GC_Profile[GC_ProfileButtonChecked].Realm				= GC_PlayerRealm
	My_GC_Profile[GC_ProfileButtonChecked].NormName				= GC_PlayerNormName
	My_GC_Profile[GC_ProfileButtonChecked].Class				= GC_PlayerClassEN

	--- Save Frame location
	My_GC_Profile[GC_ProfileButtonChecked].GC_Point, _, My_GC_Profile[GC_ProfileButtonChecked].GC_RelaPoint, 
	My_GC_Profile[GC_ProfileButtonChecked].GC_Xpos,
	My_GC_Profile[GC_ProfileButtonChecked].GC_Ypos = GoldCounter_MainFrame:GetPoint(1)

	DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r "..GC_Locale_Text.PROFILE_SAVED.." ("..GC_ProfileButtonChecked..")" )

	--- Set Profile Name on option panel
	local name = GC_GetClassColor( My_GC_Profile[GC_ProfileButtonChecked].Name, My_GC_Profile[GC_ProfileButtonChecked].Class )

	_G["GC_Profile"..GC_ProfileButtonChecked.."_ButtonDefText"]:SetText( name )

	GC_PlaySFX( 1 )
end

function GC_LoadProfile( Index )

	if ( not Index ) then Index = GC_ProfileButtonChecked --- Check if it's from Quick Menu
	end

	if ( not My_GC_Profile[Index] ) then

		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r "..GC_Locale_Text.PROFILE_NOPROFILE.." ("..Index..")" )
		PlaySound( SOUNDKIT.IG_QUEST_LOG_ABANDON_QUEST )
	return
	else
	
		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r "..GC_Locale_Text.PROFILE_LOADED..
		" ("..Index..")".." (|cff3FC7EB"..My_GC_Profile[Index].NormName.."|r)" )
	end

	My_GC_Settings_Local.Scale					= My_GC_Profile[Index].Scale
	My_GC_Settings_Local.TransView				= My_GC_Profile[Index].TransView
	My_GC_Settings_Local.TransView_SW       	= My_GC_Profile[Index].TransView_SW
	My_GC_Settings_Local.ShowGoldOnly       	= My_GC_Profile[Index].ShowGoldOnly
	My_GC_Settings_Local.ShowGoldOnly_SW    	= My_GC_Profile[Index].ShowGoldOnly_SW
	My_GC_Settings_Local.UseShiftToDrag     	= My_GC_Profile[Index].UseShiftToDrag
	My_GC_Settings_Local.UseShiftToDrag_SW  	= My_GC_Profile[Index].UseShiftToDrag_SW
	My_GC_Settings_Local.DailyReset         	= My_GC_Profile[Index].DailyReset
	My_GC_Settings_Local.DailyReset_SW      	= My_GC_Profile[Index].DailyReset_SW
	My_GC_Settings_Local.HideInCombat       	= My_GC_Profile[Index].HideInCombat
	My_GC_Settings_Local.HideInCombat_SW    	= My_GC_Profile[Index].HideInCombat_SW
	My_GC_Settings_Local.MaxHistoryRec      	= My_GC_Profile[Index].MaxHistoryRec
	My_GC_Settings_Local.Font               	= My_GC_Profile[Index].Font
	My_GC_Settings_Local.UserDateFormat     	= My_GC_Profile[Index].UserDateFormat
	My_GC_Settings_Local.Thousand_Delimiter 	= My_GC_Profile[Index].Thousand_Delimiter
	My_GC_Settings_Local.MinimapButtonUse		= My_GC_Profile[Index].MinimapButtonUse
	My_GC_Settings_Local.MinimapButtonUse_SW	= My_GC_Profile[Index].MinimapButtonUse_SW
	My_GC_Settings_Local.IconsFlash				= My_GC_Profile[Index].IconsFlash
	My_GC_Settings_Local.IconsFlash_SW    		= My_GC_Profile[Index].IconsFlash_SW
	My_GC_Settings_Local.CheckBank				= My_GC_Profile[Index].CheckBank
	My_GC_Settings_Local.CheckBank_SW			= My_GC_Profile[Index].CheckBank_SW
	My_GC_Settings_Local.SortServerOnTop		= My_GC_Profile[Index].SortServerOnTop
	My_GC_Settings_Local.SortServerOnTop_SW		= My_GC_Profile[Index].SortServerOnTop_SW
	My_GC_Settings_Local.HideHistory			= My_GC_Profile[Index].HideHistory
	My_GC_Settings_Local.HideHistory_SW			= My_GC_Profile[Index].HideHistory_SW

	My_GC_Settings_Local.LastResetDate = tonumber( date("%y%m%d") )

	-- Reset Frame location
	GoldCounter_MainFrame:ClearAllPoints()
	GoldCounter_MainFrame:SetPoint(My_GC_Profile[Index].GC_Point, UIParent,
	My_GC_Profile[Index].GC_RelaPoint, My_GC_Profile[Index].GC_Xpos,
	My_GC_Profile[Index].GC_Ypos)
	GoldCounter_MainFrame:SetUserPlaced(true)

	-- Reset Minimap button location
	GC_Icon_DB.profile.minimap.minimapPos = My_GC_Profile[Index].MinimapButtonPos
	GC_Icon:Refresh("GOLDCOUNTER", GC_Icon_DB.profile.minimap)
	
	GC_SetAddonOptions()

	--- DropDown Texts
	GC_FontDropDownList_OnClick( nil, My_GC_Settings_Local.Font )
	GC_ThouSeparator_DropDownList_OnClick( nil, My_GC_Settings_Local.Thousand_Delimiter )
	GC_DateFormat_DropDownList_OnClick( nil, My_GC_Settings_Local.UserDateFormat )

	GC_PlaySFX( 2 )
end

function GC_ClearProfile()

	if not My_GC_Profile[GC_ProfileButtonChecked] then

		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r "..GC_Locale_Text.PROFILE_NOPROFILE.." ("..GC_ProfileButtonChecked..")" )
		PlaySound( SOUNDKIT.IG_QUEST_LOG_ABANDON_QUEST )
	else
	
		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r "..GC_Locale_Text.PROFILE_DELETED..
		" ("..GC_ProfileButtonChecked..")".." (|cff3FC7EB"..My_GC_Profile[GC_ProfileButtonChecked].NormName.."|r)" )

		My_GC_Profile[GC_ProfileButtonChecked] = nil
		_G["GC_Profile"..GC_ProfileButtonChecked.."_ButtonDefText"]:SetText( GC_Locale_Text.OPTIONSPANEL_PROFILE_TEXT.." "..GC_ProfileButtonChecked )

	GC_PlaySFX( 3 )

	end

end

function GC_CardInit()

		--- Portrait Texture
		GC_CharPortraitRoundTexture:SetTexture( "interface/tradeskillframe/capacitanceuigeneral" )
		GC_CharPortraitRoundTexture:SetTexCoord( "0.2421875", "0.47265625", "0.34375", "0.828125" )
		SetPortraitTexture( GC_CharPortraitTexture, "player" )

		--- Name, Level, Realm
		GC_Card_PlayerName:SetFontObject( "PlayerCardTitleName" )
		GC_Card_PlayerName:SetText( GC_PlayerName.." ("..GC_PlayerLevel..")" )
		GC_Card_Realm:SetFontObject( "CardInit_ServerFont" )
		GC_Card_Realm:SetText( GC_PlayerRealm )

		--- Class Icon and locale class text and specialization
		GC_ClassIconTexture:SetTexture("Interface\\GLUES\\CHARACTERCREATE\\UI-CHARACTERCREATE-CLASSES")
		local coords = CLASS_ICON_TCOORDS[GC_PlayerClassEN]
		GC_ClassIconTexture:SetTexCoord( unpack(coords) )

		GC_Card_Class:SetFontObject( "CardInit_ClassFont" )
		local fClass = GC_GetClassColor( GC_PlayerClassLocale, GC_PlayerClassEN )
		GC_Card_Class:SetText( fClass )

		--- Race Icon
		GC_Card_PlayerRace:SetText( GC_PlayerRaceLocalized )

		local PlayerRaceEN = upper( GC_PlayerRaceEN )
		local RaceTexture = GC_CharRaceGender( PlayerRaceEN, GC_CharGender )
		GC_RaceIconTexture:SetTexture(RaceTexture)

		------------------------------------------------------------
		if GC_WOW_isRetail == true then --- Get Spec only in Retail
			local currentSpec = GetSpecialization()
			GC_Card_ClassSpe:SetFontObject( "SystemFont_Large" )
				if currentSpec then
					local _, currentSpecName = GetSpecializationInfo( currentSpec )

					if len(currentSpecName) < 1 then
						currentSpecName = "?"
					end
					
					GC_Card_ClassSpe:SetText( "|cffffff00[|r"..currentSpecName.."|cffffff00]|r" )
				end
		else
				GC_Card_ClassSpe:SetText( "|cffffff00[|r?|cffffff00]|r" )
		end
		------------------------------------------------------------

		GC_Card_PlayerRace:SetFontObject( "SystemFont_Large" )
		GC_Card_PlayerRace:SetText( "|cffffff00[|r"..GC_PlayerRaceLocalized.."|cffffff00]|r" )

			--- Faction Texture
			if GC_PlayerFaction == "Alliance"  then GC_FactionTexture:SetTexture( GC_FactionIconAlliance )
			elseif GC_PlayerFaction == "Horde" then GC_FactionTexture:SetTexture( GC_FactionIconHorde )
			else GC_FactionTexture:SetTexture( GC_FactionIconNeutral )
			end

		------------
		--- Check Equipped Weapons Durability

		GC_PlayerItemLevel = GC_GetPlayerItemLevel()
		GC_Card_iLevel:SetText( GC_PlayerItemLevel )
		GoldCounterCharPanel_Build() -- Update Lines Panel and Total money
		
		local WEPS_currentDura, WEPS_maxDura
		
		local WEP1_currentDura, WEP1_maximumDura = GetInventoryItemDurability( INVSLOT_MAINHAND )
		local WEP2_currentDura, WEP2_maximumDura = GetInventoryItemDurability( INVSLOT_OFFHAND )
		local WEP3_currentDura, WEP3_maximumDura = GetInventoryItemDurability( INVSLOT_RANGED )

		if not WEP1_maximumDura and not WEP2_maximumDura and not WEP3_maximumDura then
		
			GC_Gear_Weapons_None:Show()
			GC_Card_WeaponsDura:Hide()
		else
			GC_Gear_Weapons_None:Hide()
			GC_Card_WeaponsDura:Show()

			--- Weapon 1
			if WEP1_maximumDura and WEP1_maximumDura > 0 then
				WEPS_maxDura = WEP1_maximumDura
				WEPS_currentDura = WEP1_currentDura
			else
				WEPS_maxDura = 0
				WEPS_currentDura = 0
			end

			--- Weapon 2
			if WEP2_maximumDura and WEP2_maximumDura > 0 then
				WEPS_maxDura = WEPS_maxDura + WEP2_maximumDura
				WEPS_currentDura = WEPS_currentDura + WEP2_currentDura
			end

			--- Weapon 3 ( Ranged )
			if WEP3_maximumDura and WEP3_maximumDura > 0 then
				WEPS_maxDura = WEPS_maxDura + WEP3_maximumDura
				WEPS_currentDura = WEPS_currentDura + WEP3_currentDura
			end

			local Total_WEP_Dura_Perc = floor( ( WEPS_currentDura / WEPS_maxDura ) * 100 )
			
			if Total_WEP_Dura_Perc > 70 then
			
				GC_Gear_Durability.Equipped_Weapons = GC_Gear_Durability.Color_State_GOOD..Total_WEP_Dura_Perc.. "%|r"
				
			elseif Total_WEP_Dura_Perc > 30 then

				GC_Gear_Durability.Equipped_Weapons = GC_Gear_Durability.Color_State_MEDIUM..Total_WEP_Dura_Perc.. "%|r"
			
			else
				GC_Gear_Durability.Equipped_Weapons = GC_Gear_Durability.Color_State_LOW..Total_WEP_Dura_Perc.. "%|r"
			end

			GC_Card_WeaponsDura:SetText( GC_Gear_Durability.Equipped_Weapons )
			
		end
		
		--- Check Equipped Gear Durability
		local Gear_Table = { }
		local Gear_Max_Dura, Gear_Current_Dura = 0, 0
		
		Gear_Table[1], Gear_Table[2]   = GetInventoryItemDurability( INVSLOT_HEAD )
		Gear_Table[3], Gear_Table[4]   = GetInventoryItemDurability( INVSLOT_SHOULDER )
		Gear_Table[5], Gear_Table[6]   = GetInventoryItemDurability( INVSLOT_CHEST )
		Gear_Table[7], Gear_Table[8]   = GetInventoryItemDurability( INVSLOT_WAIST )
		Gear_Table[9], Gear_Table[10]  = GetInventoryItemDurability( INVSLOT_LEGS )
		Gear_Table[11], Gear_Table[12] = GetInventoryItemDurability( INVSLOT_FEET )
		Gear_Table[13], Gear_Table[14] = GetInventoryItemDurability( INVSLOT_WRIST )
		Gear_Table[15], Gear_Table[16] = GetInventoryItemDurability( INVSLOT_HAND )
		
		for index = 1, 15, 2 do
			if Gear_Table[index] then Gear_Current_Dura = Gear_Current_Dura + Gear_Table[index] end
			if Gear_Table[index+1] then Gear_Max_Dura = Gear_Max_Dura + Gear_Table[index+1] end
		end

		if not Gear_Max_Dura or Gear_Max_Dura == 0 then -- Nothing Equipped
		
			GC_Gear_Armor_None:Show()
			GC_Card_GearDura:Hide()
			
		else
		
			GC_Gear_Armor_None:Hide()
			GC_Card_GearDura:Show()

			local Total_Equip_Dura_Perc = floor( ( Gear_Current_Dura / Gear_Max_Dura ) * 100 )
			
			if Total_Equip_Dura_Perc > 70 then
			
				GC_Gear_Durability.Equipped_Stuff = GC_Gear_Durability.Color_State_GOOD..Total_Equip_Dura_Perc.. "%|r"
				
			elseif Total_Equip_Dura_Perc > 30 then

				GC_Gear_Durability.Equipped_Stuff = GC_Gear_Durability.Color_State_MEDIUM..Total_Equip_Dura_Perc.. "%|r"
			
			else
				GC_Gear_Durability.Equipped_Stuff = GC_Gear_Durability.Color_State_LOW..Total_Equip_Dura_Perc.. "%|r"
			end

			GC_Card_GearDura:SetText( GC_Gear_Durability.Equipped_Stuff )
		end

			GC_Card_Dura:SetFontObject( "CardInit_Durability" )
			GC_Card_Dura:SetText( GC_Locale_Text.TOOLTIP_INFOS_DURABILITY )


				----------------------------
				--- Information bottom Panel
				----------------------------

				if GC_PlayerLevel < GC_MaxPlayerLevel then

				---------------------------------------------
				--- XP Informations if character < Max Level
				---------------------------------------------

				--- If XP panel
				GC_XP_Data:Hide() GC_XP_NewData:Hide()
				
				GC_PlayerXP = UnitXP("player") -- In case just level up

				local MaxXP = UnitXPMax("player")
				local xpLeft = MaxXP - GC_PlayerXP
				local RestedXP = GetXPExhaustion() or 0
				local XpToLevelUp = 0
				local XpToLevelUpMultiply = ""

				----------------------------------
				--- Protect against zero divide
				local xpProgressPercent = 0
				if MaxXP > 0 then
					xpProgressPercent = (GC_PlayerXP / MaxXP) * 100
				end
				local StringXP = format("%.2f%%", xpProgressPercent )

				if xpLeft > 0 then
					RestedXP = (RestedXP / xpLeft) * 100
					if ( RestedXP > 100 ) then RestedXP = 100 end --- Not counting extra rest point of next level
				else
					RestedXP = 0
				end
				RestedXP = format("%.2f%%", RestedXP )

				if GC_LastXP > 0 then
					XpToLevelUp = floor(xpLeft / GC_LastXP) + 1
				else
					XpToLevelUp = 0
				end
				----------------------------------

				if GC_PlayerLevel == GC_MaxPlayerLevel or GC_LastXP == 0 then -- If MaxLevel or no gain
					XpToLevelUpMultiply = ""
				elseif XpToLevelUp > 0 then
					XpToLevelUpMultiply = " (x"..XpToLevelUp..")"
				end
						
				----------------------------
				--- Set results to panel ---
				----------------------------

				local Str_LastXP = GC_reformatInt( GC_LastXP )
				local Str_QuestXP = GC_reformatInt( GC_MyDailyData.QuestXP )

				GC_Card_XP:SetFontObject( "CardInit_Durability" )
				GC_Card_XP:SetText( GC_Locale_Text.TOOLTIP_INFOS_EXP )

				GC_XP_Progress:SetText( GC_Locale_Text.TOOLTIP_INFOS_PROGRESSXP )
				GC_XP_Rest:SetText( GC_Locale_Text.TOOLTIP_INFOS_REST )
				GC_XP_Recent:SetText( GC_Locale_Text.TOOLTIP_INFOS_LASTXP )
				GC_XP_QuestXP:SetText( GC_Locale_Text.PLAYER_INCOMES_QUESTS )

				GC_XP_ProgressData:SetText( StringXP )
				GC_XP_RestData:SetText( RestedXP )
				GC_XP_RecentData:SetText( Str_LastXP.." XP "..XpToLevelUpMultiply )
				GC_XP_QuestXPData:SetText( Str_QuestXP.." XP" )
				----------------------

				else

				GC_XP_Data:Show() GC_XP_NewData:Show()

				-----------------------------------
				--- Other information if Max Level
				-----------------------------------

				GC_Card_XP:SetText( GC_Locale_Text.PLAYERCARD_INFO )

				GC_XP_Progress:SetText( GC_Locale_Text.PLAYER_STAT_HP )
				GC_XP_Rest:SetText( GC_Locale_Text.PLAYER_STAT_CRIT )
				GC_XP_Recent:SetText( GC_Locale_Text.PLAYER_STAT_HASTE )
				GC_XP_QuestXP:SetText( GC_Locale_Text.PLAYER_STAT_MASTERY )
				GC_XP_Data:SetText( GC_Locale_Text.PLAYER_STAT_VERSAT )

				local HPMax   = GC_reformatInt( UnitHealthMax("player") )
				local Crit    = format("%.2f%%", GetCritChance() )
				local Haste   = format("%.2f%%", GetHaste() )
				local Mastery = "(?)"
				local Versat  = "(?)"

				GC_XP_ProgressData:SetText( HPMax )
				GC_XP_RestData:SetText( Crit )
				GC_XP_RecentData:SetText( Haste )

				-- Mastery
				if GC_WOW_isRetail or GC_WOW_isPandaria or GC_WOW_isBCAnniv then -- Mastery works above Vanilla
					Mastery = format("%.2f%%", GetMasteryEffect() )
				end
				GC_XP_QuestXPData:SetText( Mastery )

				-- Versatility
				if GC_WOW_isRetail then -- if Retail, Versatility works
					Versat  = format("%.2f%%", GetCombatRatingBonus( CR_VERSATILITY_DAMAGE_DONE ) )
				end
				GC_XP_NewData:SetText( Versat )

				end
end

function GC_ShowCharTableTooltip()

		GC_CurrentFunds = GetMoney()

		local ColoredName = GC_GetClassColor( GC_PlayerName, GC_PlayerClassEN )
		local Funds	= GC_MoneyCoinsTextures( nil, GC_CurrentFunds, true )

		local _, frameY = GoldCounter_MainFrame:GetCenter()
		local _, screenY = UIParent:GetCenter()
		local AnchorPoint, AnchorPointY = "", 0
	
		if frameY > screenY then
			AnchorPoint = "ANCHOR_BOTTOM"
			AnchorPointY = -6
		else
			AnchorPoint = "ANCHOR_TOP"
			AnchorPointY = 6
		end

		GoldCounter_Custom_Tooltip:Hide()
		GoldCounter_Custom_Tooltip:ClearLines()
		GoldCounter_Custom_Tooltip:SetOwner( _G["GC_InfoPanelButton"], AnchorPoint, 0, AnchorPointY )
		
		--- Text ---
		GoldCounter_Custom_TooltipTextLeft1:SetFontObject( GameTooltipTextSmall )
		GoldCounter_Custom_Tooltip:AddLine( GC_Locale_Text.TOOLTIP_INFOPANEL, 1, 1, 1, true )

		GoldCounter_Custom_TooltipTextLeft2:SetFontObject( GameTooltipText )
		GoldCounter_Custom_TooltipTextRight2:SetFontObject( GameTooltipText )
		GoldCounter_Custom_Tooltip:AddDoubleLine( ColoredName, Funds, nil, nil, nil, 0, 1, 0 )

		GoldCounter_Custom_Tooltip:Show()
end
