local currentFireState = -1
local fireStateChangedSinceSelection = false

local function AZRetaliateInitFunction(control, unitList)
	control._toggleState = GetFireState(unitList)
	if not retaliateStateInfo[control._toggleState] then
		LOG("Error: orders.lua - invalid toggle state: ", tostring(self._toggleState))
	end
	control:SetNewTextures(GetOrderBitmapNames(retaliateStateInfo[control._toggleState].bitmap))
	control._curHelpText = retaliateStateInfo[control._toggleState].helpText
	if control._toggleState == -1 then
		if not control.mixedIcon then
			control.mixedIcon = Bitmap(control, UIUtil.UIFile('/game/orders-panel/question-mark_bmp.dds'))
		end
		LayoutHelpers.AtRightTopIn(control.mixedIcon, control, 3, 6)
		control.mixedIcon:DisableHitTest()
		control.mixedIcon:SetAlpha(0)
		control.mixedIcon.OnHide = function(self, hidden)
			if not hidden and control:IsDisabled() then
				return true
			end
		end
	end
	control.OnEnable = function(self)
		if self.mixedIcon then
			self.mixedIcon:SetAlpha(1)
		end
		Checkbox.OnEnable(self)
	end
	control.OnDisable = function(self)
		if self.mixedIcon then
			self.mixedIcon:SetAlpha(0)
		end
		Checkbox.OnDisable(self)
	end
end

local function AZRetaliateOrderBehavior(self, modifiers)
	if not self._OnFirestateSelection then
		self._OnFirestateSelection = function(self, newState, id)
			self._toggleState = newState
			SetFireState(currentSelection, id)
			currentFireState = newState	-- AZ ADDITION
			self:SetNewTextures(GetOrderBitmapNames(retaliateStateInfo[newState].bitmap))
			self._curHelpText = retaliateStateInfo[newState].helpText
			self._popup:Destroy()
			self._popup = nil
			fireStateChangedSinceSelection = true
		end
	end
	
	if self._popup then
		self._popup:Destroy()
		self._popup = nil
	else
		self._popup = CreateFirestatePopup(self, self._toggleState)
		local function CollapsePopup(event)
			if (event.y < self._popup.Top() or event.y > self._popup.Bottom()) or (event.x < self._popup.Left() or event.x > self._popup.Right()) then
				self._popup:Destroy()
				self._popup = nil
			end
		end
		
		UIMain.AddOnMouseClickedFunc(CollapsePopup)
		
		self._popup.OnDestroy = function(self)
			UIMain.RemoveOnMouseClickedFunc(CollapsePopup)
			Checkbox.OnDestroy(self)
		end
	end
end
-- AZ ADDITION
-- GPG set most of the functions in orders.lua to local, so this way of overriding functions is easier.
do
	defaultOrdersTable["RULEUCC_RetaliateToggle"].initialStateFunc = AZRetaliateInitFunction
	defaultOrdersTable["RULEUCC_RetaliateToggle"].behavior = AZRetaliateOrderBehavior
end

function CycleRetaliateStateUp()
	--local currentFireState = GetFireState(currentSelection)
	--LOG("current state = "..currentFireState)
	ToggleFireState(currentSelection, currentFireState)
	currentFireState = currentFireState + 1
	
	if currentFireState > 2 then
		currentFireState = 0
	end
	
	orderCheckboxMap["RULEUCC_RetaliateToggle"]:SetNewTextures(GetOrderBitmapNames(retaliateStateInfo[currentFireState].bitmap))
	fireStateChangedSinceSelection = true
end

-- AZ ADDITION
-- Not actually used. Exists in case someone wants to hook this in.
function CycleRetaliateStateDown()
	CycleRetaliateStateUp()
	CycleRetaliateStateUp()
end

function SetAvailableOrders(availableOrders, availableToggles, newSelection, isOldSelection)
	# save new selection
	#LOG('available orders: ', repr(availableOrders))
	currentSelection = newSelection
	# clear existing orders
	local fireStatePopupNeeded = false
	if orderCheckboxMap["RULEUCC_RetaliateToggle"] then
		if orderCheckboxMap["RULEUCC_RetaliateToggle"]._popup then
			fireStatePopupNeeded = true
		end
	end
	
	
	orderCheckboxMap = {}
	controls.orderButtonGrid:DestroyAllItems(true)
	
	-- create our copy of orders table
	standardOrdersTable = table.deepcopy(defaultOrdersTable)
	
	-- look in blueprints for any icon or tooltip overrides
	-- note that if multiple overrides are found for the same order, then the default is used
	-- the syntax of the override in the blueprint is as follows (the overrides use same naming as in the default table above):
	-- In General table
	-- OrderOverrides = {
	--	 RULEUTC_IntelToggle = {
	--		 bitmapId = 'custom',
	--		 helpText = 'toggle_custom',
	--	 },
	--  },
	-- 
	local orderDiffs
	
	for index, unit in newSelection do
		local overrideTable = unit:GetBlueprint().General.OrderOverrides
		if overrideTable then
			for orderKey, override in overrideTable do
				if orderDiffs == nil then
					orderDiffs = {}
				end
				if orderDiffs[orderKey] != nil and (orderDiffs[orderKey].bitmapId != override.bitmapId or orderDiffs[orderKey].helpText != override.helpText) then
					-- found order diff already, so mark it false so it gets ignored when applying to table
					orderDiffs[orderKey] = false
				else
					orderDiffs[orderKey] = override
				end
			end
		end
	end
	
	-- apply overrides
	if orderDiffs != nil then
		for orderKey, override in orderDiffs do
			if override and override != false then
				if override.bitmapId then
					standardOrdersTable[orderKey].bitmapId = override.bitmapId
				end
				if override.helpText then
					standardOrdersTable[orderKey].helpText = override.helpText
				end
			end
		end
	end
	
	CreateCommonOrders(availableOrders)
	
	local numValidOrders = 0
	for i, v in availableOrders do
		if standardOrdersTable[v] then
			numValidOrders = numValidOrders + 1
		end
	end
	for i, v in availableToggles do
		if standardOrdersTable[v] then
			numValidOrders = numValidOrders + 1
		end
	end
	
	if numValidOrders <= 12 then
		CreateAltOrders(availableOrders, availableToggles, currentSelection)
	end
	
	controls.orderButtonGrid:EndBatch()
	if table.getn(currentSelection) == 0 and controls.bg.Mini then
		controls.bg.Mini(true)
	elseif controls.bg.Mini then
		controls.bg.Mini(false)
	end
	
	-- AZ ADDITION
	if not isOldSelection then
		currentFireState = GetFireState(currentSelection)
		fireStateChangedSinceSelection = false
	end
	if isOldSelection and fireStateChangedSinceSelection then
	   orderCheckboxMap["RULEUCC_RetaliateToggle"]:SetNewTextures(GetOrderBitmapNames(retaliateStateInfo[currentFireState].bitmap))
	   --LOG("isOldSelection = true")
	end
	
	local retaliateButton = orderCheckboxMap["RULEUCC_RetaliateToggle"]
	if retaliateButton then
		if fireStatePopupNeeded then
			AZRetaliateOrderBehavior(retaliateButton, nil)--retaliateButton._popup = CreateFirestatePopup(retaliateButton, retaliateButton._toggleState)
		end
		
		if controls.mouseoverDisplay then
			
		end
	end
end

function CreateMouseoverDisplay(parent, ID)
	if controls.mouseoverDisplay then
		controls.mouseoverDisplay:Destroy()
		controls.mouseoverDisplay = false
	end
	
	if not Prefs.GetOption('tooltips') then return end
	
	local createDelay = Prefs.GetOption('tooltip_delay') or 0
	
	local text = TooltipInfo['Tooltips'][ID]['title'] or ID
	local desc = TooltipInfo['Tooltips'][ID]['description'] or ID
	
	if TooltipInfo['Tooltips'][ID]['keyID'] and TooltipInfo['Tooltips'][ID]['keyID'] != "" then
		for i, v in Keymapping do
			if v == TooltipInfo['Tooltips'][ID]['keyID'] then
				local properkeyname = import('/lua/ui/dialogs/keybindings.lua').formatkeyname(i)
				text = LOCF("%s (%s)", text, properkeyname)
				break
			end
		end
	end
	
	if not text or not desc then
		return
	end

	controls.mouseoverDisplay = Tooltip.CreateExtendedToolTip(parent, text, desc)
	local Frame = GetFrame(0)
	controls.mouseoverDisplay.Bottom:Set(parent.Top)
	if (parent.Left() + (parent.Width() / 2)) - (controls.mouseoverDisplay.Width() / 2) < 0 then
		controls.mouseoverDisplay.Left:Set(4)
	elseif (parent.Right() - (parent.Width() / 2)) + (controls.mouseoverDisplay.Width() / 2) > Frame.Right() then
		controls.mouseoverDisplay.Right:Set(function() return Frame.Right() - 4 end)
	else
		LayoutHelpers.AtHorizontalCenterIn(controls.mouseoverDisplay, parent)
	end
	
	controls.mouseoverDisplay:SetAlpha(0, true)
	if createDelay then
		local mdThread = ForkThread(function()
			WaitSeconds(createDelay)
			controls.mouseoverDisplay:SetAlpha(1, true)
		end)
		controls.mouseoverDisplay.OnDestroy = function(self)
			KillThread(mdThread)  
		end
	end
end