--------------------------------------------------------------------------------
-- CT_MailModPlus R25 by Bitz (wow.SomeGate.com)
--------------------------------------------------------------------------------

CT_MAIL_NUMITEMBUTTONS = 21;

CT_MailModOptions ={ };
CT_Mail_LastInfo = { };

CT_Mail_ToList = { };
CT_Mail_Sendee = { };

CT_Mail_Mailables = { };
CT_Mail_Selected = { };

local bagID; 
local buttonID, currentPage;
local oldValue;

local function CT_Mail_VariablesLoaded()
	for i = 0, 4 do
		if ( not CT_Mail_Mailables[i] ) then CT_Mail_Mailables[i] = {}; end
		if ( not CT_Mail_Selected[i] ) then CT_Mail_Selected[i] = {}; end
	end
	CT_MailOptionTooltipCB:SetChecked(CT_MailModOptions.disableTooltip);
	CT_MailOptionHideSendConfCB:SetChecked(CT_MailModOptions.hideSendConfirmation);
	CT_MailOptionHideReturnConfCB:SetChecked(CT_MailModOptions.hideReturnConfirmation);
	CT_MailOptionBlockTradeCB:SetChecked(CT_MailModOptions.blockTrade);
end

function CT_Mail_OnEvent(event)
	if ( event == "MAIL_SEND_SUCCESS" ) then
		CT_Mail_CanSendNext = 1;
	elseif ( event == "MAIL_SHOW" ) then
	  oldValue = GetCVar("BlockTrades")
  	if ( CT_MailModOptions.blockTrade ) then
    	SetCVar("BlockTrades", 1)
  	end
  	CT_MailGlobalFrame:RegisterEvent("BAG_UPDATE");
	elseif ( event == "MAIL_CLOSED" ) then
		if ( oldValue ~= GetCVar("BlockTrades") ) then
    	SetCVar("BlockTrades", oldValue)
  	end
  	CT_MailGlobalFrame:UnregisterEvent("BAG_UPDATE");
  	collectgarbage("collect");
  elseif ( event=="TRADE_CLOSED" ) then
  	collectgarbage("collect");
	elseif ( event == "BAG_UPDATE" and CT_MailFrame:IsVisible() ) then
		CT_Mail_BagTab_SetStatus();
		CT_Mail_TableInitiate();
		CT_Mail_BagFrame_Update();
	elseif ( event == "VARIABLES_LOADED" ) then
	  CT_Mail_DropDownMenu_Init();
	  CT_Mail_VariablesLoaded();
	end
end

-- Hook the ContainerFrameItemButton_OnClick function
hooksecurefunc("ContainerFrameItemButton_OnModifiedClick", function(button)
	if ( button == "LeftButton" and IsAltKeyDown()) then
		local bag, item = this:GetParent():GetID(), this:GetID();
		if ( CT_MailFrame:IsVisible() and not CursorHasItem() ) then
			local unmailable = CT_Mail_ItemIsMailable(bag, item)
			if ( unmailable ) then
	    	DEFAULT_CHAT_FRAME:AddMessage(format(CT_MAIL_ERROR_UNMAILABLE, unmailable), 1, 0.5, 0);
			else
				if ( CT_Mail_SelectedItemExist(bag, item) == true ) then
					for k, v in pairs(CT_Mail_Selected[bag]) do
						if ( v == item ) then tremove(CT_Mail_Selected[bag], k); break;	end
					end
				else
					tinsert(CT_Mail_Selected[bag], item)
				end
				CT_MailStatusText:SetText("");
			  CT_MailMassButton:Show();
				CT_MailCODButton:Show();
				CT_MailBagTab5:Click();
				CT_Mail_SelectedFrame_Update(1);
				CT_Mail_ContainerFrame_Update();
			end
		elseif ( SendMailFrame:IsVisible() and not CursorHasItem() ) then
			PickupContainerItem(bag, item);
			ClickSendMailItemButton();
			return;
		elseif ( TradeFrame:IsVisible() and not CursorHasItem() ) then
			for i = 1, 6, 1 do
				if ( not GetTradePlayerItemLink(i) ) then
					PickupContainerItem(bag, item);
					ClickTradeButton(i);
					return;
				end
			end
		elseif ( AuctionFrameAuctions and AuctionFrameAuctions:IsVisible() and not CursorHasItem() ) then
			PickupContainerItem(bag, item);
			ClickAuctionSellItemButton();
			return;
		elseif ( not CursorHasItem() and ( not TradeFrame or not TradeFrame:IsVisible() ) and ( not AuctionFrame or not AuctionFrame:IsVisible() ) and UnitExists("target") and CheckInteractDistance("target", 2) and UnitIsFriend("player", "target") and UnitIsPlayer("target") ) then
			InitiateTrade("target");
			CT_Mail_addItem = { bag, item, UnitName("target"), 2 };
			for i = 1, NUM_CONTAINER_FRAMES, 1 do
				if ( getglobal("ContainerFrame" .. i):IsVisible() ) then
					ContainerFrame_Update(getglobal("ContainerFrame" .. i));
				end
			end
			return;
		end
	end
end);

hooksecurefunc("PickupContainerItem", function(bag, item)
	if ( MailFrame:IsVisible() ) then
		if ( CursorHasItem() ) then
			CT_MailFrame.bag = bag;
			CT_MailFrame.item = item;
		else
			CT_MailFrame.bag = nil;
			CT_MailFrame.item = nil;
		end
	end
end);

local CT_MM_oldCSMIB = ClickSendMailItemButton;
function CT_MM_newCSMIB()
	if ( MailFrame:IsVisible() and not GetSendMailItem() ) then
		CT_MailFrame.mailbag = CT_MailFrame.bag;
		CT_MailFrame.mailitem = CT_MailFrame.item;
	end
	CT_MM_oldCSMIB();
end
ClickSendMailItemButton = CT_MM_newCSMIB;

hooksecurefunc("MailFrameTab_OnClick", function(tab)
	if ( not tab ) then 
		tab = this:GetID();
	end
	
  MailFrameTab2:SetPoint("LEFT", "MailFrameTab1", "RIGHT", -15, 0)
  
	if ( tab == 3 ) then
		InboxFrame:Hide();
		SendMailFrame:Hide();
		CT_MailFrame:Show();
		CT_MailOption:Hide();
		CT_Mail_BagTab_Init();
		CT_MailRadioButton_OnClick(1);
		SendMailFrame.sendMode = "massmail";
		MailFrameTopLeft:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-TopLeft");
		MailFrameTopRight:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-TopRight");
		MailFrameBotLeft:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-BotLeft");
		MailFrameBotRight:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-BotRight");
		CT_MassMail_RememberLastSendee(); -- To remember the last sendee
		return;
	elseif ( tab == 4 ) then
		InboxFrame:Hide();
		SendMailFrame:Hide();
		CT_MailFrame:Hide();
		CT_MailOption:Show();
		CT_Mail_OptionTab_OnClick(1);
		MailFrameTopLeft:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-TopLeft");
		MailFrameTopRight:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-TopRight");
		MailFrameBotLeft:SetTexture("Interface\\PaperDollInfoFrame\\SkillFrame-BotLeft");
		MailFrameBotRight:SetTexture("Interface\\PaperDollInfoFrame\\SkillFrame-BotRight");
	else
		CT_MailFrame:Hide();
		CT_MailOption:Hide();
	end
	collectgarbage("collect");
end);

-- [1] Remember Sendee and COD Amount ------------------------------------------
function CT_Mail_RememberLastSendee()
  if ( CT_Mail_LastInfo.Sendee ) then
    local text = SendMailNameEditBox:GetText();
    if (not text or text == "") then
      SendMailNameEditBox:SetText(CT_Mail_LastInfo.Sendee);
    end
  end
end

function CT_MassMail_RememberLastSendee()
  if ( CT_Mail_LastInfo.MassSendee ) then
    local text = CT_MailNameEditBox:GetText();
    if (not text or text == "") then
      CT_MailNameEditBox:SetText(CT_Mail_LastInfo.MassSendee);
    end
  end
end

hooksecurefunc("SendMailRadioButton_OnClick", function(index)
  if ( ( CT_Mail_LastInfo.Copper or CT_Mail_LastInfo.Silver or CT_Mail_LastInfo.Gold ) and index == 2 ) then
  	local copper, silver, gold = SendMailMoneyCopper:GetText(), SendMailMoneySilver:GetText(), SendMailMoneyGold:GetText();
  	if ( copper == "" and silver == "" and gold == "" ) then
  		SendMailMoneyCopper:SetText(CT_Mail_LastInfo.Copper);
  		SendMailMoneySilver:SetText(CT_Mail_LastInfo.Silver);
  		SendMailMoneyGold:SetText(CT_Mail_LastInfo.Gold);
		end
	elseif ( index == 1 ) then
		SendMailMoneyCopper:SetText("");
  	SendMailMoneySilver:SetText("");
  	SendMailMoneyGold:SetText("");
  	SendMailErrorText:Hide();
  	SendMailErrorCoin:Hide();
	end
end);

hooksecurefunc("SendMailFrame_SendMail", function()
  CT_Mail_LastInfo.Sendee = SendMailNameEditBox:GetText();
  CT_Mail_LastInfo.Copper, CT_Mail_LastInfo.Silver, CT_Mail_LastInfo.Gold = SendMailMoneyCopper:GetText(), SendMailMoneySilver:GetText(), SendMailMoneyGold:GetText();
end);

hooksecurefunc("SendMailFrame_Reset", function()
  CT_Mail_RememberLastSendee();
end);

-- [2] New Mass Mail System ----------------------------------------------------
function CT_Mail_ItemIsMailable(bag, item)
	-- Make sure tooltip is cleared
	local i, obj = 1;
	while ( true ) do
		obj = getglobal("CT_MMTooltipTextLeft" .. i);
		if ( not obj ) then
			break;
		end
		obj:SetText("");
		i = i + 1;
	end
	
	CT_MMTooltip:SetBagItem(bag, item);
	for i = 1, CT_MMTooltip:NumLines(), 1 do
		local text = getglobal("CT_MMTooltipTextLeft" .. i):GetText();
		if ( text == ITEM_SOULBOUND ) then
			return ITEM_SOULBOUND;
		elseif ( text == ITEM_BIND_QUEST ) then
			return ITEM_BIND_QUEST;
		elseif ( text == ITEM_CONJURED ) then
			return ITEM_CONJURED;
		end
	end
end

function CT_Mail_BagTab_Init()
	for i = 4, 0, -1 do
		if GetBagName(i) ~= nil then CT_Mail_BagTab_OnClick(i); break; end
	end
	CT_Mail_BagTab_SetStatus();
end

function CT_Mail_BagTab_SetStatus()
	for i = 4, 1, -1 do
		local tab = getglobal("CT_MailBagTab"..i)
		if ( GetBagName(i) == nil ) then tab:Disable(); else tab:Enable(); end
	end
end

function CT_Mail_BagTab_OnClick(override)
	local id = override or this:GetID();
	local tab;
	PlaySound("GAMEGENERICBUTTONPRESS");
	for i = 0, 5 do
		tab = getglobal("CT_MailBagTab"..i);
		if ( tab ) then
			tab:UnlockHighlight();
		end
	end
	getglobal("CT_MailBagTab"..id):LockHighlight();
	bagID = id;
	if ( id == 5 ) then
		CT_Mail_SelectedFrame_Update(1);
	else
		CT_Mail_BagFrame_Update();
	end
end

function CT_Mail_SelectedFrame_Update(page)
	CT_MailBagTitleText:SetText(CT_MAIL_SELECTEDTITLE);
	
	for buttonID = 1, CT_MAIL_NUMITEMBUTTONS, 1 do
		local btn = getglobal("CT_MailButton" .. buttonID);
		btn:Show();
		btn.bag = nil;
		btn.item = nil;
		btn:SetNormalTexture(nil);
		btn:UnlockHighlight();
		getglobal(btn:GetName() .. "Count"):SetText("");
		getglobal("CT_MailBoxBagItem" .. buttonID .. "CB"):Hide();
	end
	
	buttonID = 0;
	currentPage = page
	for i = 4, 0, -1 do
		for k, v in pairs(CT_Mail_Selected[i]) do
			local texture, count, locked, quality, readable = GetContainerItemInfo(i, v);
			local unmailable = CT_Mail_ItemIsMailable(i, v)
			if (  not unmailable and texture ) then
				buttonID = buttonID + 1;
				if ( (currentPage - 1) * 21 < buttonID ) and ( buttonID <= currentPage * 21 ) then
					local pageButton = buttonID - (currentPage - 1) * 21
					local btn = getglobal("CT_MailButton" .. pageButton);
					btn:SetNormalTexture(texture);
					if ( count > 1 ) then
						getglobal(btn:GetName().."Count"):Show();
						getglobal(btn:GetName().."Count"):SetText(count);
					else
						getglobal(btn:GetName().."Count"):Hide();
					end
					btn.bag = i
					btn.item = v
				end
			end
		end
	end
	CT_MailBagFrame_PrevPageButton:Show();
	CT_MailBagFrame_NextPageButton:Show();
	if ( currentPage > 1 ) then
		CT_MailBagFrame_PrevPageButton:Enable();
	else
		CT_MailBagFrame_PrevPageButton:Disable();
	end
	if ( buttonID > currentPage * 21 ) then
		CT_MailBagFrame_NextPageButton:Enable();
	else
		CT_MailBagFrame_NextPageButton:Disable();
	end
	CT_Mail_BagFrameText_Update();
end

function CT_Mail_SelectedPrevPage_OnClick()
	if ( currentPage > 1 ) then
		currentPage = currentPage - 1;
	end
	CT_Mail_SelectedFrame_Update(currentPage);
end

function CT_Mail_SelectedNextPage_OnClick()
	if ( buttonID > currentPage * 21 ) then
		currentPage = currentPage + 1;
	end
	CT_Mail_SelectedFrame_Update(currentPage);
end

function CT_Mail_BagFrame_Update()
	if ( bagID == 5 ) then
		CT_Mail_SelectedFrame_Update(1);
	else
		-- Initiate Buttons
		for buttonID = 1, CT_MAIL_NUMITEMBUTTONS, 1 do
			local btn = getglobal("CT_MailButton" .. buttonID);
			btn.bag = nil;
			btn.item = nil;
			btn:SetNormalTexture(nil);
			btn:UnlockHighlight();
			getglobal(btn:GetName() .. "Count"):SetText("");
			getglobal("CT_MailBoxBagItem" .. buttonID .. "CB"):Hide();
			if ( buttonID > GetContainerNumSlots(bagID) ) then
				btn:Hide();
			else
				btn:Show();
			end
		end
		-- Find Mailable Items
		for i = 0, 4, 1 do
			for slotID = 1, GetContainerNumSlots(i), 1 do
				local texture, count, locked, quality, readable = GetContainerItemInfo(i, slotID);
				if ( CT_Mail_ItemIsMailable(i, slotID) == nil and texture ) then
					if ( CT_Mail_ItemExist(i, slotID) == true ) then else tinsert(CT_Mail_Mailables[i], slotID); end
				end
			end
		end
		-- Show Mailable Items
		local buttonID = 0;
		for slotID = 1, GetContainerNumSlots(bagID), 1 do
			local texture, count, locked, quality, readable = GetContainerItemInfo(bagID, slotID);
			local unmailable = CT_Mail_ItemIsMailable(bagID, slotID)
			if (  not unmailable and texture ) then
				buttonID = buttonID + 1;
				if buttonID > CT_MAIL_NUMITEMBUTTONS then
					break;
				end
				local btn = getglobal("CT_MailButton" .. buttonID);
				btn:SetNormalTexture(texture);
				if ( count > 1 ) then
					getglobal(btn:GetName().."Count"):Show();
					getglobal(btn:GetName().."Count"):SetText(count);
				else
					getglobal(btn:GetName().."Count"):Hide();
				end
				
				getglobal("CT_MailBoxBagItem"..buttonID.."CB"):Show();
				getglobal("CT_MailBoxBagItem"..buttonID.."CB"):SetChecked(nil);
				
				btn.bag = bagID
				btn.item = slotID
			end
		end
		-- Check Selected Items
		for k1, v1 in pairs(CT_Mail_Mailables[bagID]) do
			for k2, v2 in pairs(CT_Mail_Selected[bagID]) do
				if ( v1 == v2 ) then 
					getglobal("CT_MailBoxBagItem"..k1.."CB"):SetChecked(1);
					getglobal("CT_MailButton" .. k1):LockHighlight();
				end
			end
		end
		
		CT_MailBagTab5:SetWidth(100);
		CT_MailBagTab5:SetText(CT_MAIL_SELECTEDBUTTON);
		CT_MailBagFrame_PrevPageButton:Hide();
		CT_MailBagFrame_NextPageButton:Hide();
		
		local bagNum = bagID + 1
		CT_MailBagTitleText:SetText(format(CT_MAIL_BAGTITLE, bagNum));
		
		CT_Mail_BagFrameText_Update();
	end
end

function CT_Mail_BagFrameText_Update()
	for i = 0, 4, 1 do
		local bagNum = i + 1;
		local itemNum = getn(CT_Mail_Selected[i]);
		if ( itemNum == 0 ) then itemMark = " "; else itemMark = "*";	end
		getglobal("CT_MailBagTab"..i):SetText(bagNum..itemMark);
	end
	
	local num = CT_Mail_GetNumSelected();
	local total = CT_Mail_GetNumMailables();
	CT_Mail_CanSend(CT_MailNameEditBox);
	if ( num == 0 ) then CT_MailCostMoneyFrame:Hide(); else CT_MailCostMoneyFrame:Show(); end -- added by Bitz
	MoneyFrame_Update("CT_MailCostMoneyFrame", GetSendMailPrice()*num);
	
	if ( ( num == 0 and total == 0 ) or ( num == 0 and bagID == 5) ) then
		CT_MailAmountStatus:SetText("");
	else
		if ( num == 0 and total > 0 ) then num = ""; else num = num.."/"; end
		CT_MailAmountStatus:SetText(format(CT_MAIL_AMOUNT, num, total));
	end
end

function CT_Mail_ItemExist(bagID, slotID)
	for k, v in pairs(CT_Mail_Mailables[bagID]) do
		if ( v == slotID ) then return true; end
	end
end

function CT_MailBag_SetSelected()
	local id = this:GetID();
	local btn = getglobal("CT_MailButton" .. id);
	if ( bagID == 5 ) then
		if ( btn.bag ~= nil ) then
			for k, v in pairs(CT_Mail_Selected[btn.bag]) do
				if ( v == btn.item ) then tremove(CT_Mail_Selected[btn.bag], k); break; end
			end
			GameTooltip:Hide();
			CT_Mail_SelectedFrame_Update(currentPage);
			CT_Mail_ContainerFrame_Update();
		end
	else
		if ( not this:GetChecked() ) then
			for k, v in pairs(CT_Mail_Selected[bagID]) do
				if ( v == btn.item ) then tremove(CT_Mail_Selected[bagID], k); break; end
			end
		else
			for k, v in pairs(CT_Mail_Mailables[bagID]) do
				if ( k == id ) then tinsert(CT_Mail_Selected[bagID], v); end
			end
		end
		if ( IsAltKeyDown() ) then
			local itemName = CT_Mail_GetBagItemName(bagID, id)
	    if ( not this:GetChecked()) then
	    	DeselectedBagItem = itemName;
	    else
	    	SelectedBagItem = itemName;
	    end
	  	CT_Mail_SetSelectedSameItem(bagID, id);
	  end
	  if ( IsShiftKeyDown() ) then
	 		for i = 1, getn(CT_Mail_Selected[bagID]) do
	 			tremove(CT_Mail_Selected[bagID], i);
	 		end
	 		if ( not this:GetChecked() ) then
	    else
	    	for k, v in pairs(CT_Mail_Mailables[bagID]) do
	    		tinsert(CT_Mail_Selected[bagID], v);
	    	end
	    end
	  end
	  CT_MailStatusText:SetText("");
	  CT_MailMassButton:Show();
		CT_MailCODButton:Show();
		
		CT_Mail_BagFrame_Update();
		CT_Mail_ContainerFrame_Update();
	end
end

function CT_Mail_GetBagItemName(bagID, slotID)
	for k, v in pairs(CT_Mail_Mailables[bagID]) do
		if ( k == slotID ) then
			local itemLink = GetContainerItemLink(bagID, v);
			local found, _, itemName = string.find(itemLink, "^|%x+|H.+|h%[(.+)%]");
			return itemName;
		end
	end
end

hooksecurefunc("BagSlotButton_OnClick", function()
	if ( CT_MailFrame:IsVisible() ) then
		CT_Mail_ContainerFrame_Update();
	end
end);

hooksecurefunc("BackpackButton_OnClick", function()
	if ( CT_MailFrame:IsVisible() ) then
		CT_Mail_ContainerFrame_Update();
	end
end);

function CT_Mail_ContainerFrame_Update()
	for i = 1, NUM_CONTAINER_FRAMES, 1 do
		if ( getglobal("ContainerFrame" .. i):IsVisible() ) then
			ContainerFrame_Update(getglobal("ContainerFrame" .. i));
		end
	end
end

function CT_Mail_SetSelectedSameItem(bagID, slotID)
	for k1, v1 in pairs(CT_Mail_Mailables[bagID]) do
		local itemLink = GetContainerItemLink(bagID, v1);
		local found, _, itemName = string.find(itemLink, "^|%x+|H.+|h%[(.+)%]");
		if ( itemName == SelectedBagItem and k1 ~= slotID ) then
  	  if ( CT_Mail_SelectedItemExist(bagID, v1) == true ) then
  	  else
      	tinsert(CT_Mail_Selected[bagID], v1);
      end
		elseif ( itemName == DeselectedBagItem and k1 ~= slotID ) then
			for k2, v2 in pairs(CT_Mail_Selected[bagID]) do
				if ( v2 == v1 ) then tremove(CT_Mail_Selected[bagID], k2); break;	end
			end
		end
	end
	SelectedBagItem = nil;
	DeselectedBagItem = nil;
end

function CT_Mail_SelectedItemExist(bagID, slotID)
	for k, v in pairs(CT_Mail_Selected[bagID]) do
		if ( v == slotID ) then return true; end
	end
end

function CT_Mail_GetNumMailables()
	local total = 0;
	for i = 0, 4 do
		num = getn(CT_Mail_Mailables[i]);
		num = num + total;
		total = num;
	end
	return total;
end

function CT_Mail_GetNumSelected()
	local total = 0;
	for i = 0, 4 do
		num = getn(CT_Mail_Selected[i]);
		num = num + total;
		total = num;
	end
	return total;
end

function CT_Mail_ClearItems()
	CT_Mail_TableInitiate();
	CT_MailNameEditBox:SetText("");
	CT_MailSubjectEditBox:SetText("");
	CT_MailStatusText:SetText("");
	CT_MailSendButton:Disable();
	CT_MailAbortButton:Hide();
	CT_Mail_AcceptSendFrame:Hide();
	MoneyInputFrame_ResetMoney(CT_MailCODAmount);
end

function CT_Mail_TableInitiate()
	for i = 0, 4 do
		CT_Mail_Mailables[i] = { };
		CT_Mail_Selected[i] = { };
	end
	CT_MailCostMoneyFrame:Hide();
end

function CT_Mail_CanSend()
	local checks = 0;
	local checksRequired = 1;
	local num = CT_Mail_GetNumSelected()
	if ( strlen(CT_MailNameEditBox:GetText()) > 0 and num > 0 and GetSendMailPrice()*num <= GetMoney() ) then
		checks = checks + 1;
	end
	if ( CT_MailCODButton:GetChecked() ) then
		checksRequired = 2;
		local copper = MoneyInputFrame_GetCopper(CT_MailCODAmount)
		if ( copper > MAX_COD_AMOUNT*COPPER_PER_GOLD ) then
			CT_MailCODErrorText:Show();
			CT_MailCODErrorCoin:Show();
			CT_MailCODErrorText:SetText(format(CT_MAIL_CODERROR, MAX_COD_AMOUNT));
			CT_MailCODErrorText:SetPoint("TOPLEFT", "CT_MailCODAmountText", "TOPLEFT", 18, 11);
		elseif ( copper == 0 ) then
		else
			CT_MailCODErrorText:Hide();
			CT_MailCODErrorCoin:Hide();
			checks = checks + 1;
		end
	end
	if ( checks == checksRequired ) then
		CT_MailSendButton:Enable();
	else
		CT_MailSendButton:Disable();
	end
end

hooksecurefunc("SendMailFrame_CanSend", function()
	if ( GetLocale() == "koKR" ) then
		SendMailErrorText:SetText(format(CT_MAIL_ERROR_COD, MAX_COD_AMOUNT));
	end
end);

function CT_Mail_SendMail()
	for key, val in pairs(this.queue) do
		for i = 1, 21, 1 do
			getglobal("CT_MailBoxBagItem"..i.."CB"):Disable()
		end
		CT_MailCODAmount:Hide()
		CT_MailMassButton:Hide()
		CT_MailCODButton:Hide()
	  if ( GetLocale() == "koKR" ) then
	    CT_MailStatusText:SetText(format(CT_MAIL_SENDING, this.total, key));
	  else
		  CT_MailStatusText:SetText(format(CT_MAIL_SENDING, key, this.total));
		end
		CT_MailAbortButton:Show();
    
    CT_Mail_Queue = key;  -- Needed in CT_Mail_AbortSending()
    
		if ( GetSendMailItem() and CT_MailFrame.mailbag and CT_MailFrame.mailitem ) then
			-- There's already an item in the slot
			ClickSendMailItemButton();
			PickupContainerItem(CT_MailFrame.mailbag, CT_MailFrame.mailitem);
			CT_MailFrame.mailbag = nil;
			CT_MailFrame.mailitem = nil;
		elseif ( CursorHasItem() and CT_MailFrame.bag and CT_MailFrame.item ) then
			PickupContainerItem(CT_MailFrame.bag, CT_MailFrame.item);
			CT_MailFrame.bag = nil;
			CT_MailFrame.item = nil;
		end
		
		PickupContainerItem(val.bag, val.item);
		ClickSendMailItemButton();
    
		local name, useless, count = GetSendMailItem();
		if ( not name ) then 
		  if ( GetLocale() == "koKR" ) then
		    DEFAULT_CHAT_FRAME:AddMessage(CT_MAIL_ERROR, 1, 0, 0);
		  else
			  DEFAULT_CHAT_FRAME:AddMessage("<CTMod> "..CT_MAIL_ERROR, 1, 0, 0);
			end
		else
			local copper = val.copper
    	if ( CT_MailCODButton:GetChecked() and copper > 0 ) then
    		SetSendMailCOD(copper);
    	end
			
			local subjectstr = val.subject;
			if ( strlen(subjectstr) > 0 ) then
				subjectstr = subjectstr .. " - ";
			end
			if ( count > 1 ) then
				subjectstr = subjectstr .. name .. " (" .. count .. ")";
			else
				subjectstr = subjectstr .. name;
			end
			SendMail(val.to, subjectstr, "");
		end
		CT_MailGlobalFrame.queue[key] = nil;
		return;
	end
	for i = 1, 21, 1 do
		getglobal("CT_MailBoxBagItem"..i.."CB"):Enable();
	end
	CT_MailStatusText:SetText(format(CT_MAIL_DONESENDING, this.total));
	CT_MailAbortButton:Hide();
	CT_MailGlobalFrame:Hide();
  
	CT_MailGlobalFrame.total = 0;
	CT_MailGlobalFrame.queue = { };
	
	CT_Mail_TableInitiate();
	CT_Mail_BagFrame_Update();
	CT_MailRadioButton_OnClick(1);
	CT_MailCostMoneyFrame:Hide();
	CT_MassMail_RememberLastSendee();
end

function CT_Mail_AbortSending()
  if ( GetLocale() == "koKR" ) then
    CT_MailStatusText:SetText(format(CT_MAIL_ABORTED, CT_MailGlobalFrame.total, CT_Mail_Queue));
  else
	  CT_MailStatusText:SetText(format(CT_MAIL_ABORTED, CT_Mail_Queue, CT_MailGlobalFrame.total));
	end
	for i = 1, 21, 1 do
		getglobal("CT_MailBoxBagItem"..i.."CB"):Enable()
	end
  CT_MailGlobalFrame.queue = { };
	CT_MailGlobalFrame.total = 0;
	CT_MailGlobalFrame:Hide();
	CT_MailAbortButton:Hide();
	CT_MailCostMoneyFrame:Hide();
	CT_Mail_TableInitiate();
	CT_MassMail_RememberLastSendee();
end

function CT_Mail_FillItemTable()
  CT_Mail_LastInfo.MassSendee = CT_MailNameEditBox:GetText();
	local arr = { };
	for bagID = 0, 4, 1 do
		for k, slotID in pairs(CT_Mail_Selected[bagID]) do
			tinsert(arr, { ["item"] = slotID, ["bag"] = bagID, ["to"] = CT_MailNameEditBox:GetText(), ["subject"] = CT_MailSubjectEditBox:GetText(), ["copper"] = MoneyInputFrame_GetCopper(CT_MailCODAmount) });
		end
	end
	return arr;
end

function CT_Mail_ProcessQueue(elapsed)
	if ( not CT_Mail_CanSendNext ) then
		return;
	end
	this.sendmail = this.sendmail + elapsed;
	if ( this.sendmail > 0.5 ) then
		this.sendmail = 0;
		if ( this.total > 0 ) then
			CT_Mail_SendMail();
			CT_Mail_CanSendNext = nil;
		end
	end
end

hooksecurefunc("ContainerFrame_Update", function(frame)
	local id = frame:GetID();
	if ( CT_MailFrame:IsVisible() ) then
		if ( id ~= -2 ) then
			for k, v in pairs(CT_Mail_Selected[id]) do
				SetItemButtonDesaturated(getglobal(frame:GetName().."Item"..(frame.size-v)+1), 1, 0.5, 0.5, 0.5);
			end
		end
		if ( CT_Mail_addItem and CT_Mail_addItem[1] == frame:GetID() ) then
			SetItemButtonDesaturated(getglobal(frame:GetName() .. "Item" .. (frame.size-CT_Mail_addItem[2])+1), 1, 0.5, 0.5, 0.5);
		end
	end;
end);

hooksecurefunc("ContainerFrame_GenerateFrame", function(frame, size, id)
	if ( id ~= KEYRING_CONTAINER ) then
		local bagNum;
		if ( id > 4 ) then bagNum = id - 4; else bagNum = id + 1; end
		if ( string.find(frame:GetName(), "^ContainerFrame") ) then
			getglobal(frame:GetName().."Name"):SetText(bagNum.."."..GetBagName(id));
		end
	end
end);

-- Hook the TradeFrame OnShow
CT_Mail_oldTradeFrameShow = TradeFrame:GetScript("OnShow");
function CT_Mail_newTradeFrameShow()
	CT_Mail_oldTradeFrameShow();
	if ( CT_Mail_addItem and not CursorHasItem() and UnitName("NPC") == CT_Mail_addItem[3] ) then
		PickupContainerItem(CT_Mail_addItem[1], CT_Mail_addItem[2]);
		ClickTradeButton(1);
	end
	CT_Mail_addItem = nil;
end
TradeFrame:SetScript("OnShow", CT_Mail_newTradeFrameShow);

-- COD Button in CT_MailFrame
function CT_MailRadioButton_OnClick(index)
	if ( index == 1 ) then
		CT_MailMassButton:SetChecked(1);
		CT_MailCODButton:SetChecked(nil);
		CT_MailCODAmount:Hide();
	else
		CT_MailMassButton:SetChecked(nil);
		CT_MailCODButton:SetChecked(1);
		CT_MailCODAmount:Show();
	end
	CT_Mail_CanSend(CT_MailNameEditBox);
	PlaySound("igMainMenuOptionCheckBoxOn");
end

-- [3] Sendee List Dropdown Menu (adapted from Mailto) -------------------------
local Server, CT_Mail_ToName, CT_MassMail_ToName, CT_Mail_SavedName;
function CT_Mail_DropDownMenu_Init()
  Server = GetCVar("realmName");
  if ( not CT_Mail_ToList[Server] ) then CT_Mail_ToList[Server] = {}; end
  CT_Mail_SavedName = CT_Mail_Sendee[Server];
  CT_MailDropDownMenu.displayMode = "MENU";
  CT_MassMailDropDownMenu.displayMode = "MENU";
end

function CT_Mail_DropDownMenu_OnLoad()
  this.tooltip = CT_MAIL_DROPDOWN_TOOLTIP;
  UIDropDownMenu_Initialize(this:GetParent(), CT_Mail_ToList_Init);
  UIDropDownMenu_SetAnchor(0, 0, this:GetParent(), "TOPRIGHT", this:GetName(), "BOTTOMRIGHT");
  if ( MailTo_Init ) then
    MailToDropDownMenu:Hide();
  end
end

function CT_Mail_ToList_Init()
  local info = {value = 0, notCheckable = 1};
  local CT_Mail_NameSelected, CT_MassMail_NameSelected;
  if ( SendMailFrame:IsVisible() ) then
    CT_Mail_ToName = SendMailNameEditBox:GetText();
    if ( CT_Mail_ToName ~= '' ) then
      CT_Mail_NameSelected = CT_Mail_InList(CT_Mail_ToName);
      if ( not CT_Mail_NameSelected ) then
        info.text = string.format(CT_MAIL_SENDEEADD, CT_Mail_ToName);
        info.func = CT_Mail_ToListAdd;
      else
        info = nil;
      end
      if ( not CT_Mail_NameSelected and info ) then UIDropDownMenu_AddButton(info); end
    else
      CT_Mail_NameSelected = nil;
    end
    for key, name in pairs(CT_Mail_ToList[Server]) do
      info = {text = name, value = key, func= CT_Mail_ToListSelect}
      if ( key == CT_Mail_NameSelected ) then info.checked = 1; end
      if ( name ~= UnitName("player") ) then UIDropDownMenu_AddButton(info); end
    end
  else
    CT_MassMail_ToName = CT_MailNameEditBox:GetText();
    if ( CT_MassMail_ToName ~= '' ) then
      CT_MassMail_NameSelected = CT_Mail_InList(CT_MassMail_ToName);
      if ( not CT_MassMail_NameSelected ) then
        info.text = string.format(CT_MAIL_SENDEEADD, CT_MassMail_ToName);
        info.func = CT_Mail_ToListAdd;
      else
        info = nil;
      end
      if ( not CT_MassMail_NameSelected and info ) then UIDropDownMenu_AddButton(info); end
    else
      CT_MassMail_NameSelected = nil;
    end
    for key,name in pairs(CT_Mail_ToList[Server]) do
      info = {text = name, value = key, func = CT_Mail_ToListSelect};
      if ( key == CT_MassMail_NameSelected ) then info.checked = 1; end
      if ( name ~= UnitName("player") ) then UIDropDownMenu_AddButton(info); end
    end
  end
end

function CT_Mail_ToListSelect()
  local value = this.value;
  if ( value ) then
    CT_Mail_SavedName = CT_Mail_ToList[Server][value]
    if ( SendMailFrame:IsVisible() ) then
      SendMailNameEditBox:SetText(CT_Mail_SavedName);
      SendMailNameEditBox:HighlightText(0, -1);
      SendMailSubjectEditBox:SetFocus();
    else
      CT_MailNameEditBox:SetText(CT_Mail_SavedName);
      CT_MailNameEditBox:HighlightText(0, -1);
      CT_MailSubjectEditBox:SetFocus();
    end
  end
end

function CT_Mail_ToListAdd(name)
  if ( not name ) then
  	if ( SendMailFrame:IsVisible() ) then
  		name = CT_Mail_ToName;
  	else
  		name = CT_MassMail_ToName;
  	end
  end
  if ( getn(CT_Mail_ToList[Server]) == UIDROPDOWNMENU_MAXBUTTONS-1 ) then
  	DEFAULT_CHAT_FRAME:AddMessage(CT_MAIL_LISTFULL, 1,0,0);
  else
		tinsert(CT_Mail_ToList[Server], name);
		sort(CT_Mail_ToList[Server]);
		DEFAULT_CHAT_FRAME:AddMessage(string.format(CT_MAIL_SENDEE_ADDED, name), 1,1,0);
	end
end

function CT_Mail_InList(MCname)
  local LCname = string.lower(MCname);
  for key, name in pairs(CT_Mail_ToList[Server]) do
    if ( LCname == string.lower(name) ) then return key; end
  end
end

-- [4] Option Frame ------------------------------------------------------------
function CT_Mail_OptionTab_OnClick(override)
	local id = override or this:GetID();
	for i = 1, 2 do
		local tab = getglobal("CT_MailOptionFrameTab"..i);
		local frame = getglobal("CT_MailOptionFrame"..i);
		if ( i == id ) then
			PanelTemplates_SelectTab(tab);
			frame:Show();
		else
			PanelTemplates_DeselectTab(tab);
			frame:Hide();
		end
	end
end

function CT_Mail_SendeeListScrollBar_Update()
	local line;
	local lineplusoffset;
	FauxScrollFrame_Update(CT_MailOptionFrame1ListPanelScrollBar, getn(CT_Mail_ToList[Server]),7,16);
	for line = 1, 7 do
		local listbtn = getglobal("CT_MailOptionFrame1ListPanelButton"..line);
		lineplusoffset = line + FauxScrollFrame_GetOffset(CT_MailOptionFrame1ListPanelScrollBar);
		if ( lineplusoffset <= getn(CT_Mail_ToList[Server]) ) then
			getglobal("CT_MailOptionFrame1ListPanelButton"..line.."Name"):SetText(CT_Mail_ToList[Server][lineplusoffset]);
			listbtn.SendeeName = CT_Mail_ToList[Server][lineplusoffset];
			if ( CT_Mail_Sendee_Selected == CT_Mail_ToList[Server][lineplusoffset] ) then
				listbtn:LockHighlight();
			else
				listbtn:UnlockHighlight();
			end
			listbtn:Show();
		else
			listbtn:Hide();
		end
	end
	if ( getn(CT_Mail_ToList[Server]) == 0 ) then
		CT_MailOptionFrame1ListPanelRemove:Disable();
		CT_MailOptionFrame1ListPanelReset:Disable();
	else
		CT_MailOptionFrame1ListPanelRemove:Enable();
		CT_MailOptionFrame1ListPanelReset:Enable();
	end
end

function CT_Mail_ToListRemove()
	local key;
	for k, v in pairs(CT_Mail_ToList[Server]) do
		if ( v == CT_Mail_Sendee_Selected ) then
			tremove(CT_Mail_ToList[Server], k);
			key = k;
			DEFAULT_CHAT_FRAME:AddMessage(string.format(CT_MAIL_SENDEE_REMOVED, v), 1,0.5,0);
		end
	end
	CT_Mail_Sendee_Selected = CT_Mail_ToList[Server][key];
	CT_Mail_SendeeListScrollBar_Update();
end

StaticPopupDialogs["CT_MAIL_ADDSENDEE_CONFIRMATION"] = {
	text = TEXT(CT_MAIL_ADDSENDEE_CONFIRMATION_TEXT),
	button1 = TEXT(OKAY),
	button2 = TEXT(CANCEL),
	OnShow = function()
		local editbox = getglobal(this:GetName().."EditBox")
    editbox:SetText("");
    editbox:SetScript("OnCharComposition", SendMailFrame_SendeeAutocomplete);
    editbox:SetScript("OnChar", function()
    	if ( not this:IsInIMECompositionMode() ) then
				SendMailFrame_SendeeAutocomplete();
			end
		end);
	end,
	OnAccept = function()
		local name = getglobal(this:GetParent():GetName().."EditBox"):GetText();
		if ( CT_Mail_SendeeExist(name) == true ) then
			DEFAULT_CHAT_FRAME:AddMessage(string.format(CT_MAIL_ERROR_ADD, name), 1,0,0);
		else
			CT_Mail_ToListAdd(name);
			CT_Mail_SendeeListScrollBar_Update();
		end
	end,
	hasEditBox = 1,
	timeout = 0,
	exclusive = 1,
	hideOnEscape = 1,
};

function CT_Mail_SendeeExist(name)
	for k, v in pairs(CT_Mail_ToList[Server]) do
		if ( v == name ) then return true; end
	end
end

StaticPopupDialogs["CT_MAIL_RESETSENDEES_CONFIRMATION"] = {
	text = TEXT(CT_MAIL_RESETSENDEES_CONFIRMATION_TEXT),
	button1 = TEXT(YES),
	button2 = TEXT(NO),
	OnAccept = function()
		CT_Mail_ToList[Server] = { };
		CT_Mail_SendeeListScrollBar_Update();
		DEFAULT_CHAT_FRAME:AddMessage(CT_MAIL_SENDEE_RESET, 1,0,0);
	end,
	timeout = 0,
	exclusive = 1,
	hideOnEscape = 1,
};
