CT_RA_VersionNumber = 2.001; -- Used for number comparisons

CT_RA_Version = "v" .. CT_RA_VersionNumber;
CT_RA_MOVINGMEMBER = nil;
CT_RA_CURRSLOT = nil;
CT_RA_CurrPositions = { };
CT_RA_CustomPositions = { };
CT_RA_MainTanks = { };
CT_RA_CurrMembers = { };
CT_RA_ButtonIndexes = { };
CT_RATab_AutoPromotions = { };

function CT_RATab_OnLoad()
	PanelTemplates_SetNumTabs(FriendsFrame, 5);
	tinsert(FRIENDSFRAME_SUBFRAMES, "CT_RAOptionsFrame");
	PanelTemplates_TabResize(0, this, 90);
end

CT_oldFriendsFrame_Update = FriendsFrame_Update;

function CT_newFriendsFrame_Update()
	if ( FriendsFrame.selectedTab == 5 ) then
		FriendsFrameTopLeft:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-TopLeft");
		FriendsFrameTopRight:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-TopRight");
		FriendsFrameBottomLeft:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-BottomLeft");
		FriendsFrameBottomRight:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-BottomRight");
		FriendsFrameTitleText:SetText("CT_RaidAssist " .. CT_RA_Version);
		FriendsFrame_ShowSubFrame("CT_RAOptionsFrame");
	else
		CT_oldFriendsFrame_Update();
	end
end

FriendsFrame_Update = CT_newFriendsFrame_Update;

function CT_RAOptionsGroupButton_OnMouseDown(button)
	if ( button == "RightButton" and this.name ) then
		ToggleDropDownMenu(1, nil, getglobal("CT_RAOptionsGroupButton"..this:GetID().."DropDown"));
	end
end

function CT_RAOptions_Update()
	-- Reset group index counters;
	for i=1, NUM_RAID_GROUPS do
		getglobal("CT_RAOptionsGroup"..i).nextIndex = 1;
	end
	-- Clear out all the slots buttons
	CT_RAOptionsGroup_ResetSlotButtons();

	local numRaidMembers = GetNumRaidMembers();
	local raidGroup, color;
	local buttonName, buttonLevel, buttonClass, buttonRank;
	local name, rank, subgroup, level, class, fileName, zone, online, reqChange;
	local temp = { };
	local REDr, REDg, REDb = RED_FONT_COLOR.r, RED_FONT_COLOR.g, RED_FONT_COLOR.b;
	local GRAYr, GRAYg, GRAYb = GRAY_FONT_COLOR.r, GRAY_FONT_COLOR.g, GRAY_FONT_COLOR.b;
	for i=1, MAX_RAID_MEMBERS do
		button = getglobal("CT_RAOptionsGroupButton"..i);
		if ( i <= numRaidMembers ) then
			name, rank, subgroup, level, class, fileName, zone, online, isDead = GetRaidRosterInfo(i);
			if ( not name or not CT_RA_CurrPositions[name] ) then
				if ( name ) then
					CT_RA_CurrPositions[name] = { subgroup };
				end
			end
			if ( name and CT_RA_CurrPositions[name] ) then
				CT_RA_CurrPositions[name][2] = i;
			end
			if ( subgroup ) then
				raidGroup = getglobal("CT_RAOptionsGroup"..subgroup);
				-- To prevent errors when the server hiccups
				if ( raidGroup.nextIndex <= MEMBERS_PER_RAID_GROUP ) then
					buttonName = getglobal("CT_RAOptionsGroupButton"..i.."Name");
					buttonLevel = getglobal("CT_RAOptionsGroupButton"..i.."Level");
					buttonClass = getglobal("CT_RAOptionsGroupButton"..i.."Class");
					buttonRank = getglobal("CT_RAOptionsGroupButton"..i.."Rank");
					button.id = i;
					
					button.name = name;
					
					if ( level == 0 ) then
						level = "";
					end
					
					if ( not name ) then
						name = UNKNOWN;
					end
					
					buttonName:SetText(name);
					buttonLevel:SetText(level);
					buttonClass:SetText(class);
					if ( isDead ) then
						buttonName:SetVertexColor(REDr, REDg, REDb);
						buttonClass:SetVertexColor(REDr, REDg, REDb);
						buttonLevel:SetVertexColor(REDr, REDg, REDb);
					elseif ( online ) then
						color = RAID_CLASS_COLORS[fileName];
						if ( color ) then
							local r, g, b = color.r, color.g, color.b;
							buttonName:SetVertexColor(r, g, b);
							buttonLevel:SetVertexColor(r, g, b);
							buttonClass:SetVertexColor(r, g, b);
						end
					else
						buttonName:SetVertexColor(GRAYr, GRAYg, GRAYb);
						buttonClass:SetVertexColor(GRAYr, GRAYg, GRAYb);
						buttonLevel:SetVertexColor(GRAYr, GRAYg, GRAYb);
					end
					
					buttonRank:SetText("");
					for k, v in pairs(CT_RA_MainTanks) do
						if ( v == name ) then
							buttonRank:SetText(k);
							break;
						end
					end
					
					-- Anchor button to slot
					local slot = raidGroup.nextIndex;
					if ( not CT_RA_MOVINGMEMBER or CT_RA_MOVINGMEMBER ~= button  ) then
						button:SetPoint("TOPLEFT", "CT_RAOptionsGroup"..subgroup.."Slot"..slot, "TOPLEFT", 0, 0);
					end
					
					-- Save slot for future use
					button.slot = "CT_RAOptionsGroup"..subgroup.."Slot"..slot;
					-- Save the button's subgroup too
					button.subgroup = subgroup;
					-- Tell the slot what button is in it
					getglobal("CT_RAOptionsGroup"..subgroup.."Slot"..slot).button = button:GetName();
					raidGroup.nextIndex = raidGroup.nextIndex + 1;
					button:SetID(i);
					button:Show();
				end
			end
		else
			button:Hide();
		end
	end
end

function CT_RAOptions_UpdateGroups()
	local numRaidMembers = GetNumRaidMembers();
	local subgroup, _, online, isDead, fileName;
	local RAID_CLASS_COLORS = RAID_CLASS_COLORS;
	local REDr, REDg, REDb = RED_FONT_COLOR.r, RED_FONT_COLOR.g, RED_FONT_COLOR.b;
	local GRAYr, GRAYg, GRAYb = GRAY_FONT_COLOR.r, GRAY_FONT_COLOR.g, GRAY_FONT_COLOR.b;
	for i = 1, MAX_RAID_MEMBERS do
		_, _, _, _, _, fileName, _, online, isDead = GetRaidRosterInfo(i);
		if ( isDead ) then
			getglobal("CT_RAOptionsGroupButton"..i.."Name"):SetVertexColor(REDr, REDg, REDb);
			getglobal("CT_RAOptionsGroupButton"..i.."Class"):SetVertexColor(REDr, REDg, REDb);
			getglobal("CT_RAOptionsGroupButton"..i.."Level"):SetVertexColor(REDr, REDg, REDb);
		elseif ( online ) then
			local color = RAID_CLASS_COLORS[fileName];
			if ( color ) then
				local r, g, b = color.r, color.g, color.b;
				getglobal("CT_RAOptionsGroupButton"..i.."Name"):SetVertexColor(r, g, b);
				getglobal("CT_RAOptionsGroupButton"..i.."Class"):SetVertexColor(r, g, b);
				getglobal("CT_RAOptionsGroupButton"..i.."Level"):SetVertexColor(r, g, b);
			end
		else
			getglobal("CT_RAOptionsGroupButton"..i.."Name"):SetVertexColor(GRAYr, GRAYg, GRAYb);
			getglobal("CT_RAOptionsGroupButton"..i.."Class"):SetVertexColor(GRAYr, GRAYg, GRAYb);
			getglobal("CT_RAOptionsGroupButton"..i.."Level"):SetVertexColor(GRAYr, GRAYg, GRAYb);
		end
	end
end

function CT_RAOptions_UpdateMTs()
	local numRaidMembers = GetNumRaidMembers();
	local name, rank;
	local RAID_CLASS_COLORS = RAID_CLASS_COLORS;
	local REDr, REDg, REDb = RED_FONT_COLOR.r, RED_FONT_COLOR.g, RED_FONT_COLOR.b;
	local GRAYr, GRAYg, GRAYb = GRAY_FONT_COLOR.r, GRAY_FONT_COLOR.g, GRAY_FONT_COLOR.b;
	for i = 1, MAX_RAID_MEMBERS do
		name = GetRaidRosterInfo(i);
		rank = getglobal("CT_RAOptionsGroupButton"..i.."Rank");
		rank:SetText("");
		
		for k, v in pairs(CT_RA_MainTanks) do
			if ( v == name ) then
				rank:SetText(k);
				break;
			end
		end
	end
end

function CT_RAOptionsGroup_ResetSlotButtons()
	for i=1, NUM_RAID_GROUPS do
		for j=1, MEMBERS_PER_RAID_GROUP do
			getglobal("CT_RAOptionsGroup"..i.."Slot"..j).button = nil;
		end
	end
end

function CT_RAOptionsGroupFrame_OnUpdate(elapsed)
	if ( CT_RA_MOVINGMEMBER ) then
		local button, slot;
		CT_RA_CURRSLOT = nil;
		for i=1, NUM_RAID_GROUPS do
			for j=1, MEMBERS_PER_RAID_GROUP do
				slot = getglobal("CT_RAOptionsGroup"..i.."Slot"..j);
				if ( MouseIsOver(slot) ) then
					slot:LockHighlight();
					CT_RA_CURRSLOT = slot;
				else
					slot:UnlockHighlight();
				end
			end
		end
	end
end

function CT_RAMemberDropDown_OnLoad()
	UIDropDownMenu_Initialize(this, CT_RAMemberDropDown_Initialize, "MENU");
end

function CT_RAMemberDropDown_Initialize()
	local dropdown, info;
	if ( UIDROPDOWNMENU_OPEN_MENU ) then
		dropdown = getglobal(UIDROPDOWNMENU_OPEN_MENU);
	else
		dropdown = this;
	end
	if ( type(UIDROPDOWNMENU_MENU_VALUE) == "table" and UIDROPDOWNMENU_MENU_VALUE[1] == "Main Tanks" ) then
		info = {};
		info.text = "Main Tanks";
		info.isTitle = 1;
		UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
		local isMT;
		for key, value in pairs(CT_RA_MainTanks) do
			if ( value == UIDROPDOWNMENU_MENU_VALUE[2] ) then
				isMT = key;
				break;
			end
		end
		for i = 1, 10, 1 do
			info = {};
			if ( isMT == i ) then
				info.text = "|c00DFFFFFRemove MT " .. i .. "|r";
				info.value = { UIDROPDOWNMENU_MENU_VALUE[1], UIDROPDOWNMENU_MENU_VALUE[2], i, isMT, 1 };
				info.tooltipTitle = "Remove Main Tank"
				info.tooltipText = "Removes the Main Tank from the MT window.";
			else
				info.text = "Set MT " .. i .. "";
				info.value = { UIDROPDOWNMENU_MENU_VALUE[1], UIDROPDOWNMENU_MENU_VALUE[2], i, isMT };
				info.tooltipTitle = "Set Main Tank"
				info.tooltipText = "Sets a main tank, which allows everyone to see the main tank(s) target info";
			end
			info.func = CT_RAMemberDropDown_OnClick;
			UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
		end
		return;
	end
	if ( type(UIDROPDOWNMENU_MENU_VALUE) == "table" and UIDROPDOWNMENU_MENU_VALUE[1] == "Player Targets" ) then
		info = {};
		info.text = "Player Targets";
		info.isTitle = 1;
		info.notCheckable = 1;
		UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
		local isPT;
		if ( CT_RA_PTargets ) then
			for key, value in pairs(CT_RA_PTargets) do
				if ( value == UIDROPDOWNMENU_MENU_VALUE[2] ) then
					isPT = key;
					break;
				end
			end
		end
		info = {};
		if ( isPT ) then
			info.text = "|c00DFFFFFRemove PT|r";
			info.value = { UIDROPDOWNMENU_MENU_VALUE[1], UIDROPDOWNMENU_MENU_VALUE[2], isPT, 1 };
			info.tooltipTitle = "Remove Player Target"
			info.tooltipText = "Removes the Player Target from the PT window.";
		else
			info.text = "Set PT"
			info.value = { UIDROPDOWNMENU_MENU_VALUE[1], UIDROPDOWNMENU_MENU_VALUE[2], isPT };
			info.tooltipTitle = "Set Player Target"
			info.tooltipText = "Sets a player target, which allows you to easily see the person's health and target.";
		end
		info.func = CT_RAMemberDropDown_OnClick;
		UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
		return;
	end
	info = {};
	info.text = this.name;
	info.isTitle = 1;
	info.notCheckable = 1;
	UIDropDownMenu_AddButton(info);
	if ( CT_RA_Level < 1 ) then
		info = { };
		info.text = "|c00666666Main Tanks|r";
		info.tooltipTitle = "Promotion Required";
		info.tooltipText = "In order to set main tanks, you need to at least be a promoted user, or raid leader.";
		info.notCheckable = 1;
		UIDropDownMenu_AddButton(info);
	else
		info = {};
		info.text = "Main Tanks";
		info.value = { "Main Tanks", this.name };
		info.hasArrow = 1;
		info.notCheckable = 1;
		UIDropDownMenu_AddButton(info);
	end
	info = {};
	info.text = "Player Targets";
	info.value = { "Player Targets", this.name };
	info.hasArrow = 1;
	info.notCheckable = 1;
	UIDropDownMenu_AddButton(info);
	
	info = { };
	info.text = "Auto-Promote";
	info.tooltipTitle = "Auto-Promote";
	info.tooltipText = "When checked, this player is automatically promoted when he or she joins the raid.";
	info.checked = CT_RATab_AutoPromotions[this.name];
	info.value = this.id;
	info.func = CT_RATab_AutoPromote_OnClick;
	UIDropDownMenu_AddButton(info);
end

function CT_RAMemberDropDown_OnClick()
	if ( this.value[1] == "Main Tanks" ) then
		if ( this.value[5] ) then
			CT_RA_SendMessage("R " .. this.value[2], 1);
		else
			CT_RA_SendMessage("SET " .. this.value[3] .. " " .. this.value[2], 1);
		end
	elseif ( this.value[1] == "Player Targets" ) then
		if ( this.value[4] ) then
			tremove(CT_RA_PTargets, this.value[3]);
		else
			tinsert(CT_RA_PTargets, this.value[2]);
		end
		CT_RA_UpdatePTs(true);
	end
	CT_RA_UpdateRaidFrameData();
	CloseMenus();
end

function CT_RAMemberDropDownRemove_OnLoad()
	UIDropDownMenu_Initialize(this, CT_RAMemberDropDownRemove_Initialize, "MENU");
end

function CT_RAMemberDropDownRemove_Initialize()
	local dropdown, info;
	if ( UIDROPDOWNMENU_OPEN_MENU ) then
		dropdown = getglobal(UIDROPDOWNMENU_OPEN_MENU);
	else
		dropdown = this;
	end
	if ( this.id and this.name ) then
		info = {};
		info.text = this.name;
		info.isTitle = 1;
		info.notCheckable = 1;
		UIDropDownMenu_AddButton(info);
	
		info = {};
		info.text = "Remove MT";
		info.value = this.name;
		info.func = CT_RAMemberDropDownRemove_OnClick;
		info.notCheckable = 1;
		info.tooltipTitle = "Remove Main Tank"
		info.tooltipText = "Removes the main tank";
		UIDropDownMenu_AddButton(info);
	end
end

function CT_RAMemberDropDownRemove_OnClick()
	for k, v in pairs(CT_RA_MainTanks) do
		if ( v == this.value ) then
			CT_RA_SendMessage("R " .. v, 1);
			return;
		end
	end
end