-- SELECTED_CHAT_FRAME:AddMessage("MT: "..msg, 0.0, 0.9, 0.9)
local _G = getfenv(0)
local f = CreateFrame("Frame")

f:RegisterEvent("VARIABLES_LOADED")
f:RegisterEvent("PLAYER_ENTERING_WORLD")
f:SetScript("OnEvent", function(_, event)
	if (event == "VARIABLES_LOADED") then 
	  SCM_ChatFade(); 
	  SCM_OnLoad();
	end 
end)
-- =================================================================================
-- 기본 설정값 --
-- =================================================================================
SCMSaved= {
  enableWheel=     true;  -- 마우스 휠 스크롤 기능
  chatFade=        false; -- 대화내용 숨김 (일정시간 동안 새로운 내용이 없을결루 해당 대화창을 숨깁니다.)
---------------- 위까진 메뉴설정, 아래는 직접 수정 ( true or false ) ---------------
  MoveEditBox=     false;  -- 대화입력창 위로 표시 (true=위,false=아래)
  FadeMenuButton=  true; -- 메뉴버튼 숨김
  shortChannels=   true;  -- 짧은 채널명 (예. [1] 기존 [1. 공개]) 
};

if SCMChatDB==nil then SCMChatDB = {}; end  
if SCMChatDB["Head"] == nil then  SCMChatDB["Head"] = ""; end
if SCMChat==nil then  SCMChat = {};  end 	
if SCMChat["CallMe"] == nil then  SCMChat["CallMe"] = {}; end
	
local function print(msg)
  DEFAULT_CHAT_FRAME:AddMessage(msg);
end;
    
-- =================================================================================
-- 대화 입력창 이동
-- =================================================================================
do
	for i =1, 10 do
  local eb = _G[format("%s%d%s", "ChatFrame", i, "EditBox")] -- ChatFrameEditBox
  local cf = _G[format("%s%d", "ChatFrame", i)]
  if (SCMSaved.MoveEditBox == true) then
  	eb:ClearAllPoints()
	eb:SetPoint("BOTTOMLEFT",  cf, "TOPLEFT",  -5, 0)
	eb:SetPoint("BOTTOMRIGHT", cf, "TOPRIGHT", 5, 0)
  elseif (SCMSaved.MoveEditBox == false) then
	eb:ClearAllPoints()
	eb:SetPoint("TOPLEFT",  cf, "BOTTOMLEFT",  -5, 0)
	eb:SetPoint("TOPRIGHT", cf, "BOTTOMRIGHT", 5, 0)
  end; 

-- =================================================================================
--  알트 클릭 초대
-- =================================================================================
hooksecurefunc("SetItemRef", function(link)
    if IsAltKeyDown() and link then
	local name = link:match("^player:([^:]+).*$")
	if name then InviteUnit(name) eb:Hide() end 
    end
end)
-- =================================================================================
-- 방향키 기능 추가 
-- =================================================================================
        eb:SetAltArrowKeyMode(false)  
  end
end

-- =================================================================================
-- 채널 고정 기능 추가
-- =================================================================================
ChatTypeInfo["CHANNEL"].sticky = 1; --채널대화
ChatTypeInfo["OFFICER"].sticky = 1; --공대 오피서
ChatTypeInfo["RAID_WARNING"].sticky = 1; --공대 경보
ChatTypeInfo["WHISPER"].sticky 	= 1;  -- 귓속말

function SCM_OnLoad()
-- =================================================================================
-- 추가 슬래쉬 명령어
-- =================================================================================
  SlashCmdList["SCM"]= SCM_Command;
  SLASH_SCM1= "/scm";
  SLASH_SCM2= "/sc";
  SlashCmdList["CALCULATOR"] = function(msg) Calculator(msg) end
  SLASH_CALCULATOR1="/계산";
  SLASH_CALCULATOR2="//";
  SlashCmdList["SCMH"] = SCM_SetHead;
  SLASH_SCMH1 = "/말머리";
  SlashCmdList["SCMCM"] = SCMCM_Set;
  SLASH_SCMCM1 = "/나를불러주세요";
  SLASH_SCMCM2 = "/callme";
-- =================================================================================  
-- 귓속말 표시 설정
-- =================================================================================
  SCM_CUSTOM_CHT_FROM				= "<FR>%s:\32"; --귓속말 받음 표시
  SCM_CUSTOM_CHT_TO				= "<To>%s:\32"; --귓속말 보냄 표시
  SCM_CUSTOM_CHT_YELL                             = "[Y]%s:\32"; --외침 표시
  print(NORMAL_FONT_COLOR_CODE.."SisterChatMods"..FONT_COLOR_CODE_CLOSE.." 불러옴. "..NORMAL_FONT_COLOR_CODE.."/sc"..FONT_COLOR_CODE_CLOSE.." : 명령어 출력. ("..NORMAL_FONT_COLOR_CODE.."자매"..FONT_COLOR_CODE_CLOSE..",노르간논)");
end;

-- =================================================================================
-- 말머리
-- =================================================================================
function SCM_SetHead(msg) SCMChatDB["Head"] = msg; end
SCM_SendChatMessage = SendChatMessage;
function HEAD_SendChatMessage(msg, chatType, language, channel)
	if instype~="arena"	then SCM_SendChatMessage(SCMChatDB["Head"]..msg, chatType, language, channel); end
end
SendChatMessage = HEAD_SendChatMessage;

-- =================================================================================
-- 나를불러주세요
-- =================================================================================
function SCMCM_Set(msg)         
local c,x = string.split(" ",msg)
  if c=="" then 
         DEFAULT_CHAT_FRAME:AddMessage("|cFFFFCC00 - 나를 불러주세요 -  |r");
         DEFAULT_CHAT_FRAME:AddMessage("  |cFFFFCC00/나를불러주세요 추가 '별명' 으로 추가.|r")
         DEFAULT_CHAT_FRAME:AddMessage("  |cFFFFCC00/나를불러주세요 제거 '별명' 으로 추가.|r")
         DEFAULT_CHAT_FRAME:AddMessage("  |cFFFFCC00/나를불러주세요 '초기화' 로 목록삭제.|r")
         DEFAULT_CHAT_FRAME:AddMessage("  |cFFFFCC00/나를불러주세요 '목록' 으로 목록확인.|r")
  elseif (c=="초기화") then
      SCMChat["CallMe"] = {};
         DEFAULT_CHAT_FRAME:AddMessage("|cFFFFCC00 - 나를 불러주세요 -  |r");
         DEFAULT_CHAT_FRAME:AddMessage("  |cFFFFCC00별명 목록이 초기화 되었습니다.|r")
  elseif (c=="추가") then  
    if x==nil then
         DEFAULT_CHAT_FRAME:AddMessage("|cFFFFCC00 - 나를 불러주세요 -  |r");
         DEFAULT_CHAT_FRAME:AddMessage("  |cFFFFCC00추가 할 별명을 입력하세요.|r")
    else
      tinsert(SCMChat.CallMe,x)
         DEFAULT_CHAT_FRAME:AddMessage("|cFFFFCC00 - 나를 불러주세요 -  |r");
         DEFAULT_CHAT_FRAME:AddMessage("  |cFFFFCC00별명 |c00FFFFFF: "..x.." |CFF00FF00추가|r" ) 
    end
  elseif (c=="제거") then  
    if x==nil then
         DEFAULT_CHAT_FRAME:AddMessage("|cFFFFCC00 - 나를 불러주세요 -  |r");
         DEFAULT_CHAT_FRAME:AddMessage("  |cFFFFCC00제거 할 별명을 입력하세요.|r")
    else
      	 local _type = "string";
	 local rn = 0;
	 if( _type == "string" )then
		for i=1,#SCMChat.CallMe,1 do
			if( SCMChat.CallMe[i] == x )then
				rn = i;
			end
		end
	 end
	 tremove(SCMChat.CallMe,rn);
         DEFAULT_CHAT_FRAME:AddMessage("|cFFFFCC00 - 나를 불러주세요 -  |r");
         DEFAULT_CHAT_FRAME:AddMessage("  |cFFFFCC00별명 |c00FFFFFF: "..x.." |CFF00FF00제거|r" ) 
    end
  elseif c=="목록" then  
    if (table.getn(SCMChat.CallMe) > 0) then
         DEFAULT_CHAT_FRAME:AddMessage("|cFFFFCC00 - 나를 불러주세요 -  |r");
	   for i=1,table.getn(SCMChat.CallMe) do
	     DEFAULT_CHAT_FRAME:AddMessage("["..i.."]. "..SCMChat.CallMe[i]);
	   end
      else 
         DEFAULT_CHAT_FRAME:AddMessage("  |cFFFFCC00별명 목록이 없습니다. |r");		
      end
   end
end

-- =================================================================================
-- 나를 불러주세요 
-- =================================================================================
local hook = {}
local k = nil
local Chat = ChatFrame1
local Call_AddMessage = Chat.AddMessage
local ChatAddMessage = function(self, text, ...)
local chattypes = _G.ChatTypeInfo

  local text2 = text
  local found2 = false  
  local name2, cont2, cha2
  local s2,e2 = string.find(text2, "(|Hplayer:.-|h%[)([^%s]+)(%])");
  if not s2 then return Call_AddMessage(self, text, ...)	end

  cha2 = string.sub(text2, 1, s2-1) -- 채널
  name2 = string.sub(text2, s2, e2) -- 캐릭명
  cont2= string.sub(text2, e2+1)    -- 내용

    if (type(text2) == "string") and not string.find(name2, UnitName("player")) then

       if SCMChat["CallMe"] ~= {} then
  	    for k2, v2 in pairs(SCMChat.CallMe) do  	    
       		cont2, nMatch = gsub(cont2, v2, "|cFFFFCC00"..v2.."|r")		
     	  	if string.find(cont2,v2) then
    		    PlaySoundFile("Interface\\AddOns\\SisterChatMods\\Sound\\CallMe.wav"); 
		    color = chattypes["CHANNEL"]
		    RaidNotice_AddMessage(RaidWarningFrame, name2..cont2, color)
		    --UIErrorsFrame:AddMessage(name2..cont2, 1, 1, 0, 1.0, UIERRORS_HOLD_TIME);
    		end
    	    end
       end
   end
   return Call_AddMessage(self, cha2..name2..cont2, ...)	
end

for i=1,NUM_CHAT_WINDOWS do
  if i~=2 then                   --전투 로그창 제외
    k = _G['ChatFrame'..i];
    hook[k] = k.AddMessage;
    k.AddMessage = ChatAddMessage;
  end
end  

-- =================================================================================
-- 채널명 줄임
-- =================================================================================
if (SCMSaved.shortChannels) then
local _G = getfenv(0)
local gsub = _G.string.gsub
local hooks = {}
local h = nil
local CHANNEL_STYLE = "[%1]"

local function AddMessage(frame, text, ...)
  local arg= { ... };  
     if event == "CHAT_MSG_CHANNEL" then  text = text:gsub( "%[%d+%.%s?[^%]%-]+%]%s?", CHANNEL_STYLE:gsub("%%1", arg8, 1), 1 ) end 
  return hooks[frame](frame, text, ...)
end

for i=1,NUM_CHAT_WINDOWS do
  h = _G['ChatFrame'..i];
  hooks[h] = h.AddMessage;
  h.AddMessage = AddMessage;
end    
end

-- =================================================================================
-- SisterChatMods 명령어
-- =================================================================================
function SCM_Command(msg)
  local cs= NORMAL_FONT_COLOR_CODE;
  local ce= FONT_COLOR_CODE_CLOSE;
  local header= cs.."SisterChatMods: "..ce;
  if (msg == "") then
    print(header.."설정을 위한 명령어들 입니다.:");
    print(cs.."/sc 채널"..ce.." 채널명 표시 형식 전환");
    print(cs.."/sc 휠"..ce.."  마우스 휠 스크롤 On/Off");
    print(cs.."/sc 지속"..ce.." 대화 지속 On/Off\n         '일정시간 후 대화내용이 숨겨짐을 방지합니다.'");
    print(cs.."/sc 입력창"..ce.." 대화 입력창 위/아래 전환");
    print(cs.."/tt or /ㅅㅅ"..ce.." 대상에게 귓속말");
    print(cs.."/말머리 내용"..ce.." 말머리 설정");
    print(cs.."/나를불러주세요"..ce.." 나를불러주세요 설정");
    print(cs.."/해산"..ce.." 공격대 해산 '공격대장만 이용가능'");
    print(cs.."/파탈"..ce.." 파티 탈퇴");
    print(cs.."/계산 '수식'"..ce.." 간단한 계산기");
    print(cs.."/전체승급"..ce.." 공대원 전체 부공대장으로 승급(본인이 공대장일 경우)");
  elseif (msg == "채널") then
      print(header.."sisterchatmods.lua파일을 메모장 등으로 불러낸 후\n                     shortChannels=true 값을 false로 수정 저장 후 리로드");
  elseif (msg == "휠") then
    if (SCMSaved.enableWheel) then
      print(header.."마우스 휠 스크롤 끔");
      SCMSaved.enableWheel= false;
    else
      print(header.."마우스 휠 스크롤 켬");
      SCMSaved.enableWheel= true;
    end;
  elseif (msg == "지속") then
    if (SCMSaved.chatFade) then
      print(header.."대화 지속 기능 켬.");
      SCMSaved.chatFade= false;
      SCM_ChatFade()
    else
      print(header.."대화 지속 기능 끔 - 2분 동안 새글이 없으면 해당 대화창의 대화내용을 숨깁니다.");
      SCMSaved.chatFade= true;
      SCM_ChatFade()
    end
  elseif (msg == "입력창") then
      print(header.."sisterchatmods.lua파일을 메모장 등으로 불러낸 후\n                     MoveEditBox=true 값을 false로 수정 저장 후 리로드");
  end;
end;

-- =================================================================================
-- 대화 지속 
-- =================================================================================
function SCM_ChatFade()
	for i = 1, 7 do
		local chatframe = getglobal("ChatFrame"..i);
		chatframe:SetFading(SCMSaved.chatFade);
	end
end

-- =================================================================================
-- 마우스 오버 툴팁 --
-- =================================================================================
local function hook(k,v,f) k[k:GetScript(v) and "HookScript" or "SetScript"](k,v,f) end
local function enter(self, link)
	local linktype = link:match("^([^:]+)")
	if linktype and linktype ~= "enchant" and linktype ~= "trade" then		
	    GameTooltip:SetOwner(self, "anchor_cursor")
	    pcall(GameTooltip.SetHyperlink, GameTooltip, link)
	end
end

for i = 1, NUM_CHAT_WINDOWS do
    hook(_G["ChatFrame"..i], "OnHyperlinkEnter", enter)
    hook(_G["ChatFrame"..i], "OnHyperlinkLeave", function() GameTooltip:Hide() end)
end

-- =================================================================================
-- "/해산" : 공대 해산 
-- =================================================================================

local function RaidDisband()
	if IsRaidLeader() then
		local pName = UnitName("player")
		SendChatMessage("모두 수고하셨습니다.", "RAID")
		for i = 1, GetNumRaidMembers() do
			local name, _, _, _, _, _, _, online = GetRaidRosterInfo(i)
			if online and name ~= pName then
				UninviteUnit(name)
			end
		end
		LeaveParty()
	else
		DEFAULT_CHAT_FRAME:AddMessage("|cff88ffaa당신은 공대장이 아닙니다. 해산할 수 없습니다.")
	end
end

SLASH_RaidDisband1 = "/해산"
SlashCmdList.RaidDisband = RaidDisband

-- =================================================================================
-- '/파탈' 파티탈퇴
-- =================================================================================
local function Party(cmd)
  LeaveParty()
end

SlashCmdList["CANParty"] = function(cmd)
  Party(cmd);
end

SLASH_CANParty1 = "/파탈";

-- =================================================================================
-- Clear ChatFrame : 모든 채팅창 내용 지우기 (전투로그 제외)
-- =================================================================================
local function ClearChatFrame(cmd)
  local cf;
     for i = 1, NUM_CHAT_WINDOWS do
       if i~=2 then               -- Skip Combatlog
          cf = getglobal("ChatFrame"..i);
          if( (cf ~= nil)) then
            cf:Clear();
          end
       end
    end
end

SlashCmdList["ClearChat"] = function(cmd)
	ClearChatFrame(cmd);
end

SLASH_ClearChat1 = "/cls";
SLASH_ClearChat2 = "/친";

-- =================================================================================
-- More Font Size : 폰트 크기 세부 설정
-- =================================================================================
CHAT_FONT_HEIGHTS = {
    [1] = 7,     [2] = 8,    [3] = 9,    [4] = 10,    [5] = 11,    [6] = 12,    [7] = 13,    [8] = 14,    [9] = 15,    [10] = 16,
    [11] = 17,    [12] = 18,    [13] = 19,    [14] = 20,    [15] = 21,    [16] = 22,    [17] = 24,    [18] = 32
}

-- =================================================================================
-- 마우스 휠 사용 및 추가기능
-- =================================================================================
 
hooksecurefunc('FloatingChatFrame_OnMouseScroll', function(self, dir)
	if dir > 0 then
		if IsShiftKeyDown() then
			self:ScrollToTop()
		elseif IsControlKeyDown() then
			--only need to scroll twice because of blizzards scroll
			self:ScrollUp()
			self:ScrollUp()
		end
	elseif dir < 0 then
		if IsShiftKeyDown() then
			self:ScrollToBottom()
		elseif IsControlKeyDown() then
			--only need to scroll twice because of blizzards scroll
			self:ScrollDown()
			self:ScrollDown()
		end
	end
	--ToggleBottomButton(self)
end)
--[[  local function hide (h) 
    h:SetScript('OnShow', h.Hide);
    h:Hide();
  end

  local function show(h)
    h:SetScript('OnShow', h.Show);
    h:Show();
  end

  function bottom()
     this:GetParent():ScrollToBottom();
    hide(getglobal(this:GetParent():GetName()..'BottomButton'));
  end

  function scroll(chatframe, y)
  if (SCMSaved.enableWheel) then
   if ( y > 0 ) then
      if IsShiftKeyDown() then
         for i = 1,5 do
         chatframe:ScrollUp();
	 end
      elseif IsControlKeyDown() then
         chatframe:ScrollToTop();
      else
         chatframe:ScrollUp();
      end
      if chatframe:AtBottom() then
        hide(getglobal(chatframe:GetName()..'BottomButton'));
      else
        show(getglobal(chatframe:GetName()..'BottomButton'));
      end
   elseif (y < 0 ) then
      if IsShiftKeyDown() then
         for i = 1,5 do 
	 chatframe:ScrollDown();
	 end
      elseif IsControlKeyDown() then
       	 chatframe:ScrollToBottom();
      else
         chatframe:ScrollDown();
      end
      if chatframe:AtBottom() then
        hide(getglobal(chatframe:GetName()..'BottomButton'));
      end
   end
  end
  end
  ]]
-- =================================================================================
-- 버튼 숨김, 맨아래로 버튼
-- =================================================================================
do
	ChatFrameMenuButton.Show = ChatFrameMenuButton.Hide --Hide the chat shortcut button for emotes/languages/etc
	ChatFrameMenuButton:Hide() --Hide the chat shortcut button for emotes/languages/etc
	FriendsMicroButton.Show = FriendsMicroButton.Hide --Hide the "Friends Online" count button
	FriendsMicroButton:Hide() --Hide the "Friends Online" count button

	for i = 1, 10 do
		local f = _G[format("%s%d%s", "ChatFrame", i, "ButtonFrame")]
		f.Show = f.Hide --Hide the up/down arrows
		f:Hide() --Hide the up/down arrows
		_G[format("%s%d", "ChatFrame", i)]:SetClampRectInsets(0,0,0,0) --Allow the chat frame to move to the end of the screen
	end
end
  --[[ 
local dummy = function() end

for i=1,NUM_CHAT_WINDOWS do
  
    local iBtmButton = _G['ChatFrame'..i..'BottomButton'];
    local iFrame = _G['ChatFrame'..i];
    iBtmButton:ClearAllPoints();
    iBtmButton:SetScale(0.7);
    iBtmButton:SetPoint("RIGHT", iFrame, "RIGHT", 0, 0);
    iBtmButton:SetPoint("LEFT", iFrame, "RIGHT", -32, 0);
    iBtmButton:SetPoint("TOP", iFrame, "BOTTOM", 0, 28);
    iBtmButton:SetPoint("BOTTOM", iFrame, "BOTTOM", 0, -4);
    if SCMSaved.FadeMenuButton then
    hide(_G['ChatFrame'..i..'UpButton']);
    hide(_G['ChatFrame'..i..'DownButton']);
    hide(iBtmButton);
    hide(ChatFrameMenuButton);
    end
    local c = _G['ChatFrame'..i];
    c:EnableMouseWheel(true);
    c:SetScript('OnMouseWheel', scroll);

    local cb = _G['ChatFrame'..i..'BottomButton'];
    cb:SetScript("OnClick",bottom);
end  ]]

-- =================================================================================
-- Neon Chat       입력창 테두리 해당 채널색에 맞게 변형
-- =================================================================================

local chatborder = CreateFrame("Button", nil, ChatFrame1EditBox)
chatborder:SetBackdrop(GameTooltip:GetBackdrop())
chatborder:SetBackdropColor(0,0,0,0)
chatborder:EnableMouse(false)

local chateditbox = CreateFrame("Button", nil, ChatFrame1EditBox)
chateditbox:SetBackdrop(GameTooltip:GetBackdrop())
chateditbox:SetBackdropColor(0,0,0,0)

hooksecurefunc("ChatEdit_UpdateHeader", function(editbox)
	if ACTIVE_CHAT_EDIT_BOX then
		local type = editbox:GetAttribute("chatType")
		local frame = string.match(ACTIVE_CHAT_EDIT_BOX:GetName(), "^(.-)EditBox$")
		
		if ( type == "CHANNEL" ) then
			local id = GetChannelName(editbox:GetAttribute("channelTarget"))
			if id == 0 then	
				--chatborder:SetBackdropBorderColor(0.5,0.5,0.5)
				chateditbox:SetBackdropBorderColor(0.5,0.5,0.5)
				chateditbox:SetBackdropColor(0.5/3,0.5/3,0.5/3)
			else 
				--chatborder:SetBackdropBorderColor(ChatTypeInfo[type..id].r,ChatTypeInfo[type..id].g,ChatTypeInfo[type..id].b)
				chateditbox:SetBackdropBorderColor(ChatTypeInfo[type..id].r,ChatTypeInfo[type..id].g,ChatTypeInfo[type..id].b)
				chateditbox:SetBackdropColor(ChatTypeInfo[type..id].r/3,ChatTypeInfo[type..id].g/3,ChatTypeInfo[type..id].b/3)
			end
		else
			--chatborder:SetBackdropBorderColor(ChatTypeInfo[type].r,ChatTypeInfo[type].g,ChatTypeInfo[type].b)
			chateditbox:SetBackdropBorderColor(ChatTypeInfo[type].r,ChatTypeInfo[type].g,ChatTypeInfo[type].b)
			chateditbox:SetBackdropColor(ChatTypeInfo[type].r/3,ChatTypeInfo[type].g/3,ChatTypeInfo[type].b/3)
		end
		
		chatborder:SetParent(ACTIVE_CHAT_EDIT_BOX)
		chatborder:ClearAllPoints()
		chatborder:SetPoint("TOPLEFT", frame.."TopLeftTexture",0,0)
		chatborder:SetPoint("BOTTOMRIGHT", frame.."BottomRightTexture",0,1)
		chateditbox:SetParent(ACTIVE_CHAT_EDIT_BOX)
		chateditbox:ClearAllPoints()
		chateditbox:SetPoint("CENTER",ACTIVE_CHAT_EDIT_BOX:GetName())
		local width = _G[frame]:GetWidth()
		local height = _G[ACTIVE_CHAT_EDIT_BOX:GetName()]:GetHeight()
		chateditbox:SetWidth(width+10)
		chateditbox:SetHeight(height-8)
		chateditbox:SetFrameLevel(_G[frame.."EditBox"]:GetFrameLevel()-1)

	else
		chatborder:SetBackdropBorderColor(0,0,0,0)
		chateditbox:SetBackdropBorderColor(0,0,0,0)
		chateditbox:SetBackdropColor(0,0,0,0)
	end
	
	for chatframe=1,CURRENT_CHAT_FRAME_ID do
		for i=6,8 do select(i, _G["ChatFrame"..chatframe.."EditBox"]:GetRegions()):Hide() end
		_G["ChatFrame"..chatframe.."EditBoxFocusLeft"]:Hide()
		_G["ChatFrame"..chatframe.."EditBoxFocusLeft"].Show = _G["ChatFrame"..chatframe.."EditBoxFocusLeft"].Hide
		_G["ChatFrame"..chatframe.."EditBoxFocusMid"]:Hide()
		_G["ChatFrame"..chatframe.."EditBoxFocusMid"].Show = _G["ChatFrame"..chatframe.."EditBoxFocusMid"].Hide
		_G["ChatFrame"..chatframe.."EditBoxFocusRight"]:Hide()
		_G["ChatFrame"..chatframe.."EditBoxFocusRight"].Show = _G["ChatFrame"..chatframe.."EditBoxFocusRight"].Hide
	end

end)

-- =================================================================================
--  채널줄임
-- =================================================================================
local _G = getfenv(0)
_G.CHAT_GUILD_GET =                 "[G] %s:\32"
_G.CHAT_RAID_GET =                  "[R] %s:\32"
_G.CHAT_PARTY_GET =                 "[P] %s:\32"
_G.CHAT_PARTY_LEADER_GET =          "[PL] %s:\32"
_G.CHAT_PARTY_GUIDE_GET =	    "[DG] %s:\32" --3.3.2 던전가이드 추가
_G.CHAT_RAID_WARNING_GET =          "|cffff0000[|r[RW]|cffff0000]|r %s:\32"
_G.CHAT_RAID_LEADER_GET =           "|cffff3399[|r[RL]|cffff3399]|r %s:\32"
_G.CHAT_OFFICER_GET =               "[O] %s:\32"
_G.CHAT_BATTLEGROUND_GET =          "[BG] %s:\32"
_G.CHAT_BATTLEGROUND_LEADER_GET =   "|cffff0000[|r[BL]|cffff0000]|r %s:\32"
_G.CHAT_SAY_GET =                   "%s:\32"
_G.CHAT_YELL_GET =                  "[Y] %s:\32"
_G.CHAT_WHISPER_GET =               "[FR] %s:\32"
_G.CHAT_WHISPER_INFORM_GET =        "[To] %s:\32"
_G.CHAT_FLAG_AFK =                  "[비움] "
_G.CHAT_FLAG_DND =                  "[용무중] "
_G.CHAT_FLAG_GM =                   "[GM] "  

-- =================================================================================
--URL 링크 복사
-- =================================================================================
local currentLink = nil
local ref = _G["SetItemRef"]

local gsub = _G.string.gsub
local ipairs = _G.ipairs
local pairs = _G.pairs
local fmt = _G.string.format
local sub = _G.string.sub

local tlds = {COM = true,UK = true,NET = true,INFO = true,CO = true,DE = true,FR = true,ES = true,BE = true,CC = true,US = true,KO = true,CH = true,TW = true,}
local style = "|cffFFFF00|Hurl:%s|h[%s]|h|r"
local tokennum, matchTable = 1, {}
local function RegisterMatch(text)
	local token = "\255\254\253"..tokennum.."\253\254\255"
	matchTable[token] = strreplace(text, "%", "%%")
	tokennum = tokennum + 1
	return token
end
local function Link(link, ...)
	if not link then
		return ""
	end
	return RegisterMatch(fmt(style, link, link))
end
local function Link_TLD(link, tld, ...)
	if not link or not tld then
		return ""
	end
	if tlds[strupper(tld)] then
        return RegisterMatch(fmt(style, link, link))
    else
        return RegisterMatch(link)
    end
end

local patterns = {
		-- X://Y url
	{ pattern = "(%a+://%S+)", matchfunc=Link},
	{ pattern = "%f[%S](%a[%w%.+-]+://%S+)", matchfunc=Link},
		-- www.X.Y url
	{ pattern = "(www%.[%w_-%%]+%.%S+)", matchfunc=Link},
	{ pattern = "%f[%S](www%.[%w_-%%]+%.%S+)", matchfunc=Link},
		-- X@Y.Z email
	{ pattern = "(%S+@[%w_-%%%.]+%.(%a%a+))", matchfunc=Link_TLD},
		-- X.Y.Z/WWWWW url with path
	{ pattern = "^([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", matchfunc=Link_TLD},
	{ pattern = "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", matchfunc=Link_TLD},
		-- X.Y.Z url
	{ pattern = "([%w_-%%%.]+[%w_-%%]%.(%a%a+))", matchfunc=Link_TLD},
	{ pattern = "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+))", matchfunc=Link_TLD},
}

local function filterFunc(self, event, msg, ...)
	for _, v in ipairs(patterns) do
		msg = gsub(msg, v.pattern, v.matchfunc)
	end
	for k,v in pairs(matchTable) do
		msg = gsub(msg, k, v)
		matchTable[k] = nil
	end
	return false, msg, ...
end

local function AddEvents()
	local events = {
		"CHAT_MSG_CHANNEL", "CHAT_MSG_YELL",
		"CHAT_MSG_GUILD", "CHAT_MSG_OFFICER",
		"CHAT_MSG_PARTY", "CHAT_MSG_RAID",
		"CHAT_MSG_RAID_LEADER",
		"CHAT_MSG_SAY", "CHAT_MSG_WHISPER",
	}
	for _,event in ipairs(events) do
		ChatFrame_AddMessageEventFilter(event, filterFunc)
	end
end
AddEvents()

local function SetItem(link, ...)
	if sub(link, 1, 3) == "url" then
		currentLink = sub(link, 5)
		StaticPopup_Show("BCMUrlCopyDialog")
		return
	end
	return ref(link, ...)
end
_G["SetItemRef"] = SetItem
-- =================================================================================
-- URL 팝업 박스
-- =================================================================================
StaticPopupDialogs["BCMUrlCopyDialog"] = {
	text = "URL",
	button2 = TEXT(CLOSE),
	hasEditBox = 1,
	hasWideEditBox = 1,
	showAlert = 1,
	OnShow = function()
		local editBox = _G[this:GetName().."WideEditBox"]
		editBox:SetText(currentLink)
		editBox:SetFocus()
		editBox:HighlightText(0)
		local button = _G[this:GetName().."Button2"]
		button:ClearAllPoints()
		button:SetWidth(200)
		button:SetPoint("CENTER", editBox, "CENTER", 0, -30)
		_G[this:GetName().."AlertIcon"]:Hide()
	end,
	EditBoxOnEscapePressed = function() this:GetParent():Hide() end,
	timeout = 0,
	whileDead = 1,
	hideOnEscape = 1,
}

-- =================================================================================
-- 계산기
-- =================================================================================
function Calculator(msg)
	local origHandler = geterrorhandler()
	seterrorhandler(function (msg)
		print("잘못된 계산식입니다.")
	end)
	msg = "local answer="..msg..";if answer then SendChatMessage(\"계산: "..msg.."\",\"SAY\");SendChatMessage(\"결과: \"..answer,\"SAY\") end"
	RunScript(msg)
	seterrorhandler(origHandler)
end
-- =================================================================================
-- 타겟 귓속말 /tt or /ㅅㅅ
-- =================================================================================

local function tellTarget(s)
  if not UnitExists('target') and UnitName('target') and UnitIsPlayer('target') and GetDefaultLanguage('player') == GetDefaultLanguage('target') or not (s and s:len()>0) then
    return
  end
local name, realm = UnitName('target')
  if realm and realm ~= GetRealmName() then
      name = ('%s-%s'):format(name, realm)
  end
SendChatMessage(s, 'WHISPER', nil, name)
end

SlashCmdList['TELLTARGET'] = tellTarget
SLASH_TELLTARGET1 = '/tt'
SLASH_TELLTARGET2 = '/ㅅㅅ'

--------------------------------------------------------------------------------------------------
-- 공대원 전체 부공대장으로 일괄승급 (참고: AllPromote by yhpdoit)
--------------------------------------------------------------------------------------------------

local function AllPromote()
	if IsRaidLeader() then
		local pName = UnitName("player")
		for i = 1, GetNumRaidMembers() do
			local name, _, _, _, _, _, _, online = GetRaidRosterInfo(i)
			if online and name ~= pName then
				PromoteToAssistant(name)
			end
		end
		SendChatMessage("공대원 모두 승급해드렸습니다. 자유롭게 초대해주시기 바랍니다.", "RAID")
	else
		DEFAULT_CHAT_FRAME:AddMessage("|cff88ffaa당신은 공대장이 아닙니다. 승급 권한이 없습니다.")
	end
end

local function AllDemote()
	if IsRaidLeader() then
		local pName = UnitName("player")
		for i = 1, GetNumRaidMembers() do
			local name, _, _, _, _, _, _, online = GetRaidRosterInfo(i)
			if online and name ~= pName then
				DemoteAssistant(name)
			end
		end
		SendChatMessage("공대원 모두 승급해드렸습니다. 자유롭게 초대해주시기 바랍니다.", "RAID")
	else
		DEFAULT_CHAT_FRAME:AddMessage("|cff88ffaa당신은 공대장이 아닙니다. 승급 권한이 없습니다.")
	end
end
SLASH_AllPromote1 = "/전체승급"
SlashCmdList.AllPromote = AllPromote
SLASH_AllDemote1 = "/전체강등"
SlashCmdList.AllDemote = AllDemote

--[[		채팅 복사		]]--

--[[		Settings		]]--

--TOP, BOTTOM, LEFT, RIGHT, BOTTOMLEFT, BOTTOMRIGHT, TOPLEFT, TOPRIGHT
local BUTTON_POSITION = "TOPRIGHT"
--Try wowhead.com for spell icons
local BUTTON_ICON = "Spell_ChargePositive"

--[[		ChatCopy Module		]]--
local lines = {}

local function createFrames()
	--[[		Create our frames on demand		]]--
	local frame = CreateFrame("Frame", "BCMCopyFrame", UIParent)
	frame:SetBackdrop({bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
		edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
		tile = true, tileSize = 16, edgeSize = 16,
		insets = {left = 3, right = 3, top = 5, bottom = 3}}
	)
	frame:SetBackdropColor(0,0,0,1)
	frame:SetWidth(500)
	frame:SetHeight(400)
	frame:SetPoint("CENTER", UIParent, "CENTER")
	frame:Hide()
	frame:SetFrameStrata("DIALOG")

	local scrollArea = CreateFrame("ScrollFrame", "BCMCopyScroll", frame, "UIPanelScrollFrameTemplate")
	scrollArea:SetPoint("TOPLEFT", frame, "TOPLEFT", 8, -30)
	scrollArea:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -30, 8)

	local editBox = CreateFrame("EditBox", "BCMCopyBox", frame)
	editBox:SetMultiLine(true)
	editBox:SetMaxLetters(99999)
	editBox:EnableMouse(true)
	editBox:SetAutoFocus(false)
	editBox:SetFontObject(ChatFontNormal)
	editBox:SetWidth(400)
	editBox:SetHeight(270)
	editBox:SetScript("OnEscapePressed", function() frame:Hide() end)

	scrollArea:SetScrollChild(editBox)

	local close = CreateFrame("Button", "BCMCloseButton", frame, "UIPanelCloseButton")
	close:SetPoint("TOPRIGHT", frame, "TOPRIGHT")
end

do
	local button = CreateFrame("Button", "BCMCopyChat")
	button:SetPoint(BUTTON_POSITION)
	button:SetHeight(10) --LoadUp Height
	button:SetWidth(10) --LoadUp Width
	button:SetNormalTexture("Interface\\Icons\\"..BUTTON_ICON)
	button:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square")
	button:SetScript("OnClick", function(frame)
		local cf = frame:GetParent()
		local _, size = cf:GetFont()
		FCF_SetChatWindowFontSize(cf, cf, 0.01)
		local ct = 1
		for i = select("#", cf:GetRegions()), 1, -1 do
			local region = select(i, cf:GetRegions())
			if region:GetObjectType() == "FontString" then
				lines[ct] = tostring(region:GetText())
				ct = ct + 1
			end
		end
		local lineCt = ct - 1
		local text = table.concat(lines, "\n", 1, lineCt)
		FCF_SetChatWindowFontSize(cf, cf, size)
		if not BCMCopyFrame then createFrames() end
		BCMCopyFrame:Show()
		BCMCopyBox:SetText(text)
		BCMCopyBox:HighlightText(0)
		wipe(lines)
	end)
	button:SetScript("OnEnter", function(frame)
		frame:SetHeight(28) --Big Height
		frame:SetWidth(28) --Big Width
		GameTooltip:SetOwner(frame)
		GameTooltip:ClearLines()
		GameTooltip:AddLine("클릭-채팅내용 복사")
		GameTooltip:Show()
	end)
	button:SetScript("OnLeave", function(frame)
		frame:SetHeight(10) --Small Height
		frame:SetWidth(10) --Small Width
		GameTooltip:Hide()
	end)
	button:Hide()

	--[[		Show/Hide Copy Chat button on demand		]]--
	local t = 0
	local fadein = FCF_FadeInChatFrame
	FCF_FadeInChatFrame = function(frame)
		local time = GetTime()
		if time - t > 0.5 then
			--Stupid hack to make up for all docked chat frames being faded in
			--e.g. if you have 5 frames on 1 dock, this will trigger 5 times.
			BCMCopyChat:ClearAllPoints()
			BCMCopyChat:SetParent(frame)
			BCMCopyChat:SetPoint(BUTTON_POSITION, frame)
			BCMCopyChat:Show()
			t = time
		end
		return fadein(frame)
	end

	local fadeout = FCF_FadeOutChatFrame
	FCF_FadeOutChatFrame = function(frame)
		BCMCopyChat:Hide()
		fadeout(frame)
	end
end
