local function IsFilledSoulGem(bagId, slotIndex)
    return IsItemSoulGem(SOUL_GEM_TYPE_FILLED, bagId, slotIndex)
end

local function SortComparator(left, right)
    return GetSoulGemItemInfo(left.data.bag, left.data.index) < GetSoulGemItemInfo(right.data.bag, right.data.index)
end

local function ChargeSquireRebuildList()
	local listDialog = ZO_InventorySlot_GetItemListDialog()

	listDialog:ClearList()

    local itemList = PLAYER_INVENTORY:GenerateListOfVirtualStackedItems(INVENTORY_BACKPACK, IsFilledSoulGem)
    for itemId, itemInfo in pairs(itemList) do
        listDialog:AddListItem(itemInfo)
    end

	listDialog:CommitList(SortComparator)

end

local function ChargeSquireLoaded(eventCode, addOnName)
	if(addOnName ~= "ChargeSquire") then return end

	local dialog = ESO_Dialogs["CHARGE_ITEM"]

	local hookfunction = dialog.buttons[1].callback
	local charger = SOUL_GEM_ITEM_CHARGER.chargesUnderlayBar

	dialog.canQueue = true

	-- Now we hook the 'item charge' function of the dialog
	dialog.buttons[1].callback =
		function()
    		-- Find out if we're filling the bar completely
    		if charger:GetValue() < charger.max then
    			-- And queue up the same dialog if not
				ZO_Dialogs_ShowDialog("CHARGE_ITEM", ESO_Dialogs["CHARGE_ITEM"].customControl().data)
				-- And callback a relisting of the gems
    			zo_callLater(ChargeSquireRebuildList, 500)
    		end
			hookfunction()
		end

end

EVENT_MANAGER:RegisterForEvent("ChargeSquireLoaded", EVENT_ADD_ON_LOADED, ChargeSquireLoaded)