WoWInterface SVN BrokerFactions

[/] [trunk/] [Broker_Factions/] [Broker_Factions.lua] - Rev 54

Compare with Previous | Blame | View Log

-- Broker_Factions : A simple Data Broker reputation display/monitor by Tristanian
-- based on ideas by Titan Factions (Phanx) and FactionsFu (Elkano)
-- my compliments to both of them

-- Embeds & stuff, create DO etc...
local BRFaction = CreateFrame("Frame", "Broker_Factions")
local tooltip = LibStub("LibQTip-1.0")
local L = LibStub("AceLocale-3.0"):GetLocale("Broker_Factions", true)
BRFaction.obj = LibStub:GetLibrary("LibDataBroker-1.1"):NewDataObject("Broker_Factions", {type = "data source", label = "Broker Factions", icon = "Interface\\Icons\\INV_Misc_TabardPVP_03", text = "|cffffff9a"..L["No Faction"].."|r"})
LibStub("AceTimer-3.0"):Embed(BRFaction)
LibStub("AceHook-3.0"):Embed(BRFaction)

BRFaction:RegisterEvent("ADDON_LOADED")
BRFaction:RegisterEvent("PLAYER_ENTERING_WORLD")
BRFaction:RegisterEvent("PLAYER_LOGIN")
BRFaction:RegisterEvent("UPDATE_FACTION")
BRFaction:RegisterEvent("CHAT_MSG_COMBAT_FACTION_CHANGE")
BRFaction:RegisterEvent("CHAT_MSG_SYSTEM")

BRFaction:SetScript("OnEvent", function(_, event, ...)
        BRFaction[event](BRFaction, ...)
end)

-- local variables go here

local _G = getfenv(0)

local repLabel = {
        [1] = "|cff8b0000".._G["FACTION_STANDING_LABEL1"].."|r",        -- Hated
        [2] = "|cffff1919".._G["FACTION_STANDING_LABEL2"].."|r",        -- Hostile
        [3] = "|cffff8C00".._G["FACTION_STANDING_LABEL3"].."|r",        -- Unfriendly
        [4] = "|cffc0c0c0".._G["FACTION_STANDING_LABEL4"].."|r",        -- Neutral
        [5] = "|cffffffff".._G["FACTION_STANDING_LABEL5"].."|r",        -- Friendly
        [6] = "|cff19ff19".._G["FACTION_STANDING_LABEL6"].."|r",        -- Honored
        [7] = "|cff4169e1".._G["FACTION_STANDING_LABEL7"].."|r",        -- Revered
        [8] = "|cff9932cc".._G["FACTION_STANDING_LABEL8"].."|r",        -- Exalted
}

local tt = nil
local isPEW = nil
local FactionID = {}
local FactionList = {}
local headers = {}
local FactionDataLabel = ""
local totaltime = 0
local returnarg = {}

-- Ace config table

local options = {
        name = "Broker Factions",
        childGroups = "tab", type = "group",
        args = {
                general = {
                        name = L["General"],
                        order = 1, type = "group",
                        args = {
                                header = {
                                        name = L["Minimalistic LDB plugin that allows simple faction reputation monitoring."].."\n",
                                        order = 1, type = "description", cmdHidden = true
                                },
                                choosefaction = {
                                        order = 2, type = "select",
                                        name = L["Faction Monitoring"],
                                        desc = L["Select a faction to watch on the button/block."],
                                        get = function() return Broker_FactionsConfig.MonitoredFaction end,
                                        set = function(_,v) 
                                        -- unset Blizzard monitor watch
                                        Broker_FactionsConfig.UseBlizzMonitor = false                   
                                        Broker_FactionsConfig.MonitoredFaction = v
                                        BRFaction:Update()
                                        end,
                                        values = function()                     
                                        FactionList = {}
                                        local name, isHeader, hasRep
                                        local num = GetNumFactions()
                                        for i = 1, num do
                                                name = tostring(GetFactionInfo(i))
                                                isHeader = select(9, GetFactionInfo(i))
                                                hasRep = select(11, GetFactionInfo(i))
                                                if not isHeader or (isHeader and hasRep) then
                                                        if not IsFactionInactive(i) then
                                                                FactionList[name] = "|cff19ff19"..name.."|r"
                                                        end
                                                end
                                        end                                     
                                        FactionList[L["No Faction"]] = "|cffff2020"..L["No Faction"].."|r"
                                        -- match monitored faction no matter if its collapsed
                                        FactionList[Broker_FactionsConfig.MonitoredFaction] = "|cffffff9a"..Broker_FactionsConfig.MonitoredFaction.."|r"
                                        table.sort(FactionList)                         
                                        return FactionList                              
                                        end,
                                },
                                nulloption = {
                                        order = 3,
                                        type = "description",
                                        name = "",              
                                        cmdHidden = true
                                },
                                blizzardmonitor = {
                                        order = 4, type = "toggle", width = "full",
                                        name = L["Use Blizzard's faction watch"],
                                        desc = L["Sets the faction watched on the button/block to the faction set in the character's reputation tab."],
                                        get = function() return Broker_FactionsConfig.UseBlizzMonitor end,
                                        set = function(_,v) 
                                        Broker_FactionsConfig.AutoSetOnGains = false
                                        Broker_FactionsConfig.UseBlizzMonitor = v 
                                        BRFaction:Update()
                                        end,
                                },
                                autosetongains = {
                                        order = 5, type = "toggle", width = "full",
                                        name = L["Auto faction watch on reputation gains"],
                                        desc = L["Automatically sets the faction watched on the button/block to the last faction you gained reputation with."],
                                        get = function() return Broker_FactionsConfig.AutoSetOnGains end,
                                        set = function(_,v) 
                                        Broker_FactionsConfig.UseBlizzMonitor = false
                                        Broker_FactionsConfig.AutoSetOnGains = v 
                                        BRFaction:Update()
                                        end,
                                },
                                ignorenegativegains = {
                                        order = 6, type = "toggle", width = "full",
                                        name = L["Ignore negative reputation gains"],
                                        desc = L["Turning this option on will cause the button/block not to auto-switch to a faction, when getting negative reputation with it."],
                                        get = function() return Broker_FactionsConfig.IgnoreNegativeGains end,
                                        set = function(_,v)                                     
                                        Broker_FactionsConfig.IgnoreNegativeGains = v                                   
                                        end,
                                },
                                ignoreexaltedrepgains = {
                                        order = 7, type = "toggle", width = "full",
                                        name = L["Ignore Exalted factions"],
                                        desc = L["Turning this option on will cause the button/block not to auto-switch to a faction you are exalted with, when reputation with it, is modified."],
                                        get = function() return Broker_FactionsConfig.IgnoreExaltedGains end,
                                        set = function(_,v)                                     
                                        Broker_FactionsConfig.IgnoreExaltedGains = v                                    
                                        end,
                                },                              
                                resetsessiongains = {
                                        order = 8, type = "execute",
                                        name = L["Reset Session Gains"],
                                        desc = L["Resets the reputation session gain counters."],
                                        func = function()
                                                BRFaction.FactionValues = {}
                                                BRFaction:SetInitialReputation()
                                                BRFaction:Update()
                                        end,
                                },
                        },
                },
                button = {
                        name = L["Button"],
                        order = 2, type = "group",
                        args = {
                                hideText = {
                                        order = 1, type = "toggle", width = "full",
                                        name = L["Hide Monitored Faction"],
                                        desc = L["Hides faction text from the button."],
                                        get = function() return Broker_FactionsConfig.HideText end,
                                        set = function(_,v) Broker_FactionsConfig.HideText = v 
                                        BRFaction:Update()
                                        end,
                                },                      
                                sessiongainsbutton = {
                                        order = 2, type = "toggle", width = "full",
                                        name = L["Show Session Gains"],
                                        desc = L["Appends session reputation gains in the form of [xxx], to the button label."],
                                        get = function() return Broker_FactionsConfig.ShowSessionGainsButton end,
                                        set = function(_,v) Broker_FactionsConfig.ShowSessionGainsButton = v 
                                        BRFaction:Update()
                                        end,
                                },
                                standingbutton = {
                                        order = 3, type = "toggle", width = "full",
                                        name = L["Show Standing"],
                                        desc = L["Appends faction standing, to the button label."],
                                        get = function() return Broker_FactionsConfig.ShowStandingButton end,
                                        set = function(_,v) Broker_FactionsConfig.ShowStandingButton = v 
                                        BRFaction:Update()
                                        end,
                                },
                                showpercentbutton = {
                                        order = 4, type = "toggle", width = "full",
                                        name = L["Show Percentages"],
                                        desc = L["Appends percentage values to the button label."],
                                        get = function() return Broker_FactionsConfig.ShowPercentButton end,
                                        set = function(_,v) Broker_FactionsConfig.ShowPercentButton = v 
                                        BRFaction:Update()
                                        end,
                                },
                                showrawbutton = {
                                        order = 5, type = "toggle", width = "full",
                                        name = L["Show Raw Numbers"],
                                        desc = L["Appends raw numbers in the form of (xxx/xxxx), to the button label."],
                                        get = function() return Broker_FactionsConfig.ShowRawButton end,
                                        set = function(_,v) Broker_FactionsConfig.ShowRawButton = v 
                                        BRFaction:Update()
                                        end,
                                },
                                showreptogobutton = {
                                        order = 6, type = "toggle", width = "full",
                                        name = L["Show Reputation To Go"],
                                        desc = L["Appends remaining reputation to reach the next standing, to the button label."],
                                        get = function() return Broker_FactionsConfig.ShowRepToGoButton end,
                                        set = function(_,v) Broker_FactionsConfig.ShowRepToGoButton = v 
                                        BRFaction:Update()
                                        end,
                                },
                                colorizeText = {
                                        order = 7, type = "toggle", width = "full",
                                        name = L["Colorize faction statistics"],
                                        desc = L["Change color of percentages/raw numbers/'to go' according to faction reputation standing."],
                                        get = function() return Broker_FactionsConfig.ColorizeFactionButton end,
                                        set = function(_,v) Broker_FactionsConfig.ColorizeFactionButton = v 
                                        BRFaction:Update()
                                        end,
                                },
                        },
                },
                tooltip = {
                        name = L["Tooltip"],
                        order = 3, type = "group",
                        args = {
                                hidehinttip = {
                                        order = 1, type = "toggle", width = "full",
                                        name = L["Hide Hint Text"],
                                        desc = L["Hides the tooltip information/hint text."],
                                        get = function() return Broker_FactionsConfig.HideHintTip end,
                                        set = function(_,v) Broker_FactionsConfig.HideHintTip = v
                                        end,
                                },
                                showCollapsedHeaders = {
                                        order = 2, type = "toggle", width = "full",
                                        name = L["Show Collapsed Headers"],
                                        desc = L["Toggles display of collapsed faction headers (normally hidden), on the tooltip."],
                                        get = function() return Broker_FactionsConfig.ShowCollapsedHeadersTip end,
                                        set = function(_,v) Broker_FactionsConfig.ShowCollapsedHeadersTip = v
                                        end,
                                },
                                showCollapsedHeadersSuffix = {
                                        order = 3, type = "toggle", width = "full",
                                        name = L["Show Collapsed Header Suffix"],
                                        desc = L["Appends a '+' label suffix to collapsed faction headers (assuming collapsed headers are shown)."],
                                        get = function() return Broker_FactionsConfig.ShowCollapsedSuffixTip end,
                                        set = function(_,v) Broker_FactionsConfig.ShowCollapsedSuffixTip = v
                                        end,
                                },
                                hideExalted = {
                                        order = 4, type = "toggle", width = "full",
                                        name = L["Hide Exalted Factions"],
                                        desc = L["Hides factions with Exalted standing, from the tooltip."],
                                        get = function() return Broker_FactionsConfig.HideExalted end,
                                        set = function(_,v) Broker_FactionsConfig.HideExalted = v
                                        end,
                                },
                                sessiongainstip = {
                                        order = 5, type = "toggle", width = "full",
                                        name = L["Show Session Gains"],
                                        desc = L["Inserts a new tooltip column, showing session reputation gains in the form of 'xxx'."],
                                        get = function() return Broker_FactionsConfig.ShowSessionGainsTip end,
                                        set = function(_,v) Broker_FactionsConfig.ShowSessionGainsTip = v
                                        end,
                                },
                                standingtip = {
                                        order = 6, type = "toggle", width = "full",
                                        name = L["Show Standing"],
                                        desc = L["Inserts a new tooltip column, showing faction standing."],
                                        get = function() return Broker_FactionsConfig.ShowStandingTip end,
                                        set = function(_,v) Broker_FactionsConfig.ShowStandingTip = v
                                        end,
                                },
                                showpercenttip = {
                                        order = 7, type = "toggle", width = "full",
                                        name = L["Show Percentages"],
                                        desc = L["Inserts a new tooltip column, showing reputation percentage values."],
                                        get = function() return Broker_FactionsConfig.ShowPercentTip end,
                                        set = function(_,v) Broker_FactionsConfig.ShowPercentTip = v                                    
                                        end,
                                },
                    showrawtip = {
                                        order = 8, type = "toggle", width = "full",
                                        name = L["Show Raw Numbers"],
                                        desc = L["Inserts a new tooltip column, showing reputation raw numbers in the form of 'xxx/xxxx'."],
                                        get = function() return Broker_FactionsConfig.ShowRawTip end,
                                        set = function(_,v) Broker_FactionsConfig.ShowRawTip = v
                                        end,
                                },
                                showreptogotip = {
                                        order = 9, type = "toggle", width = "full",
                                        name = L["Show Reputation To Go"],
                                        desc = L["Inserts a new tooltip column, showing remaining reputation to reach the next standing."],
                                        get = function() return Broker_FactionsConfig.ShowRepToGoTip end,
                                        set = function(_,v) Broker_FactionsConfig.ShowRepToGoTip = v
                                        end,
                                },
                                settooltipscale = {
                                        order = 10, type = "range", width = "full",
                                        name = L["Tooltip Scale"],                      
                                        desc = L["Move the slider to adjust scaling for the tooltip."],
                                        min = 0.5, max = 1.3, step = 0.01,
                                        get = function() return Broker_FactionsConfig.ToolTipScale end,
                                        set = function(_,v)
                                        if v < 0.5 then v = 0.5 end
                                        if v > 1.3 then v = 1.3 end
                                        Broker_FactionsConfig.ToolTipScale = v end,
                                },
                                showslider = {
                                        order = 11, type = "toggle",
                                        name = L["Enable Scrolling"],
                                        desc = L["Activates and displays a scrolling slider bar, for the tooltip."],
                                        get = function() return Broker_FactionsConfig.ShowSlider end,
                                        set = function(_,v) Broker_FactionsConfig.ShowSlider = v
                                        end,
                                },
                                slidermaxheight = {
                                        order = 12, type = "range",
                                        name = L["Tooltip Maximum Height"],
                                        desc = L["Sets the tooltip maximum height, after which it will be scrollable."],
                                        min = 100, max = 2000, step = 5,
                                        get = function() return Broker_FactionsConfig.SliderMaxHeight end,
                                        set = function(_,v) 
                                        if v < 100 then v = 100 end
                                        if v > 2000 then v = 2000 end
                                        Broker_FactionsConfig.SliderMaxHeight = v end,
                                        disabled = function() return not Broker_FactionsConfig.ShowSlider end,
                                },
                        },
                },
        },
}

-- Add config to Blizzard menu
LibStub("AceConfig-3.0"):RegisterOptionsTable("Broker Factions", options)
LibStub("AceConfigDialog-3.0"):AddToBlizOptions("Broker Factions")


function BRFaction:ADDON_LOADED(addon)
        if addon == "Broker_Factions" then              
                if not Broker_FactionsConfig then 
        -- initialize default configuration
        Broker_FactionsConfig = { 
                        MonitoredFaction = L["No Faction"],
                        CollapsedFactions = {},         
                        UseBlizzMonitor = false,                
                        HideExalted = false,
                        HideText = false,
                        AutoSetOnGains = false,
                        ShowStandingButton = true,
                        ShowStandingTip = true,
                        ShowPercentButton = true,
                        ShowPercentTip = true,
                }
        end
        -- not exactly "clean" but ensures that compatibility doesn't break with pre-1.4 versions
        -- and no savedvar wiping is required
        if not Broker_FactionsConfig.ToolTipScale then Broker_FactionsConfig.ToolTipScale = 1 end
  
        -- 1.5 new savedvars
        if not Broker_FactionsConfig.ShowSessionGainsButton then Broker_FactionsConfig.ShowSessionGainsButton = false end
        if not Broker_FactionsConfig.ShowSessionGainsTip then Broker_FactionsConfig.ShowSessionGainsTip = false end
        if not Broker_FactionsConfig.ShowStandingButton then Broker_FactionsConfig.ShowStandingButton = false end
        if not Broker_FactionsConfig.ShowStandingTip then Broker_FactionsConfig.ShowStandingTip = false end
        if not Broker_FactionsConfig.ShowPercentButton then Broker_FactionsConfig.ShowPercentButton = false end
        if not Broker_FactionsConfig.ShowPercentTip then Broker_FactionsConfig.ShowPercentTip = false end
        if not Broker_FactionsConfig.ShowRawButton then Broker_FactionsConfig.ShowRawButton = false end
        if not Broker_FactionsConfig.ShowRawTip then Broker_FactionsConfig.ShowRawTip = false end
        if not Broker_FactionsConfig.ShowRepToGoButton then Broker_FactionsConfig.ShowRepToGoButton = false end
        if not Broker_FactionsConfig.ShowRepToGoTip then Broker_FactionsConfig.ShowRepToGoTip = false end
        -- 1.6 new savedvars
        if not Broker_FactionsConfig.IgnoreNegativeGains then Broker_FactionsConfig.IgnoreNegativeGains = false end
        if not Broker_FactionsConfig.ColorizeFactionButton then Broker_FactionsConfig.ColorizeFactionButton = false end
        -- 1.8 savedvars
        if not Broker_FactionsConfig.IgnoreExaltedGains then Broker_FactionsConfig.IgnoreExaltedGains = false end
        -- 1.9 savedvars
        if not Broker_FactionsConfig.ShowCollapsedHeadersTip then Broker_FactionsConfig.ShowCollapsedHeadersTip = false end
        if not Broker_FactionsConfig.ShowCollapsedSuffixTip then Broker_FactionsConfig.ShowCollapsedSuffixTip = false end
        -- 2.0 savedvars
        if not Broker_FactionsConfig.ShowSlider then Broker_FactionsConfig.ShowSlider = false end
        if not Broker_FactionsConfig.SliderMaxHeight then Broker_FactionsConfig.SliderMaxHeight = 600 end
        -- 3.0 savedvars
        if not Broker_FactionsConfig.HideHintTip then Broker_FactionsConfig.HideHintTip = false end
  self:UnregisterEvent("ADDON_LOADED")
  self.ADDON_LOADED = nil
        end
end

local function ColorizeLabel(standing, label)
        local coloredLabel = {
        [1] = "|cff8b0000"..label.."|r",        -- Hated
        [2] = "|cffff1919"..label.."|r",        -- Hostile
        [3] = "|cffff8C00"..label.."|r",        -- Unfriendly
        [4] = "|cffc0c0c0"..label.."|r",        -- Neutral
        [5] = "|cffffffff"..label.."|r",        -- Friendly
        [6] = "|cff19ff19"..label.."|r",        -- Honored
        [7] = "|cff4169e1"..label.."|r",        -- Revered
        [8] = "|cff9932cc"..label.."|r",        -- Exalted
}
        if standing > 0 and standing < 9 then
                return coloredLabel[standing]
        end
        return label
end

local function hidett(self, elapsed)
        totaltime = totaltime + elapsed
        if totaltime > 0.2 then
                totaltime = 0
                if tt and not MouseIsOver(tt) then
                        tt:SetScript("OnEnter", nil)
                        tt:SetScript("OnLeave", nil)                    
                        tooltip:Release(tt)                     
                        tt = nil
                        BRFaction:SetScript("OnUpdate", nil)
                elseif not tt then
                        BRFaction:SetScript("OnUpdate", nil)
                end
        end
end

local function ClickHandlerFunc(cell, arg1, button)
        -- Obligatory sanity checks
        if not arg1 or type(arg1)~= "table" then return end     
        if not arg1[1] or not arg1[2] or not arg1[3] or not arg1[4] or not arg1[5] then return end
        -- Assign table fields
        local FactionName = arg1[1]
        local Header = arg1[2]
        local Rep = arg1[3]
        local Collapsed = arg1[4]
        local IndexID = arg1[5]
        -- Handlers
                if button == "LeftButton" and (Header == 0 or (Header == 1 and Rep == 1)) and not IsControlKeyDown() and not IsShiftKeyDown() then
                                Broker_FactionsConfig.MonitoredFaction = FactionName
                                BRFaction:Update()
                elseif button == "LeftButton" and (Header == 0 or (Header == 1 and Rep == 1)) and not Broker_FactionsConfig.UseBlizzMonitor and IsControlKeyDown() then
                        -- toggle Blizzard watched faction according to our watched faction
                        local watched = GetWatchedFactionInfo()
                        if watched == FactionName then
                                SetWatchedFactionIndex(0)
                        else
                                SetWatchedFactionIndex(IndexID)
                        end
                elseif button == "LeftButton" and (Header == 0 or (Header == 1 and Rep == 1)) and IsShiftKeyDown() then
                                if ChatFrameEditBox:IsVisible() then
                                        -- construct proper faction label from name
                                        local factionlabel = BRFaction:CreateFactionLabel(IndexID)
                                        if not factionlabel then return end -- safeguard: something went horribly wrong and the faction label was never created
                                        -- remove color codes *sigh*
                                        local tmpstr, line, normalized  
                                        local normalized = ""
                                        line = string.gsub(factionlabel, "|r", "")
                                        while(string.len(line) > 0) do
                                        local pos = string.find(line, "|cff", 1, true);
                                                if pos then
                                                        tmpstr = string.sub(line,1,pos-1);
                                                        line = string.sub(line,pos + 10);                               
                                                else
                                                tmpstr = line
                                                line = ""
                                                end
                                        normalized = normalized..tmpstr
                                  end                   
                                 ChatFrameEditBox:Insert(normalized)
                          end
                elseif button == "RightButton" and Header == 1 then
                        if Collapsed == 0 then
                                CollapseFactionHeader(IndexID)
                        else
                                ExpandFactionHeader(IndexID)
                        end
                        tt:Clear()
                        BRFaction:Drawtooltip()
                end
end


function BRFaction:SetInitialReputation()
        local name, barValue, isHeader, hasRep
        local num = GetNumFactions()
        if num == 0 then 
                -- debug
                --DEFAULT_CHAT_FRAME:AddMessage("|cff19ff19".."Broker Factions:".."|r"..L["Faction index not yet initialized !"])
                return
        end
        for i = 1, num do
                name = tostring(GetFactionInfo(i))
                barValue = select(6, GetFactionInfo(i))
                isHeader = select(9, GetFactionInfo(i))
                hasRep = select(11, GetFactionInfo(i))
                        if not isHeader or (isHeader and hasRep) then
                                BRFaction.FactionValues[name] = barValue                                
                                -- debug                                        
                                --DEFAULT_CHAT_FRAME:AddMessage ("Adding Faction: "..name.." with initial value of "..barValue)
                        end
        end
         table.sort(BRFaction.FactionValues)
end

function BRFaction:CreateFactionLabel(i)
        local name, _, standingID, barMin, barMax, barValue, atWarWith, _, isHeader, isCollapsed, hasRep, _, _ = GetFactionInfo(i)
        local FullLine, LabelFaction, LabelSession, LabelStanding, LabelPercent, LabelRaw, LabelRepToGo
        
        if name then
                if not isHeader or (isHeader and hasRep) then
        
                                -- Faction Label
                                LabelFaction = ""
                                if standingID > 3 then
                                        LabelFaction = "|cff19ff19"..name.."|r"                         
                                elseif standingID < 3 then
                                        LabelFaction = "|cffff1919"..name.."|r"
                                else
                                        LabelFaction = "|cffffff00"..name.."|r"
                                end

                                -- Session gains
                                LabelSession = ""
                        if BRFaction.FactionValues then
                                if Broker_FactionsConfig.ShowSessionGainsButton then
                                        if not BRFaction.FactionValues[name] then
                                                BRFaction.FactionValues[name] = barValue
                                        end
                                        local gain = barValue - BRFaction.FactionValues[name]
                                        if gain > 0 then
                                                LabelSession = "|cffffff9a".."[".."+"..gain.."]|r "
                                        elseif gain < 0 then
                                          LabelSession = "|cffff2020".."["..gain.."]|r "
                                         end
                                end
                        end
                        
                          -- Faction Standing
                          LabelStanding = ""
                          if Broker_FactionsConfig.ShowStandingButton then
                                        LabelStanding = repLabel[standingID]
                                end
                                
                                -- Faction Percent
                                LabelPercent = ""
                                if Broker_FactionsConfig.ShowPercentButton then
                                        LabelPercent = " "..math.floor( (barValue - barMin)/(barMax - barMin) * 100 ).."%"
                                end

                                -- Faction Raw
                                LabelRaw = ""
                                if Broker_FactionsConfig.ShowRawButton then
                                        LabelRaw = " ("..barValue - barMin.."/"..barMax - barMin..")"
                                end
                                
                                -- Faction ToGo
                                LabelRepToGo = ""
                                if Broker_FactionsConfig.ShowRepToGoButton then
                                        LabelRepToGo = " "..string.format(L["%s to go"], barMax - barValue)                             
                                end
                                
                                FullLine = LabelFaction.." "..LabelSession..LabelStanding..LabelPercent..LabelRaw..LabelRepToGo
                                
                                if Broker_FactionsConfig.ColorizeFactionButton then
                                        FullLine = LabelFaction.." "..LabelSession..LabelStanding..ColorizeLabel(standingID, LabelPercent..LabelRaw..LabelRepToGo)
                                end
          else
                 -- a header was requested, which isn't right but return something
                  FullLine = "|cffffffff"..name.."|r"
          end
        else
                -- something went wrong/faction index changed (?)
                FullLine = "|cffff2020"..L["Unknown Faction"].."|r"                     
        end
        return FullLine
end


function BRFaction:GetFactionFromIndex()
        local name      
        local factionlabel = nil
        local num = GetNumFactions()
        for i = 1, num do
                name = GetFactionInfo(i)
                if Broker_FactionsConfig.MonitoredFaction == name then
                        if IsFactionInactive(i) then
                                factionlabel = Broker_FactionsConfig.MonitoredFaction..": ".."|cffff2020"..L["Inactive Faction"].."|r"
                        else
                                factionlabel = self:CreateFactionLabel(i)
                        end
                        break
                end
        end
        return factionlabel
end

function BRFaction:BRHook_CollapseFactionHeader(i)
local name, description, standingID, barMin, barMax, barValue, atWarWith, canToggleAtWar, isHeader, isCollapsed, hasRep, isWatched, isChild = GetFactionInfo(i)
if not (name and isHeader) then return end
local found = nil;
        for index, _ in ipairs(Broker_FactionsConfig.CollapsedFactions) do
                if name == Broker_FactionsConfig.CollapsedFactions[index] then
                        found = true;
                end
        end     
        if not found and name ~= _G["FACTION_INACTIVE"] then table.insert(Broker_FactionsConfig.CollapsedFactions, name) end    
end

function BRFaction:BRHook_ExpandFactionHeader(i)
local name, description, standingID, barMin, barMax, barValue, atWarWith, canToggleAtWar, isHeader, isCollapsed, hasRep, isWatched, isChild = GetFactionInfo(i)
if not name then return end
        for index, _ in ipairs(Broker_FactionsConfig.CollapsedFactions) do
                if name == Broker_FactionsConfig.CollapsedFactions[index] then          
                        table.remove(Broker_FactionsConfig.CollapsedFactions, index)                    
                end
        end     
end

function BRFaction:CheckCollapsed()
-- Initialize session gains     
if not BRFaction.FactionValues then
        BRFaction.FactionValues = {}
        BRFaction:SetInitialReputation()
end

-- return if there are no factions to collapse
if table.getn(Broker_FactionsConfig.CollapsedFactions) == 0 then return end
        local num = GetNumFactions()
        FactionID = {}          
        -- put the Faction ID's in a table, if they are headers
        for i=1, num do
                local name, _, _, _, _, _, _, _, isHeader, isCollapsed, _, _, _ = GetFactionInfo(i)             
                if isHeader then        
                        for index, _ in ipairs(Broker_FactionsConfig.CollapsedFactions) do              
                                if Broker_FactionsConfig.CollapsedFactions[index] == name then
                                        -- Simple Debug
                                        --DEFAULT_CHAT_FRAME:AddMessage(name.." "..i);
                                        table.insert(FactionID, i)                      
                                end
                        end
                end
        end
        
        table.sort(FactionID)           
        -- Collapse the stored ID's                               
                                for index=#FactionID,1, -1 do                           
                                local name, _, _, _, _, _, _, _, isHeader, isCollapsed, _, _, _ = GetFactionInfo(FactionID[index])              
                                        if isHeader then
                                          -- Simple Debug
                                          --DEFAULT_CHAT_FRAME:AddMessage(name.." "..FactionID[index]);
                                                CollapseFactionHeader(FactionID[index])
                                        end
                                        FactionID[index]= nil;                          
                                end
                                
        BRFaction:CancelAllTimers()
end

function BRFaction:Update()
        if Broker_FactionsConfig.HideText then self.obj.text = "" return end
  -- if UseBlizzardMonitor set the MonitoredFaction to that of Blizzy's
        if Broker_FactionsConfig.UseBlizzMonitor then
                local name
                local watched = GetWatchedFactionInfo()
                        if watched and not string.find(Broker_FactionsConfig.MonitoredFaction, watched) then                                    
                                Broker_FactionsConfig.MonitoredFaction = watched                                        
                        end
        end
        if Broker_FactionsConfig.MonitoredFaction ~= L["No Faction"] then
                self.obj.text = self:GetFactionFromIndex() or Broker_FactionsConfig.MonitoredFaction..": ".."|cffff2020"..L["Hidden Faction"].."|r"
        else
                self.obj.text = "|cffffff9a"..L["No Faction"].."|r"
        end
        FactionDataLabel = self.obj.text or ""  
end


function BRFaction:Drawtooltip()
local i, j
local colnum = 1
local nonheaderset = nil
local name, standingID, barMin, barMax, barValue, atWarWith, isHeader, isCollapsed, hasRep, HeaderLine  
local num = GetNumFactions()

-- Draw tooltip
        local colcount = tt:GetColumnCount()
        local templine = tt:AddLine("")
        tt:SetCell(templine, 1, _G["HIGHLIGHT_FONT_COLOR_CODE"].."Broker Factions", nil, "CENTER", colcount)
        tt:AddLine(" ") 
        tt:AddHeader(unpack(headers,1,colcount))
        
        -- Iterate through faction index
        for i = 1, num do
                colnum = 1
                local display = {}
                name, _, standingID, barMin, barMax, barValue, atWarWith, _, isHeader, isCollapsed, hasRep, _, _ = GetFactionInfo(i)
                if name == _G["FACTION_INACTIVE"] then
                        break -- we do not display inactive factions so break the loop here
                end
                -- if we don't have a header or we have a header with valid reputation
                if not isHeader or (isHeader and hasRep) then
                        if Broker_FactionsConfig.HideExalted and standingID == 8 then -- optionally exclude exalted factions
                        else                            
                                -- Faction Label                                
                                if standingID > 3 then
                                        display[colnum] = "|cff19ff19"..name.."|r"                              
                                elseif standingID < 3 then
                                        display[colnum] = "|cffff1919"..name.."|r"
                                else
                                        display[colnum] = "|cffffff00"..name.."|r"
                                end
                                
                                -- Check for Special Headers with rep
                                if hasRep then
                                        if isCollapsed and Broker_FactionsConfig.ShowCollapsedSuffixTip then
                                                display[colnum] = "|cffffffff"..name.."|r".." ".._G["RED_FONT_COLOR_CODE"].."(+)".."|r"
                                        else
                                                display[colnum] = "|cffffffff"..name.."|r"
                                        end
                                        tt:AddLine(" ")
                                end
                                
                                -- insert empty column so that the actual 2nd column isn't too near faction names
                                        colnum = colnum + 1
                                        display[colnum] = "   "
                                        
                                -- Session gains                                
                                if BRFaction.FactionValues then
                                        if Broker_FactionsConfig.ShowSessionGainsTip then                                               
                                                if not BRFaction.FactionValues[name] then
                                                        BRFaction.FactionValues[name] = barValue
                                                end
                                                local gain = barValue - BRFaction.FactionValues[name]                                   
                                                if gain > 0 then
                                                        display[colnum] = "|cffffff9a".."+"..gain.."|r"
                                                elseif gain < 0 then
                                                display[colnum] = "|cffff2020"..gain.."|r"
                                                else
                                                        display[colnum] = "|cffc0c0c0"..gain.."|r"
                                                end                                     
                                        end
                                end
                                                                
                                -- Faction Standing
                                if Broker_FactionsConfig.ShowStandingTip then
                                        colnum = colnum + 1
                                        display[colnum] = repLabel[standingID]
                                end
                                
                                -- Faction Percent                              
                                if Broker_FactionsConfig.ShowPercentTip then
                                        colnum = colnum + 1
                                        display[colnum] = _G["NORMAL_FONT_COLOR_CODE"].." "..math.floor( (barValue - barMin)/(barMax - barMin) * 100 ).."%"                             
                                end

                                -- Faction Raw                          
                                if Broker_FactionsConfig.ShowRawTip then
                                        colnum = colnum + 1
                                        display[colnum] = _G["NORMAL_FONT_COLOR_CODE"].." "..barValue - barMin.."/"..barMax - barMin                    
                                end
                                
                                -- Faction ToGo                         
                                if Broker_FactionsConfig.ShowRepToGoTip then
                                        colnum = colnum + 1
                                        display[colnum] = _G["NORMAL_FONT_COLOR_CODE"].." "..string.format("%s", barMax - barValue)                             
                                end
                                                                 
                                 templine = tt:AddLine(unpack(display, 1, colcount))
                                 -- Construct the return table here
                                 -- Structure: returnarg = { <Faction Name>, <isHeader>, <hasRep>, <isCollapsed>, <IndexID>}
                                 -- Faction Name : string, eg "Kirin Tor"
                                 -- isHeader : integer, 1 - true, 0 - false
                                 -- hasRep : integer, 1 - true, 0 - false
                                 -- isCollapsed : integer, 1 - true, 0 - false
                                 -- IndexID : integer that indicates the faction index
                                 returnarg = {}
                                 returnarg[1] = name
                                 if isHeader then returnarg[2] = 1 else returnarg[2] = 0 end
                                 if hasRep then returnarg[3] = 1 else returnarg[3] = 0 end
                                 if isCollapsed then returnarg[4] = 1 else returnarg[4] = 0 end
                                 returnarg[5] = i
                                 tt:SetCellScript(templine, 1, "OnMouseDown", ClickHandlerFunc , returnarg)
                                 nonheaderset = true
                        end
                else
                 -- We have a header folks !
                  if not isCollapsed then                 
                        tt:AddLine(" ")
                                HeaderLine = "|cffffffff"..name.."|r"
                                templine = tt:AddLine(HeaderLine)
                                -- Construct the return table here
                                returnarg = {}
                                returnarg[1] = name
                                if isHeader then returnarg[2] = 1 else returnarg[2] = 0 end
                                if hasRep then returnarg[3] = 1 else returnarg[3] = 0 end
                                if isCollapsed then returnarg[4] = 1 else returnarg[4] = 0 end
                                returnarg[5] = i
                                tt:SetCellScript(templine, 1, "OnMouseDown", ClickHandlerFunc , returnarg)
                        elseif isCollapsed and Broker_FactionsConfig.ShowCollapsedHeadersTip then
                                tt:AddLine(" ")
                                        if Broker_FactionsConfig.ShowCollapsedSuffixTip then
                                                HeaderLine = "|cffffffff"..name.."|r".." ".._G["RED_FONT_COLOR_CODE"].."(+)".."|r"
                                        else
                                                HeaderLine = "|cffffffff"..name.."|r"
                                        end
                                templine = tt:AddLine(HeaderLine)
                                -- Construct the return table here
                                returnarg = {}
                                returnarg[1] = name
                                if isHeader then returnarg[2] = 1 else returnarg[2] = 0 end
                                if hasRep then returnarg[3] = 1 else returnarg[3] = 0 end
                                if isCollapsed then returnarg[4] = 1 else returnarg[4] = 0 end
                                returnarg[5] = i
                                tt:SetCellScript(templine, 1, "OnMouseDown", ClickHandlerFunc , returnarg)
                        end
                end             
        end     
        -- Tooltip Hint
        if not Broker_FactionsConfig.HideHintTip then
                tt:AddLine(" ")
                templine = tt:AddLine("")
                tt:SetCell(templine, 1, L["|cffeda55fLeft Click|r |cff19ff19on plugin to open Blizzard's Reputation tab."], nil, "LEFT", colcount)
                templine = tt:AddLine("")
                tt:SetCell(templine, 1, L["|cffeda55fLeft Click|r |cff19ff19on faction name to watch on the button/block."], nil, "LEFT", colcount)
                templine = tt:AddLine("")
                tt:SetCell(templine, 1, L["|cffeda55fRight Click|r |cff19ff19on plugin to open Configuration Menu."], nil, "LEFT", colcount)
                templine = tt:AddLine("")
                tt:SetCell(templine, 1, L["|cffeda55fRight Click|r |cff19ff19on faction header to expand or collapse it."], nil, "LEFT", colcount)
                templine = tt:AddLine("")
                tt:SetCell(templine, 1, L["|cffeda55fShift+Left Click|r |cff19ff19to paste Reputation info into chat."], nil, "LEFT", colcount)
                templine = tt:AddLine("")
                tt:SetCell(templine, 1, L["|cffeda55fCtrl+Left Click|r |cff19ff19to toggle Reputation bar watch."], nil, "LEFT", colcount)
        end
        
        if not nonheaderset then
                -- hide column header titles since we have no real faction data
                for i=1, colcount do
                        tt:SetCell(3, i, "")
                end
        end
        
        if Broker_FactionsConfig.ShowSlider then
                tt:UpdateScrolling(Broker_FactionsConfig.SliderMaxHeight)       
        end
end

function BRFaction.obj.OnEnter(self)
        local colnum = 1        
        local orientation = {}
        headers = {}
        
        -- conditions, set headers and orientations
        -- Faction
        headers[colnum] = L["|cffeda55fFaction"]
        orientation[colnum] = "LEFT"
        
        -- insert empty column so that the actual 2nd column isn't too near faction names
        colnum = colnum + 1
        headers[colnum] = "  "
        orientation[colnum] = "CENTER"
        
        -- Session gains
        if Broker_FactionsConfig.ShowSessionGainsTip then               
                headers[colnum] = L["|cffeda55fSession"]        
        end
        -- Standing
        if Broker_FactionsConfig.ShowStandingTip then
                colnum = colnum + 1
                headers[colnum] = L["|cffeda55fStatus"]         
                orientation[colnum] = "CENTER"
        end
        -- Faction Percent
        if Broker_FactionsConfig.ShowPercentTip then
                colnum = colnum + 1
                headers[colnum] = "|cffeda55f%"
                orientation[colnum] = "RIGHT"
        end
        -- Faction Raw
        if Broker_FactionsConfig.ShowRawTip then
                colnum = colnum + 1
                headers[colnum] = L["|cffeda55fRaw"]
                orientation[colnum] = "CENTER"
        end
        -- Faction ToGo
        if Broker_FactionsConfig.ShowRepToGoTip then
                colnum = colnum + 1
                headers[colnum] = L["|cffeda55fTo Go"]
                orientation[colnum] = "RIGHT"
        end
        
        local maxentries = #orientation
        if maxentries ~= 1 then orientation[maxentries] = "RIGHT" end

        -- acquire frame
        tt = tooltip:Acquire("Broker_Factions", colnum, unpack(orientation,1,maxentries))
        tt:EnableMouse(true)
        tt:SetScript("OnEnter", function(self) BRFaction:SetScript("OnUpdate", nil) end)
        tt:SetScript("OnLeave", function(self) BRFaction:SetScript("OnUpdate", hidett) end)
        tt:SmartAnchorTo(self)
        tt:Clear()
        tt:SetScale(Broker_FactionsConfig.ToolTipScale or 1)
        tt:SetBackdropBorderColor(1, 1, 1, 1)
        BRFaction:Drawtooltip() 
        tt:Show()
end

function BRFaction.obj.OnLeave()        
        if tt and tt:IsVisible() then
                BRFaction:SetScript("OnUpdate", hidett)
        end             
end


function BRFaction.obj.OnClick(self, button)
        if tt then
                tt:SetScript("OnEnter", nil)
                tt:SetScript("OnLeave", nil)
                tooltip:Release(tt)
                tt = nil
        end
        if button == "LeftButton" and IsShiftKeyDown() then
                if ChatFrameEditBox:IsVisible() then                    
                        -- remove color codes for obj.text *sigh*
                        local tmpstr, line, normalized; 
                        local normalized = ""
                        line = string.gsub(FactionDataLabel, "|r", "")
                        while(string.len(line) > 0) do
                        local pos = string.find(line, "|cff", 1, true);
                                if pos then
                                        tmpstr = string.sub(line,1,pos-1);
                                        line = string.sub(line,pos + 10);                               
                                else
                                tmpstr = line
                                line = ""
                                end
                                normalized = normalized..tmpstr
                        end                     
                        ChatFrameEditBox:Insert(normalized)
                end
        elseif button == "LeftButton" and IsControlKeyDown() then
                local num = GetNumFactions()
                local watched = GetWatchedFactionInfo()
                local monitorID = 0
                local name
                for i = 1, num do
                        name = GetFactionInfo(i)                        
                        if Broker_FactionsConfig.MonitoredFaction == name then
                                monitorID = i;
                                break
                        end
                  end
                -- toggle Blizzard watched faction according to our watched faction             
                if watched == Broker_FactionsConfig.MonitoredFaction then
                        SetWatchedFactionIndex(0)
                else
                        SetWatchedFactionIndex(monitorID)
                end
        elseif button == "LeftButton" then
                ToggleCharacter("ReputationFrame")
        elseif button == "RightButton" then             
                InterfaceOptionsFrame_OpenToCategory("Broker Factions")
        end
end


function BRFaction:PLAYER_LOGIN()
        local factionGroup = UnitFactionGroup("player")
                if factionGroup == "Horde" then
                        self.obj.icon = "Interface\\Icons\\INV_Misc_TabardPVP_04"
    else
        self.obj.icon = "Interface\\Icons\\INV_Misc_TabardPVP_03"
        end
        self:UnregisterEvent("PLAYER_LOGIN")
  self.PLAYER_LOGIN = nil
end

function BRFaction:PLAYER_ENTERING_WORLD()      
        isPEW = true    
end

function BRFaction:UPDATE_FACTION()
        if isPEW then
                self:CancelAllTimers()
                self:ScheduleTimer(self.CheckCollapsed, 1)                      
                isPEW = nil;
        end
        
        BRFaction:Update()
end


function BRFaction:CHAT_MSG_COMBAT_FACTION_CHANGE(msg)
-- Auto-set faction to monitor, on reputation gains/losses
if Broker_FactionsConfig.AutoSetOnGains then
        local faction = nil

        if not Broker_FactionsConfig.IgnoreNegativeGains then
        _,_,faction = string.find (msg, "^"..L["Reputation with (.*) decreased"])
        end

        if not faction then
                _,_,faction = string.find (msg, "^"..L["Reputation with (.*) increased"])
        end     
        
        -- safeguard/workaround for mixed locales, ManniAT's idea
        if faction then faction = string.gsub(faction, "^'(.*)'$", "%1") end
        
                
        if faction and faction ~= "" and faction ~= Broker_FactionsConfig.MonitoredFaction then
        
                if Broker_FactionsConfig.IgnoreExaltedGains then
                -- check for exalted faction
                local num = GetNumFactions()
                        local name, standingID
                                for i = 1, num do
                                        name = tostring(GetFactionInfo(i))
                                        standingID = select(3, GetFactionInfo(i))
                                                -- if we are exalted with faction we gained rep with, and IgnoreExalted is on, return with no update
                                                if name == faction and standingID == 8 then return end
                                end
                end
                                        
                -- Unset UseBlizzMonitor
                Broker_FactionsConfig.UseBlizzMonitor = false
                Broker_FactionsConfig.MonitoredFaction = faction
                self:Update()
        end
end
        
end


function BRFaction:AddNewFaction(fname)
if not fname then return end

local num = GetNumFactions()
                local name, barValue, isHeader
                        for i = 1, num do
        name = tostring(GetFactionInfo(i))
              barValue = select(6, GetFactionInfo(i))
                if name == fname and barValue then                                              
            BRFaction.FactionValues[fname] = barValue                                           
                                                break
          end
      end
        table.sort(BRFaction.FactionValues)     
end


function BRFaction:CHAT_MSG_SYSTEM(msg)
local rep, faction, i
local repfound = nil

_,_,rep,faction = string.find(msg, "^"..L["You are now (%a+) with (.*)%."])

if not rep or not faction then return end

if rep and faction then 
        faction = string.gsub(faction, "^'(.*)'$", "%1") 
        rep = string.gsub(rep, "^'(.*)'$", "%1")
end

-- safeguard/workaround for mixed locales, ManniAT's idea
for i=1, 8 do
        if rep == _G["FACTION_STANDING_LABEL"..i] then
                repfound = true
                break
        end
end

if not repfound then
        local temprep = rep
        rep = faction
        faction = temprep
end

        if rep and faction and BRFaction.FactionValues then
                if not BRFaction.FactionValues[faction] then
                        self:ScheduleTimer("AddNewFaction", 1, faction)
                end             
        end

end


-- Hooks
BRFaction:SecureHook("CollapseFactionHeader", "BRHook_CollapseFactionHeader")
BRFaction:SecureHook("ExpandFactionHeader", "BRHook_ExpandFactionHeader")

Compare with Previous | Blame