local addonName, addon = ...

addon:RegisterDefaultSetting("autoRepair", true)
addon:RegisterDefaultSetting("mailShow", true)
addon:RegisterDefaultSetting("durabilityShow", true)
addon:RegisterDefaultSetting("backpackShow", true)
addon:RegisterDefaultSetting("moneyShow", true)
addon:RegisterDefaultSetting("clockShow", true)
addon:RegisterDefaultSetting("latencyShow", true)
addon:RegisterDefaultSetting("fpsShow", true)
addon:RegisterDefaultSetting("socialShow", true)
addon:RegisterDefaultSetting("guildShow", true)
addon:RegisterDefaultSetting("speedShow", true)
addon:RegisterDefaultSetting("clock24hr", false)
addon:RegisterDefaultSetting("GuildRepair", true)
addon:RegisterDefaultSetting("dashboardScale", 1)
addon:RegisterDefaultSetting("CurrentMail", 0)

local SIZE = 15
local DURABILITY_MID_RANGE = 50
local FPS_MID_RANGE = 20
local BAG_SPACE_MID_RANGE = 50
local LATENCY_MID_RANGE = 300
local PERFORMANCEBAR_UPDATE_INTERVAL = PERFORMANCEBAR_UPDATE_INTERVAL or 10
local date, floor, max, min, tonumber = date, floor, max, min, tonumber
local GetFramerate, GetGameTime, GetNetStats = GetFramerate, GetGameTime, GetNetStats

local colors, CLASS = CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS, addon.CLASS

--[[-----------------------------------------------------------------------------
Mail frame
-------------------------------------------------------------------------------]]
local mailFrame = CreateFrame('Frame', nil, UIParent)
mailFrame:SetHeight(SIZE)
mailFrame.text = mailFrame:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
mailFrame.text:SetFont([[Fonts\FRIZQT__.TTF]], 12, 'NORMAL')
mailFrame.text:SetShadowOffset(1, -1)
mailFrame.text:SetJustifyH('RIGHT')
mailFrame.text:SetPoint('RIGHT')
mailFrame.texture = mailFrame:CreateTexture()
mailFrame.texture:SetTexture([[Interface\AddOns\]] .. addonName .. [[\Media\MailIcon]])
mailFrame.texture:SetPoint('RIGHT', mailFrame.text, 'LEFT')
mailFrame.texture:SetHeight(12)
mailFrame.texture:SetWidth(12)

mailFrame.text:SetText(" 188")
mailFrame:SetWidth(mailFrame.text:GetStringWidth() + mailFrame.texture:GetWidth() - 8)

mailFrame:EnableMouse(true)
mailFrame:SetScript('OnEnter', function(self)
	if not HasNewMail() then return end
	GameTooltip:SetOwner(self, 'ANCHOR_TOP', 0, 1)
	MinimapMailFrameUpdate()
	GameTooltip:Show()
	self.tooltip = true
end)
mailFrame:SetScript('OnLeave', addon.HideTooltip)

mailFrame:SetScript('OnEvent', function(self, event)
	if HasNewMail() then
		self.text:SetTextColor(0, 1, 0)
		self.texture:SetVertexColor(0, 1, 0)
	else
		self.text:SetTextColor(1, 1, 1)
		self.texture:SetVertexColor(1, 1, 1)
	end
	if event == "PLAYER_ENTERING_WORLD" then
		self.text:SetText(addon.settings.CurrentMail)
	end
	if event == "MAIL_INBOX_UPDATE" then
		self.text:SetText(GetInboxNumItems())
		addon.settings.CurrentMail = GetInboxNumItems()
	end
	if self.tooltip then
		MinimapMailFrameUpdate()
	end
end)
mailFrame:RegisterEvent('PLAYER_ENTERING_WORLD')
mailFrame:RegisterEvent('MAIL_INBOX_UPDATE')
mailFrame:RegisterEvent('UPDATE_PENDING_MAIL')

--[[-----------------------------------------------------------------------------
Quests
-------------------------------------------------------------------------------]]
local questFrame = CreateFrame('button', nil, UIParent)
questFrame:SetHeight(SIZE)

local questFrameText = questFrame:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
questFrameText:SetFont([[Fonts\FRIZQT__.TTF]], 12)
questFrameText:SetShadowOffset(1, -1)
questFrameText:SetJustifyH('RIGHT')
questFrameText:SetPoint('RIGHT')

questFrame.texture = questFrame:CreateTexture()
questFrame.texture:SetTexture([[Interface\AddOns\]] .. addonName .. [[\Media\QuestIcon]])
questFrame.texture:SetPoint('RIGHT', questFrameText, 'LEFT')
questFrame.texture:SetTexCoord(0.25, 0.75, 0.25, 0.75)
questFrame.texture:SetHeight(12)
questFrame.texture:SetWidth(12)

questFrameText:SetText(" 25/25")
questFrame:SetWidth(questFrameText:GetStringWidth() + questFrame.texture:GetWidth())

questFrame:SetScript('OnEvent', function(self, event)
	local numEntries, numQuests = GetNumQuestLogEntries()
	questFrameText:SetFormattedText("%s/25", numQuests)
end)
questFrame:RegisterEvent('PLAYER_ENTERING_WORLD')
questFrame:RegisterEvent('QUEST_LOG_UPDATE')
questFrame:EnableMouse(true)
questFrame:RegisterForClicks('AnyUp')
questFrame:SetScript('OnClick', function(self)
	if button == 'LeftButton' then
		ToggleFrame(QuestLogFrame)
	else
		ToggleFrame(QuestLogFrame)
	end
end)

questFrame:SetScript('OnEnter', function(self)
	GameTooltip:SetOwner(self, 'ANCHOR_TOP', 0, 1)
	GameTooltip:AddLine(MicroButtonTooltipText(QUESTLOG_BUTTON, "TOGGLEQUESTLOG"));
	GameTooltip:Show()
	self.tooltip = true
end)
questFrame:SetScript('OnLeave', addon.HideTooltip)

--[[-----------------------------------------------------------------------------
Armor durability
-------------------------------------------------------------------------------]]
local durabilityFrame = CreateFrame('Button', nil, UIParent)
durabilityFrame:SetHeight(SIZE)

local durabilityFrameText = durabilityFrame:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
durabilityFrameText:SetFont([[Fonts\FRIZQT__.TTF]], 12)
durabilityFrameText:SetShadowOffset(1, -1)
durabilityFrameText:SetJustifyH('RIGHT')
durabilityFrameText:SetPoint('RIGHT')

durabilityFrame.texture = durabilityFrame:CreateTexture()
durabilityFrame.texture:SetTexture([[Interface\Icons\Trade_BlackSmithing]])
durabilityFrame.texture:SetPoint('RIGHT', durabilityFrameText, 'LEFT')
durabilityFrame.texture:SetTexCoord(0.07, 0.93, 0.07, 0.93)
durabilityFrame.texture:SetHeight(12)
durabilityFrame.texture:SetWidth(12)

durabilityFrameText:SetText("  100%")
durabilityFrame:SetWidth(durabilityFrameText:GetStringWidth() + durabilityFrame.texture:GetWidth())

local slots = {
	'HeadSlot',
	'NeckSlot',
	'ShoulderSlot',
	'ShirtSlot',
	'ChestSlot',
	'WaistSlot',
	'LegsSlot',
	'FeetSlot',
	'WristSlot',
	'HandsSlot',
	'Finger0Slot',
	'Finger1Slot',
	'Trinket0Slot',
	'Trinket1Slot',
	'BackSlot',
	'MainHandSlot',
	'SecondaryHandSlot',
	'RangedSlot',
	'TabardSlot'
}
slots[0] = 'AmmoSlot'
addon.itemSlots = slots

local myTip = nil
local function OnEnter(self)
	if not myTip then
		myTip = CreateFrame('GameTooltip')
		myTip:Hide()
	end

	local equipRepairCost, invRepairCost = 0, 0
	for id = 1, #slots do
		local _, _, repairCost = myTip:SetInventoryItem('player', id, true)
		if repairCost and repairCost > 0 then
			equipRepairCost = equipRepairCost + repairCost
		end
	end

	for bag = 0, NUM_BAG_FRAMES do
		for slot = 1, GetContainerNumSlots(bag) do
			local _, repairCost = myTip:SetBagItem(bag, slot)
			if repairCost and repairCost > 0 then
				invRepairCost = invRepairCost + repairCost
			end
		end
	end

	GameTooltip:SetOwner(self, 'ANCHOR_TOP', 0, 1)
	GameTooltip:AddLine(_G['REPAIR_COST'])
	GameTooltip:AddDoubleLine(_G['CURRENTLY_EQUIPPED'], addon:MoneyToString(equipRepairCost))
	--GameTooltip:AddDoubleLine(_G['TUTORIAL_TITLE10'], addon:MoneyToString(invRepairCost))
	GameTooltip:AddDoubleLine(_G['REPAIR_ALL_ITEMS'], addon:MoneyToString(equipRepairCost + invRepairCost))
	GameTooltip:AddLine(" ")
	GameTooltip:AddLine("|cffeda55fLeft Click|r toggle Auto-Repair  " .. (addon.settings.autoRepair and "|cff88ff88on|r" or "|cffff8888off|r"), 0.2, 1, 0.2)
	GameTooltip:AddLine("|cffeda55fRight Click|r toggle Guild Funds  " .. (addon.settings.GuildRepair and "|cff88ff88on|r" or "|cffff8888off|r"), 0.2, 1, 0.2)
	GameTooltip:Show()
end

durabilityFrame:SetScript('OnEnter', OnEnter)
durabilityFrame:SetScript('OnLeave', addon.HideTooltip)

durabilityFrame:RegisterForClicks('AnyUp')
durabilityFrame:SetScript('OnClick', function(self, button)
	if button == 'LeftButton' then
		if addon.settings.autoRepair == true then
			addon.settings.autoRepair = false
			UIErrorsFrame:AddMessage("Auto-Repair: Off", 1, 0, 0, 53, 3);
		elseif addon.settings.autoRepair == false then
			addon.settings.autoRepair = true
			UIErrorsFrame:AddMessage("Auto-Repair: On", 0, 1, 0, 53, 3);
		end
		OnEnter(self)
	end	
	if button == 'RightButton' then
		if addon.settings.GuildRepair == true then
			addon.settings.GuildRepair = false
			UIErrorsFrame:AddMessage("Guild-Repair: Off", 1, 0, 0, 53, 3);
		elseif addon.settings.GuildRepair == false then
			addon.settings.GuildRepair = true
			UIErrorsFrame:AddMessage("Guild-Repair: On", 0, 1, 0, 53, 3);
		end
		OnEnter(self)
	end	
end)

durabilityFrame:SetScript('OnEvent', function()
	local durability = 1
	for id = 0, #slots do
		local current, maximum = GetInventoryItemDurability(id)
		if current and maximum ~= 0 then
			local value = current / maximum
			if value < durability then
				durability = value
			end
		end
	end
	durability = floor(durability * 100 + 0.5)
	durabilityFrameText:SetTextColor(1 - min(max(durability - DURABILITY_MID_RANGE, 0) / DURABILITY_MID_RANGE, 1), min(durability / DURABILITY_MID_RANGE, 1), 0)
	durabilityFrameText:SetFormattedText("%s%%", durability)
end)
durabilityFrame:RegisterEvent('PLAYER_LOGIN')
durabilityFrame:RegisterEvent('UPDATE_INVENTORY_ALERTS')
durabilityFrame:RegisterEvent('UPDATE_INVENTORY_DURABILITY')
durabilityFrame:RegisterEvent('UNIT_INVENTORY_CHANGED')
durabilityFrame:RegisterEvent('MERCHANT_CLOSED')
durabilityFrame:RegisterEvent('PLAYER_DEAD')

addon.RegisterEvent("DashBoard-AutoRepair", 'MERCHANT_SHOW', function()
	if addon.settings.autoRepair and CanMerchantRepair() then
		if addon.settings.GuildRepair == true then
			local cost = GetRepairAllCost()
			if cost > 0 and cost <= GetMoney() then
				RepairAllItems(1)
				print("|cff33ff99" .. addonName .. "|r: Repaired all equipment for " .. addon:MoneyToString(cost) .."(Guild Funds)")
			end
		else
			local cost = GetRepairAllCost()
			if cost > 0 and cost <= GetMoney() then
				RepairAllItems()
				print("|cff33ff99" .. addonName .. "|r: Repaired all equipment for " .. addon:MoneyToString(cost) .. "(Your Funds)")
			end
		end
	end
end)

--[[-----------------------------------------------------------------------------
Backpack button
-------------------------------------------------------------------------------]]
local backpackButton = CreateFrame('Button', nil, UIParent, 'SecureHandlerClickTemplate')

backpackButton:SetHeight(SIZE)
addon.backpackButton = backpackButton

local backpackButtonText = backpackButton:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
backpackButtonText:SetFont([[Fonts\FRIZQT__.TTF]], 12)
backpackButtonText:SetShadowOffset(1, -1)
backpackButtonText:SetJustifyH('RIGHT')
backpackButtonText:SetPoint('RIGHT')

backpackButton.texture = backpackButton:CreateTexture()
backpackButton.texture:SetTexture([[Interface\AddOns\]] .. addonName .. [[\Media\BagIcon]])
backpackButton.texture:SetPoint('RIGHT', backpackButtonText, 'LEFT')
backpackButton.texture:SetHeight(SIZE)
backpackButton.texture:SetWidth(SIZE)

backpackButtonText:SetText(" 888/888")
backpackButton:SetWidth(backpackButtonText:GetStringWidth() + backpackButton.texture:GetWidth())

backpackButton:RegisterForClicks('LeftButtonUp', 'RightButtonUp')
backpackButton:SetAttribute('_onclick', [[
	if button == 'LeftButton' then
		control:CallMethod("ToggleBags")
	else
		local bagBar = self:GetFrameRef("bagBar")
		if bagBar:IsVisible() then
			bagBar:Hide()
		else
			bagBar:Show()
		end
	end
]])

function backpackButton:ToggleBags()
	if Baggins then
		Baggins:ToggleBackpack()
	else
		OpenAllBags()
	end
end

backpackButton:SetScript('OnEvent', function(self)
	local free, total = 0, 0
	for bag = 0, NUM_BAG_FRAMES do
		free = free + GetContainerNumFreeSlots(bag)
		total = total + GetContainerNumSlots(bag)
	end
	local freePercent = floor(free / total * 100 + 0.5)
	backpackButtonText:SetTextColor(1 - min(max(freePercent - BAG_SPACE_MID_RANGE, 0) / BAG_SPACE_MID_RANGE, 1), min(freePercent / BAG_SPACE_MID_RANGE, 1), 0)
	backpackButtonText:SetFormattedText("%s/%s", free, total)
end)
backpackButton:RegisterEvent('PLAYER_ENTERING_WORLD')
backpackButton:RegisterEvent('UNIT_INVENTORY_CHANGED')
backpackButton:RegisterEvent('BAG_UPDATE')

local function OnEnter(self)
	GameTooltip:SetOwner(self, 'ANCHOR_TOP', 0, 1)
	GameTooltip:AddLine("|cffeda55fLeft Click|r toggle Inventory", 0.2, 1, 0.2)
	GameTooltip:AddLine("|cffeda55fRight Click|r toggle Bag & Keyring Bar", 0.2, 1, 0.2)
	GameTooltip:Show()
end

backpackButton:SetScript('OnEnter', OnEnter)
backpackButton:SetScript('OnLeave', addon.HideTooltip)


--[[-----------------------------------------------------------------------------
Money
-------------------------------------------------------------------------------]]
local moneyFrame = CreateFrame('Button', nil, UIParent)
moneyFrame:SetHeight(SIZE)
moneyFrame:SetWidth(1)

moneyFrame.text = moneyFrame:CreateFontString()
moneyFrame.text:SetFont([[Fonts\FRIZQT__.TTF]], 12)
moneyFrame.text:SetShadowOffset(1, -1)
moneyFrame.text:SetTextColor(1, 1, 1)
moneyFrame.text:SetAllPoints()

moneyFrame:SetScript('OnEvent', function(self)
	self:SetWidth(0)
	self.text:SetText(addon:MoneyToString(GetMoney(), true))
	self:SetWidth(self.text:GetStringWidth())
end)
moneyFrame:RegisterEvent('PLAYER_LOGIN')
moneyFrame:RegisterEvent('PLAYER_MONEY')


--[[-----------------------------------------------------------------------------
Clock
-------------------------------------------------------------------------------]]
local clock = CreateFrame('Button', nil, UIParent)
clock:SetHeight(SIZE)

local clockText = clock:CreateFontString(nil, 'ARTWORK')
clockText:SetFont([[Fonts\FRIZQT__.TTF]], 12)
clockText:SetTextColor(1, 1, 1, 1)
clockText:SetShadowOffset(1, -1)
clockText:SetJustifyH('RIGHT')
clockText:SetPoint('RIGHT')

clockText:SetText(" 18:88pm")
clock:SetWidth(clockText:GetStringWidth())

clock:RegisterForClicks('LeftButtonUp', 'RightButtonUp')
clock:SetScript('OnClick', function(self, button)
	if button == 'LeftButton' then
		ToggleTimeManager()
	else
		ToggleCalendar()
	end
end)

local server_hour, server_minute = 0, 0
local function OnEnter(self)
	if self.tooltip then
		GameTooltip:ClearLines()
	else
		GameTooltip:SetOwner(self, 'ANCHOR_TOP',0 , 1)
	end
	GameTooltip:AddDoubleLine("Today's Date", date("%A, %B %d, %Y"))
	GameTooltip:AddDoubleLine("Local Time", clockText:GetText())
	GameTooltip:AddDoubleLine("Server Time", ("%d:%.02d %sm"):format(server_hour ~= 0 and server_hour or 12, server_minute, server_hour >= 12 and "p" or "a"))
	GameTooltip:AddLine(" ")
	GameTooltip:AddLine("|cffeda55fLeft Click|r toggles the Time Manager", 0.2, 1, 0.2)
	GameTooltip:AddLine("|cffeda55fRight Click|r toggles the Calendar", 0.2, 1, 0.2)
	if not self.tooltip then
		GameTooltip:Show()
		self.tooltip = true
	end
end
clock:SetScript('OnEnter', OnEnter)

clock:SetScript('OnLeave', addon.HideTooltip)

clock:SetScript('OnMouseDown', function(self, button)
	if button ~= 'LeftButton' or not IsAltKeyDown() then return end
	self:ClearAllPoints()
	self:StartMoving()
	self.moving = true
end)

function addon:SetClockHrFormat()
		
	if addon.settings.clock24hr == false then
		clockText:SetText(("%d:%s"):format(tonumber(date("%I")), date("%M%p"):lower()))
	else
		clockText:SetText(server_hour .. ":" .. server_minute)
	end
end

local previousMinute, timer = -1, 5
clock:SetScript('OnUpdate', function(self, elapsed)
	timer = timer + elapsed
	if timer < 5 then return end
	timer = 0
	server_hour, server_minute = GetGameTime()
	if server_minute == previousMinute then return end
	previousMinute = server_minute
	addon:SetClockHrFormat()
	if self.tooltip then
		OnEnter(self)
	end
end)

local clockHighlight = clock:CreateTexture(nil, "BACKGROUND")
clockHighlight:SetHeight(SIZE)
clockHighlight:SetWidth((clockText:GetStringWidth() - 6))
clockHighlight:SetPoint("CENTER", clock, "CENTER", 5, 0)

local CalendarEventResponse = CreateFrame('frame', nil, UIParent)
CalendarEventResponse:RegisterEvent("PLAYER_ENTERING_WORLD")
CalendarEventResponse:RegisterEvent("CALENDAR_UPDATE_EVENT")
CalendarEventResponse:RegisterEvent("CALENDAR_UPDATE_PENDING_INVITES")
CalendarEventResponse:RegisterEvent("CALENDAR_NEW_EVENT")

CalendarEventResponse:SetScript('OnEvent', function(self)
	for alldays = 1,30 do
		local GetAllEventInvites = CalendarGetNumPendingInvites()
	
		if GetAllEventInvites ~= 0 then 
			clockHighlight:SetTexture("Interface/PlayerFrame/UI-PlayerFrame-Deathknight-Glow.blp")
		else
			clockHighlight:SetTexture(nil)
		end
	end
end)

--[[-----------------------------------------------------------------------------
Latency
-------------------------------------------------------------------------------]]
local latencyFrame = CreateFrame('Frame', nil, UIParent)

latencyFrame:SetHeight(SIZE)

local latencyText = latencyFrame:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
latencyText:SetFont([[Fonts\FRIZQT__.TTF]], 12)
latencyText:SetShadowOffset(1, -1)
latencyText:SetJustifyH('RIGHT')
latencyText:SetPoint('RIGHT')

latencyText:SetText(" 888ms")
latencyFrame:SetWidth(latencyText:GetStringWidth())

local timer = 10
latencyFrame:SetScript('OnUpdate', function(self, elapsed)
	timer = timer + elapsed
	if timer < PERFORMANCEBAR_UPDATE_INTERVAL then return end
	timer = 0
	local _, _, latency = GetNetStats()
	latencyText:SetTextColor(min(latency / LATENCY_MID_RANGE, 1), 1 - min(max(latency - LATENCY_MID_RANGE, 0) / LATENCY_MID_RANGE, 1), 0)
	latencyText:SetFormattedText("%sms", latency)
end)

--[[-----------------------------------------------------------------------------
FPS
-------------------------------------------------------------------------------]]
local fpsFrame = CreateFrame('Frame', nil, UIParent)
fpsFrame:SetHeight(SIZE)

local fpsText = fpsFrame:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
fpsText:SetFont([[Fonts\FRIZQT__.TTF]], 12)
fpsText:SetShadowOffset(1, -1)
fpsText:SetJustifyH('RIGHT')
fpsText:SetPoint('RIGHT')

fpsText:SetText(" 188fps")
fpsFrame:SetWidth(fpsText:GetStringWidth())

local timer = 1
fpsFrame:SetScript('OnUpdate', function(self, elapsed)
	timer = timer + elapsed
	if timer < 1 then return end
	timer = 0
	local fps = floor(GetFramerate() + 0.5)
	fpsText:SetTextColor(1 - min(max(fps - FPS_MID_RANGE, 0) / FPS_MID_RANGE, 1), min(fps / FPS_MID_RANGE, 1), 0)
	fpsText:SetFormattedText("%sfps", fps)
end)


--[[-----------------------------------------------------------------------------
Social/Friends
-------------------------------------------------------------------------------]]
local SocialFrame = CreateFrame('button', nil, UIParent, 'SecureHandlerClickTemplate')
SocialFrame:SetHeight(SIZE)

SocialFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
SocialFrame:RegisterEvent("FRIENDLIST_UPDATE")
SocialFrame:RegisterEvent("BN_FRIEND_ACCOUNT_ONLINE")
SocialFrame:RegisterEvent("BN_FRIEND_ACCOUNT_OFFLINE")
SocialFrame.text = SocialFrame:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
SocialFrame.text:SetFont([[Fonts\FRIZQT__.TTF]], 12, 'NORMAL')
SocialFrame.text:SetShadowOffset(1, -1)
SocialFrame.text:SetJustifyH('RIGHT')
SocialFrame.text:SetPoint('RIGHT')
SocialFrame.texture = SocialFrame:CreateTexture()
SocialFrame.texture:SetTexture("Interface/FriendsFrame/UI-Toast-FriendOnlineIcon.blp")
SocialFrame.texture:SetPoint('RIGHT', SocialFrame.text, 'LEFT')
SocialFrame.texture:SetHeight(20)
SocialFrame.texture:SetWidth(20)
SocialFrame.text:SetText("188")
SocialFrame:SetWidth(SocialFrame.text:GetStringWidth() + SocialFrame.texture:GetWidth() - 10)
SocialFrame:EnableMouse(true)
SocialFrame:RegisterForClicks('AnyUp')
SocialFrame:SetScript('OnEnter', function(self)
	
	
	GameTooltip:SetOwner(self, 'ANCHOR_TOP', 0, 1)
	
	local numBNetFriends, numBNetOnline = BNGetNumFriends();
	local numWoWFriends, numWoWOnline = GetNumFriends();
	local sPlural = "s";
	
	if (numBNetOnline + numWoWOnline) == 1 then
		sPlural = "";
	end
	--GameTooltip:AddLine(MicroButtonTooltipText(SOCIAL, "TOGGLEFRIENDSTAB"));
	GameTooltip:AddLine(MicroButtonTooltipText(SOCIALS ,"TOGGLESOCIAL"));
	
	GameTooltip:AddLine((numBNetOnline + numWoWOnline) .. " Friend" .. sPlural .. " Online", 0, 1, 0);
	-- Battle.net Friends
	for i = 1, numBNetFriends, 1 do
		local sPresenceID, sNameFirst, sNameLast, sCharName, sCharID, sClient, bIsOnline = BNGetFriendInfo(i);
		if bIsOnline then
			local sArea = sClient;
			if sClient == "WoW" then
				local _, _, _, sServer = BNGetToonInfo(sPresenceID);
				sArea = sServer;
			end
			GameTooltip:AddLine(sCharName .. " (" .. sArea .. ") [" .. sNameFirst .. " " .. sNameLast .. "]", 0, 1, 1 );
		end
	end
	-- Regular Friends
	for i = 1, numWoWFriends, 1 do
		local sName, iLevel, sClass, sArea, bConnected, sNote, fStatus = GetFriendInfo(i);
		local color = colors[CLASS[sClass]]
		if bConnected then
			GameTooltip:AddLine(sName, color.r, color.g, color.b);
		end
	end
	GameTooltip:Show()

	self.tooltip = true
end)
SocialFrame:SetScript('OnLeave', addon.HideTooltip)

SocialFrame:SetScript('OnEvent', function(self)
	local numberOfFriends, onlineFriends = GetNumFriends()
	local BNnumberOfFriends, BNonlineFriends = BNGetNumFriends()
	
	if onlineFriends > 0 then
		self.text:SetTextColor(0, 1, 0)
		--self.texture:SetVertexColor(0, 1, 0)
	elseif BNonlineFriends > 0 then
		self.text:SetTextColor(0, 1, 0)
	else
		self.text:SetTextColor(1, 1, 1)
		--self.texture:SetVertexColor(1, 1, 1)
	end
	self.text:SetText(onlineFriends + BNonlineFriends)
	if self.tooltip then
		FriendsList_Update()
	end
end)

SocialFrame:SetScript('OnClick', function(self)
	if button == 'LeftButton' then
		ToggleFriendsFrame()
		else
		ToggleFriendsFrame()
		end
end)

--[[-----------------------------------------------------------------------------
Social/Friends
-------------------------------------------------------------------------------]]
local GuildFrame = CreateFrame('button', nil, UIParent, 'SecureHandlerClickTemplate')
GuildFrame:SetHeight(SIZE)
GuildFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
GuildFrame:RegisterEvent("GUILD_ROSTER_UPDATE")
GuildFrame:RegisterEvent("PLAYER_GUILD_UPDATE")

GuildFrame.text = GuildFrame:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
GuildFrame.text:SetFont([[Fonts\FRIZQT__.TTF]], 12, 'NORMAL')
GuildFrame.text:SetShadowOffset(1, -1)
GuildFrame.text:SetJustifyH('RIGHT')
GuildFrame.text:SetPoint('RIGHT')

GuildMicroButtonTabard:SetParent(GuildFrame)
GuildMicroButtonTabard:SetPoint('RIGHT', GuildFrame.text, 'LEFT')
GuildMicroButtonTabard:SetHeight(5)
GuildMicroButtonTabard:SetWidth(5)
GuildMicroButtonTabard.emblem:SetHeight(9)
GuildMicroButtonTabard.emblem:SetWidth(9)
GuildMicroButtonTabard.background:SetHeight(26)
GuildMicroButtonTabard.background:SetWidth(21)
GuildMicroButtonTabard.emblem:SetPoint("CENTER", GuildMicroButtonTabard.background, "CENTER", 0, -4)

GuildFrame.texture1 = GuildFrame:CreateTexture()
GuildFrame.texture1:SetTexture("Interface/Buttons/UI-MicroButton-Guild-Banner.blp")
GuildFrame.texture1:SetPoint('RIGHT', GuildFrame.text, 'LEFT', 0, 4)
GuildFrame.texture1:SetHeight(26)
GuildFrame.texture1:SetWidth(21)
GuildFrame.texture2 = GuildFrame:CreateTexture()
GuildFrame.texture2:SetTexture("Interface/GuildFrame/GuildEmblems_01.blp")
GuildFrame.texture2:SetPoint('CENTER', GuildFrame.texture1, 'CENTER', 0, -4)
GuildFrame.texture2:SetHeight(9)
GuildFrame.texture2:SetWidth(9)

GuildFrame.text:SetText("188")
GuildFrame:SetWidth(GuildFrame.text:GetStringWidth() + GuildFrame.texture1:GetWidth() - 10)

GuildFrame:EnableMouse(true)
GuildFrame:RegisterForClicks('AnyUp')
GuildFrame:SetScript('OnEnter', function(self)
	

	
	GameTooltip:SetOwner(self, 'ANCHOR_TOP', 0, 1)
	

	GameTooltip:AddLine(MicroButtonTooltipText(GUILD, "TOGGLEGUILDTAB"));
	if IsInGuild() == nil then
		GameTooltip:AddLine("Not in a Guild")
	else

	local total = GetNumGuildMembers(true)
	local onlineTotal = 0
	local offlineTotal = 0
	for i = 1, total 
	   do 
	   -- get info
	   local name, rank, rankIndex, level, class, zone, note, officernote, online, status, classFileName = GetGuildRosterInfo(i)
	   if online and name ~= GetUnitName("player")
	   then
		  onlineTotal = onlineTotal + 1
	   else
		  offlineTotal = offlineTotal + 1
	   end
	end
	
	local sPlural = "s";
	
	if  onlineTotal == 1 then
		sPlural = "";
	end
	
	GameTooltip:AddLine((onlineTotal) .. " Guildie" .. sPlural .. " Online", 0, 1, 0);

	for index = 1, total, 1 do
		local gName, gRank,_, gLevel, gClass,_,_,_, gConnected, gStatus, gFileName = GetGuildRosterInfo(index);
		local color = colors[CLASS[gClass]]
		if gConnected and gName ~= GetUnitName("player") then
			GameTooltip:AddLine(gName, color.r, color.g, color.b);
		end
	end

	
	end
	GameTooltip:Show()

	self.tooltip = true
end)
GuildFrame:SetScript('OnLeave', addon.HideTooltip)

GuildFrame:SetScript('OnEvent', function(self)
	GuildRoster()
		
	local total = GetNumGuildMembers(true)
	local onlineTotal = 0
	local offlineTotal = 0
	for i = 1, total 
	   do 
	   -- get info
	   local name, rank, rankIndex, level, class, zone, note, officernote, online, status, classFileName = GetGuildRosterInfo(i)
	   if online and name ~= GetUnitName("player")
	   then
		  onlineTotal = onlineTotal + 1
	   else
		  offlineTotal = offlineTotal + 1
	   end
	end

	
	if onlineTotal > 0 then
		self.text:SetTextColor(0, 1, 0)
		--self.texture:SetVertexColor(0, 1, 0)
	else
		self.text:SetTextColor(1, 1, 1)
		--self.texture:SetVertexColor(1, 1, 1)
	end
	self.text:SetText(onlineTotal)
	
	if IsInGuild() == nil then 
		GuildFrame.texture1:Show()
		GuildFrame.texture2:Show()
	else
		GuildFrame.texture1:Hide()
		GuildFrame.texture2:Hide()
	end
end)

GuildFrame:SetScript('OnClick', function(self, button)
	if button == 'LeftButton' then
		ToggleGuildFrame()
	else
		ToggleGuildFrame()
	end
end)

--[[-----------------------------------------------------------------------------
Speed
-------------------------------------------------------------------------------]]
local speedFrame = CreateFrame('button', nil, UIParent)
speedFrame:SetHeight(SIZE)

local speedFrameText = speedFrame:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
speedFrameText:SetFont([[Fonts\FRIZQT__.TTF]], 12)
speedFrameText:SetShadowOffset(1, -1)
speedFrameText:SetJustifyH('RIGHT')
speedFrameText:SetPoint('RIGHT')

speedFrame.texture = speedFrame:CreateTexture()
speedFrame.texture:SetTexture("Interface/TAXIFRAME/UI-Taxi-Icon-Green.blp")
speedFrame.texture:SetPoint('LEFT', speedFrame, 'LEFT')
speedFrame.texture:SetTexCoord(0.25, 0.75, 0.25, 0.75)
speedFrame.texture:SetHeight(10)
speedFrame.texture:SetWidth(10)
speedFrame:SetWidth(46)

speedFrame:SetScript('OnEvent', function(self, event)
	local s = string.format("%d%%", (GetUnitSpeed("Player") / 7) * 100);

	speedFrameText:SetText(s)

end)

speedFrame:SetScript('OnUpdate', function(self)
	local s = string.format("%d%%", (GetUnitSpeed("Player") / 7) * 100);

	speedFrameText:SetText(s)

end)
speedFrame:RegisterEvent('PLAYER_ENTERING_WORLD')
speedFrame:EnableMouse(true)

speedFrame:SetScript('OnClick', function(self)
	
end)

speedFrame:SetScript('OnEnter', function(self)
	GameTooltip:SetOwner(self, 'ANCHOR_TOP', 0, 1)
	GameTooltip:Show()
	self.tooltip = true
end)
questFrame:SetScript('OnLeave', addon.HideTooltip)

--[[-----------------------------------------------------------------------------
DashBoard Layout
-------------------------------------------------------------------------------]]
local DashBoardFrame = CreateFrame('frame', nil, UIParent)
DashBoardFrame:SetPoint('TOPRIGHT', addon.skin, 'TOPRIGHT', -20, -11)
DashBoardFrame:SetFrameStrata("HIGH")
DashBoardFrame:SetHeight(200)
DashBoardFrame:SetWidth(500)


function addon:DashLayout()
	
	clock:SetPoint('TOPRIGHT', DashBoardFrame, 'TOPRIGHT', 0, 0)
	SocialFrame:SetPoint('TOPRIGHT', clock, 'TOPLEFT', 0, 0)
	GuildFrame:SetPoint('TOPRIGHT', SocialFrame, 'TOPLEFT', 0, 0)
	questFrame:SetPoint('RIGHT', GuildFrame, 'LEFT', -5, 0)
	backpackButton:SetPoint('RIGHT', questFrame, 'LEFT')
	
	mailFrame:SetPoint('TOPRIGHT', clock, 'BOTTOMRIGHT', 0, -2)
	if addon.settings.speedShow == true then
		speedFrame:Show()
		speedFrame:SetPoint('TOPRIGHT', mailFrame, 'TOPLEFT', 0, 0)	
		durabilityFrame:SetPoint('RIGHT', speedFrame, 'LEFT', -5, 0)
		moneyFrame:SetPoint('RIGHT', durabilityFrame, 'LEFT')
	elseif addon.settings.speedShow == false then
		speedFrame:Hide()
		durabilityFrame:SetPoint('RIGHT', mailFrame, 'LEFT', -5, 0)
		moneyFrame:SetPoint('RIGHT', durabilityFrame, 'LEFT')
	end
	
	if addon.settings.latencyShow == true then
		latencyFrame:Show()
		fpsFrame:Show()
		latencyFrame:SetPoint('TOPRIGHT', mailFrame, 'BOTTOMRIGHT', 0, 0)
		fpsFrame:SetPoint('RIGHT', latencyFrame, 'LEFT')
	elseif addon.settings.latencyShow == false then
		latencyFrame:Hide()
		fpsFrame:Hide()
	end
	-- set scale
	clock:SetScale(addon.settings.dashboardScale)
	GuildFrame:SetScale(addon.settings.dashboardScale)
	questFrame:SetScale(addon.settings.dashboardScale)
	backpackButton:SetScale(addon.settings.dashboardScale)
	mailFrame:SetScale(addon.settings.dashboardScale)
	speedFrame:SetScale(addon.settings.dashboardScale)
	durabilityFrame:SetScale(addon.settings.dashboardScale)
	moneyFrame:SetScale(addon.settings.dashboardScale)
	latencyFrame:SetScale(addon.settings.dashboardScale)
	fpsFrame:SetScale(addon.settings.dashboardScale)
	SocialFrame:SetScale(addon.settings.dashboardScale)
	end

addon.RegisterEvent("DashBoard-Layout", 'PLAYER_ENTERING_WORLD', function()
	addon:DashLayout()
end)

--[[-----------------------------------------------------------------------------
Money tooltip overrides
-------------------------------------------------------------------------------]]
local moneyGained, moneySpent, LDBObj = 0, 0
addon.RegisterEvent("DashBoard-MoneyTooltip-Update", 'PLAYER_MONEY', function()
	local money = GetMoney()
	local diff = money - addon.settings.money
	if diff > 0 then
		moneyGained = moneyGained + diff
	else
		moneySpent = moneySpent - diff
	end
	addon.settings.money = money
	if LDBObj then
		LDBObj.text = addon:MoneyToString(money, true)
	end
end)

addon.RegisterEvent("DashBoard-MoneyTooltip-Initialize", 'PLAYER_ENTERING_WORLD', function(self, event)
	addon.UnregisterEvent(self, event)

	if type(addon.settings.money) ~= 'number' then
		addon.settings.money = GetMoney() or 0
	end
	addon:RegisterDefaultSetting("money", 0)
	if LDBObj then
		LDBObj.text = addon:MoneyToString(addon.settings.money, true)
	end
end)

local function OnEnter(self)
	local tooltip = GameTooltip
	tooltip:SetOwner(self, 'ANCHOR_TOP', 0, 1)
	tooltip:AddLine("Cash flow:")
	if moneyGained > 0 or moneySpent > 0 then
		tooltip:AddLine(" ")
		tooltip:AddLine("This session")
		tooltip:AddDoubleLine("Gained", addon:MoneyToString(moneyGained, true), 1, 1, 1, 1, 1, 1)
		tooltip:AddDoubleLine("Spent", addon:MoneyToString(moneySpent, true), 1, 1, 1, 1, 1, 1)
		if moneyGained - moneySpent > 0 then
			tooltip:AddDoubleLine(" ", "|cff00ff00(+)|r " .. addon:MoneyToString(moneyGained - moneySpent, true), 1, 1, 1, 1, 1, 1)
		else
			tooltip:AddDoubleLine(" ", "|cffff0000(-)|r " .. addon:MoneyToString(moneySpent - moneyGained, true), 1, 1, 1, 1, 1, 1)
		end
	end
	tooltip:AddLine(" ")
	local total, colors, color = 0, CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS
	for name, settings in pairs(_G[addonName .. "Settings"][GetRealmName()]) do
			color = colors[settings.class]
			tooltip:AddDoubleLine(name, addon:MoneyToString(settings.money, true), color.r, color.g, color.b, 1, 1, 1)
			total = total + settings.money
	end
	tooltip:AddLine(" ")
	tooltip:AddDoubleLine("Total", addon:MoneyToString(total, true), NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1, 1, 1)
	tooltip:Show()
end

-- Simple bag frame support:
-- 	true means multiple frames and reanchoring
-- 	false means a single frame
local bagNames = {
	['ContainerFrame1MoneyFrame'] = true,			-- Blizzard Backpack
	['MerchantMoneyFrame'] = true,					-- Blizzard Merchant Frame
	['OneBagFrameMoneyFrame'] = true,				-- OneBag
	['BagginsMoneyFrame'] = false,					-- Baggins
	['CombuctorFrame1MoneyFrameClick'] = false,	-- Combuctor Bag
	['CombuctorFrame2MoneyFrameClick'] = false,	-- Combuctor Bank
	['ARKINV_Frame1StatusGold'] = true,				-- ArkInventory Bag
	['ARKINV_Frame3StatusGold'] = true,				-- ArkInventory Bank
	['BBCont1_1MoneyFrame'] = true,					-- BaudBag bag
	['BBCont2_1MoneyFrame'] = true,					-- BaudBag bank
	['FBoH_BagViewFrame_1_GoldFrame'] = true,		-- FBoH
	['FBoH_BagViewFrame_2_GoldFrame'] = true,		-- FBoH
	['BagnonMoney0'] = true,							-- Bagnon
	['BagnonMoney1'] = true,							-- Bagnon
	['TokenFrameMoneyFrame'] = true,					-- GUI
}

local cargBagsHooked, frames = false, { moneyFrame }
addon.RegisterEvent("DashBoard-MoneyTooltipHooks", 'ADDON_LOADED', function(self, event)
	if cargBags and not cargBagsHooked then
		cargBagsHooked = true
		for _, object in pairs(cargBags.Objects) do
			if object.Money then
				bagNames[object.Money:GetName()] = true
			end
		end
	end

	for name, hasCoins in pairs(bagNames) do
		if _G[name] then
			frames[#frames + 1] = _G[name]
			if hasCoins then
				frames[#frames + 1] = _G[name .. 'CopperButton']
				frames[#frames + 1] = _G[name .. 'SilverButton']
				frames[#frames + 1] = _G[name .. 'GoldButton']
				_G[name .. 'CopperButton'].tooltipAnchor = _G[name]
				_G[name .. 'SilverButton'].tooltipAnchor = _G[name]
				_G[name .. 'GoldButton'].tooltipAnchor = _G[name]
			end
			bagNames[name] = nil
		end
	end

	for index = #frames, 1, -1 do
		local frame = frames[index]
		frame:EnableMouse(true)
		frame:HookScript('OnEnter', OnEnter)
		frame:HookScript('OnLeave', addon.HideTooltip)
		frames[index] = nil
	end

	if not LDBObj and LibStub and LibStub('LibDataBroker-1.1', true) then
		LDBObj = LibStub('LibDataBroker-1.1'):NewDataObject(addonName .. "Money", {
			type = 'data source',
			label = addonName .. "Money",
			OnEnter = OnEnter,
			OnLeave = addon.HideTooltip
		})
	end

	if next(bagNames) then return end
	addon.UnregisterEvent(self, event)
end)