-- Shopkeeper Main Addon File
-- Last Updated August 10, 2014
-- Written July 2014 by Dan Stone (@khaibit) - dankitymao@gmail.com
-- Released under terms in license accompanying this file.
-- Distribution without license is prohibited!

-- Sort the scan results by 'ordering' order (asc/desc).
-- We sort both the search result table and the master scan results table because either we do it
-- now or we sort at separate times and try to keep track of what state each is in.  No thanks!
function Shopkeeper.SortByPrice(ordering)
  Shopkeeper.curSort[1] = "price"
  Shopkeeper.curSort[2] = ordering
  if ordering == "asc" then
    -- If they're viewing prices per-unit, then we need to sort on price / quantity.
    if Shopkeeper.savedVariables.showUnitPrice then
      table.sort(Shopkeeper.SearchTable, function(sortA, sortB)
        -- In case quantity ends up 0 or nil somehow, let's not divide by it
        if sortA[5] and sortA[5] > 0 and sortB[5] and sortB[5] > 0 then
          return (sortA[7] / sortA[5]) > (sortB[7] / sortB[5])
        else
          return sortA[7] > sortB[7]
        end
      end)
      table.sort(Shopkeeper.ScanResults, function(sortA, sortB)
        if sortA[5] and sortA[5] > 0 and sortB[5] and sortB[5] > 0 then
          return (sortA[7] / sortA[5]) > (sortB[7] / sortB[5])
        else
          return sortA[7] > sortB[7]
        end
      end)
      table.sort(Shopkeeper.SelfSales, function(sortA, sortB)
        if sortA[5] and sortA[5] > 0 and sortB[5] and sortB[5] > 0 then
          return (sortA[7] / sortA[5]) > (sortB[7] / sortB[5])
        else
          return sortA[7] > sortB[7]
        end
      end)
    -- Otherwise just sort on pure price.
    else
      table.sort(Shopkeeper.SearchTable, function(sortA, sortB)
        return sortA[7] > sortB[7]
      end)
      table.sort(Shopkeeper.ScanResults, function(sortA, sortB)
        return sortA[7] > sortB[7]
      end)
      table.sort(Shopkeeper.SelfSales, function(sortA, sortB)
        return sortA[7] > sortB[7]
      end)
    end
    ShopkeeperWindowSortPrice:SetTexture("/esoui/art/miscellaneous/list_sortheader_icon_sortup.dds")
  else
    -- And the same thing with descending sort
    if Shopkeeper.savedVariables.showUnitPrice then
      table.sort(Shopkeeper.SearchTable, function(sortA, sortB)
        return (sortA[7] / sortA[5]) < (sortB[7] / sortB[5])
      end)
      table.sort(Shopkeeper.ScanResults, function(sortA, sortB)
        return (sortA[7] / sortA[5]) < (sortB[7] / sortB[5])
      end)
      table.sort(Shopkeeper.SelfSales, function(sortA, sortB)
        return (sortA[7] / sortA[5]) < (sortB[7] / sortB[5])
      end)
    else
      table.sort(Shopkeeper.SearchTable, function(sortA, sortB)
        return sortA[7] < sortB[7]
      end)
      table.sort(Shopkeeper.ScanResults, function(sortA, sortB)
        return sortA[7] < sortB[7]
      end)
      table.sort(Shopkeeper.SelfSales, function(sortA, sortB)
        return sortA[7] < sortB[7]
      end)
    end
    ShopkeeperWindowSortPrice:SetTexture("/esoui/art/miscellaneous/list_sortheader_icon_sortdown.dds")
  end

  ShopkeeperWindowSortTime:SetTexture("/esoui/art/miscellaneous/list_sortheader_icon_neutral.dds")

  Shopkeeper.DisplayRows()
end

-- Sort the scan results by 'ordering' order (asc/desc).
-- We sort both the search result table and the master scan results table because either we do it
-- now or we sort at separate times and try to keep track of what state each is in.  No thanks!
function Shopkeeper.SortByTime(ordering)
  Shopkeeper.curSort[1] = "time"
  Shopkeeper.curSort[2] = ordering
  if ordering == "asc" then
    table.sort(Shopkeeper.SearchTable, function(sortA, sortB)
      return sortA[6] < sortB[6]
    end)
    table.sort(Shopkeeper.ScanResults, function(sortA, sortB)
      return sortA[6] < sortB[6]
    end)
    table.sort(Shopkeeper.SelfSales, function(sortA, sortB)
      return sortA[6] < sortB[6]
    end)
    ShopkeeperWindowSortTime:SetTexture("/esoui/art/miscellaneous/list_sortheader_icon_sortup.dds")
  else
    table.sort(Shopkeeper.SearchTable, function(sortA, sortB)
      return sortA[6] > sortB[6]
    end)
    table.sort(Shopkeeper.ScanResults, function(sortA, sortB)
      return sortA[6] > sortB[6]
    end)
    table.sort(Shopkeeper.SelfSales, function(sortA, sortB)
      return sortA[6] > sortB[6]
    end)
    ShopkeeperWindowSortTime:SetTexture("/esoui/art/miscellaneous/list_sortheader_icon_sortdown.dds")
  end

  ShopkeeperWindowSortPrice:SetTexture("/esoui/art/miscellaneous/list_sortheader_icon_neutral.dds")

  Shopkeeper.DisplayRows()
end

-- A convenience function to switch betwteen ascending and descending sort
-- as well as between price and time sorting if the other is currently active
function Shopkeeper.PriceSort()
  if Shopkeeper.curSort[1] == "price" and Shopkeeper.curSort[2] == "desc" then
    Shopkeeper.SortByPrice("asc")
  else
    Shopkeeper.SortByPrice("desc")
  end
end

-- A convenience function to switch betwteen ascending and descending sort
-- as well as between price and time sorting if the other is currently active
function Shopkeeper.TimeSort()
  if Shopkeeper.curSort[1] == "time" and Shopkeeper.curSort[2] == "desc" then
    Shopkeeper.SortByTime("asc")
  else
    Shopkeeper.SortByTime("desc")
  end
end

-- Calculate some stats based on the player's sales
-- And return them as a table.
function Shopkeeper.SalesStats(statsDays)
  local itemsSold = 0
  local goldMade = 0
  local largestSingle = {0, nil}
  local oldestTime = 0
  local newestTime = 0
  local kioskSales = 0
  -- 86,400 seconds in a day; this will be the epoch time statsDays ago
  local statsDaysEpoch = GetTimeStamp() - (86400 * statsDays)

  -- Loop through the player's sales and create the stats as appropriate
  -- (everything or everything with a timestamp after statsDaysEpoch)
  for i = 1, #Shopkeeper.SelfSales do
    local theItem = Shopkeeper.SelfSales[i]
    if statsDays == 0 or theItem[6] > statsDaysEpoch then
      itemsSold = itemsSold + 1
      if #theItem > 8 and theItem[9] then
        kioskSales = kioskSales + 1
      end
      goldMade = goldMade + theItem[7]
      if oldestTime == 0 or theItem[6] < oldestTime then oldestTime = theItem[6] end
      if newestTime == 0 or theItem[6] > newestTime then newestTime = theItem[6] end
      if theItem[7] > largestSingle[1] then largestSingle = {theItem[7], theItem[3]} end
     end
  end

  -- Newest timestamp seen minus oldest timestamp seen is the number of seconds between
  -- them; divided by 86,400 it's the number of days (or at least close enough for this)
  local timeWindow = newestTime - oldestTime
  local dayWindow = 1
  if timeWindow > 86400 then dayWindow = math.floor(timeWindow / 86400) + 1 end
  local goldPerDay = math.floor(goldMade / dayWindow)
  local kioskPercentage = 0
  if itemsSold > 0 then
    kioskPercentage = math.floor((kioskSales / itemsSold) * 100)
  end

  -- If they have the option set to show prices post-cut, calculate that here
  if not Shopkeeper.savedVariables.showFullPrice then
    local cutMult = 1 - (GetTradingHouseCutPercentage() / 100)
    goldMade = math.floor(goldMade * cutMult + 0.5)
    goldPerDay = math.floor(goldPerDay * cutMult + 0.5)
    largestSingle[1] = math.floor(largestSingle[1] * cutMult + 0.5)
  end

  -- Return the statistical data in a convenient table
  return { numSold = itemsSold,
           numDays = dayWindow,
           totalGold = goldMade,
           avgGold = goldPerDay,
           biggestSale = largestSingle,
           kioskPercent = kioskPercentage, }
end

-- Update all the fields of the stats window based on the response from SalesStats()
function Shopkeeper.UpdateStatsWindow()
  local sliderLevel = ShopkeeperStatsWindowSlider:GetValue()
  if sliderLevel == 0 then
    ShopkeeperStatsWindowSliderSettingLabel:SetText(Shopkeeper.translate('statsTimeAll'))
  else
    ShopkeeperStatsWindowSliderSettingLabel:SetText(string.format(Shopkeeper.translate('statsTimeSome'), sliderLevel))
  end

  local newStats = Shopkeeper.SalesStats(sliderLevel)
  ShopkeeperStatsWindowItemsSoldLabel:SetText(string.format(Shopkeeper.translate('statsItemsSold'), Shopkeeper.localizedNumber(newStats['numSold']), newStats['kioskPercent']))
  ShopkeeperStatsWindowTotalGoldLabel:SetText(string.format(Shopkeeper.translate('statsTotalGold'), Shopkeeper.localizedNumber(newStats['totalGold']), Shopkeeper.localizedNumber(newStats['avgGold'])))
  ShopkeeperStatsWindowBiggestSaleLabel:SetText(string.format(Shopkeeper.translate('statsBiggest'), zo_strformat("<<t:1>>", newStats['biggestSale'][2]), Shopkeeper.localizedNumber(newStats['biggestSale'][1])))
end

-- LibAddon init code
function Shopkeeper:LibAddonInit()
  local LAM = LibStub("LibAddonMenu-2.0")
  if LAM then
    local LMP = LibStub("LibMediaProvider-1.0")
    if LMP then
      local panelData = {
        type = "panel",
        name = "Shopkeeper",
        displayName = "Shopkeeper",
        author = "Khaibit",
        version = Shopkeeper.version,
        registerForDefaults = true,
      }
      LAM:RegisterAddonPanel("ShopkeeperOptions", panelData)

      local optionsData = {
        [1] = {
          type = "submenu",
          name = Shopkeeper.translate('alertOptionsName'),
          tooltip = Shopkeeper.translate('alertOptionsTip'),
          controls = {
            [1] = {
              type = "checkbox",
              name = Shopkeeper.translate('saleAlertAnnounceName'),
              tooltip = Shopkeeper.translate('saleAlertAnnounceTip'),
              getFunc = function() return Shopkeeper.savedVariables.showAnnounceAlerts end,
              setFunc = function(value) Shopkeeper.savedVariables.showAnnounceAlerts = value end,
            },
            [2] = {
              type = "checkbox",
              name = Shopkeeper.translate('saleAlertChatName'),
              tooltip = Shopkeeper.translate('saleAlertChatTip'),
              getFunc = function() return Shopkeeper.savedVariables.showChatAlerts end,
              setFunc = function(value) Shopkeeper.savedVariables.showChatAlerts = value end,
            },
            [3] = {
              type = "dropdown",
              name = Shopkeeper.translate('alertTypeName'),
              tooltip = Shopkeeper.translate('alertTypeTip'),
              choices = Shopkeeper.soundKeys(),
              getFunc = function() return Shopkeeper.searchSounds(Shopkeeper.savedVariables.alertSoundName) end,
              setFunc = function(value)
                Shopkeeper.savedVariables.alertSoundName = Shopkeeper.searchSoundNames(value)
                PlaySound(Shopkeeper.savedVariables.alertSoundName)
              end,
            },
            [4] = {
              type = "checkbox",
              name = Shopkeeper.translate('multAlertName'),
              tooltip = Shopkeeper.translate('multAlertTip'),
              getFunc = function() return Shopkeeper.savedVariables.showMultiple end,
              setFunc = function(value) Shopkeeper.savedVariables.showMultiple = value end,
            },
          },
        },
        [2] = {
          type = "checkbox",
          name = Shopkeeper.translate('openMailName'),
          tooltip = Shopkeeper.translate('openMailTip'),
          getFunc = function() return Shopkeeper.savedVariables.openWithMail end,
          setFunc = function(value)
            Shopkeeper.savedVariables.openWithMail = value
            if value then
              -- Register for the mail scenes
              MAIL_INBOX_SCENE:AddFragment(Shopkeeper.uiFragment)
              MAIL_SEND_SCENE:AddFragment(Shopkeeper.uiFragment)
            else
              -- Unregister for the mail scenes
              MAIL_INBOX_SCENE:RemoveFragment(Shopkeeper.uiFragment)
              MAIL_SEND_SCENE:RemoveFragment(Shopkeeper.uiFragment)
            end
          end,
        },
        [3] = {
          type = "checkbox",
          name = Shopkeeper.translate('openStoreName'),
          tooltip = Shopkeeper.translate('openStoreTip'),
          getFunc = function() return Shopkeeper.savedVariables.openWithStore end,
          setFunc = function(value)
            Shopkeeper.savedVariables.openWithStore = value
            if value then
              -- Register for the store scene
              TRADING_HOUSE_SCENE:AddFragment(Shopkeeper.uiFragment)
            else
              -- Unregister for the store scene
              TRADING_HOUSE_SCENE:RemoveFragment(Shopkeeper.uiFragment)
            end
          end,
        },
        [4] = {
          type = "checkbox",
          name = Shopkeeper.translate('fullSaleName'),
          tooltip = Shopkeeper.translate('fullSaleTip'),
          getFunc = function() return Shopkeeper.savedVariables.showFullPrice end,
          setFunc = function(value)
            Shopkeeper.savedVariables.showFullPrice = value
            Shopkeeper.DisplayRows()
          end,
        },
        [5] = {
          type = "slider",
          name = Shopkeeper.translate('scanFreqName'),
          tooltip = Shopkeeper.translate('scanFreqTip'),
          min = 60,
          max = 600,
          getFunc = function() return Shopkeeper.savedVariables.scanFreq end,
          setFunc = function(value)
            Shopkeeper.savedVariables.scanFreq = value
            EVENT_MANAGER:UnregisterForUpdate(Shopkeeper.name)
            local scanInterval = value * 1000
            EVENT_MANAGER:RegisterForUpdate(Shopkeeper.name, scanInterval, function() Shopkeeper:ScanStores(false) end)
          end,
        },
        [6] = {
          type = "slider",
          name = Shopkeeper.translate('historyDepthName'),
          tooltip = Shopkeeper.translate('historyDepthTip'),
          min = 500,
          max = 7500,
          getFunc = function() return Shopkeeper.savedVariables.historyDepth end,
          setFunc = function(value) Shopkeeper.savedVariables.historyDepth = value end,
        },
        [7] = {
          type = "dropdown",
          name = Shopkeeper.translate('windowFontName'),
          tooltip = Shopkeeper.translate('windowFontTip'),
          choices = LMP:List(LMP.MediaType.FONT),
          getFunc = function() return Shopkeeper.savedVariables.windowFont end,
          setFunc = function(value)
            Shopkeeper.savedVariables.windowFont = value
            Shopkeeper.UpdateFonts()
          end,
        },
      }
      LAM:RegisterOptionControls("ShopkeeperOptions", optionsData)
    end
  end
end

-- Filters the ScanResults (or SelfSales) table into the SearchTable,
-- using the Shopkeeper.viewMode to determine which one to use.
function Shopkeeper.DoSearch(searchText)
  Shopkeeper.SearchTable = {}
  local searchTerm = string.lower(searchText)
  local acctName = GetDisplayName()
  local tableToUse = Shopkeeper.ScanResults
  if Shopkeeper.viewMode == "self" then tableToUse = Shopkeeper.SelfSales end

  -- Actually carry out the search
  for j = 1, #tableToUse do
    local result = tableToUse[j]
    if result then
      if searchText == nil or searchText == " " then
        table.insert(Shopkeeper.SearchTable, result)
      else
        for i = 1, 3 do
          local fixedTerm = result[i]
          if i == 3 then
            fixedTerm = GetItemLinkName(fixedTerm)
          end

          if string.lower(fixedTerm):find(searchTerm) then
            if result[i] ~= nil then
              table.insert(Shopkeeper.SearchTable, result)
              break
            end
          end
        end
      end
    end
  end

  Shopkeeper.DisplayRows()
end

-- Switch between all sales and your sales
function Shopkeeper.SwitchViewMode()
  if Shopkeeper.viewMode == "self" then
    ShopkeeperSwitchViewButton:SetText(Shopkeeper.translate('viewModeYourName'))
    ShopkeeperWindowTitle:SetText("Shopkeeper - " .. Shopkeeper.translate('allSalesTitle'))
    ShopkeeperMiniSwitchViewButton:SetText(Shopkeeper.translate('viewModeYourName'))
    ShopkeeperMiniWindowTitle:SetText("Shopkeeper - " .. Shopkeeper.translate('allSalesTitle'))
    Shopkeeper.viewMode = "all"
  else
    ShopkeeperSwitchViewButton:SetText(Shopkeeper.translate('viewModeAllName'))
    ShopkeeperWindowTitle:SetText("Shopkeeper - " .. Shopkeeper.translate('yourSalesTitle'))
    ShopkeeperMiniSwitchViewButton:SetText(Shopkeeper.translate('viewModeAllName'))
    ShopkeeperMiniWindowTitle:SetText("Shopkeeper - " .. Shopkeeper.translate('yourSalesTitle'))
    Shopkeeper.viewMode = "self"
  end

  if Shopkeeper.savedVariables.viewSize == "full" then
    Shopkeeper.DoSearch(ShopkeeperWindowSearchBox:GetText())
  else
    Shopkeeper.DoSearch(ShopkeeperMiniWindowSearchBox:GetText())
  end
end

function Shopkeeper.SwitchPriceMode()
  if Shopkeeper.savedVariables.showUnitPrice then
    Shopkeeper.savedVariables.showUnitPrice = false
    ShopkeeperPriceSwitchButton:SetText(Shopkeeper.translate('showUnitPrice'))
    ShopkeeperWindowPrice:SetText(Shopkeeper.translate('priceColumnName'))
    ShopkeeperMiniPriceSwitchButton:SetText(Shopkeeper.translate('showUnitPrice'))
    ShopkeeperMiniWindowPrice:SetText(Shopkeeper.translate('priceColumnName'))
  else
    Shopkeeper.savedVariables.showUnitPrice = true
    ShopkeeperPriceSwitchButton:SetText(Shopkeeper.translate('showTotalPrice'))
    ShopkeeperWindowPrice:SetText(Shopkeeper.translate('priceEachColumnName'))
    ShopkeeperMiniPriceSwitchButton:SetText(Shopkeeper.translate('showTotalPrice'))
    ShopkeeperMiniWindowPrice:SetText(Shopkeeper.translate('priceEachColumnName'))
  end

  if Shopkeeper.curSort[1] == "price" then
    Shopkeeper.SortByPrice(Shopkeeper.curSort[2])
  else
    Shopkeeper.DisplayRows()
  end

end

-- Called after store scans complete, updates the search table
-- and slider range, then sorts the fresh table.
-- Once this is done writes out to the saved variables scan history
-- and updates the displayed table, sending a message to chat if
-- the scan was initiated via the 'refresh' button.
function Shopkeeper:PostScan(doAlert)
  if Shopkeeper.savedVariables.viewSize == "full" then
    Shopkeeper.DoSearch(ShopkeeperWindowSearchBox:GetText())
  else
    Shopkeeper.DoSearch(ShopkeeperMiniWindowSearchBox:GetText())
  end
  -- Scale the slider's range to the number of items we have minus the number of rows
  local sliderMax = 0
  local tableToUse = Shopkeeper.ScanResults
  if Shopkeeper.viewMode == "self" then tableToUse = Shopkeeper.SelfSales end
  if #tableToUse > 15 then sliderMax = (#tableToUse - 15) end
  ShopkeeperWindowSlider:SetMinMax(0, sliderMax)
  sliderMax = 0
  if #tableToUse > 8 then sliderMax = (#tableToUse - 8) end
  ShopkeeperMiniWindowSlider:SetMinMax(0, sliderMax)

  if Shopkeeper.curSort[1] == "time" then
    Shopkeeper.SortByTime(Shopkeeper.curSort[2])
  else
    Shopkeeper.SortByPrice(Shopkeeper.curSort[2])
  end
  Shopkeeper.acctSavedVariables.scanHistory = Shopkeeper.ScanResults
  Shopkeeper.DisplayRows()
  if doAlert then CHAT_SYSTEM:AddMessage("[Shopkeeper] " .. Shopkeeper.translate('refreshDone')) end

  -- If there's anything in the alert queue, handle it.
  if #Shopkeeper.alertQueue > 0 then
    -- Play an alert chime once if there are any alerts in the queue
    -- On-screen alerts play their own sounds, so only do this if they only get chat alerts
    if Shopkeeper.savedVariables.showChatAlerts and not Shopkeeper.savedVariables.showAnnounceAlerts then
      PlaySound(Shopkeeper.savedVariables.alertSoundName)
    end

    local numSold = 0
    local totalGold = 0
    local numAlerts = #Shopkeeper.alertQueue
    local lastEvent = {}
    for i = 1, numAlerts do
      local theEvent = table.remove(Shopkeeper.alertQueue, 1)
      numSold = numSold + 1

      -- Adjust the price if they want the post-cut prices instead
      local dispPrice = theEvent.salePrice
      if not Shopkeeper.savedVariables.showFullPrice then
        local cutPrice = price * (1 - (GetTradingHouseCutPercentage() / 100))
        dispPrice = math.floor(cutPrice + 0.5)
      end
      totalGold = totalGold + dispPrice

      -- If they want multiple alerts, we'll alert on each loop iteration
      -- or if there's only one.
      if Shopkeeper.savedVariables.showMultiple or numAlerts == 1 then
        -- Insert thousands separators for the price
        local stringPrice = Shopkeeper.localizedNumber(dispPrice)

        -- Only make a sound on the first one if sounds are turned on
        -- To avoid sound spam on multiple sales
        -- (Because of how and/or work in LUA, "X and Y or Z" is equivalent
        -- to the C-style ternary operator "X ? Y : Z" so long as Y is not
        -- false or nil.)
        local alertSound = (i > 1) and SOUNDS.NONE or Shopkeeper.savedVariables.alertSoundName

        -- On-screen alert - need to do something to avoid queueing identical messages in a row
        if Shopkeeper.savedVariables.showAnnounceAlerts then

          local textTime = Shopkeeper.textTimeSince(theEvent.saleTime, true)
          local alertSuffix = ""
          if lastEvent[1] ~= nil and theEvent.itemName == lastEvent[1].itemName and textTime == lastEvent[2] then
            lastEvent[3] = lastEvent[3] + 1
            alertSuffix = " (" .. lastEvent[3] .. ")"
          else
            lastEvent[1] = theEvent
            lastEvent[2] = textTime
            lastEvent[3] = 1
          end
          -- German word order differs so argument order also needs to be changed
          -- Also due to plurality differences in German, need to differentiate
          -- single item sold vs. multiple of an item sold.
          if Shopkeeper.locale == "de" then
            if theEvent.quant > 1 then
              CENTER_SCREEN_ANNOUNCE:AddMessage("ShopkeeperAlert", CSA_EVENT_SMALL_TEXT, alertSound,
                string.format(Shopkeeper.translate('salesAlertColor'), theEvent.quant, zo_strformat("<<t:1>>", theEvent.itemName),
                              stringPrice, theEvent.guild, textTime) .. alertSuffix)
            else
              CENTER_SCREEN_ANNOUNCE:AddMessage("ShopkeeperAlert", CSA_EVENT_SMALL_TEXT, alertSound,
                string.format(Shopkeeper.translate('salesAlertColorSingle'),zo_strformat("<<t:1>>", theEvent.itemName),
                              stringPrice, theEvent.guild, textTime) .. alertSuffix)
            end
          else
            CENTER_SCREEN_ANNOUNCE:AddMessage("ShopkeeperAlert", CSA_EVENT_SMALL_TEXT, alertSound,
              string.format(Shopkeeper.translate('salesAlertColor'), zo_strformat("<<t:1>>", theEvent.itemName),
                            theEvent.quant, stringPrice, theEvent.guild, textTime) .. alertSuffix)
          end
        end

        -- Chat alert
        if Shopkeeper.savedVariables.showChatAlerts then
          if Shopkeeper.locale == "de" then
            if theEvent.quant > 1 then
              CHAT_SYSTEM:AddMessage(string.format("[Shopkeeper] " .. Shopkeeper.translate('salesAlert'),
                                     theEvent.quant, zo_strformat("<<t:1>>", theEvent.itemName), stringPrice, theEvent.guild, Shopkeeper.textTimeSince(theEvent.saleTime, true)))
            else
              CHAT_SYSTEM:AddMessage(string.format("[Shopkeeper] " .. Shopkeeper.translate('salesAlertSingle'),
                                     zo_strformat("<<t:1>>", theEvent.itemName), stringPrice, theEvent.guild, Shopkeeper.textTimeSince(theEvent.saleTime, true)))
            end
          else
            CHAT_SYSTEM:AddMessage(string.format("[Shopkeeper] " .. Shopkeeper.translate('salesAlert'),
                                   zo_strformat("<<t:1>>", theEvent.itemName), theEvent.quant, stringPrice, theEvent.guild, Shopkeeper.textTimeSince(theEvent.saleTime, true)))
          end
        end
      end
    end

    -- Otherwise, we'll just alert once with a summary at the end
    if not Shopkeeper.savedVariables.showMultiple and numAlerts > 1 then
      -- Insert thousands separators for the price
      local stringPrice = Shopkeeper.localizedNumber(totalGold)

      if Shopkeeper.savedVariables.showAnnounceAlerts then
        CENTER_SCREEN_ANNOUNCE:AddMessage("ShopkeeperAlert", CSA_EVENT_SMALL_TEXT, Shopkeeper.savedVariables.alertSoundName,
          string.format(Shopkeeper.translate('salesGroupAlertColor'), numSold, stringPrice))
      else
        CHAT_SYSTEM:AddMessage(string.format("[Shopkeeper] " .. Shopkeeper.translate('salesGroupAlert'),
                               numSold, stringPrice))
      end
    end
  end

  -- Finally, update the table just in case
  Shopkeeper.DisplayRows()
end

-- Makes sure all the necessary data is there, and adds the passed-in event theEvent
-- to the ScanResults and SelfSales table.  If doAlert is true, also adds it to
-- alertQueue, which means an alert may fire during PostScan.
function Shopkeeper:InsertEvent(theEvent, doAlert)
  local thePlayer = string.lower(GetDisplayName())

  if theEvent.itemName ~= nil and theEvent.seller ~= nil and theEvent.buyer ~= nil and theEvent.salePrice ~= nil then
    -- Grab the icon
    local itemIcon, _, _, _ = GetItemLinkInfo(theEvent.itemName)

    -- Insert the entry into the ScanResults table
    table.insert(Shopkeeper.ScanResults, {theEvent.buyer, theEvent.guild, theEvent.itemName, itemIcon,
                                          theEvent.quant, theEvent.saleTime, theEvent.salePrice,
                                          theEvent.seller, theEvent.kioskSale})

    -- And then, if it's the player's sale, insert into that table
    if string.lower(theEvent.seller) == thePlayer then
      table.insert(Shopkeeper.SelfSales, {theEvent.buyer, theEvent.guild, theEvent.itemName, itemIcon,
                                          theEvent.quant, theEvent.saleTime, theEvent.salePrice,
                                          theEvent.seller, theEvent.kioskSale})
      if doAlert and (Shopkeeper.savedVariables.showChatAlerts or Shopkeeper.savedVariables.showAnnounceAlerts) then
        table.insert(Shopkeeper.alertQueue, theEvent)
      end
    end
  end
end

-- Actually carries out of the scan of a specific guild store's sales history.
-- Grabs all the members of the guild first to determine if a sale came from the
-- guild's kiosk (guild trader) or not.
-- Calls InsertEvent to actually insert the event into the ScanResults and SelfSales
-- tables.
function Shopkeeper:DoScan(guildID, checkOlder, doAlert)
  local numEvents = GetNumGuildEvents(guildID, GUILD_HISTORY_SALES)
  local prevEvents = 0
  if Shopkeeper.numEvents[guildID] ~= nil then prevEvents = Shopkeeper.numEvents[guildID] end

  if numEvents > prevEvents then
    local guildMemberInfo = {}
    -- Index the table with the account names themselves as they're
    -- (hopefully!) unique - search much faster
    for i = 1, GetNumGuildMembers(guildID) do
      local guildMemInfo, _, _, _, _ = GetGuildMemberInfo(guildID, i)
      guildMemberInfo[string.lower(guildMemInfo)] = true
    end

    for i = (prevEvents + 1), numEvents do
      local theEvent = {}
      _, theEvent.secsSince, theEvent.seller, theEvent.buyer,
      theEvent.quant, theEvent.itemName, theEvent.salePrice, _ = GetGuildEventInfo(guildID, GUILD_HISTORY_SALES, i)
      theEvent.guild = GetGuildName(guildID)
      theEvent.saleTime = GetTimeStamp() - theEvent.secsSince

      -- If we didn't add an entry to guildMemberInfo earlier setting the
      -- buyer's name index to true, then this was either bought at a kiosk
      -- or the buyer left the guild after buying but before we scanned.
      -- Close enough!
      theEvent.kioskSale = (guildMemberInfo[string.lower(theEvent.buyer)] == nil)

      -- If we're doing a deep scan, revert to timestamp checking
      -- For reasons I cannot determine, I am getting items not previously
      -- seen up to 13 seconds BEFORE the last call to RequestGuildHistoryCategoryNewest.
      -- Bizarre, but adding this fudge factor hasn't resulted in dupes...yet.
      if checkOlder then
        if Shopkeeper.acctSavedVariables.lastScan[guildID] == nil or GetDiffBetweenTimeStamps(theEvent.saleTime, (Shopkeeper.acctSavedVariables.lastScan[guildID] - 13)) >= 0 then
          Shopkeeper:InsertEvent(theEvent, false)
        end

      -- Otherwise, all new events are assumed good
      -- Inspiration for event number-based handling from sirinsidiator
      else
        Shopkeeper:InsertEvent(theEvent, true)
      end
    end
  end

  -- We got through any new (to us) events, so update the timestamp and number of events
  Shopkeeper.acctSavedVariables.lastScan[guildID] = Shopkeeper.requestTimestamp
  Shopkeeper.numEvents[guildID] = numEvents

  -- If we have another guild to scan, see if we need to check older and scan it
  if guildID < GetNumGuilds() then
    local nextGuild = guildID + 1
    local nextCheckOlder = false
    if Shopkeeper.numEvents[nextGuild] == nil or Shopkeeper.numEvents[nextGuild] == 0 then nextCheckOlder = true end
    RequestGuildHistoryCategoryNewest(nextGuild, GUILD_HISTORY_SALES)
    Shopkeeper.requestTimestamp = GetTimeStamp()
    if nextCheckOlder then
      zo_callLater(function() Shopkeeper:ScanOlder(nextGuild, doAlert) end, 1500)
    else
      zo_callLater(function() Shopkeeper:DoScan(nextGuild, false, doAlert) end, 1500)
    end
  -- Otherwise, start the postscan routines
  else
    Shopkeeper.isScanning = false
    Shopkeeper:PostScan(doAlert)
  end
end

-- Repeatedly checks for older events until there aren't anymore or we've run past
-- the timestamp of the last scan, then called DoScan to pick up sales events
function Shopkeeper:ScanOlder(guildNum, doAlert)
  local numEvents = GetNumGuildEvents(guildNum, GUILD_HISTORY_SALES)
  local _, secsSince, _, _, _, _, _, _ = GetGuildEventInfo(guildNum, GUILD_HISTORY_SALES, numEvents)
  local secsSinceScan = nil
  if Shopkeeper.acctSavedVariables.lastScan[guildNum] ~= nil then
    secsSinceScan = GetTimeStamp() - Shopkeeper.acctSavedVariables.lastScan[guildNum]
  end

  if DoesGuildHistoryCategoryHaveMoreEvents(guildNum, GUILD_HISTORY_SALES) and
     (secsSinceScan == nil or secsSinceScan > secsSince) then
    RequestGuildHistoryCategoryOlder(guildNum, GUILD_HISTORY_SALES)
    zo_callLater(function() Shopkeeper:ScanOlder(guildNum, doAlert) end, 1500)
  else
    zo_callLater(function() Shopkeeper:DoScan(guildNum, true, doAlert) end, 1500)
  end
end

-- Scans all stores a player has access to with delays between them.
function Shopkeeper:ScanStores(doAlert)
  -- If it's been less than a minute since we last scanned the store,
  -- don't do it again so we don't hammer the server either accidentally
  -- or on purpose
  local timeLimit = GetTimeStamp() - 60
  local guildNum = GetNumGuilds()
  -- Nothing to scan!
  if guildNum == 0 then return end

  if not Shopkeeper.isScanning and ((Shopkeeper.acctSavedVariables.lastScan[1] == nil) or (timeLimit > Shopkeeper.acctSavedVariables.lastScan[1])) then
    Shopkeeper.isScanning = true
    local checkOlder = false

    if Shopkeeper.numEvents[1] == nil or Shopkeeper.numEvents[1] == 0 then checkOlder = true end
    RequestGuildHistoryCategoryNewest(1, GUILD_HISTORY_SALES)

    Shopkeeper.requestTimestamp = GetTimeStamp()
    if checkOlder then
      zo_callLater(function() Shopkeeper:ScanOlder(1, doAlert) end, 1500)
    else
      zo_callLater(function() Shopkeeper:DoScan(1, checkOlder, doAlert) end, 1500)
    end
  end
end

-- Handle the refresh button - do a scan if it's been more than a minute
-- since the last successful one.
function Shopkeeper.DoRefresh()
  local timeStamp = GetTimeStamp()

  -- If it's been less than a minute since we last scanned the store,
  -- don't do it again so we don't hammer the server either accidentally
  -- or on purpose
  local timeLimit = timeStamp - 59
  local guildNum = GetNumGuilds()
  if guildNum > 0 then
    if Shopkeeper.acctSavedVariables.lastScan[1] == nil or timeLimit > Shopkeeper.acctSavedVariables.lastScan[1] then
      CHAT_SYSTEM:AddMessage("[Shopkeeper] " .. Shopkeeper.translate('refreshStart'))
      Shopkeeper:ScanStores(true)

    else
      CHAT_SYSTEM:AddMessage("[Shopkeeper] " .. Shopkeeper.translate('refreshWait'))
    end
  end
end

-- Handle the reset button - clear out the search and scan tables,
-- and set the time of the last scan to -1.  The next interval scan
-- will grab the sales histories from each guild to re-populate.
function Shopkeeper.DoReset()
  Shopkeeper.ScanResults = {}
  Shopkeeper.SelfSales = {}
  Shopkeeper.SearchTable = {}
  Shopkeeper.acctSavedVariables.scanHistory = {}
  Shopkeeper.acctSavedVariables.lastScan = {}
  Shopkeeper.DisplayRows()
  Shopkeeper.isScanning = false
  Shopkeeper.numEvents = {}
  CHAT_SYSTEM:AddMessage("[Shopkeeper] " .. Shopkeeper.translate('resetDone'))
  CHAT_SYSTEM:AddMessage("[Shopkeeper] " .. Shopkeeper.translate('refreshStart'))
  Shopkeeper:ScanStores(true)
end

-- Set up the labels and tooltips from translation files and do a couple other UI
-- setup routines
function Shopkeeper:SetupShopkeeperWindow()
  -- Shopkeeper button in guild store screen
  local reopenShopkeeper = CreateControlFromVirtual("ShopkeeperReopenButton", ZO_TradingHouseLeftPane, "ZO_DefaultButton")
  reopenShopkeeper:SetAnchor(CENTER, ZO_TradingHouseLeftPane, BOTTOM, 0, 5)
  reopenShopkeeper:SetWidth(200)
  reopenShopkeeper:SetText("Shopkeeper")
  reopenShopkeeper:SetHandler("OnClicked", Shopkeeper.ToggleShopkeeperWindow)

  -- Shopkeeper button in mail screen
  local shopkeeperMail = CreateControlFromVirtual("ShopkeeperMailButton", ZO_MailInbox, "ZO_DefaultButton")
  shopkeeperMail:SetAnchor(TOPLEFT, ZO_MailInbox, TOPLEFT, 100, 4)
  shopkeeperMail:SetWidth(200)
  shopkeeperMail:SetText("Shopkeeper")
  shopkeeperMail:SetHandler("OnClicked", Shopkeeper.ToggleShopkeeperWindow)

  -- Set column headers and search label from translation
  ShopkeeperWindowBuyer:SetText(Shopkeeper.translate('buyerColumnName'))
  ShopkeeperWindowGuild:SetText(Shopkeeper.translate('guildColumnName'))
  ShopkeeperWindowItemName:SetText(Shopkeeper.translate('itemColumnName'))
  ShopkeeperWindowSellTime:SetText(Shopkeeper.translate('timeColumnName'))
  ShopkeeperMiniWindowGuild:SetText(Shopkeeper.translate('guildColumnName'))
  ShopkeeperMiniWindowItemName:SetText(Shopkeeper.translate('itemColumnName'))
  ShopkeeperMiniWindowSellTime:SetText(Shopkeeper.translate('timeColumnName'))

  if Shopkeeper.savedVariables.showUnitPrice then
    ShopkeeperWindowPrice:SetText(Shopkeeper.translate('priceEachColumnName'))
    ShopkeeperMiniWindowPrice:SetText(Shopkeeper.translate('priceEachColumnName'))
  else
    ShopkeeperWindowPrice:SetText(Shopkeeper.translate('priceColumnName'))
    ShopkeeperMiniWindowPrice:SetText(Shopkeeper.translate('priceColumnName'))
  end
  ShopkeeperWindowSearchLabel:SetText(Shopkeeper.translate('searchBoxName'))
  ShopkeeperMiniWindowSearchLabel:SetText(Shopkeeper.translate('searchBoxName'))

  -- Set second half of window title from translation
  ShopkeeperWindowTitle:SetText("Shopkeeper - " .. Shopkeeper.translate('yourSalesTitle'))
  ShopkeeperMiniWindowTitle:SetText("Shopkeeper - " .. Shopkeeper.translate('yourSalesTitle'))

  -- And set the stats window title and slider label from translation
  ShopkeeperStatsWindowTitle:SetText("Shopkeeper " .. Shopkeeper.translate('statsTitle'))
  ShopkeeperStatsWindowSliderLabel:SetText(Shopkeeper.translate('statsDays'))

  -- Set up some helpful tooltips for the Buyer, Item, Time, and Price column headers
  ShopkeeperWindowBuyer:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('buyerTooltip')) end)

  ShopkeeperWindowItemName:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('itemTooltip')) end)

  ShopkeeperMiniWindowItemName:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('itemTooltip')) end)

  ShopkeeperWindowSellTime:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('sortTimeTip')) end)

  ShopkeeperMiniWindowSellTime:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('sortTimeTip')) end)

  ShopkeeperWindowPrice:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('sortPriceTip')) end)

  ShopkeeperMiniWindowPrice:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('sortPriceTip')) end)

  -- View switch button
  ShopkeeperSwitchViewButton:SetText(Shopkeeper.translate('viewModeAllName'))
  ShopkeeperMiniSwitchViewButton:SetText(Shopkeeper.translate('viewModeAllName'))

  -- Total / unit price switch button
  if Shopkeeper.savedVariables.showUnitPrice then
    ShopkeeperPriceSwitchButton:SetText(Shopkeeper.translate('showTotalPrice'))
  else
    ShopkeeperPriceSwitchButton:SetText(Shopkeeper.translate('showUnitPrice'))
  end

  if Shopkeeper.savedVariables.showUnitPrice then
    ShopkeeperMiniPriceSwitchButton:SetText(Shopkeeper.translate('showTotalPrice'))
  else
    ShopkeeperMiniPriceSwitchButton:SetText(Shopkeeper.translate('showUnitPrice'))
  end

  -- Refresh button
  ShopkeeperRefreshButton:SetText(Shopkeeper.translate('refreshLabel'))
  ShopkeeperMiniRefreshButton:SetText(Shopkeeper.translate('refreshLabel'))

  -- Reset button
  ShopkeeperResetButton:SetText(Shopkeeper.translate('resetLabel'))
  ShopkeeperMiniResetButton:SetText(Shopkeeper.translate('resetLabel'))

  -- Make the 15 rows that comprise the visible table
  if #Shopkeeper.DataRows == 0 then
    local dataRowOffsetX = 25
    local dataRowOffsetY = 74
    for i = 1, 15 do
      local dRow = CreateControlFromVirtual("ShopkeeperDataRow", ShopkeeperWindow, "ShopkeeperDataRow", i)
      dRow:SetSimpleAnchorParent(dataRowOffsetX, dataRowOffsetY+((dRow:GetHeight()+2)*(i-1)))
      Shopkeeper.DataRows[i] = dRow
    end
  end

  -- And 8 for the mini window
  if #Shopkeeper.MiniDataRows == 0 then
    local dataRowOffsetX = 10
    local dataRowOffsetY = 74
    for i = 1, 8 do
      local dRow = CreateControlFromVirtual("ShopkeeperMiniDataRow", ShopkeeperMiniWindow, "ShopkeeperMiniDataRow", i)
      dRow:SetSimpleAnchorParent(dataRowOffsetX, dataRowOffsetY+((dRow:GetHeight()+2)*(i-1)))
      Shopkeeper.MiniDataRows[i] = dRow
    end
  end

  -- Stats buttons
  ShopkeeperWindowStatsButton:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('statsTooltip'))
  end)
  ShopkeeperMiniWindowStatsButton:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('statsTooltip'))
  end)

  -- View size change buttons
  ShopkeeperWindowViewSizeButton:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('sizeTooltip'))
  end)
  ShopkeeperMiniWindowViewSizeButton:SetHandler("OnMouseEnter", function(self)
    ZO_Tooltips_ShowTextTooltip(self, TOP, Shopkeeper.translate('sizeTooltip'))
  end)

  -- Slider setup
  ShopkeeperWindow:SetHandler("OnMouseWheel", Shopkeeper.OnSliderMouseWheel)
  ShopkeeperWindowSlider:SetValue(0)
  ShopkeeperMiniWindow:SetHandler("OnMouseWheel", Shopkeeper.OnSliderMouseWheel)
  ShopkeeperMiniWindowSlider:SetValue(0)
  ShopkeeperStatsWindowSlider:SetValue(0)

  -- Search handler
  ZO_PreHookHandler(ShopkeeperWindowSearchBox, "OnTextChanged", function(self) Shopkeeper.DoSearch(ShopkeeperWindowSearchBox:GetText()) end)
  ZO_PreHookHandler(ShopkeeperMiniWindowSearchBox, "OnTextChanged", function(self) Shopkeeper.DoSearch(ShopkeeperMiniWindowSearchBox:GetText()) end)

  -- We're all set, so make sure we're using the right font and then update the UI
  Shopkeeper.windowFont = Shopkeeper.savedVariables.windowFont
  Shopkeeper:UpdateFonts()
  Shopkeeper.DisplayRows()
end

-- Init function
function Shopkeeper:Initialize()
  local Defaults =  {
    ["showChatAlerts"] = false,
    ["showMultiple"] = true,
    ["openWithMail"] = true,
    ["openWithStore"] = true,
    ["showFullPrice"] = true,
    ["winLeft"] = 30,
    ["winTop"] = 30,
    ["miniWinLeft"] = 30,
    ["miniWinTop"] = 30,
    ["statsWinLeft"] = 720,
    ["statsWinTop"] = 820,
    ["windowFont"] = "ProseAntique",
    ["historyDepth"] = 3000,
    ["scanFreq"] = 120,
    ["showAnnounceAlerts"] = true,
    ["alertSoundName"] = "Book_Acquired",
    ["showUnitPrice"] = false,
    ["viewSize"] = "full",
  }

  local acctDefaults = {
    ["lastScan"] = {},
    ["scanHistory"] = {},
  }

  self.savedVariables = ZO_SavedVars:New("ShopkeeperSavedVars", 1, GetDisplayName(), Defaults)
  self.acctSavedVariables = ZO_SavedVars:NewAccountWide("ShopkeeperSavedVars", 1, GetDisplayName(), acctDefaults)
  self.ScanResults = Shopkeeper.acctSavedVariables.scanHistory

  -- Update the lastScan value, as it was previously a number
  if type(Shopkeeper.acctSavedVariables.lastScan) == "number" then
    local guildNum = GetNumGuilds()
    local oldStamp = Shopkeeper.acctSavedVariables.lastScan
    Shopkeeper.acctSavedVariables.lastScan = {}
    for i = 1, guildNum do Shopkeeper.acctSavedVariables.lastScan[i] = oldStamp end
  end

  self:LibAddonInit()
  self:SetupShopkeeperWindow()
  self:RestoreWindowPosition()
  self.SortByTime("desc")

  -- We'll grab their locale now, it's really only used for a couple things as
  -- most localization is handled by the i18n/$(language).lua files
  Shopkeeper.locale = GetCVar('Language.2')
  if Shopkeeper.locale ~= "en" and Shopkeeper.locale ~= "de" and Shopkeeper.locale ~= "fr" then
    Shopkeeper.locale = "en"
  end

  -- Rather than constantly managing the length of the history, we'll just
  -- truncate it once at init-time since we now have it sorted.  As a result
  -- it will fluctuate in size depending on how active guild stores are and
  -- how long someone plays for at a time, but that's OK as it shouldn't impact
  -- performance too severely unless someone plays for 24+ hours straight
  local historyDepth = self.savedVariables.historyDepth
  if #self.ScanResults > historyDepth then
    for i = (historyDepth + 1), #self.ScanResults do
      table.remove(self.ScanResults)
    end
  end

  -- Now that we've truncated, populate the SelfSales table
  local loggedInAccount = string.lower(GetDisplayName())
  for i = 1, #self.ScanResults do
    if string.lower(self.ScanResults[i][8]) == loggedInAccount then table.insert(self.SelfSales, self.ScanResults[i]) end
  end

  -- Populate the search table
  self.DoSearch(nil)

  -- Add the shopkeeper window to the mail and trading house scenes if the
  -- player's settings indicate they want that behavior
  Shopkeeper.uiFragment = ZO_FadeSceneFragment:New(ShopkeeperWindow)
  Shopkeeper.miniUiFragment = ZO_FadeSceneFragment:New(ShopkeeperMiniWindow)

  if self.savedVariables.openWithMail then
    if self.savedVariables.viewSize == "full" then
      MAIL_INBOX_SCENE:AddFragment(Shopkeeper.uiFragment)
      MAIL_SEND_SCENE:AddFragment(Shopkeeper.uiFragment)
    else
      MAIL_INBOX_SCENE:AddFragment(Shopkeeper.miniUiFragment)
      MAIL_SEND_SCENE:AddFragment(Shopkeeper.miniUiFragment)
    end
  end

  if self.savedVariables.openWithStore then
    if self.savedVariables.viewSize == "full" then
      TRADING_HOUSE_SCENE:AddFragment(Shopkeeper.uiFragment)
    else
      TRADING_HOUSE_SCENE:AddFragment(Shopkeeper.miniUiFragment)
    end
  end

  -- Because we allow manual toggling of the Shopkeeper window in those scenes (without
  -- making that setting permanent), we also have to hide the window on closing them
  -- if they're not part of the scene.
  EVENT_MANAGER:RegisterForEvent(Shopkeeper.name, EVENT_MAIL_CLOSE_MAILBOX, function()
    if not Shopkeeper.savedVariables.openWithMail then
      ShopkeeperWindow:SetHidden(true)
      ShopkeeperMiniWindow:SetHidden(true)
    end
  end)
  EVENT_MANAGER:RegisterForEvent(Shopkeeper.name, EVENT_CLOSE_TRADING_HOUSE, function()
    if not Shopkeeper.savedVariables.openWithStore then
      ShopkeeperWindow:SetHidden(true)
      ShopkeeperMiniWindow:SetHidden(true)
    end
  end)

  -- We also want to make sure the Shopkeeper windows are hidden in the game menu
  ZO_PreHookHandler(ZO_GameMenu_InGame, "OnShow", function()
    ShopkeeperWindow:SetHidden(true)
    ShopkeeperStatsWindow:SetHidden(true)
    ShopkeeperMiniWindow:SetHidden(true)
  end)

  -- I could do this with action layer pop/push, but it's kind've a pain
  -- when it's just these I want to hook
  EVENT_MANAGER:RegisterForEvent(Shopkeeper.name, EVENT_CLOSE_BANK, function()
    ShopkeeperWindow:SetHidden(true)
    ShopkeeperMiniWindow:SetHidden(true)
  end)
  EVENT_MANAGER:RegisterForEvent(Shopkeeper.name, EVENT_CLOSE_GUILD_BANK, function()
    ShopkeeperWindow:SetHidden(true)
    ShopkeeperMiniWindow:SetHidden(true)
  end)
  EVENT_MANAGER:RegisterForEvent(Shopkeeper.name, EVENT_CLOSE_STORE, function()
    ShopkeeperWindow:SetHidden(true)
    ShopkeeperMiniWindow:SetHidden(true)
  end)
  EVENT_MANAGER:RegisterForEvent(Shopkeeper.name, EVENT_END_CRAFTING_STATION_INTERACT, function()
    ShopkeeperWindow:SetHidden(true)
    ShopkeeperMiniWindow:SetHidden(true)
  end)

  -- RegisterForUpdate lets us scan at a given interval (in ms), so we'll use that to
  -- keep the sales history updated
  local scanInterval = self.savedVariables.scanFreq * 1000
  EVENT_MANAGER:RegisterForUpdate(Shopkeeper.name, scanInterval, function() Shopkeeper:ScanStores(false) end)

  -- Right, we're all set up, so give the client a few seconds to catch up on everything
  -- and then do an initial (deep) scan in case it's been a while since the player
  -- logged on.
  zo_callLater(function() Shopkeeper:ScanStores(false) end, 5000)

end

-- Event handler for the OnAddOnLoaded event
function Shopkeeper.OnAddOnLoaded(event, addonName)
  if addonName == Shopkeeper.name then
    Shopkeeper:Initialize()
  end
end

-- Register for the OnAddOnLoaded event
EVENT_MANAGER:RegisterForEvent(Shopkeeper.name, EVENT_ADD_ON_LOADED, Shopkeeper.OnAddOnLoaded)

-- Set up /shopkeeper as a slash command toggle for the main window
SLASH_COMMANDS["/shopkeeper"] = function() Shopkeeper.ToggleShopkeeperWindow() end