-- ArenaLog GUI / Browser
ARENALOGBROWSER_NUM_ROWS = 16;
ARENALOGBROWSER_ROW_HEIGHT = 18;
ARENALOGBROWSER_ROW_TEXT_OFFSET = -30;
ARENALOGBROWSER_NUM_CLASS_ICONS = 10;
ARENALOGBROWSER_DEFAULT_NAME_WIDTH = 185;

ArenaLog_ClassIcons = {
    [0] = { 0.75, 0.75, 1.0, 1.0 }, -- Empty
    [1] = { 0, 0.25, 0, 0.25 },     -- Warrior
    [2] = { 0.5, 0.75, 0, 0.25 },   -- Rogue
    [3] = { 0, 0.25, 0.25, 0.5 },   -- Hunter
    [4] = { 0, 0.25, 0.5, 0.75 },   -- Paladin
    [5] = { 0.25, 0.5, 0.25, 0.5 }, -- Shaman
    [6] = { 0.75, 1.0, 0, 0.25 },   -- Druid
    [7] = { 0.75, 1.0, 0.25, 0.5 }, -- Warlock
    [8] = { 0.25, 0.5, 0, 0.25 },   -- Mage
    [9] = {0.5, 0.75, 0.25, 0.5 },  -- Priest
    [10] = {0.25, 0.5, 0.5, 0.75 }, -- Death Knight
};

ArenaLog_ClassColors = {
    [0] = "|c00ffffff",
    [1] = "|c00c79c6e",
    [2] = "|c00fff589",
    [3] = "|c00abd473",
    [4] = "|c00f58cba",
    [5] = "|c002459ff",
    [6] = "|c00ff7d0a",
    [7] = "|c009482c9",
    [8] = "|c0069ccf0",
    [9] = "|c00ffffff",
    [10] = "|c00c41f3b",
};

local browser = { };
browser.selectedBracket = 1;
browser.selectedTeam = "";

ArenaLog_BrowserCache = {};

function browser.OnLoad(self)
    PanelTemplates_SetNumTabs(self, 3);
    self.selectedTab = 1;
    browser.selectedBracket = 1;
    -- Get team name
    browser.selectedTeam = ArenaLog:GetTeamFromBracket(2);    
end

function browser:InitPanels()
    local bracketSize = { 2, 3, 5 };
    local brackets = {};
    for i = 1, 3 do
        brackets[i] = {
            ["size"] = bracketSize[i],
            ["currentPanel"] = "teams",
            ["teams"] = {
                ["loaded"] = false,
                ["sortColumn"] = "date",
                ["sortOrder"] = "desc",
                ["scrollOffset"] = 0,
            },
            ["games"] = {
                ["loaded"] = false,
                ["sortColumn"] = "date",
                ["sortOrder"] = "desc",
                ["scrollOffset"] = 0,
                ["selectedTeam"] = 0,
            },
            ["scores"] = {
                ["loaded"] = false,
                ["sortColumn"] = "team",
                ["sortOrder"] = "asc",
                ["scrollOffset"] = 0,
            },
            ["comps"] = {
                ["loaded"] = false,
                ["sortColumn"] = "ratio",
                ["sortOrder"] = "desc",
                ["scrollOffset"] = 0,
            },
        };            
    end

    browser.brackets = brackets;
end
 
-- Ensures no cache access will return nil
function browser:EnsureCacheTable(teamName, pane)
    if ArenaLog_BrowserCache[teamName] == nil then
        ArenaLog_BrowserCache[teamName] = {};
    end
    if ArenaLog_BrowserCache[teamName][pane] == nil then
        ArenaLog_BrowserCache[teamName][pane] = {};
    end
end

function browser:GetCurrentPanel()
    return browser.brackets[browser.selectedBracket]["currentPanel"];
end

function browser:OnShow()
    if browser.brackets == nil then browser:InitPanels() end;
    if browser.selectedBracket == nil then 
        browser.selectedBracket = 1;        
    end
    
    PanelTemplates_SetTab(ArenaLogBrowserFrame, browser.selectedBracket);

    local bracket = browser.brackets[browser.selectedBracket];

    if (bracket[bracket.currentPanel]["loaded"] == false) then
        browser:Update();
    end

    PlaySound("igCharacterInfoTab");
end

--This function is called when the browser's state has changed in a way that requires
--a cache load or new panel screen, it is not called often.
function browser:Update()
    -- Get team name
    local tabIndex = browser.selectedBracket;
    local pane = browser:GetCurrentPanel();
    local teamSize = browser.brackets[tabIndex]["size"]; 
    local teamName = ArenaLog:GetTeamFromBracket(teamSize);    
    browser.selectedTeam = teamName;
    
    -- Set team label
    local nameString = teamName;
    if (pane == "games" or pane == "scores") then
        -- Add enemy team name
        local selectedRow = browser.brackets[tabIndex]["teams"]["selectedRow"];
        local enemyTeamRow = ArenaLog_BrowserCache[teamName]["teams"][selectedRow];
        nameString = nameString.."|c00ff0000 vs. |r"..enemyTeamRow["name"];
    end
        
    ArenaLogBrowserFrameTeamLabel:SetText(nameString);
    
    
    -- Load updated cache if needed
    if pane == "teams" then
        browser:SetupEnemyTeams();
        if (browser.brackets[tabIndex][pane]["loaded"] == false) then
            browser:UpdateCache(teamName, pane);
        end
    elseif pane == "comps" then
        browser:SetupComps();
        if (browser.brackets[tabIndex][pane]["loaded"] == false) then
            browser:UpdateCache(teamName, pane);
        end
    elseif pane == "games" then
        browser:SetupGames();
        browser:UpdateCache(teamName, pane);
    elseif pane == "scores" then
        browser:SetupScores();
        browser:UpdateCache(teamName, pane);
    end
    
    -- Update rows
    local scrollOffset = browser.brackets[tabIndex][pane]["scrollOffset"];
    FauxScrollFrame_OnVerticalScroll(ArenaLogBrowserScrollFrame, scrollOffset*ARENALOGBROWSER_ROW_HEIGHT, ARENALOGBROWSER_ROW_HEIGHT, browser.UpdateRows);
end


function browser.Tab_OnClick(tab)    
    if (tab == nil) then
        tab = getglobal("ArenaLogBrowserFrameTab1");
    end
    local tabIndex = tab:GetID();
    browser.selectedBracket = tabIndex;
    PanelTemplates_SetTab(ArenaLogBrowserFrame, tabIndex);
    
    browser:Update();
    
    PlaySound("igCharacterInfoTab");
end

function browser:ResetCache()
    ArenaLog_BrowserCache = {};
    browser:InitPanels(); 
    if (ArenaLogBrowserFrame:IsShown() == 1) then
        browser:Update();
    end
end


--[[
This filters the ArenaLog_Data table into a set of results for a particular
bracket and detail.  This does not sort.  Additional arguments are for searching
for specific teams/players.

--]]
function browser:UpdateCache(teamName, pane, arg1, arg2, arg3)
    if teamName == nil then return end;
    browser:EnsureCacheTable(teamName, pane);
    local results = {};
    local row = {};
    if ArenaLog_Data[teamName] ~= nil then
        if pane == "teams" then -- Cache enemy team listing
            local db = ArenaLog_Data[teamName]["enemyTeams"];       
            for k, v in pairs(db) do
                -- Return comp array
                local name = { strsplit("-", k) };
                row = {
                    ["name"] = strtrim(name[1]),
                    ["realm"] = strtrim(name[2]),
                    ["wins"] = v["wins"],
                    ["losses"] = v["losses"],
                    ["ratingChange"] = v["ratingChange"],
                    ["lastPlayed"] = v["lastPlayed"],
                    ["comp"] = ArenaLog.GetTeamCompArray(teamName, strtrim(name[1]), strtrim(name[2])),
                };
                table.insert(results, row);
            end
        elseif pane == "games" then --Cache game listing vs enemy team
            -- We get the team lookup based on the row selected in the previous pane.
            local selectedRow = browser.brackets[browser.selectedBracket]["teams"]["selectedRow"];
            local enemyTeamRow = ArenaLog_BrowserCache[teamName]["teams"][selectedRow];
            for _, v in pairs(ArenaLog_Data[teamName]["games"]) do
                if (v["enemyTeamName"] == enemyTeamRow["name"] and v["enemyTeamRealm"] == enemyTeamRow["realm"]) then
                    row = {
                        ["zone"] = v["zone"],
                        ["winner"] = v["winner"],
                        ["duration"] = v["duration"],
                        ["timestamp"] = v["timestamp"],
                        ["playerTeamRatingOld"] = v["playerTeamRatingOld"],
                        ["playerTeamRatingNew"] = v["playerTeamRatingNew"],
                        ["enemyTeamRatingOld"] = v["enemyTeamRatingOld"],
                        ["enemyTeamRatingNew"] = v["enemyTeamRatingNew"],
                        ["playerTeamSkill"] = v["playerTeamSkill"],
                        ["enemyTeamSkill"] = v["enemyTeamSkill"],
                    };
                    table.insert(results, row);
                end
            end       
        elseif pane == "scores" then --Cache scores listing for a game
            -- Look up game based on selecting the game in the previous pane
            local selectedRow = browser.brackets[browser.selectedBracket]["games"]["selectedRow"];
            local gameRow = ArenaLog_BrowserCache[teamName]["games"][selectedRow];
            -- Search for game based on timestamp field
            for _, v in pairs(ArenaLog_Data[teamName]["games"]) do
                if (v["timestamp"] == gameRow["timestamp"]) then
                    for _, score in pairs(v["scores"]) do
                        row = {
                            ["name"] = score["name"],
                            ["team"] = score["teamName"],
                            ["kills"] = score["killingBlows"],
                            ["deaths"] = score["deaths"],
                            ["race"] = score["race"],
                            ["filename"] = score["filename"],
                            ["damage"] = score["damageDone"],
                            ["healing"] = score["healingDone"],
                        };
                        table.insert(results, row);                        
                    end
                    break;
                end
            end
        elseif pane == "comps" then -- Cache enemy team listing
            local db = ArenaLog_Data[teamName]["enemyComps"];       
            for k, v in pairs(db) do
                -- Return comp array
                local compArray = { strsplit(" ", k) };
                row = {
                    ["wins"] = v["wins"],
                    ["losses"] = v["losses"],
                    ["ratingChange"] = v["ratingChange"],
                    ["comp"] = compArray,
                };
                table.insert(results, row);
            end
        end
    end
        
    browser.brackets[browser.selectedBracket][pane]["loaded"] = true;
    ArenaLog_BrowserCache[teamName][pane] = results;
    browser:SortCache(browser.brackets[browser.selectedBracket][pane]["sortColumn"]);
end

--Generates fake data for testing
function browser:TestCache(teamName, pane, arg1, arg2, arg3)
    if teamName == nil then return end;
    browser:EnsureCacheTable(teamName, pane);
    local results = {};
    local row = {};
    local classes = { "WARRIOR", "HUNTER", "PRIEST", "WARLOCK", "MAGE", "DEATHKNIGHT", "ROGUE", "DRUID", "SHAMAN", "PALADIN" };
    local zones = { "Lordaeron Arena", "Dalaran Arena", "Nagrand Arena", "Blade's Edge Arena" };
    if pane == "teams" then        
        for i=1, math.random(20, 34) do
            local name = { "Team Name "..i, " Sargeras" };            
            local comp = {};
            for i=1, math.random(5,8) do
                table.insert(comp, classes[math.random(1,10)]);
            end
            table.sort(comp);
            row = {
                ["name"] = strtrim(name[1]),
                ["realm"] = strtrim(name[2]),
                ["wins"] = math.random(0, 15),
                ["losses"] = math.random(0,15),
                ["ratingChange"] = math.random(0,60)-30,
                ["lastPlayed"] = time()+math.random(0, 100000),
                ["comp"] = comp,
            };
            table.insert(results, row);
        end
    elseif pane == "games" then
        for i=1, math.random(3, 12) do
            local zone = zones[math.random(1,4)];
            local win = math.random(0,1);
            local winBool;
            if win == 1 then winBool = true else winBool = false end;
            local ratingChange = math.random(1, 24);
            if (winBool == false) then ratingChange = ratingChange * -1 end;
            local oldRating = math.random(1500, 2000);
            local newRating = oldRating+ratingChange;
            
            row = {
                ["zone"] = zone,
                ["winner"] = winBool,
                ["duration"] = math.random(200, 500),
                ["timestamp"] = time() + math.random(-300000, 0),
                ["playerTeamRatingOld"] = oldRating,
                ["playerTeamRatingNew"] = newRating,
                ["enemyTeamRatingOld"] = oldRating,
                ["enemyTeamRatingNew"] = (oldRating - ratingChange),
            };
            table.insert(results, row);
        end
    end
    browser.brackets[browser.selectedBracket][pane]["loaded"] = true;
    ArenaLog_BrowserCache[teamName][pane] = results;
end

function browser:SortCache(column)    
    local index = browser.selectedBracket;
    local teamName = browser.selectedTeam;
    local pane = browser:GetCurrentPanel();
    local db = ArenaLog_BrowserCache[teamName][pane];
    local sortFunc, field;
    
    local paneOptions = browser.brackets[index][pane];

    if column == "name" then
        if (pane == "teams" or pane == "scores") then field = "name" elseif pane == "games" then field = "zone" end;
        if paneOptions["sortOrder"] == "asc" then
            sortFunc = function(a,b) return string.lower(a[field]) > string.lower(b[field]) end;
        else
            sortFunc = function(a,b) return string.lower(a[field]) < string.lower(b[field]) end;
        end
    elseif column == "ratio" then
        if paneOptions["sortOrder"] == "asc" then                
            sortFunc = function(a,b) return (a["wins"] - a["losses"]) < (b["wins"] - b["losses"]) end;
        else 
            sortFunc = function(a,b) return (a["wins"] - a["losses"]) > (b["wins"] - b["losses"]) end;
        end
    elseif column == "rating" then
        if pane == "teams" or pane == "comps" then
            sortFunc = browser:GenericSort("ratingChange", paneOptions["sortOrder"]);
        elseif pane == "games" then
            if paneOptions["sortOrder"] == "asc" then                
                sortFunc = function(a,b) return (a["playerTeamRatingNew"] - a["playerTeamRatingOld"]) < (b["playerTeamRatingNew"] - b["playerTeamRatingOld"]) end;
            else 
                sortFunc = function(a,b) return (a["playerTeamRatingNew"] - a["playerTeamRatingOld"]) > (b["playerTeamRatingNew"] - b["playerTeamRatingOld"]) end;
            end
        end
    elseif column == "date" then
        if pane == "teams" then field = "lastPlayed" elseif pane == "games" then field = "timestamp" end;
        sortFunc = browser:GenericSort(field, paneOptions["sortOrder"]);
    elseif column == "comp" then
        if (pane == "teams") then
            if paneOptions["sortOrder"] == "asc" then                
                sortFunc = function(a,b) return ArenaLog.GetCompositionString(a["comp"]) > ArenaLog.GetCompositionString(b["comp"]) end;
            else 
                sortFunc = function(a,b) return ArenaLog.GetCompositionString(a["comp"]) < ArenaLog.GetCompositionString(b["comp"]) end;
            end
        else
            if paneOptions["sortOrder"] == "asc" then                
                sortFunc = function(a,b) return table.concat(a["comp"], " ") > table.concat(b["comp"], " ") end;
            else 
                sortFunc = function(a,b) return table.concat(a["comp"], " ") < table.concat(b["comp"], " ") end;
            end
        end            
    elseif column == "oldrating1" then
        if paneOptions["sortOrder"] == "asc" then
            sortFunc = function(a,b) return a["playerTeamRatingNew"] > b["playerTeamRatingOld"] end;
        else
            sortFunc = function(a,b) return a["playerTeamRatingNew"] < b["playerTeamRatingOld"] end;
        end
    elseif column == "oldrating2" then
        if paneOptions["sortOrder"] == "asc" then
            sortFunc = function(a,b) return a["enemyTeamRatingNew"] > b["enemyTeamRatingOld"] end;
        else
            sortFunc = function(a,b) return a["enemyTeamRatingNew"] < b["enemyTeamRatingOld"] end;
        end
    else
        sortFunc = browser:GenericSort(column, paneOptions["sortOrder"]);
    end
    
    table.sort(db, sortFunc);
    
    -- Flip sort order for pane:column
    if browser.brackets[index][pane]["sortOrder"] == "asc" then
        browser.brackets[index][pane]["sortOrder"] = "desc"
    else
        browser.brackets[index][pane]["sortOrder"] = "asc"
    end
    
    ArenaLog_BrowserCache[teamName][pane] = db;
end

function browser:GenericSort(field, order)
    if order == "asc" then
        return (function(a,b) return a[field] < b[field] end);
    else
        return (function(a,b) return a[field] > b[field] end);
    end
end

function browser:SetupEnemyTeams()
    -- Enable correct columns
    ArenaLogBrowserColumnKB:Hide()
    ArenaLogBrowserColumnDamage:Hide()
    ArenaLogBrowserColumnHealing:Hide()
    ArenaLogBrowserColumnRatio:Show()
    ArenaLogBrowserColumnRatingChange:Show()
    ArenaLogBrowserColumnOldRating1:Hide()
    ArenaLogBrowserColumnOldRating2:Hide()
    ArenaLogBrowserColumnComp:Show()
    ArenaLogBrowserColumnDate:Show()
    ArenaLogBrowserColumnDuration:Hide()
    ArenaLogBrowserColumnTeam:Hide()
    ArenaLogBrowserColumnName:Show()
    
    -- Set up columns
    ArenaLogBrowserColumnNameText:SetText(ARENALOG_COLUMNTEXT_TEAM);
    ArenaLogBrowserColumnDateText:SetText(ARENALOG_COLUMNTEXT_LASTPLAYED);
    ArenaLogBrowserColumnComp:SetWidth(17*ARENALOGBROWSER_NUM_CLASS_ICONS);
    ArenaLogBrowserColumnRatio:SetPoint("LEFT", "ArenaLogBrowserColumnName", "RIGHT", 0 ,0);
    ArenaLogBrowserColumnRatingChange:SetPoint("LEFT", "ArenaLogBrowserColumnRatio", "RIGHT", 16, 0);
    ArenaLogBrowserColumnComp:SetPoint("LEFT", "ArenaLogBrowserColumnRatingChange", "RIGHT", 16, 0);
    
    
    --Hide scrollframe
    ArenaLogBrowserScrollFrame:Hide();

    -- Align row columns
    local rowFrame, name, ratio, ratingChange, comp, date, factionLeft, factionRight, oldRating1, oldRating2, duration, team, class, killingBlows, damage, healing;

    --align each successive cell with the one above it
    for i=1, ARENALOGBROWSER_NUM_ROWS do
        rowFrame = getglobal("ArenaLogBrowserRow"..i);
        rowFrame:SetWidth(ArenaLogBrowserFrame:GetWidth()-168);
        --Obtain column objects
        name =          getglobal("ArenaLogBrowserRow"..i.."Name");
        ratio =         getglobal("ArenaLogBrowserRow"..i.."Ratio");
        ratingChange =  getglobal("ArenaLogBrowserRow"..i.."RatingChange");
        comp =          getglobal("ArenaLogBrowserRow"..i.."Classes");
        date =          getglobal("ArenaLogBrowserRow"..i.."Date");
        factionLeft =   getglobal("ArenaLogBrowserRow"..i.."FactionLeft");
        factionRight =  getglobal("ArenaLogBrowserRow"..i.."FactionRight");
        oldRating1 =    getglobal("ArenaLogBrowserRow"..i.."OldRating1");
        oldRating2 =    getglobal("ArenaLogBrowserRow"..i.."OldRating2");
        duration =      getglobal("ArenaLogBrowserRow"..i.."Duration");
        team =          getglobal("ArenaLogBrowserRow"..i.."Team");
        class =         getglobal("ArenaLogBrowserRow"..i.."ClassIcon");
        killingBlows =  getglobal("ArenaLogBrowserRow"..i.."KB");
        damage =        getglobal("ArenaLogBrowserRow"..i.."Damage");
        healing =       getglobal("ArenaLogBrowserRow"..i.."Healing");
        
        -- show/hide
        comp:Show(); ratio:Show(); ratingChange:Show(); date:Show();
        oldRating1:Hide();  oldRating2:Hide();      duration:Hide();    team:Hide();
        class:Hide();       killingBlows:Hide();    damage:Hide();  healing:Hide();
        name:Show();
        
        if (i==1) then
            name:SetPoint("CENTER", "ArenaLogBrowserColumnName", "CENTER", 8, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            ratio:SetPoint("CENTER", "ArenaLogBrowserColumnRatio", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            ratingChange:SetPoint("CENTER", "ArenaLogBrowserColumnRatingChange", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            comp:SetPoint("CENTER", "ArenaLogBrowserColumnComp", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            date:SetPoint("CENTER", "ArenaLogBrowserColumnDate", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
        else
            name:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Name", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            ratio:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Ratio", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            ratingChange:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."RatingChange", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            comp:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Classes", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            date:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Date", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
        end        
        
        if (i%2 == 0) then
            factionLeft:SetVertexColor(1, 1, 1, 0.2);
            factionRight:SetVertexColor(1, 1, 1, 0.2);
        else
            factionLeft:SetVertexColor(1, 1, 1, 0);
            factionRight:SetVertexColor(1, 1, 1, 0);
        end
    end

    -- Set up buttons
    ArenaLogBrowserButtonGotoText:SetText(ARENALOG_VIEW_GAMES);
    local selectedRow = browser.brackets[browser.selectedBracket]["teams"]["selectedRow"];
    if selectedRow and selectedRow > 0 then
        ArenaLogBrowserButtonGoto:Enable();
    else
        ArenaLogBrowserButtonGoto:Disable();
    end
    
    ArenaLogBrowserButtonCompsText:SetText(ARENALOG_VIEW_COMPS);
    
    ArenaLogBrowserButtonBack:Disable();
end

function browser:SetupGames()
    -- Enable correct columns
    ArenaLogBrowserColumnKB:Hide()
    ArenaLogBrowserColumnDamage:Hide()
    ArenaLogBrowserColumnHealing:Hide()
    ArenaLogBrowserColumnRatio:Hide()
    ArenaLogBrowserColumnRatingChange:Show()
    ArenaLogBrowserColumnOldRating1:Show()
    ArenaLogBrowserColumnOldRating2:Show()
    ArenaLogBrowserColumnComp:Hide()
    ArenaLogBrowserColumnDate:Show()    
    ArenaLogBrowserColumnDuration:Show()
    ArenaLogBrowserColumnTeam:Hide()
    
    -- Set up columns
    ArenaLogBrowserColumnNameText:SetText(ARENALOG_COLUMNTEXT_ZONE);
    ArenaLogBrowserColumnDateText:SetText(ARENALOG_COLUMNTEXT_DATE);
    ArenaLogBrowserColumnRatingChange:SetPoint("LEFT", "ArenaLogBrowserColumnName", "RIGHT", 16, 0);
    
    --Hide scrollframe
    ArenaLogBrowserScrollFrame:Hide();

    -- Align row columns
    local rowFrame, name, ratingChange, playerRating, enemyRating, date, factionLeft, factionRight, comp, ratio, duration, team, class, killingBlows, damage, healing;

    --align each successive cell with the one above it
    for i=1, ARENALOGBROWSER_NUM_ROWS do
        rowFrame = getglobal("ArenaLogBrowserRow"..i);
        rowFrame:SetWidth(ArenaLogBrowserFrame:GetWidth()-168);
        --Obtain column objects
        name =          getglobal("ArenaLogBrowserRow"..i.."Name");
        ratingChange =  getglobal("ArenaLogBrowserRow"..i.."RatingChange");
        playerRating =  getglobal("ArenaLogBrowserRow"..i.."OldRating1");
        enemyRating =   getglobal("ArenaLogBrowserRow"..i.."OldRating2");
        date =          getglobal("ArenaLogBrowserRow"..i.."Date");
        factionLeft =   getglobal("ArenaLogBrowserRow"..i.."FactionLeft");
        factionRight =  getglobal("ArenaLogBrowserRow"..i.."FactionRight");
        ratio =         getglobal("ArenaLogBrowserRow"..i.."Ratio");
        comp =          getglobal("ArenaLogBrowserRow"..i.."Classes");
        duration =      getglobal("ArenaLogBrowserRow"..i.."Duration");
        team =          getglobal("ArenaLogBrowserRow"..i.."Team");
        class =         getglobal("ArenaLogBrowserRow"..i.."ClassIcon");
        killingBlows =  getglobal("ArenaLogBrowserRow"..i.."KB");
        damage =        getglobal("ArenaLogBrowserRow"..i.."Damage");
        healing =       getglobal("ArenaLogBrowserRow"..i.."Healing");
        
        --Show/hide
        ratingChange:Show(); date:Show();
        comp:Hide();
        ratio:Hide();
        playerRating:Show();
        enemyRating:Show();
        duration:Show();
        team:Hide();
        class:Hide(); killingBlows:Hide(); damage:Hide(); healing:Hide();
        
        if (i==1) then
            name:SetPoint("CENTER", "ArenaLogBrowserColumnName", "CENTER", 8, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            ratingChange:SetPoint("CENTER", "ArenaLogBrowserColumnRatingChange", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            playerRating:SetPoint("CENTER", "ArenaLogBrowserColumnOldRating1", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            enemyRating:SetPoint("CENTER", "ArenaLogBrowserColumnOldRating2", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            date:SetPoint("CENTER", "ArenaLogBrowserColumnDate", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            duration:SetPoint("CENTER", "ArenaLogBrowserColumnDuration", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
        else
            name:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Name", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            ratingChange:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."RatingChange", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            playerRating:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."OldRating1", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            enemyRating:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."OldRating2", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            date:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Date", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            duration:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Duration", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
        end        
        
        if (i%2 == 0) then
            factionLeft:SetVertexColor(1, 1, 1, 0.2);
            factionRight:SetVertexColor(1, 1, 1, 0.2);
        else
            factionLeft:SetVertexColor(1, 1, 1, 0);
            factionRight:SetVertexColor(1, 1, 1, 0);
        end
    end

    -- Set up buttons
    ArenaLogBrowserButtonGotoText:SetText(ARENALOG_VIEW_SCORES);
    local selectedRow = browser.brackets[browser.selectedBracket]["games"]["selectedRow"];
    if selectedRow and selectedRow > 0 then
        ArenaLogBrowserButtonGoto:Enable();
    else
        ArenaLogBrowserButtonGoto:Disable();
    end

    ArenaLogBrowserButtonBack:Enable();
end

function browser:SetupScores()
    -- Enable correct columns
    ArenaLogBrowserColumnKB:Show()
    ArenaLogBrowserColumnDamage:Show()
    ArenaLogBrowserColumnHealing:Show()
    ArenaLogBrowserColumnRatio:Hide()
    ArenaLogBrowserColumnRatingChange:Hide()
    ArenaLogBrowserColumnOldRating1:Hide()
    ArenaLogBrowserColumnOldRating2:Hide()
    ArenaLogBrowserColumnComp:Hide()
    ArenaLogBrowserColumnDate:Hide()    
    ArenaLogBrowserColumnDuration:Hide()
    ArenaLogBrowserColumnTeam:Show()
    
    -- Set up columns
    ArenaLogBrowserColumnNameText:SetText(ARENALOG_COLUMNTEXT_PLAYER);
    
    --Hide scrollframe
    ArenaLogBrowserScrollFrame:Hide();

    -- Align row columns
    local rowFrame, name, ratingChange, playerRating, enemyRating, date, factionLeft, factionRight, comp, ratio, duration, team, class, killingBlows, damage, healing;

    --align each successive cell with the one above it
    for i=1, ARENALOGBROWSER_NUM_ROWS do
        rowFrame = getglobal("ArenaLogBrowserRow"..i);
        rowFrame:SetWidth(ArenaLogBrowserFrame:GetWidth()-168);
        --Obtain column objects
        name =          getglobal("ArenaLogBrowserRow"..i.."Name");
        killingBlows =  getglobal("ArenaLogBrowserRow"..i.."KB");
        damage =        getglobal("ArenaLogBrowserRow"..i.."Damage");
        healing =       getglobal("ArenaLogBrowserRow"..i.."Healing");
        ratingChange =  getglobal("ArenaLogBrowserRow"..i.."RatingChange");
        playerRating =  getglobal("ArenaLogBrowserRow"..i.."OldRating1");
        enemyRating =   getglobal("ArenaLogBrowserRow"..i.."OldRating2");
        date =          getglobal("ArenaLogBrowserRow"..i.."Date");
        factionLeft =   getglobal("ArenaLogBrowserRow"..i.."FactionLeft");
        factionRight =  getglobal("ArenaLogBrowserRow"..i.."FactionRight");
        ratio =         getglobal("ArenaLogBrowserRow"..i.."Ratio");
        comp =          getglobal("ArenaLogBrowserRow"..i.."Classes");
        duration =      getglobal("ArenaLogBrowserRow"..i.."Duration");
        team =          getglobal("ArenaLogBrowserRow"..i.."Team");
        class =         getglobal("ArenaLogBrowserRow"..i.."ClassIcon");
        
        --Show/hide
        killingBlows:Show();
        damage:Show();
        healing:Show();
        comp:Hide();
        ratio:Hide();
        playerRating:Hide();
        enemyRating:Hide();
        duration:Hide();
        team:Show();
        class:Show();
        ratingChange:Hide();
        date:Hide();
        
        if (i==1) then
            class:SetPoint("CENTER", "ArenaLogBrowserColumnName", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET);
            name:SetPoint("CENTER", "ArenaLogBrowserColumnName", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            team:SetPoint("CENTER", "ArenaLogBrowserColumnTeam", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            killingBlows:SetPoint("CENTER", "ArenaLogBrowserColumnKB", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            damage:SetPoint("CENTER", "ArenaLogBrowserColumnDamage", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            healing:SetPoint("CENTER", "ArenaLogBrowserColumnHealing", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);            
        else
            class:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."ClassIcon", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            name:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Name", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            team:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Team", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            killingBlows:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."KB", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            damage:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Damage", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            healing:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Healing", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);     
        end        
        
        if (i%2 == 0) then
            factionLeft:SetVertexColor(1, 1, 1, 0.2);
            factionRight:SetVertexColor(1, 1, 1, 0.2);
        else
            factionLeft:SetVertexColor(1, 1, 1, 0);
            factionRight:SetVertexColor(1, 1, 1, 0);
        end
    end

    -- Set up buttons
    ArenaLogBrowserButtonGoto:Disable();
    ArenaLogBrowserButtonBack:Enable();
end

function browser:SetupComps()
    -- Enable correct columns
    ArenaLogBrowserColumnKB:Hide()
    ArenaLogBrowserColumnDamage:Hide()
    ArenaLogBrowserColumnHealing:Hide()
    ArenaLogBrowserColumnRatio:Show()
    ArenaLogBrowserColumnRatingChange:Show()
    ArenaLogBrowserColumnOldRating1:Hide()
    ArenaLogBrowserColumnOldRating2:Hide()
    ArenaLogBrowserColumnComp:Show()
    ArenaLogBrowserColumnDate:Hide()    
    ArenaLogBrowserColumnDuration:Hide()
    ArenaLogBrowserColumnTeam:Hide()
    ArenaLogBrowserColumnName:Hide()
    
    --local compWidth = browser.brackets[browser.selectedBracket]["size"] * 17;
    local compWidth = 5 * 17;
    -- Set up columns
    ArenaLogBrowserColumnComp:SetWidth(compWidth);
    ArenaLogBrowserColumnComp:SetPoint("LEFT", "ArenaLogBrowserColumnName", "LEFT", 8, 0);    
    ArenaLogBrowserColumnRatio:SetPoint("LEFT", "ArenaLogBrowserColumnComp", "RIGHT", 24, 0);
    
    --Hide scrollframe
    ArenaLogBrowserScrollFrame:Hide();

    -- Align row columns
    local rowFrame, name, ratingChange, playerRating, enemyRating, date, factionLeft, factionRight, comp, ratio, duration, team, class, killingBlows, damage, healing;

    --align each successive cell with the one above it
    for i=1, ARENALOGBROWSER_NUM_ROWS do
        rowFrame = getglobal("ArenaLogBrowserRow"..i);
        rowFrame:SetWidth(ArenaLogBrowserFrame:GetWidth()-168);
        --Obtain column objects
        name =          getglobal("ArenaLogBrowserRow"..i.."Name");
        killingBlows =  getglobal("ArenaLogBrowserRow"..i.."KB");
        damage =        getglobal("ArenaLogBrowserRow"..i.."Damage");
        healing =       getglobal("ArenaLogBrowserRow"..i.."Healing");
        ratingChange =  getglobal("ArenaLogBrowserRow"..i.."RatingChange");
        playerRating =  getglobal("ArenaLogBrowserRow"..i.."OldRating1");
        enemyRating =   getglobal("ArenaLogBrowserRow"..i.."OldRating2");
        date =          getglobal("ArenaLogBrowserRow"..i.."Date");
        factionLeft =   getglobal("ArenaLogBrowserRow"..i.."FactionLeft");
        factionRight =  getglobal("ArenaLogBrowserRow"..i.."FactionRight");
        ratio =         getglobal("ArenaLogBrowserRow"..i.."Ratio");
        comp =          getglobal("ArenaLogBrowserRow"..i.."Classes");
        duration =      getglobal("ArenaLogBrowserRow"..i.."Duration");
        team =          getglobal("ArenaLogBrowserRow"..i.."Team");
        class =         getglobal("ArenaLogBrowserRow"..i.."ClassIcon");
        
        --Show/hide
        killingBlows:Hide();    damage:Hide();  healing:Hide();
        comp:Show();            ratio:Show();   playerRating:Hide();
        enemyRating:Hide();     duration:Hide();    team:Hide();
        class:Hide();           ratingChange:Show();    date:Hide();
        name:Hide();
        
        comp:SetWidth(compWidth);
        
        
        
        if (i==1) then
            ratio:SetPoint("CENTER", "ArenaLogBrowserColumnRatio", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            ratingChange:SetPoint("CENTER", "ArenaLogBrowserColumnRatingChange", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
            comp:SetPoint("CENTER", "ArenaLogBrowserColumnComp", "CENTER", 0, ARENALOGBROWSER_ROW_TEXT_OFFSET+6);
        else
            ratio:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Ratio", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            ratingChange:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."RatingChange", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
            comp:SetPoint("CENTER", "ArenaLogBrowserRow"..(i-1).."Classes", "CENTER", 0, -ARENALOGBROWSER_ROW_HEIGHT);
        end        
        
        if (i%2 == 0) then
            factionLeft:SetVertexColor(1, 1, 1, 0.2);
            factionRight:SetVertexColor(1, 1, 1, 0.2);
        else
            factionLeft:SetVertexColor(1, 1, 1, 0);
            factionRight:SetVertexColor(1, 1, 1, 0);
        end
    end

    -- Set up buttons
    ArenaLogBrowserButtonGoto:Disable();
    ArenaLogBrowserButtonBack:Disable();
    
    ArenaLogBrowserButtonCompsText:SetText(ARENALOG_VIEW_TEAMS);
end

function browser:UpdateRows()
    local teamName = browser.selectedTeam;
    
    -- Get current cache set
    local pane = browser.brackets[browser.selectedBracket]["currentPanel"];
    local db;
    if teamName ~= nil then        
        db = ArenaLog_BrowserCache[teamName][pane];
    else
        db = {}
    end
    
    local rowFrame, name, ratio, ratingChange, comp, dateStr, classIcon, iconTex, bgLeft, bgRight, playerRating, enemyRating, duration, class, team, kills, damage, healing;
    
    -- Update scrollframe
    local hasScrollBar, scrollOffset = 0, 0;
	if ( #db > ARENALOGBROWSER_NUM_ROWS ) then
		hasScrollBar = 1;
		ArenaLogBrowserScrollFrame:Show();
        FauxScrollFrame_Update(ArenaLogBrowserScrollFrame, #db, ARENALOGBROWSER_NUM_ROWS, ARENALOGBROWSER_ROW_HEIGHT );
        scrollOffset = FauxScrollFrame_GetOffset(ArenaLogBrowserScrollFrame);
        browser.brackets[browser.selectedBracket][pane]["scrollOffset"] = scrollOffset;
	else
		ArenaLogBrowserScrollFrame:Hide();
    end
    
    local selectedRow = browser.brackets[browser.selectedBracket][pane]["selectedRow"];
    if selectedRow == nil then selectedRow = 0 end;
    
    for i=1, ARENALOGBROWSER_NUM_ROWS do
        rowFrame = getglobal("ArenaLogBrowserRow"..i);
        
        if db[i+scrollOffset] ~= nil then
            local row = db[i+scrollOffset];
            
            bgLeft =        getglobal("ArenaLogBrowserRow"..i.."FactionLeft");
            bgRight =       getglobal("ArenaLogBrowserRow"..i.."FactionRight");
            
            if pane == "teams" then
                --Obtain column objects
                name =          getglobal("ArenaLogBrowserRow"..i.."Name");
                ratio =         getglobal("ArenaLogBrowserRow"..i.."Ratio");
                ratingChange =  getglobal("ArenaLogBrowserRow"..i.."RatingChange");
                dateStr =       getglobal("ArenaLogBrowserRow"..i.."Date");
                compFrame =     getglobal("ArenaLogBrowserRow"..i.."Classes");                
                
                --Format column objects
                local ratioColor, ratingColor;
                if row["wins"] >= row["losses"] then ratioColor = "|c0000ff00" else ratioColor = "|c00ff0000" end;
                if row["ratingChange"] >= 0 then ratingColor = "|c0000ff00" else ratingColor = "|c00ff0000" end;
                name:SetText("|c0000ffff"..row["name"].."|r|c00ffffff - "..row["realm"].."|r");
                ratio:SetText(ratioColor..row["wins"].." : "..row["losses"].."|r");
                ratingChange:SetText(ratingColor..row["ratingChange"].."|r");
                dateStr:SetText(date("%m/%d/%y %I:%M %p", row["lastPlayed"]));

                -- Set comp icons
                for k=1, ARENALOGBROWSER_NUM_CLASS_ICONS do                    
                    classIcon = getglobal("ArenaLogBrowserRow"..i.."ClassesIcon"..k);
                    if row["comp"][k] ~= nil then
                        iconTex = ArenaLog_ClassIcons[ArenaLog.classTable[ row["comp"][k] ]];
                        classIcon:Show();
                        classIcon:SetTexCoord(iconTex[1], iconTex[2], iconTex[3], iconTex[4]);
                    else
                        classIcon:Hide();
                    end                    
                end                
                compFrame:SetWidth(17 * #row["comp"]);     
                
            elseif pane == "games" then
                name =          getglobal("ArenaLogBrowserRow"..i.."Name");
                ratingChange =  getglobal("ArenaLogBrowserRow"..i.."RatingChange");
                playerRating =  getglobal("ArenaLogBrowserRow"..i.."OldRating1");
                enemyRating =   getglobal("ArenaLogBrowserRow"..i.."OldRating2");
                dateStr =       getglobal("ArenaLogBrowserRow"..i.."Date");
                duration =      getglobal("ArenaLogBrowserRow"..i.."Duration");

                local ratingColor, winColor;
                if (row["playerTeamRatingNew"] - row["playerTeamRatingOld"]) >= 0 then ratingColor = "|c0000ff00" else ratingColor = "|c00ff0000" end;
                if row["winner"] == true then winColor = "|c0000ff00" else winColor = "|c00ff0000" end;
                
                local duration_min = floor(row["duration"] / 60);
                local duration_sec = row["duration"] % 60;
                if (duration_sec < 10) then duration_sec = "0"..duration_sec end;
                
                local mm_text_player, mm_text_enemy = "", "";
                if row["enemyTeamSkill"] ~= nil then mm_text_enemy = " |cff88aabb[" .. row["enemyTeamSkill"] .. "]|r" end;
                if row["playerTeamSkill"] ~= nil then mm_text_player = " |cff88aabb[" .. row["playerTeamSkill"] .. "]|r" end;

                name:SetText(winColor..row["zone"].."|r");
                ratingChange:SetText(ratingColor..(row["playerTeamRatingNew"] - row["playerTeamRatingOld"]).."|r");
                playerRating:SetText(row["playerTeamRatingOld"] .. mm_text_player);
                enemyRating:SetText(row["enemyTeamRatingOld"] .. mm_text_enemy);
                dateStr:SetText(date("%m/%d/%y %I:%M %p", row["timestamp"]));
                duration:SetText(duration_min..":"..duration_sec);
                
            elseif pane == "scores" then
                class =     getglobal("ArenaLogBrowserRow"..i.."ClassIcon");
                name =      getglobal("ArenaLogBrowserRow"..i.."Name");
                team =      getglobal("ArenaLogBrowserRow"..i.."Team");
                kills =     getglobal("ArenaLogBrowserRow"..i.."KB");
                damage =    getglobal("ArenaLogBrowserRow"..i.."Damage");
                healing =   getglobal("ArenaLogBrowserRow"..i.."Healing");
                
                local teamColor;
                if row["team"] == teamName then teamColor = "|c0000ff00" else teamColor = "|c00ff0000" end;
                iconTex = ArenaLog_ClassIcons[ArenaLog.classTable[row["filename"]]];
                local classColor = ArenaLog_ClassColors[ArenaLog.classTable[row["filename"]]];
                
                class:SetTexCoord(iconTex[1], iconTex[2], iconTex[3], iconTex[4]);                
                name:SetText("         "..classColor..row["name"].."|r");
                team:SetText(teamColor..row["team"].."|r");
                kills:SetText(row["kills"]);
                damage:SetText(row["damage"]);
                healing:SetText(row["healing"]); 
                
            elseif pane == "comps" then
                --Obtain column objects
                ratio =         getglobal("ArenaLogBrowserRow"..i.."Ratio");
                ratingChange =  getglobal("ArenaLogBrowserRow"..i.."RatingChange");
                compFrame =     getglobal("ArenaLogBrowserRow"..i.."Classes");               
                
                --Format column objects
                local ratioColor, ratingColor;
                if row["wins"] >= row["losses"] then ratioColor = "|c0000ff00" else ratioColor = "|c00ff0000" end;
                if row["ratingChange"] >= 0 then ratingColor = "|c0000ff00" else ratingColor = "|c00ff0000" end;
                ratio:SetText(ratioColor..row["wins"].." : "..row["losses"].."|r");
                ratingChange:SetText(ratingColor..row["ratingChange"].."|r");

                -- Set comp icons
                for k=1, ARENALOGBROWSER_NUM_CLASS_ICONS do                    
                    classIcon = getglobal("ArenaLogBrowserRow"..i.."ClassesIcon"..k);
                    if row["comp"][k] ~= nil then
                        iconTex = ArenaLog_ClassIcons[(row["comp"][k] + 0)]; --Enforce numeric.  It is parsed from a string.
                        classIcon:Show();
                        classIcon:SetTexCoord(iconTex[1], iconTex[2], iconTex[3], iconTex[4]);
                    else
                        classIcon:Hide();
                    end                    
                end                
                compFrame:SetWidth(17 * #row["comp"]);     
            
            end
            
            -- Set highlighted row
            if (i+scrollOffset == selectedRow) then
                bgLeft:SetVertexColor(1, 1, 0, 0.8);
                bgRight:SetVertexColor(1, 1, 0, 0.8);
            else
                if (i % 2 == 0) then
                    bgLeft:SetVertexColor(1, 1, 1, 0.2);
                    bgRight:SetVertexColor(1, 1, 1, 0.2);
                else
                    bgLeft:SetVertexColor(1, 1, 1, 0);
                    bgRight:SetVertexColor(1, 1, 1, 0);
                end
            end
            
            rowFrame:Show();
        else
            rowFrame:Hide();
        end            
    end    
end

function browser:SetTab(tabIndex)
    browser.selectedBracket = tabIndex;
end

function browser.Row_OnEnter(row)
    local rowName = row:GetName();
    local bgLeft = getglobal(rowName.."FactionLeft");
    local bgRight = getglobal(rowName.."FactionRight");
    bgLeft:SetVertexColor(0.0, 1.0 , 0.0, 0.6);
    bgRight:SetVertexColor(0.0, 1.0 , 0.0, 0.6);
end

function browser.Row_OnLeave(row)
    local rowName = row:GetName();
    local bgLeft = getglobal(rowName.."FactionLeft");
    local bgRight = getglobal(rowName.."FactionRight");
    
    local pane = browser.brackets[browser.selectedBracket]["currentPanel"];
    
    local scrollOffset, selectedRow = 0, 0;
    if (ArenaLogBrowserScrollFrame:IsVisible()) then
        scrollOffset = FauxScrollFrame_GetOffset(ArenaLogBrowserScrollFrame);
    end    
    local selectedRow = browser.brackets[browser.selectedBracket][pane]["selectedRow"];
    if selectedRow ~= nil then selectedRow = selectedRow - scrollOffset end;
    
    if (selectedRow and row:GetID() == selectedRow) then
        bgLeft:SetVertexColor(1, 1, 0, 0.8);
        bgRight:SetVertexColor(1, 1, 0, 0.8);
    else
        if ((row:GetID() % 2) == 0) then
            bgLeft:SetVertexColor(1, 1, 1, 0.2);
            bgRight:SetVertexColor(1, 1, 1, 0.2);
        else
            bgLeft:SetVertexColor(1, 1, 1, 0);
            bgRight:SetVertexColor(1, 1, 1, 0);
        end
    end
end

function browser.Row_OnClick(row)
    local scrollOffset = 0;
    if (ArenaLogBrowserScrollFrame:IsVisible()) then
        scrollOffset = FauxScrollFrame_GetOffset(ArenaLogBrowserScrollFrame);
    end
    local pane = browser.brackets[browser.selectedBracket]["currentPanel"];
    local prevSelected = browser.brackets[browser.selectedBracket][pane]["selectedRow"];
    if prevSelected ~= nil then prevSelected = prevSelected - scrollOffset else prevSelected = 0 end;
    
    --Unselect previous row
    if (prevSelected > 0 and prevSelected <= ARENALOGBROWSER_NUM_ROWS) then --We're only doing this if the previous row was on the screen.  
        local bgLeft = getglobal("ArenaLogBrowserRow"..prevSelected.."FactionLeft");
        local bgRight = getglobal("ArenaLogBrowserRow"..prevSelected.."FactionRight");
        if (prevSelected % 2 == 0) then
            bgLeft:SetVertexColor(1, 1, 1, 0.2);
            bgRight:SetVertexColor(1, 1, 1, 0.2);
        else
            bgLeft:SetVertexColor(1, 1, 1, 0);
            bgRight:SetVertexColor(1, 1, 1, 0);
        end
    end
    
    --Select new row
    browser.brackets[browser.selectedBracket][pane]["selectedRow"] = row:GetID() + scrollOffset;
    
    local rowName = row:GetName();
    bgLeft = getglobal(rowName.."FactionLeft");
    bgRight = getglobal(rowName.."FactionRight");
    bgLeft:SetVertexColor(1, 1, 0, .8);
    bgRight:SetVertexColor(1, 1, 0, .8);
    
    -- Enable goto button
    if (pane == "teams" or pane == "games") then
        ArenaLogBrowserButtonGoto:Enable();
    end
    
    PlaySound("igMainMenuOptionCheckBoxOn");
end

function browser.GotoButton_OnClick(button)
    local pane = browser:GetCurrentPanel();
    if pane == "teams" then
        browser.brackets[browser.selectedBracket]["currentPanel"] = "games";
        browser:Update();
    elseif pane == "games" then
        browser.brackets[browser.selectedBracket]["currentPanel"] = "scores";
        browser:Update();
    end
    
    PlaySound("igMainMenuOptionCheckBoxOn");
end

function browser.BackButton_OnClick(button)
    local pane = browser:GetCurrentPanel();
    if pane == "games" then
        browser.brackets[browser.selectedBracket]["currentPanel"] = "teams";
        browser.brackets[browser.selectedBracket]["games"]["selectedRow"] = 0; -- Forget scroll position.
        browser:Update();
    elseif pane == "scores" then
        browser.brackets[browser.selectedBracket]["currentPanel"] = "games";
        browser.brackets[browser.selectedBracket]["scores"]["selectedRow"] = 0; -- Forget scroll position.
        browser:Update();
    end
    PlaySound("igMainMenuOptionCheckBoxOn");
end

function browser.CompButton_OnClick(button)
    local pane = browser:GetCurrentPanel();
    if pane == "comps" then
        browser.brackets[browser.selectedBracket]["currentPanel"] = "teams";
        browser:Update();
    else
        browser.brackets[browser.selectedBracket]["currentPanel"] = "comps";
        browser:Update();
    end
end

function ArenaLog:ShowBrowser()
    if (ArenaLogBrowserFrame:IsShown()) then
        ArenaLogBrowserFrame:Hide();
    else
        ArenaLog:UpdatePlayerTeams();
        ArenaLogBrowserFrame:Show();
    end
end

function browser.BrowserFrame_Resize(width)
	if ( not width ) then
		width=800;
	end
	
	ArenaLogBrowserFrame:SetWidth(width);
	
	ArenaLogBrowserFrameTopBackground:SetWidth(ArenaLogBrowserFrame:GetWidth()-129);
	ArenaLogBrowserFrameTopBackground:SetTexCoord(0, ArenaLogBrowserFrameTopBackground:GetWidth()/256, 0, 0.5);
	ArenaLogBrowserFrameBottomBackground:SetWidth(ArenaLogBrowserFrame:GetWidth()-129);
	ArenaLogBrowserFrameBottomBackground:SetTexCoord(0, ArenaLogBrowserFrameTopBackground:GetWidth()/256, 0, 0.5);
	ArenaLogBrowserFrame.scrollBarButtonWidth = ArenaLogBrowserFrame:GetWidth() - 165;
	ArenaLogBrowserFrame.buttonWidth = ArenaLogBrowserFrame:GetWidth() - 137;
	ArenaLogBrowserScrollFrame:SetWidth(ArenaLogBrowserFrame.scrollBarButtonWidth);
    
	return width;
end

function browser.TeamButton_OnClick()
    local teamIndex = PVPTeamDetails.team --Gets the currently opened pane
    browser:SetTab(teamIndex);
    PanelTemplates_SetTab(ArenaLogBrowserFrame, teamIndex);
    ArenaLogBrowserFrame:Show();      
    browser:Update(); 
end


ArenaLog.Browser = browser;