--Creates a controller group.

function ControllerGroups:CreateControllerGroup()
	local ControllerGroup = {}
	local Frames = {}
	local Active = false
	local FirstFrame
	
	--Sets the group to be active.
	function ControllerGroup:SetActive(IsActive,IsPriority)
		if IsActive ~= Active then
			if IsActive then
				if IsPriority then
					table.insert(ActivePriorityControllerGroups,1,ControllerGroup)
				else
					table.insert(ActiveControllerGroups,1,ControllerGroup)
				end
			else
				for Id,Group in pairs(ActiveControllerGroups) do
					if Group == ControllerGroup then
						table.remove(ActiveControllerGroups,Id)
						break
					end
				end
				for Id,Group in pairs(ActivePriorityControllerGroups) do
					if Group == ControllerGroup then
						table.remove(ActivePriorityControllerGroups,Id)
						break
					end
				end
				
				UpdateActiveButton()
			end
			
			Active = IsActive
			UpdateActiveButton()
		end
	end
	
	--Set the first frame when the group is activated.
	function ControllerGroup:SetFirstFrame(Frame)
		if ControllerGroup:FrameInGroup(Frame) then
			FirstFrame = Frame
		else
			FirstFrame = nil
		end
	end
	
	--Returns if the frame is in the group.
	function ControllerGroup:FrameInGroup(Frame)
		for _,OtherFrame in pairs(Frames) do
			if Frame == OtherFrame then
				return true
			end
		end
		
		return false
	end
	
	--Adds a frame to the controller group.
	function ControllerGroup:AddFrame(Frame)
		if not ControllerGroup:FrameInGroup(Frame) then
			table.insert(Frames,Frame)
			
			if Active then UpdateActiveButton() end
		end
	end
	
	--Removes a frame from the controller.
	function ControllerGroup:RemoveFrame(Frame)
		for Id,OtherFrame in pairs(Frames) do
			if Frame == OtherFrame then
				table.remove(Frames,Id)
				
				if Active then UpdateActiveButton() end
				return
			end
		end
	end
	
	--Clears all frames in the controller group.
	function ControllerGroup:ClearFrames()
		Frames = {}
		if Active then UpdateActiveButton() end
	end
	
	--Returns if the group is active.
	function ControllerGroup:IsActive()
		return GetActiveGroup() == ControllerGroup
	end
	
	--Returns all the frames in the group.
	function ControllerGroup:GetFrames()
		return Frames
	end
	
	--Returns the first frame in teh group.
	function ControllerGroup:GetFirstFrame()
		return ((FirstFrame and ControllerGroup:FrameInGroup(FirstFrame)) and FirstFrame) or Frames[1]
	end
	
	return ControllerGroup
end
