local UnitIconCache = { }
local StratIconCache = { }
local bgUpCache = { }
local bgDownCache = { }
local bgOverCache = { }

local land_up = UIUtil.UIFile('/icons/units/land_up.dds')
local land_down = UIUtil.UIFile('/icons/units/land_down.dds')
local land_over = UIUtil.UIFile('/icons/units/land_over.dds')
local divider_horizontal_bmp = UIUtil.UIFile('/game/c-q-e-panel/divider_horizontal_bmp.dds')
local divider_bmp = UIUtil.UIFile('/game/c-q-e-panel/divider_bmp.dds')
local arrow_vert_bmp = UIUtil.UIFile('/game/c-q-e-panel/arrow_vert_bmp.dds')
local arrow_bmp = UIUtil.UIFile('/game/c-q-e-panel/arrow_bmp.dds')
local selection_brackets_player_highlighted = UIUtil.UIFile('/game/selection/selection_brackets_player_highlighted.dds')
local fuel = UIUtil.UIFile('/game/unit_view_icons/fuel.dds')
local default_icon = UIUtil.UIFile('/icons/units/default_icon.dds')
local glow = UIUtil.UIFile('/game/units_bmp/glow.dds')

function SetIconTextures(control, optID)
	local id = optID or control.Data.id

	-- AZ ADDITION
	-- Load the unit icons into a cache instead of retrieving it every time.
	-- This helps performance significantly.
	if id then
		if not UnitIconCache[id] then
			if DiskGetFileInfo(UIUtil.UIFile('/icons/units/'..id..'_icon.dds')) then
				UnitIconCache[id] = UIUtil.UIFile('/icons/units/'..id..'_icon.dds')
			else
				UnitIconCache[id] = default_icon
			end
		end
		control.Icon:SetTexture(UnitIconCache[id])
		
		if __blueprints[id].StrategicIconName then
			local iconName = __blueprints[id].StrategicIconName
			if DiskGetFileInfo('/textures/ui/common/game/strategicicons/'..iconName..'_rest.dds') then
				control.StratIcon:SetTexture('/textures/ui/common/game/strategicicons/'..iconName..'_rest.dds')
				control.StratIcon.Height:Set(control.StratIcon.BitmapHeight)
				control.StratIcon.Width:Set(control.StratIcon.BitmapWidth)
			else
				control.StratIcon:SetSolidColor('ff00ff00')
			end
		else
			control.StratIcon:SetSolidColor('00000000')
		end
	else
        control.Icon:SetTexture(default_icon)
        control.StratIcon:SetSolidColor('ff00ff00')
    end
    
    -- END AZ ADDITION
end

function CommonLogic()
    controls.choices:SetupScrollControls(controls.scrollMin, controls.scrollMax, controls.pageMin, controls.pageMax)
    controls.secondaryChoices:SetupScrollControls(controls.secondaryScrollMin, controls.secondaryScrollMax, controls.secondaryPageMin, controls.secondaryPageMax)
    
    controls.secondaryProgress:SetNeedsFrameUpdate(true)
    controls.secondaryProgress.OnFrame = function(self, delta)
        if sortedOptions.selection[1] and not sortedOptions.selection[1]:IsDead() and sortedOptions.selection[1]:GetWorkProgress() then
            controls.secondaryProgress:SetValue(sortedOptions.selection[1]:GetWorkProgress())
        end
        if controls.secondaryChoices.top == 1 and not controls.selectionTab:IsChecked() and not controls.constructionGroup:IsHidden() then
            self:SetAlpha(1, true)
        else
            self:SetAlpha(0, true)
        end
    end
    
    controls.secondaryChoices.SetControlToType = function(control, type)
        if type == 'spacer' then
            if controls.secondaryChoices._vertical then
                control.Icon:SetTexture(divider_horizontal_bmp)
                control.Width:Set(48)
                control.Height:Set(20)
            else
                control.Icon:SetTexture(divider_bmp)
                control.Width:Set(20)
                control.Height:Set(48)
            end
            control.Icon.Width:Set(control.Icon.BitmapWidth)
            control.Icon.Height:Set(control.Icon.BitmapHeight)
            control.Count:SetText('')
            control:Disable()
            control.StratIcon:SetSolidColor('00000000')
            control:SetSolidColor('00000000')
            control.BuildKey = nil
        elseif type == 'queuestack' or type == 'attachedunit' then
            SetIconTextures(control)
            local up, down, over, dis = GetBackgroundTextures(control.Data.id)
            control:SetNewTextures(up, down, over, dis)
            control:SetUpAltButtons(down,down,down,down)
            control.tooltipID = LOC(__blueprints[control.Data.id].Description) or 'no description'
            control.mAltToggledFlag = false
            control.Height:Set(48)
            control.Width:Set(48)
            control.Icon.Height:Set(48)
            control.Icon.Width:Set(48)
            control.BuildKey = nil
            if control.Data.count > 1 then 
                control.Count:SetText(control.Data.count)
                control.Count:SetColor('ffffffff')
            else
                control.Count:SetText('')
            end
            
            control.Icon:Show()
            control:Enable()
        end
    end
    
    controls.secondaryChoices.CreateElement = function()
        local btn = Button(controls.choices)
        
        btn.Icon = Bitmap(btn)
        btn.Icon:DisableHitTest()
        LayoutHelpers.AtCenterIn(btn.Icon, btn)
        
        btn.StratIcon = Bitmap(btn.Icon)
        btn.StratIcon:DisableHitTest()
        LayoutHelpers.AtTopIn(btn.StratIcon, btn.Icon, 4)
        LayoutHelpers.AtLeftIn(btn.StratIcon, btn.Icon, 4)
        
        btn.Count = UIUtil.CreateText(btn.Icon, '', 20, UIUtil.bodyFont)
        btn.Count:SetColor('ffffffff')
        btn.Count:SetDropShadow(true)
        btn.Count:DisableHitTest()
        LayoutHelpers.AtBottomIn(btn.Count, btn, 4)
        LayoutHelpers.AtRightIn(btn.Count, btn, 3)
        btn.Count.Depth:Set(function() return btn.Icon.Depth() + 10 end)
        
        btn.Glow = Bitmap(btn)
        btn.Glow:SetTexture(glow)
        btn.Glow:DisableHitTest()
        LayoutHelpers.FillParent(btn.Glow, btn)
        btn.Glow:SetAlpha(0)
        btn.Glow.Incrementing = 1
        btn.Glow.OnFrame = function(glow, elapsedTime)
            local curAlpha = glow:GetAlpha()
            curAlpha = curAlpha + (elapsedTime * glow.Incrementing * GLOW_SPEED)
            if curAlpha > UPPER_GLOW_THRESHHOLD then
                curAlpha = UPPER_GLOW_THRESHHOLD
                glow.Incrementing = -1
            elseif curAlpha < LOWER_GLOW_THRESHHOLD then
                curAlpha = LOWER_GLOW_THRESHHOLD
                glow.Incrementing = 1
            end
            glow:SetAlpha(curAlpha)
        end
        
        btn.HandleEvent = function(self, event)
            if event.Type == 'MouseEnter' then
                PlaySound(Sound({Cue = "UI_MFD_Rollover", Bank = "Interface"}))
                Tooltip.CreateMouseoverDisplay(self, self.tooltipID, nil, false)
            elseif event.Type == 'MouseExit' then
                Tooltip.DestroyMouseoverDisplay()
            end
            return CustomHandleEvent(self, event)	-- AZ ADDITION
        end
        
        btn.OnRolloverEvent = OnRolloverHandler
        btn.OnClick = OnClickHandler
        
        return btn
    end
    
    controls.choices.CreateElement = function()
        local btn = Button(controls.choices)
        
        btn.Icon = Bitmap(btn)
        btn.Icon:DisableHitTest()
        LayoutHelpers.AtCenterIn(btn.Icon, btn)
        
        btn.StratIcon = Bitmap(btn.Icon)
        btn.StratIcon:DisableHitTest()
        LayoutHelpers.AtTopIn(btn.StratIcon, btn.Icon, 4)
        LayoutHelpers.AtLeftIn(btn.StratIcon, btn.Icon, 4)
        
        btn.Count = UIUtil.CreateText(btn.Icon, '', 20, UIUtil.bodyFont)
        btn.Count:SetColor('ffffffff')
        btn.Count:SetDropShadow(true)
        btn.Count:DisableHitTest()
        LayoutHelpers.AtBottomIn(btn.Count, btn)
        LayoutHelpers.AtRightIn(btn.Count, btn)
        
        btn.Glow = Bitmap(btn)
        btn.Glow:SetTexture(glow)
        btn.Glow:DisableHitTest()
        LayoutHelpers.FillParent(btn.Glow, btn)
        btn.Glow:SetAlpha(0)
        btn.Glow.Incrementing = 1
        btn.Glow.OnFrame = function(glow, elapsedTime)
            local curAlpha = glow:GetAlpha()
            curAlpha = curAlpha + (elapsedTime * glow.Incrementing * GLOW_SPEED)
            if curAlpha > UPPER_GLOW_THRESHHOLD then
                curAlpha = UPPER_GLOW_THRESHHOLD
                glow.Incrementing = -1
            elseif curAlpha < LOWER_GLOW_THRESHHOLD then
                curAlpha = LOWER_GLOW_THRESHHOLD
                glow.Incrementing = 1
            end
            glow:SetAlpha(curAlpha)
        end    
        
        btn.HandleEvent = function(self, event)
            if event.Type == 'MouseEnter' then
                PlaySound(Sound({Cue = "UI_MFD_Rollover", Bank = "Interface"}))
                Tooltip.CreateMouseoverDisplay(self, self.tooltipID, nil, false)
            elseif event.Type == 'MouseExit' then
                Tooltip.DestroyMouseoverDisplay()
			end
            return CustomHandleEvent(self, event)			-- AZ ADDITION
        end
        
        btn.OnRolloverEvent = OnRolloverHandler
        btn.OnClick = OnClickHandler
        
        return btn
    end
    
    controls.choices.SetControlToType = function(control, type)
        if type == 'arrow' then
            control.Count:SetText('')
            control:Disable()
            control:SetSolidColor('00000000')
            if controls.choices._vertical then
                control.Icon:SetTexture(arrow_vert_bmp)
                control.Width:Set(48)
                control.Height:Set(20)
            else
                control.Icon:SetTexture(arrow_bmp)
                control.Width:Set(20)
                control.Height:Set(48)
            end
            control.Icon.Depth:Set(function() return control.Depth() + 5 end)
            control.Icon.Height:Set(control.Icon.BitmapHeight)
            control.Icon.Width:Set(30)
            control.StratIcon:SetSolidColor('00000000')
            control.BuildKey = nil
        elseif type == 'spacer' then
            if controls.choices._vertical then
                control.Icon:SetTexture(divider_horizontal_bmp)
                control.Width:Set(48)
                control.Height:Set(20)
            else
                control.Icon:SetTexture(divider_bmp)
                control.Width:Set(20)
                control.Height:Set(48)
            end
            control.Icon.Width:Set(control.Icon.BitmapWidth)
            control.Icon.Height:Set(control.Icon.BitmapHeight)
            control.Count:SetText('')
            control:Disable()
            control.StratIcon:SetSolidColor('00000000')
            control:SetSolidColor('00000000')
            control.BuildKey = nil
        elseif type == 'enhancement' then
            control.Icon:SetSolidColor('00000000')
            control:SetNewTextures(GetEnhancementTextures(control.Data.unitID, control.Data.icon))
            local _,down,over,_,up = GetEnhancementTextures(control.Data.unitID, control.Data.icon)
            control:SetUpAltButtons(up,up,up,up)
            control.tooltipID = LOC(control.Data.enhTable.Name) or 'no description'
            control.mAltToggledFlag = control.Data.Selected
            control.Height:Set(48)
            control.Width:Set(48)
            control.Icon.Height:Set(48)
            control.Icon.Width:Set(48)
            control.Icon.Depth:Set(function() return control.Depth() + 1 end)
            control.Count:SetText('')
            control.StratIcon:SetSolidColor('00000000')
            control.BuildKey = nil
            if control.Data.Disabled then
                control:Disable()
                if not control.Data.Selected then
                    control.Icon:SetSolidColor('aa000000')
                end
            else
                control:Enable()
            end
        elseif type == 'templates' then
            control.mAltToggledFlag = false
            SetIconTextures(control, control.Data.template.icon)
            control:SetNewTextures(GetBackgroundTextures(control.Data.template.icon))
            control.Height:Set(48)
            control.Width:Set(48)
            if control.Data.template.icon then
                control.Icon:SetTexture('/textures/ui/common/icons/units/'..control.Data.template.icon..'_icon.dds')
            else
                control.Icon:SetTexture('/textures/ui/common/icons/units/default_icon.dds')
            end
            control.Icon.Height:Set(48)
            control.Icon.Width:Set(48)
            control.Icon.Depth:Set(function() return control.Depth() + 1 end)
            control.StratIcon:SetSolidColor('00000000')
            control.tooltipID = control.Data.template.name or 'no description'
            control.BuildKey = control.Data.template.key
            if showBuildIcons and control.Data.template.key then 
                control.Count:SetText(string.char(control.Data.template.key) or '')
                control.Count:SetColor('ffff9000')
            else
                control.Count:SetText('')
            end
            control.Icon:Show()
            control:Enable()
        elseif type == 'item' then
            SetIconTextures(control)			-- HERE HERE HERE
            control:SetNewTextures(GetBackgroundTextures(control.Data.id))
            local _,down = GetBackgroundTextures(control.Data.id)
            control.tooltipID = LOC(__blueprints[control.Data.id].Description) or 'no description'
            control:SetUpAltButtons(down,down,down,down)
            control.mAltToggledFlag = false
            control.Height:Set(48)
            control.Width:Set(48)
            control.Icon.Height:Set(48)
            control.Icon.Width:Set(48)
            control.Icon.Depth:Set(function() return control.Depth() + 1 end)
            control.BuildKey = nil
            if showBuildIcons then 
                local unitBuildKeys = BuildMode.GetUnitKeys(sortedOptions.selection[1]:GetBlueprint().BlueprintId, GetCurrentTechTab())
                control.Count:SetText(unitBuildKeys[control.Data.id] or '')
                control.Count:SetColor('ffff9000')
            else
                control.Count:SetText('')
            end
            control.Icon:Show()
            control:Enable()
            
            if newTechUnits and table.find(newTechUnits, control.Data.id) then
                table.remove(newTechUnits, table.find(newTechUnits, control.Data.id))
                control.NewInd = Bitmap(control, selection_brackets_player_highlighted)
                control.NewInd.Height:Set(80)
                control.NewInd.Width:Set(80)
                LayoutHelpers.AtCenterIn(control.NewInd, control)
                control.NewInd:DisableHitTest()
                control.NewInd.Incrementing = false
                control.NewInd:SetNeedsFrameUpdate(true)
                control.NewInd.OnFrame = function(ind, delta)
                    local newAlpha = ind:GetAlpha() - delta / 5
                    if newAlpha < 0 then
                        ind:SetAlpha(0)
                        ind:SetNeedsFrameUpdate(false)
                        return
                    else
                        ind:SetAlpha(newAlpha)
                    end
                    if ind.Incrementing then
                        local newheight = ind.Height() + delta * 100
                        if newheight > 80 then
                            ind.Height:Set(80)
                            ind.Width:Set(80)
                            ind.Incrementing = false
                        else
                            ind.Height:Set(newheight)
                            ind.Width:Set(newheight)
                        end
                    else
                        local newheight = ind.Height() - delta * 100
                        if newheight < 50 then
                            ind.Height:Set(50)
                            ind.Width:Set(50)
                            ind.Incrementing = true
                        else
                            ind.Height:Set(newheight)
                            ind.Width:Set(newheight)
                        end
                    end
                end
            end
        elseif type == 'unitstack' then
            SetIconTextures(control)
            control:SetNewTextures(GetBackgroundTextures(control.Data.id))
            control.tooltipID = LOC(__blueprints[control.Data.id].Description) or 'no description'
            control.mAltToggledFlag = false
            control.Height:Set(48)
            control.Width:Set(48)
            control.Icon.Height:Set(48)
            control.Icon.Width:Set(48)
            
            -- AZ ADDITION
            -- Create the LowFuel icon only for buttons that could conceivably need it!
            -- Why GPG thought it necessary to create it for everything (including spacers) is beyond me.
            -- Even better would be to create it only when needed, but I'm lazy.
				control.LowFuel = Bitmap(control)
				control.LowFuel:SetSolidColor('ffff0000')
				control.LowFuel:DisableHitTest()
				LayoutHelpers.FillParent(control.LowFuel, control)
				control.LowFuel:DisableHitTest()
				control.LowFuel.Incrementing = 1
				control.LowFuelIcon = Bitmap(control.LowFuel, fuel)
				LayoutHelpers.AtLeftIn(control.LowFuelIcon, control, 4)
				LayoutHelpers.AtBottomIn(control.LowFuelIcon, control, 4)
				control.LowFuelIcon:DisableHitTest()
				control.LowFuel.OnFrame = function(glow, elapsedTime)
					local curAlpha = glow:GetAlpha()
					curAlpha = curAlpha + (elapsedTime * glow.Incrementing)
					if curAlpha > .4 then
						curAlpha = .4
						glow.Incrementing = -1
					elseif curAlpha < 0 then
						curAlpha = 0
						glow.Incrementing = 1
					end
					glow:SetAlpha(curAlpha)
				end
				control.LowFuel:SetAlpha(0)
				control.LowFuelIcon:SetAlpha(0)
            
            control.BuildKey = nil
            if control.Data.lowFuel then
                control.LowFuel:SetNeedsFrameUpdate(true)
                control.LowFuelIcon:SetAlpha(1)
            else
                control.LowFuel:SetNeedsFrameUpdate(false)
            end
            if table.getn(control.Data.units) > 1 then 
                control.Count:SetText(table.getn(control.Data.units))
                control.Count:SetColor('ffffffff')
            else
                control.Count:SetText('')
            end
            control.Icon:Show()
            control:Enable()
        end
    end
end

-- AZ ADDITION
-- Rewrites Button.HandleEvent to trigger OnClick when the mouse is clicked, not released.
-- Makes construction feel more responsive and fixes "dropped clicks".
function CustomHandleEvent(self, event)
    local eventHandled = false

    if event.Type == 'MouseEnter' then
        if self.mAltToggledFlag then
            self:SetTexture(self.mAltHighlight)
        else
            self:SetTexture(self.mHighlight)
        end
        self:OnRolloverEvent('enter')
        self:Play()
        if self.mRolloverCue then
            local sound = Sound({Cue = self.mRolloverCue, Bank = "Interface",})
            PlaySound(sound)
        end
        self.mMouseOver = true
        eventHandled = true
    elseif event.Type == 'MouseExit' then
        if self.mAltToggledFlag then
            self:SetTexture(self.mAltNormal)
        else
            self:SetTexture(self.mNormal)
        end
        self:OnRolloverEvent('exit')
        self:Play()
        self.mMouseOver = false
        eventHandled = true
    elseif event.Type == 'ButtonPress' or event.Type == 'ButtonDClick' then
        self:OnClick(event.Modifiers)
        if self.mClickCue then
            local sound = Sound({Cue = self.mClickCue, Bank = "Interface",})
            PlaySound(sound)
        end
        self:Play()
        eventHandled = true
    end

    return eventHandled
end

-- AZ ADDITION
-- Load these from a cache.
function GetBackgroundTextures(unitID)
    local bp = __blueprints[unitID]
    local validIcons = {land = true, air = true, sea = true, amph = true}
    local icon = bp.General.Icon
    if validIcons[icon] then
		if not bgUpCache[icon] then
			bgUpCache[icon] = UIUtil.UIFile('/icons/units/'..icon..'_up.dds')
			bgDownCache[icon] = UIUtil.UIFile('/icons/units/'..icon..'_down.dds')
			bgOverCache[icon] = UIUtil.UIFile('/icons/units/'..icon..'_over.dds')
		end
    
        return bgUpCache[icon], bgDownCache[icon], bgOverCache[icon], bgUpCache[icon]
    else
        return land_up, land_down, land_over, land_up
    end
end

function OnQueueChanged(newQueue)
    currentCommandQueue = newQueue
    if not controls.selectionTab:IsChecked() then
        SetSecondaryDisplay('buildQueue')
    end
end

function SetSecondaryDisplay(type)
    local data = { }
    
    if type == 'buildQueue' then
        if currentCommandQueue and table.getn(currentCommandQueue) > 0 then
			-- Build the queue how the game wants to build it by default.
            for index, unit in currentCommandQueue do
                table.insert(data, {type = 'queuestack', id = unit.id, count = unit.count, position = index})
            end
            
            untrimmedQueueDisplay = table.deepcopy(data)
            
            -- Now trim off stuff we don't want.
            local trimmedData = { }
            for index, queueStack in data do
				if queueStack.count > 0 then
					table.insert(trimmedData, queueStack)
				end
            end
            
            -- AZ ADDITION
            -- Merge neighboring queue items of the same unit ID.
            local i = 1
            local n = table.getn(trimmedData)
            while i + 1 <= n do
				if trimmedData[i].id == trimmedData[i + 1].id then
					trimmedData[i].count = trimmedData[i].count + trimmedData[i + 1].count
					table.remove(trimmedData, i + 1)
					n = n - 1
				else
					i = i + 1
				end
            end
            
            data = trimmedData
        end
        if table.getn(sortedOptions.selection) == 1 and table.getn(data) > 0 then
            controls.secondaryProgress:SetNeedsFrameUpdate(true)
        else
            controls.secondaryProgress:SetNeedsFrameUpdate(false)
            controls.secondaryProgress:SetAlpha(0, true)
        end
    elseif type == 'attached' then
        local attachedUnits = EntityCategoryFilterDown(categories.MOBILE, GetAttachedUnitsList(sortedOptions.selection))
        if attachedUnits and table.getn(attachedUnits) > 0 then
            for _, v in attachedUnits do
                table.insert(data, {type = 'attachedunit', id = v:GetBlueprint().BlueprintId, unit = v})
            end
        end
        controls.secondaryProgress:SetAlpha(0, true)
    end
    
    controls.secondaryChoices:Refresh(data)
end

-- AZ ADDITION
function RecursiveDecreaseBuildCountInQueue(position, count)
    local i = position
    local n = table.getn(untrimmedQueueDisplay)
    while i <= n do
		if untrimmedQueueDisplay[i].count ~= 0 then
			if untrimmedQueueDisplay[i].id == untrimmedQueueDisplay[position].id and count > 0 then
				local countRemaining = count - untrimmedQueueDisplay[i].count
				DecreaseBuildCountInQueue(i, count)
				count = countRemaining
			else
				i = n + 1
			end
		end
		i = i + 1
    end
 end

function OnClickHandler(button, modifiers)
    PlaySound(Sound({Cue = "UI_MFD_Click", Bank = "Interface"}))
    local item = button.Data
    if item.type == 'item' then
        ClearBuildTemplates()
        local blueprint = __blueprints[item.id]
        local count = 1
        local performUpgrade = false
        local buildCmd = "build"

        if modifiers.Ctrl or modifiers.Shift then
            count = 5
        end

        if modifiers.Left then
            # see if we are issuing an upgrade order
            if blueprint.General.UpgradesFrom == 'none' then
                performUpgrade = false
            else
                for i,v in sortedOptions.selection do
                    if v then   # it's possible that your unit will have died by the time this gets to it
                        local unitBp = v:GetBlueprint()
                        if blueprint.General.UpgradesFrom == unitBp.BlueprintId then
                            performUpgrade = true
                        elseif blueprint.General.UpgradesFrom == unitBp.General.UpgradesTo then
                            performUpgrade = true
                        elseif blueprint.General.UpgradesFromBase != "none" then
                            # try testing against the base
                            if blueprint.General.UpgradesFromBase == unitBp.BlueprintId then
                                performUpgrade = true
                            elseif blueprint.General.UpgradesFromBase == unitBp.General.UpgradesFromBase then
                                performUpgrade = true
                            end
                        end                        
                    end
                end
            end

            if performUpgrade then
                IssueBlueprintCommand("UNITCOMMAND_Upgrade", item.id, 1, false)
            else
                if blueprint.Physics.MotionType == 'RULEUMT_None' or EntityCategoryContains(categories.NEEDMOBILEBUILD, item.id) then
                    # stationary means it needs to be placed, so go in to build mobile mode
					import('/lua/ui/game/commandmode.lua').StartCommandMode(buildCmd, {name=item.id})
                else
                    # if the item to build can move, it must be built by a factory
                    #TODO -what about mobile factories?
                    IssueBlueprintCommand("UNITCOMMAND_BuildFactory", item.id, count)
                end
            end
        else
            local unitIndex = false
            if currentCommandQueue then
				for index, unitStack in currentCommandQueue do
					if unitStack.id == item.id then
						unitIndex = index
					end
				end
				if unitIndex != false then
					RecursiveDecreaseBuildCountInQueue(unitIndex, count)
				end
            end
        end
    elseif item.type == 'unitstack' then
        if modifiers.Left then
            SelectUnits(item.units)
        elseif modifiers.Right then
            local selection = {}
            for _, unit in sortedOptions.selection do
                local found = false
                for _, checkUnit in item.units do
                    if checkUnit == unit then
                        found = true
                        break
                    end
                end
                if not found then
                    table.insert(selection, unit)
                end
            end
            SelectUnits(selection)
        end
    elseif item.type == 'attachedunit' then
        if modifiers.Left then
            -- Toggling selection of the entity
            button:OnAltToggle()
    
            -- Add or Remove the entity to the session selection
            if button.mAltToggledFlag then
                AddToSessionExtraSelectList(item.unit)
            else
                RemoveFromSessionExtraSelectList(item.unit)
            end
        end
    elseif item.type == 'templates' then
        ClearBuildTemplates()
        if modifiers.Right then
            if button.OptionMenu then
                button.OptionMenu:Destroy()
                button.OptionMenu = nil
            else
                button.OptionMenu = CreateTemplateOptionsMenu(button)
            end
            for _, otherBtn in controls.choices.Items do
                if button != otherBtn and otherBtn.OptionMenu then
                    otherBtn.OptionMenu:Destroy()
                    otherBtn.OptionMenu = false
                end
            end
        else
            import('/lua/ui/game/commandmode.lua').StartCommandMode('build', {name=item.template.templateData[3][1]})
            SetActiveBuildTemplate(item.template.templateData)
        end
    elseif item.type == 'enhancement' then
        local existingEnhancements = EnhanceCommon.GetEnhancements(sortedOptions.selection[1]:GetEntityId())
        if existingEnhancements[item.enhTable.Slot] and existingEnhancements[item.enhTable.Slot] != item.enhTable.Prerequisite then
            if existingEnhancements[item.enhTable.Slot] != item.id then
            UIUtil.QuickDialog(GetFrame(0), "<LOC enhancedlg_0000>Choosing this enhancement will destroy the existing enhancement in this slot.  Are you sure?", 
                "<LOC _Yes>", function()
                        ForkThread(function()
                            local orderData = {
                                # UserVerifyScript='/lua/ui/game/EnhanceCommand.lua',
                                TaskName = "EnhanceTask",
                                Enhancement = existingEnhancements[item.enhTable.Slot]..'Remove',
                            }
                            IssueCommand("UNITCOMMAND_Script", orderData, true)
                            WaitSeconds(.5)
                            orderData = {
                                # UserVerifyScript='/lua/ui/game/EnhanceCommand.lua',
                                TaskName = "EnhanceTask",
                                Enhancement = item.id,
                            }
                            IssueCommand("UNITCOMMAND_Script", orderData, true)
                        end)
                    end,
                "<LOC _No>", nil,
                nil, nil,
                true,  {worldCover = true, enterButton = 1, escapeButton = 2})
            end
        else
            local orderData = {
                # UserVerifyScript='/lua/ui/game/EnhanceCommand.lua',
                TaskName = "EnhanceTask",
                Enhancement = item.id,
            }
            IssueCommand("UNITCOMMAND_Script", orderData, true)
        end
    elseif item.type == 'queuestack' then
        local count = 1
        if modifiers.Shift or modifiers.Ctrl then
            count = 5
        end
        if modifiers.Left then
            IncreaseBuildCountInQueue(item.position, count)
        elseif modifiers.Right then
			-- AZ ADDITION
            RecursiveDecreaseBuildCountInQueue(item.position, count)
        end
    end
end