InvenSimulatorUI = CreateFrame("Frame", "InvenSimulatorUI", UIParent)
InvenSimulatorUI:SetScript("OnEvent", function(self, event, ...) self[event](self, ...) end)
InvenSimulatorUI:RegisterEvent("ADDON_LOADED")
InvenSimulatorUI:Hide()

InvenSimulatorUI.level = 80
InvenSimulatorUI.class = InvenSimulator.class
InvenSimulatorUI.race = InvenSimulator.race
InvenSimulatorUI.hasMana = UnitPowerMax("player", 0)
InvenSimulatorUI.hasMana = (InvenSimulatorUI.hasMana and InvenSimulatorUI.hasMana > 0) and true or nil
InvenSimulatorUI.maxItemIds = 57000
InvenSimulatorUI.build = tonumber(select(2, GetBuildInfo()) or 0)
InvenSimulatorUI.playerTexture = "Interface\\Icons\\Achievement_Character_"..(InvenSimulator.race2 == "Scourge" and "Undead" or InvenSimulator.race2).."_"..InvenSimulator.sex2
InvenSimulatorUI.frames = { [InvenSimulatorUI] = true }
InvenSimulatorUI.specTable = {}
InvenSimulatorUI.tooltipTable = {}
InvenSimulatorUI.slotsEquipLoc = {
	[1] = { ["INVTYPE_HEAD"] = true },
	[2] = { ["INVTYPE_NECK"] = true },
	[3] = { ["INVTYPE_SHOULDER"] = true },
	[4] = { ["INVTYPE_BODY"] = true },
	[5] = { ["INVTYPE_CHEST"] = true, ["INVTYPE_ROBE"] = true },
	[6] = { ["INVTYPE_WAIST"] = true },
	[7] = { ["INVTYPE_LEGS"] = true },
	[8] = { ["INVTYPE_FEET"] = true },
	[9] = { ["INVTYPE_WRIST"] = true },
	[10] = { ["INVTYPE_HAND"] = true },
	[11] = { ["INVTYPE_FINGER"] = true },
	[12] = { ["INVTYPE_FINGER"] = true },
	[13] = { ["INVTYPE_TRINKET"] = true },
	[14] = { ["INVTYPE_TRINKET"] = true },
	[15] = { ["INVTYPE_CLOAK"] = true },
	[16] = { ["INVTYPE_WEAPON"] = true, ["INVTYPE_2HWEAPON"] = true, ["INVTYPE_WEAPONMAINHAND"] = true },
	[17] = nil,
	[18] = nil,
	[19] = { ["INVTYPE_TABARD"] = true },
}
InvenSimulatorUI.statMenuList = { "기본 능력치", "근접", "원거리", "주문", "방어" }
InvenSimulatorUI.statDetailList = {
	["기본 능력치"] = { "힘", "민첩성", "체력", "지능", "정신력", "방어도" },
	["근접"] = { "공격력", "속도", "전투력", "적중도", "치명타율", "숙련" },
	["원거리"] = { "원거리 공격력", "원거리 속도", "원거리 전투력", "원거리 적중도", "원거리 치명타율" },
	["주문"] = { "주문 공격력", "주문 치유량", "주문 적중도", "극대화율", "주문 가속도", "5초당 마나 회복량" },
	["방어"] = { "방어도", "방어 숙련", "회피율", "무기 막기", "방패 막기", "탄력도" },
}
InvenSimulatorUI.statReplaceValue = { ["원거리 공격력"] = "공격력", ["원거리 속도"] = "속도", ["원거리 전투력"] = "전투력", ["원거리 적중도"] = "적중도", ["원거리 치명타율"] = "치명타율", ["주문 적중도"] = "적중도", ["주문 가속도"] = "가속도", ["5초당 마나 회복량"] = "마나 회복량", ["주문 공격력"] = "공격력 증가", ["주문 치유량"] = "치유량 증가" }
InvenSimulatorUI.statPattern = { ["속도"] = "%.2f", ["원거리 속도"] = "%.2f", ["치명타율"] = "%.2f%%", ["원거리 치명타율"] = "%.2f%%", ["극대화율"] = "%.2f%%", ["회피율"] = "%.2f%%", ["무기 막기"] = "%.2f%%", ["방패 막기"] = "%.2f%%" }
InvenSimulatorUI.tradeSkillList = { "연금술", "재봉술", "가죽세공", "대장기술", "기계공학", "마법부여", "보석세공", "주문각인", "채광", "무두질", "약초채집" }
InvenSimulatorUI.spellSchools = { SPELL_SCHOOL1_NAME, SPELL_SCHOOL2_NAME, SPELL_SCHOOL3_NAME, SPELL_SCHOOL4_NAME, SPELL_SCHOOL5_NAME, SPELL_SCHOOL6_NAME }

local tooltip = CreateFrame("GameTooltip", "IIC2UI_Tooltip", UIParent, "GameTooltipTemplate")
function tooltip:GetLineText(line)
	if type(line) == "number" and tooltip:NumLines() >= line then
		tooltip.text = tooltip.text or {}
		tooltip.text[line] = tooltip.text[line] or _G[tooltip:GetName().."TextLeft"..line]
		if tooltip.text[line] then
			return tooltip.text[line]:GetText(), tooltip.text[line]:GetTextColor()
		end
	end
	return nil, nil, nil, nil
end

local LIS = LibStub("LibItemSpec-2.0")

local _G = getfenv(0)
local unpack = _G.unpack
local type = _G.type
local pairs = _G.pairs
local ipairs = _G.ipairs
local tinsert = _G.table.insert
local tremove = _G.table.remove
local GetItemInfo = _G.GetItemInfo
local GetItemIcon = _G.GetItemIcon
local GetSpellTexture = _G.GetSpellTexture
local CursorCanGoInSlot = _G.CursorCanGoInSlot
local GetItemQualityColor = _G.GetItemQualityColor
local GetInventoryItemQuality = _G.GetInventoryItemQuality
local GetCursorPosition = _G.GetCursorPosition
local GetNumTalents = _G.GetNumTalents
local GetTalentTabInfo = _G.GetTalentTabInfo
local GetTalentInfo = _G.GetTalentInfo

local cursorType, cursorItemLink, cursorItemID, itemSubType, itemEquipLoc
local uniqueItemCache, raceClassItemCache, equipableSlot = {}, {}, {}
local equipableLink, raceCheck, classCheck, uniqueCheck
local emptyfunc = function() end

function InvenSimulatorUI:ADDON_LOADED()
	self:UnregisterEvent("ADDON_LOADED")
	if self.db then return end
	if InvenSimulatorCharDB and (InvenSimulatorCharDB.class ~= self.class or InvenSimulatorCharDB.race ~= self.race) then
		InvenSimulatorCharDB = nil
	end
	InvenSimulatorCharDB = InvenSimulatorCharDB or {
		pos = { "CENTER", 0, 0 }, itemListPos = { "CENTER", 0, 0 }, talentPos = { "CENTER", 0, 0 }, itemEnchantPos = { "CENTER", 0, 0 },
		saveItemPos = { "CENTER", 0, 0 },
		class = self.class, race = self.race, buffs = {},
		left = "기본 능력치", right = "근접",
		rotation = 0.61, showHelm = ShowingHelm() and true or nil, showCloak = ShowingCloak() and true or nil,
		profile = nil, profiles = {}, saveItem = {},
	}
	InvenSimulatorCharDB.buffs = InvenSimulatorCharDB.buffs or {}
	InvenSimulatorCharDB.saveItem = InvenSimulatorCharDB.saveItem or {}
	self.db = InvenSimulatorCharDB
	InvenSimulatorSaveDB = InvenSimulatorSaveDB or {}
	self.savedb = InvenSimulatorSaveDB
	self.playerFullLocation = UnitName("player").." - "..GetRealmName()
	self.savedb[self.playerFullLocation] = nil
	if self.db.lastShowChar == self.playerFullLocation then
		self.db.lastShowChar = nil
	end
	if self.db.profiles == nil then
		self.db.profiles = {}
	end
	if self.db.tradeSkill == nil then
		self.db.tradeSkill = {}
		for i = 1, #self.tradeSkillList do
			if GetSpellTexture(self.tradeSkillList[i]) or (self.tradeSkillList[i] == "채광" and GetSpellTexture("제련술")) then
				tinsert(self.db.tradeSkill, self.tradeSkillList[i])
				if #self.db.tradeSkill == 2 then
					break
				end
			end
		end
		self.db.tradeSkill[1] = self.db.tradeSkill[1] or "없음"
		self.db.tradeSkill[2] = self.db.tradeSkill[2] or "없음"
	end
	if self.db.items == nil then
		self.db.items = {}
		self.db.itemsQuality = {}
		self:CopyItem()
	else
		for i = 1, 19 do
			LIS:SetTooltip(self.db.items[i])
		end
	end
	if self.db.ammo == nil then
		self.db.ammo = LIS:GetItemID(GetInventoryItemLink("player", 0))
	end
	self.db.buffs = self.db.buffs or {}
	self.talentTabNames = {}
	for i = 1, 3 do
		self.talentTabNames[i] = GetTalentTabInfo(i)
	end
	if self.db.talents == nil then
		self.db.talents = {}
		self:CopyTalent()
	else
		for p in pairs(self.db.talents) do
			if p:find(";") then
				break
			else
				self:CopyTalent()
				break
			end
		end
	end
	if self.db.glyphs == nil then
		self.db.glyphs = {}
		self:CopyGlyphs()
	end
	self.db.stance = self.db.stance or {}
	for i = 11, 17 do
		if i ~= 15 then
			self:IsUniqueItem(GetInventoryItemLink("player", i))
			self:IsUniqueItem(InvenSimulatorCharDB.items[i])
		end
	end
	self.qualityColor, self.qualityColorHex = {}, {}
	local r, g, b
	for i = 0, 7 do
		r, g, b = GetItemQualityColor(i)
		self.qualityColor[i] = { r, g, b }
		self.qualityColorHex[i] = ("|cff%02x%02x%02x"):format(r * 255, g * 255, b * 255)
	end
	self:InitClassItemType()
	self:CreateFrame()
	self:ApplyFakeDrag()
	self:InitDataTable()
	self:Show()
	self:RegisterEvent("PLAYER_LOGOUT")
end

function InvenSimulatorUI:PLAYER_LOGOUT()
	local talent1, talent2, talent3 = InvenSimulatorTalentFrame:GetSpentPoints(1), InvenSimulatorTalentFrame:GetSpentPoints(2), InvenSimulatorTalentFrame:GetSpentPoints(3)
	local mainTalent
	if talent1 == 0 and talent2 == 0 and talent3 == 0 then
		mainTalent = ""
	elseif talent1 >= talent2 and talent1 >= talent3 then
		mainTalent = InvenSimulatorTalentFrame:GetTalentTabName(1).." "
	elseif talent2 >= talent1 and talent2 >= talent3 then
		mainTalent = InvenSimulatorTalentFrame:GetTalentTabName(2).." "
	elseif talent3 >= talent1 and talent3 >= talent2 then
		mainTalent = InvenSimulatorTalentFrame:GetTalentTabName(3).." "
	else
		mainTalent = ""
	end
	self.savedb[self.playerFullLocation] = { info = ("%s %s (%s%d/%d/%d)"):format(self.race, self.class, mainTalent, talent1, talent2, talent3) }
	for p, v in pairs(self.db.items) do
		self.savedb[self.playerFullLocation][p] = v
	end
end

function InvenSimulatorUI:ShowTop(frame)
	self.frames[frame] = true
	frame:SetToplevel(true)
	frame:Show()
	local maxLevel = frame:GetFrameLevel()
	for f in pairs(self.frames) do
		if f:IsShown() then
			maxLevel = max(maxLevel, f:GetFrameLevel())
		end
	end
	if maxLevel >= frame:GetFrameLevel() then
		maxLevel = maxLevel + 5
		frame:SetFrameLevel(maxLevel)
		if frame.levelElements then
			for p, v in pairs(frame.levelElements) do
				p:SetFrameLevel(maxLevel + v)
			end
		end
		frame:Show()
	end
end

function InvenSimulatorUI:ChangeTradeSkill(id, skill)
	if id == 1 or id == 2 then
		self.db.tradeSkill[id] = skill or "없음"
		local deGemCount, deGemNum = 0, 0
		for i = 1, 19 do
			if self.db.items[i] then
				self:SetItem(i, self.db.items[i])
			end
		end
		self:ScanItem()
		self:ModelUpdate()
		if self.itemListFrame and self.itemListFrame:IsShown() then
			self:OpenItemList(self.itemListFrame.openSlotID)
		end
	end
end

function InvenSimulatorUI:HasTradeSkill(skill)
	if not skill then
		return true
	elseif self.db.tradeSkill[1] == skill or self.db.tradeSkill[2] == skill then
		return true
	else
		return nil
	end
end

function InvenSimulatorUI:CopyTalent()
	for p in pairs(InvenSimulatorCharDB.talents) do
		InvenSimulatorCharDB.talents[p] = nil
	end
	local n, tabName, name, point
	for i = 1, 3 do
		n = GetNumTalents(i)
		for j = 1 , n do
			name, _, _, _, point = GetTalentInfo(i, j)
			if point and point > 0 then
				InvenSimulatorCharDB.talents[self.talentTabNames[i]..";"..name] = point
			end
		end
	end
end

function InvenSimulatorUI:GetTalentPoint(talent)
	if talent:find(";") then
		if InvenSimulatorCharDB.talents[talent] then
			return InvenSimulatorCharDB.talents[talent]
		else
			talent = talent:gsub("(.+);", "")
		end
	end
	for i = 1, 3 do
		if InvenSimulatorCharDB.talents[self.talentTabNames[i]..";"..talent] then
			return InvenSimulatorCharDB.talents[self.talentTabNames[i]..";"..talent]
		end
	end
	return 0
end

function InvenSimulatorUI:CopyGlyphs()
	if self.talentFrame.glyph then
		for i = 1, 6 do
			self.talentFrame:SetGlyph(i, select(3, GetGlyphSocketInfo(i)), true)
		end
		InvenSimulatorUI:Calculate()
	else
		for i = 1, 6 do
			self.db.glyphs[i] = select(3, GetGlyphSocketInfo(i))
		end
	end
end

function InvenSimulatorUI:HasGlyphs(glyph)
	if type(glyph) == "string" then
		for i = 1, 6 do
			if self.db.glyphs[i] and GetSpellInfo(self.db.glyphs[i]) == glyph then
				return i
			end
		end
	elseif type(glyph) == "number" then
		for i = 1, 6 do
			if self.db.glyphs[i] == glyph then
				return i
			end
		end
	else
		return nil
	end
end

function InvenSimulatorUI:CopyItem()
	for i = 1, 19 do
		InvenSimulatorCharDB.items[i] = nil
	end
	for i = 1, 19 do
		InvenSimulatorCharDB.items[i] = GetInventoryItemLink("player", i)
		if InvenSimulatorCharDB.items[i] then
			InvenSimulatorCharDB.items[i] = self:FixItemLink(InvenSimulatorCharDB.items[i], i)
			InvenSimulatorCharDB.itemsQuality[i] = GetInventoryItemQuality("player", i)
		else
			InvenSimulatorCharDB.itemsQuality[i] = 0
		end
	end
	InvenSimulatorCharDB.ammo = LIS:GetItemID(GetInventoryItemLink("player", 0) or nil)
end

function InvenSimulatorUI:GetCursorItemLink()
	cursorType, cursorItemID, cursorItemLink = GetCursorInfo()
	if cursorType == "item" then
		if type(cursorItemLink) == "string" and cursorItemLink:find("item:(%d+)") then
			return cursorItemLink
		end
	elseif cursorType == "merchant" then
		if cursorItemID then
			cursorItemLink = GetMerchantItemLink(cursorItemID)
			if type(cursorItemLink) == "string" and cursorItemLink:find("item:(%d+)") then
				return cursorItemLink
			end
		end
	end
end

function InvenSimulatorUI:GetEquipableLink()
	return equipableLink
end

function InvenSimulatorUI:CreateFrame()
	if self.initFrame then return end
	self.initFrame = true
	local function frameOnEnter()
		InvenSimulatorUI.enterParent = true
	end
	local function frameOnLeave()
		InvenSimulatorUI.enterParent = nil
	end
	local function frameOnMouseDown(_, button)
		if button == "LeftButton" then
			cursorItemLink = InvenSimulatorUI:GetCursorItemLink()
			if cursorItemLink and cursorItemLink == equipableLink then
				InvenSimulatorUI:EquipItem(0, equipableLink)
			end
		end
		ClearCursor()
	end
	local function frameOnReceiveDrag()
		frameOnMouseDown(nil, "LeftButton")
	end
	self:SetScript("OnShow", function() PlaySound("igCharacterInfoOpen") end)
	self:SetScript("OnHide", function(self)
		self.hasItemData = nil
		for f in pairs(self.frames) do f:Hide() end
		PlaySound("igCharacterInfoClose")
	end)
	self:SetScript("OnEnter", frameOnEnter)
	self:SetScript("OnLeave", frameOnLeave)
	self:SetScript("OnMouseUp", frameOnMouseDown)
	self:SetScript("OnReceiveDrag", frameOnReceiveDrag)
	self:SetScript("OnDragStart", self.StartMoving)
	self:SetScript("OnDragStop", function(self)
		self:StopMovingOrSizing()
		self.db.pos[1], _, _, self.db.pos[2], self.db.pos[3] = self:GetPoint()
	end)
	self:ClearAllPoints()
	self:SetPoint(unpack(self.db.pos))
	self:SetWidth(340)
	self:SetHeight(426)
	self:SetScale(InvenSimulatorDB.scale or 1)
	self:SetToplevel(true)
	self:EnableMouse(true)
	self:SetClampedToScreen(true)
	self:RegisterForDrag("LeftButton", "RightButton")
	self:SetMovable(true)
	local function createTexture(texture, width, height, ...)
		local frame = InvenSimulatorUI:CreateTexture(nil, "BORDER")
		frame:SetTexture(texture)
		frame:SetWidth(width)
		frame:SetHeight(height)
		frame:SetPoint(...)
		return frame
	end
	createTexture("Interface\\PaperDollInfoFrame\\UI-Character-CharacterTab-L1", 256, 256, "TOPLEFT", -12, 12)
	createTexture("Interface\\PaperDollInfoFrame\\UI-Character-CharacterTab-R1", 128, 256, "TOPLEFT", 244, 12)
	createTexture("Interface\\PaperDollInfoFrame\\UI-Character-CharacterTab-BottomLeft", 256, 256, "TOPLEFT", -12, -244)
	createTexture("Interface\\PaperDollInfoFrame\\UI-Character-CharacterTab-BottomRight", 128, 256, "TOPLEFT", 244, -244)
	self.portrait = self:CreateTexture(nil, "BACKGROUND")
	self.portrait:SetWidth(60)
	self.portrait:SetHeight(60)
	self.portrait:SetPoint("TOPLEFT", -3, 6)
	SetPortraitToTexture(self.portrait, InvenSimulator.icon)
	self.title = self:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
	self.title:SetHeight(14)
	self.title:SetFormattedText("%s v%s", InvenSimulator.addonName, InvenSimulator.version)
	self.title:SetPoint("TOP", 17, -6)
	self.profileName = self:CreateFontString(nil, "OVERLAY", "GameFontNormal")
	self.profileName:SetHeight(14)
	self.profileName:SetPoint("TOP", self.title, "BOTTOM", 0, -4)
	self:UpdateProfileName()
	self.modelFrame = CreateFrame("DressUpModel", nil, self)
	self.modelFrame:SetWidth(233)
	self.modelFrame:SetHeight(215)
	self.modelFrame:SetPoint("TOPLEFT", 53, -66)
	self.modelFrame:SetScript("OnShow", function()
		InvenSimulatorUI:ModelUpdate()
	end)
	self.modelFrame:EnableMouse(true)
	self.modelFrame:SetScript("OnEnter", frameOnEnter)
	self.modelFrame:SetScript("OnLeave", frameOnLeave)
	self.modelFrame:SetScript("OnReceiveDrag", frameOnReceiveDrag)
	self.modelFrame:SetScript("OnMouseDown", function(self, button)
		if button == "LeftButton" then
			if CursorHasItem() then
				frameOnMouseDown(nil, button)
			else
				self.cursor_x = GetCursorPosition()
				self.dragging = true
			end
		end
	end)
	self.modelFrame:SetScript("OnMouseUp", function(self, button)
		if button == "LeftButton" and self.dragging then
			self.dragging = nil
		end
	end)
	self.modelFrame:SetScript("OnUpdate", function(self, timer)
		if self.dragging then
			self.cursor_px = GetCursorPosition()
			if self.cursor_x > self.cursor_px then
				Model_RotateLeft(self, (self.cursor_x - self.cursor_px) * timer)
			else
				Model_RotateRight(self, (self.cursor_px - self.cursor_x) * timer)
			end
			self.cursor_x = self.cursor_px
			InvenSimulatorUI.db.rotation = self.rotation
		end
	end)
	self.modelFrame.rotation = self.db.rotation or 0.61
	self.modelFrame:SetRotation(self.modelFrame.rotation)
	self.modelFrame:SetUnit("player")
	self.modelFrame:RefreshUnit()
	self.modelFrame:Undress()
	self.closeButton = CreateFrame("Button", nil, self, "UIPanelCloseButton")
	self.closeButton:SetPoint("CENTER", self, "TOPRIGHT", -12, -13)
	self.slots = {}
	local slotName = { "HeadSlot", "NeckSlot", "ShoulderSlot", "BackSlot", "ChestSlot", "ShirtSlot", "TabardSlot", "WristSlot", "HandsSlot", "WaistSlot", "LegsSlot", "FeetSlot", "Finger0Slot", "Finger1Slot", "Trinket0Slot", "Trinket1Slot", "MainHandSlot", "SecondaryHandSlot", "RangedSlot" }
	local itemSlot, id, textureName, checkRelic
	local itemSlotOnEvent = function(self)
		if CursorCanGoInSlot(self:GetID()) then
			self:LockHighlight()
		else
			self:UnlockHighlight()
		end
	end
	local itemSlotOnEnter = function(self)
		if InvenSimulatorUI.enterSlot ~= self:GetID() then
			itemSlot:SetScript("OnUpdate", itemSlotOnEnter)
		end
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
		if InvenSimulatorUI.db.items[self:GetID()] then
			GameTooltip:SetHyperlink(InvenSimulatorUI.db.items[self:GetID()])
		else
			GameTooltip:AddLine(self.tooltipText)
		end
		self:RegisterEvent("MODIFIER_STATE_CHANGED")
		GameTooltip:Show()
		InvenSimulatorUI.enterSlot = self:GetID()
		CursorUpdate(self)
	end
	local itemSlotOnLeave = function(self)
		GameTooltip:Hide()
		ResetCursor()
		self:SetScript("OnUpdate", nil)
		InvenSimulatorUI.enterSlot = nil
		self:UnregisterEvent("MODIFIER_STATE_CHANGED")
	end
	local itemSlotOnClick = function(self, button)
		if button == "LeftButton" and IsModifierKeyDown() and InvenSimulatorUI.db.items[self:GetID()] then
			if IsShiftKeyDown() then
				if TinyPad and TinyPadEditBox and TinyPadEditBox:IsShown() and TinyPad.has_focus then
					TinyPadEditBox:Insert(InvenSimulatorUI.db.items[self:GetID()])
				else
					ChatFrame1EditBox:Show()
					ChatFrame1EditBox:Insert(InvenSimulatorUI.db.items[self:GetID()])
				end
			elseif IsControlKeyDown() then
				DressUpItemLink(InvenSimulatorUI.db.items[self:GetID()])
			else
				--SetItemRef(InvenSimulatorUI.db.items[self:GetID()], GetItemInfo(InvenSimulatorUI.db.items[self:GetID()]), button)
				ShowUIPanel(ItemRefTooltip)
				if not ItemRefTooltip:IsShown() then
					ItemRefTooltip:SetOwner(UIParent, "ANCHOR_PRESERVE")
				end
				ItemRefTooltip:SetHyperlink(InvenSimulatorUI.db.items[self:GetID()])
			end
		elseif button == "LeftButton" and GetCursorInfo() then
			cursorItemLink = InvenSimulatorUI:GetCursorItemLink()
			if cursorItemLink and cursorItemLink == equipableLink then
				InvenSimulatorUI:EquipItem(self:GetID(), equipableLink)
			end
			ClearCursor()
		elseif not self.isFakeDragging and not self.preventClick then
			InvenSimulatorUI:OpenMenu(self)
		end
		self.preventClick = nil
	end
	local itemSlotOnReceiveDrag = function(self)
		itemSlotOnClick(self, "LeftButton")
	end
	local itemSlotOnDoubleClick = function(self, button)
		if CursorHasItem() then
			itemSlotOnClick(self, "LeftButton")
		else
			LibStub("LibDropMenu-2.0"):CloseMenu(1)
			InvenSimulatorUI:OpenItemList(self:GetID())
		end
	end
	local itemSlotOnEvent = function(self, event)
		if InvenSimulatorUI:IsVisible() and InvenSimulatorUI.enterSlot == self:GetID() then
			if IsShiftKeyDown() then
				GameTooltip:Hide()
				itemSlotOnEnter(self)
			elseif ShoppingTooltip1:IsShown() then
				ShoppingTooltip1:Hide()
				ShoppingTooltip2:Hide()
				ShoppingTooltip3:Hide()
			end
		else
			self:UnregisterEvent("MODIFIER_STATE_CHANGED")
		end
	end
	for index, slot in ipairs(slotName) do
		itemSlot = CreateFrame("Button", "InvenSimulatorUI"..slot, self)
		itemSlot:RegisterForClicks("LeftButtonUp", "RightButtonUp")
		itemSlot:SetWidth(37)
		itemSlot:SetHeight(37)
		itemSlot:SetNormalTexture("Interface\\Buttons\\UI-Quickslot2")
		itemSlot.normalTexture = itemSlot:GetNormalTexture()
		itemSlot.normalTexture:SetWidth(64)
		itemSlot.normalTexture:SetHeight(64)
		itemSlot.normalTexture:ClearAllPoints()
		itemSlot.normalTexture:SetPoint("CENTER", 0, -1)
		itemSlot:SetPushedTexture("Interface\\Buttons\\UI-Quickslot-Depress")
		itemSlot:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square", "ADD")
		itemSlot.icon = itemSlot:CreateTexture("InvenSimulatorUI"..slot.."IconTexture", "BORDER")
		itemSlot.icon:SetAllPoints()
		itemSlot.border = itemSlot:CreateTexture(nil, "OVERLAY")
		itemSlot.border:SetTexture("Interface\\Buttons\\UI-ActionButton-Border")
		itemSlot.border:SetBlendMode("ADD")
		itemSlot.border:SetAlpha(0.75)
		itemSlot.border:SetWidth(68)
		itemSlot.border:SetHeight(68)
		itemSlot.border:SetPoint("CENTER", 0, 1)
		id, textureName = GetInventorySlotInfo(slot)
		itemSlot:SetID(id)
		itemSlot.backgroundTextureName = (id == 18 and UnitHasRelicSlot("player")) and "Interface\\Paperdoll\\UI-PaperDoll-Slot-Relic.blp" or textureName
		itemSlot.tooltipText = _G[(id == 18 and UnitHasRelicSlot("player")) and "RELICSLOT" or slot:upper()]
		self.slots[id] = itemSlot
		self:SetItem(id, self.db.items[id], true)
		if self.db.items[id] then
			self.modelFrame:TryOn(self.db.items[id])
		end
		if index == 1 then
			itemSlot:SetPoint("TOPLEFT", 9, -62)
		elseif index == 9 then
			itemSlot:SetPoint("TOPLEFT", 293, -62)
		elseif index == 17 then
			itemSlot:SetPoint("TOPLEFT", self, "BOTTOMLEFT", 110, 54)
		elseif index < 17 then
			itemSlot:SetPoint("TOPLEFT", _G["InvenSimulatorUI"..slotName[index - 1]], "BOTTOMLEFT", 0, -4)
		else
			itemSlot:SetPoint("TOPLEFT", _G["InvenSimulatorUI"..slotName[index - 1]], "TOPRIGHT", 5, 0)
		end
		itemSlot:SetScript("OnEnter", itemSlotOnEnter)
		itemSlot:SetScript("OnLeave", itemSlotOnLeave)
		itemSlot:SetScript("OnClick", itemSlotOnClick)
		itemSlot:SetScript("OnDoubleClick", itemSlotOnDoubleClick)
		itemSlot:SetScript("OnReceiveDrag", itemSlotOnReceiveDrag)
		itemSlot:SetScript("OnEvent", itemSlotOnEvent)
	end
	if self.slots[18].tooltipText ~= _G["RELICSLOT"] then
		self.ammoSlot = CreateFrame("Button", "InvenSimulatorUIAmmoSlot", self)
		self.ammoSlot:SetID(0)
		self.ammoSlot:SetWidth(27)
		self.ammoSlot:SetHeight(27)
		self.ammoSlot:SetPoint("LEFT", self.slots[18], "RIGHT", 15, 0)
		self.ammoSlot.background = self.ammoSlot:CreateTexture(nil, "BACKGROUND")
		self.ammoSlot.background:SetWidth(41)
		self.ammoSlot.background:SetHeight(41)
		self.ammoSlot.background:SetTexture("Interface\\PaperdollInfoFrame\\UI-Character-AmmoSlot")
		self.ammoSlot.background:SetTexCoord(0, 0.640625, 0, 0.640625)
		self.ammoSlot.background:SetPoint("CENTER", 1, 0)
		self.ammoSlot.arrow = self.ammoSlot:CreateTexture(nil, "OVERLAY")
		self.ammoSlot.arrow:SetTexture("Interface\\PaperdollInfoFrame\\UI-Character-AmmoSlot")
		self.ammoSlot.arrow:SetTexCoord(0.64062, 1, 0, 0.640625)
		self.ammoSlot.arrow:SetWidth(23)
		self.ammoSlot.arrow:SetHeight(41)
		self.ammoSlot.arrow:SetPoint("CENTER", -22, 0)
		self.ammoSlot:SetPushedTexture("Interface\\Buttons\\UI-Quickslot-Depress")
		self.ammoSlot:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square", "ADD")
		self.ammoSlot.icon = self.ammoSlot:CreateTexture("InvenSimulatorUIAmmoSlotIconTexture", "BORDER")
		self.ammoSlot.icon:SetAllPoints()
		self.ammoSlot.border = self.ammoSlot:CreateTexture(nil, "OVERLAY")
		self.ammoSlot.border:SetTexture("Interface\\Buttons\\UI-ActionButton-Border")
		self.ammoSlot.border:SetBlendMode("ADD")
		self.ammoSlot.border:SetAlpha(0.75)
		self.ammoSlot.border:SetWidth(49)
		self.ammoSlot.border:SetHeight(49)
		self.ammoSlot.border:SetPoint("CENTER", 0, 1)
		self.ammoSlot.border:Hide()
		self.ammoSlot.backgroundTextureName = select(2, GetInventorySlotInfo("AmmoSlot"))
		self.ammoSlot.tooltipText = "탄환 및 화살"
		self.ammoSlot:SetScript("OnEnter", function(self)
			GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
			if InvenSimulatorUI.db.ammo then
				GameTooltip:SetHyperlink("item:"..InvenSimulatorUI.db.ammo)
			else
				GameTooltip:AddLine(self.tooltipText)
			end
			GameTooltip:Show()
		end)
		self.ammoSlot:SetScript("OnLeave", GameTooltip_Hide)
		self.ammoSlot:SetScript("OnClick", function() InvenSimulatorUI:OpenAmmoMenu() end)

		self:ToggleAmmoSlot()
	end
	local resists = { "비전 저항력", "화염 저항력", "자연 저항력", "냉기 저항력", "암흑 저항력" }
	local resistsCoord = { { 0, 1, 0.2265625, 0.33984375 }, { 0, 1, 0, 0.11328125 }, { 0, 1, 0.11328125, 0.2265625 }, { 0, 1, 0.33984375, 0.453125 }, { 0, 1, 0.453125, 0.56640625 } }
	self.resistFrame = CreateFrame("Frame", "InvenSimulatorUIResistFrame", self)
	self.resistFrame:SetWidth(32)
	self.resistFrame:SetHeight(160)
	self.resistFrame:SetPoint("TOPRIGHT", self.modelFrame, "TOPRIGHT")
	local function resistButtonOnEnter(self)
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
		GameTooltip:AddLine(self.name.." "..self.resist, 1, 1, 1)
		GameTooltip:AddLine(RESISTANCE_TOOLTIP_SUBTEXT:format(self.name2, InvenSimulatorUI.level, self.resistLevel), NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1)
		GameTooltip:Show()
	end
	for i = 1, #resists do
		self.resistFrame[i] = CreateFrame("Frame", "InvenSimulatorUIResistFrame"..i, self.resistFrame)
		self.resistFrame[i]:SetWidth(32)
		self.resistFrame[i]:SetHeight(29)
		self.resistFrame[i].name = resists[i]
		self.resistFrame[i].name2 = resists[i]:match("(.+) 저항력")
		self.resistFrame[i].icon = self.resistFrame[i]:CreateTexture(nil, "OVERLAY")
		self.resistFrame[i].icon:SetAllPoints()
		self.resistFrame[i].icon:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-ResistanceIcons")
		self.resistFrame[i].icon:SetTexCoord(unpack(resistsCoord[i]))
		self.resistFrame[i].text = self.resistFrame[i]:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
		self.resistFrame[i].text:SetPoint("BOTTOM", 0, 3)
		self.resistFrame[i]:EnableMouse(true)
		self.resistFrame[i]:SetScript("OnEnter", resistButtonOnEnter)
		self.resistFrame[i]:SetScript("OnLeave", GameTooltip_Hide)
		if i == 1 then
			self.resistFrame[i]:SetPoint("TOP")
		else
			self.resistFrame[i]:SetPoint("TOP", self.resistFrame[i - 1], "BOTTOM")
		end
	end
	self.avgItemLevelText = self.modelFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	self.avgItemLevelText:SetPoint("TOPLEFT", 2, 0)
	self.avgItemLevelText:SetText("평균 아이템 레벨:")
	self.maxHelathText = self.modelFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	self.maxHelathText:SetPoint("TOPLEFT", self.avgItemLevelText, "BOTTOMLEFT", 0, -1)
	self.maxHelathText:SetText("생명력:")
	self.maxManaText = self.modelFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	self.maxManaText:SetPoint("TOPLEFT", self.maxHelathText, "BOTTOMLEFT", 0, -1)
	self.maxManaText:SetText("마나:")
	self.talentPointsText = self.modelFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
	self.talentPointsText:SetPoint("TOPLEFT", self.maxManaText, "BOTTOMLEFT", 0, -1)
	self.talentPointsText:SetText("특성:")
	self.setTextLine = {}
	for i = 1, 5 do
		self.setTextLine[i] = self.modelFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
		if i == 1 then
			self.setTextLine[i]:SetPoint("BOTTOMLEFT", self.modelFrame, "BOTTOMLEFT", 2, 28)
		else
			self.setTextLine[i]:SetPoint("BOTTOMLEFT", self.setTextLine[i - 1], "TOPLEFT", 0, 1)
		end
	end
	local gemNames = { "용의 눈", "푸른색 보석", "노란색 보석", "붉은색 보석", "얼개 보석" }
	local gemIcons = { "Interface\\Icons\\INV_Jewelcrafting_DragonsEye02", "Interface\\Icons\\INV_Jewelcrafting_Gem_17", "Interface\\Icons\\INV_Jewelcrafting_Gem_15", "Interface\\Icons\\INV_Jewelcrafting_Gem_16", "Interface\\Icons\\INV_Jewelcrafting_ShadowSpirit_02" }
	self.gemFrames = {}
	local function gemButtonOnEnter(self)
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
		GameTooltip:AddLine(self.name.." "..self.count:GetText(), 1, 1, 1)
		GameTooltip:Show()
	end
	for i = 1, #gemNames do
		self.gemFrames[i] = CreateFrame("Frame", "InvenSimulatorUIGemFrame"..(#gemNames - i + 1), self.modelFrame)
		self.gemFrames[i]:EnableMouse()
		self.gemFrames[i]:SetWidth(23)
		self.gemFrames[i]:SetHeight(23)
		self.gemFrames[i]:SetScript("OnEnter", gemButtonOnEnter)
		self.gemFrames[i]:SetScript("OnLeave", GameTooltip_Hide)
		self.gemFrames[i].name = gemNames[i]
		self.gemFrames[i].icon = self.gemFrames[i]:CreateTexture(nil, "OVERLAY")
		self.gemFrames[i].icon:SetAllPoints()
		self.gemFrames[i].icon:SetTexture(gemIcons[i])
		self.gemFrames[i].icon:SetTexCoord(0.07, 0.93, 0.07, 0.93)
		self.gemFrames[i].count = self.gemFrames[i]:CreateFontString(nil, "OVERLAY", "NumberFontNormal")
		self.gemFrames[i].count:SetPoint("BOTTOMRIGHT", self.gemFrames[i], "BOTTOMRIGHT", 0, 0)
		self.gemFrames[i].count:SetText(0)
		self.gemFrames[i]:SetScale(0.75)
		if i == 1 then
			self.gemFrames[i]:SetPoint("BOTTOMRIGHT", self.modelFrame, "BOTTOMRIGHT", -2, 34)
			self.gemFrames[i].hasJewelCrafting = true
		else
			self.gemFrames[i]:SetPoint("RIGHT", self.gemFrames[i - 1], "LEFT", 1, 0)
		end
	end
	self.attributesFrame = CreateFrame("Frame", nil, self)
	self.attributesFrame:SetWidth(230)
	self.attributesFrame:SetHeight(78)
	self.attributesFrame:SetPoint("TOPLEFT", 55, -279)
	self.attributesFrame.left = self.attributesFrame:CreateTexture(nil, "ARTWORK")
	self.attributesFrame.left:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-StatBackground")
	self.attributesFrame.left:SetTexCoord(0, 0.8984375, 0, 0.125)
	self.attributesFrame.left:SetWidth(115)
	self.attributesFrame.left:SetHeight(16)
	self.attributesFrame.left:SetPoint("TOPLEFT", -1, 0)
	local middle = self.attributesFrame:CreateTexture(nil, "ARTWORK")
	middle:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-StatBackground")
	middle:SetTexCoord(0, 0.8984375, 0.125, 0.1953125)
	middle:SetWidth(115)
	middle:SetHeight(53)
	middle:SetPoint("TOPLEFT", self.attributesFrame.left, "BOTTOMLEFT", 0, 0)
	local bottom = self.attributesFrame:CreateTexture(nil, "ARTWORK")
	bottom:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-StatBackground")
	bottom:SetTexCoord(0, 0.8984375, 0.484375, 0.609375)
	bottom:SetWidth(115)
	bottom:SetHeight(16)
	bottom:SetPoint("TOPLEFT", middle, "BOTTOMLEFT", 0, 0)
	for i = 1, 6 do
		self.attributesFrame.left[i] = CreateFrame("Frame", "InvenSimulatorStatFrameLeft"..i, self.attributesFrame, "StatFrameTemplate")
		self.attributesFrame.left[i].label = _G["InvenSimulatorStatFrameLeft"..i.."Label"]
		self.attributesFrame.left[i].text = _G["InvenSimulatorStatFrameLeft"..i.."StatText"]
		self.attributesFrame.left[i]:SetID(i)
		self.attributesFrame.left[i]:SetScript("OnEnter", self.ShowStatTooltip)
		if i == 1 then
			self.attributesFrame.left[i]:SetPoint("TOPLEFT", self.attributesFrame.left, 6, -3)
		else
			self.attributesFrame.left[i]:SetPoint("TOPLEFT", self.attributesFrame.left[i - 1], "BOTTOMLEFT")
		end
	end
	self.attributesFrame.right = self.attributesFrame:CreateTexture(nil, "ARTWORK")
	self.attributesFrame.right:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-StatBackground")
	self.attributesFrame.right:SetTexCoord(0, 0.8984375, 0, 0.125)
	self.attributesFrame.right:SetWidth(115)
	self.attributesFrame.right:SetHeight(16)
	self.attributesFrame.right:SetPoint("TOPLEFT", self.attributesFrame.left, "TOPRIGHT", 0, 0)
	middle = self.attributesFrame:CreateTexture(nil, "ARTWORK")
	middle:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-StatBackground")
	middle:SetTexCoord(0, 0.8984375, 0.125, 0.1953125)
	middle:SetWidth(115)
	middle:SetHeight(53)
	middle:SetPoint("TOPLEFT", self.attributesFrame.right, "BOTTOMLEFT", 0, 0)
	bottom = self.attributesFrame:CreateTexture(nil, "ARTWORK")
	bottom:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-StatBackground")
	bottom:SetTexCoord(0, 0.8984375, 0.484375, 0.609375)
	bottom:SetWidth(115)
	bottom:SetHeight(16)
	bottom:SetPoint("TOPLEFT", middle, "BOTTOMLEFT", 0, 0)
	for i = 1, 6 do
		self.attributesFrame.right[i] = CreateFrame("Frame", "InvenSimulatorStatFrameRight"..i, self.attributesFrame, "StatFrameTemplate")
		self.attributesFrame.right[i].label = _G["InvenSimulatorStatFrameRight"..i.."Label"]
		self.attributesFrame.right[i].text = _G["InvenSimulatorStatFrameRight"..i.."StatText"]
		self.attributesFrame.right[i]:SetID(i)
		self.attributesFrame.right[i]:SetScript("OnEnter", self.ShowStatTooltip)
		if i == 1 then
			self.attributesFrame.right[i]:SetPoint("TOPLEFT", self.attributesFrame.right, 6, -3)
		else
			self.attributesFrame.right[i]:SetPoint("TOPLEFT", self.attributesFrame.right[i - 1], "BOTTOMLEFT")
		end
	end
	local dropdownOnClick = function(self, id)
		UIDropDownMenu_SetSelectedValue(self.owner, self.value)
		InvenSimulatorUI.db[id] = self.value
		InvenSimulatorUI:UpdateStatList(id)
	end
	local dropdownInitialize = function(self)
		local info = UIDropDownMenu_CreateInfo()
		for i, text in ipairs(InvenSimulatorUI.statMenuList) do
			info.text = text
			info.value = text
			info.func = dropdownOnClick
			info.owner = UIDROPDOWNMENU_OPEN_MENU
			info.checked = InvenSimulatorUI.db[self.id] == text and 1 or nil
			info.arg1 = self.id
			UIDropDownMenu_AddButton(info)
		end
	end
	local dropdownOnShow = function(self)
		UIDropDownMenu_Initialize(self, dropdownInitialize)
		UIDropDownMenu_SetSelectedValue(self, InvenSimulatorUI.db[self.id])
		InvenSimulatorUI:UpdateStatList(self.id)
	end
	self.attributesFrame.left.dropdown = CreateFrame("Frame", "InvenSimulatorStatFrameLeftDropDown", self.attributesFrame, "UIDropDownMenuTemplate")
	self.attributesFrame.left.dropdown.id = "left"
	self.attributesFrame.left.dropdown:EnableMouse(true)
	self.attributesFrame.left.dropdown:SetPoint("BOTTOMLEFT", self.attributesFrame.left, "TOPLEFT", -17, -8)
	self.attributesFrame.left.dropdown:SetScript("OnShow", dropdownOnShow)
	UIDropDownMenu_Initialize(self.attributesFrame.left.dropdown, dropdownInitialize)
	UIDropDownMenu_SetSelectedValue(self.attributesFrame.left.dropdown, self.db.left)
	UIDropDownMenu_SetWidth(self.attributesFrame.left.dropdown, 99)
	UIDropDownMenu_JustifyText(self.attributesFrame.left.dropdown, "LEFT")
	self.attributesFrame.right.dropdown = CreateFrame("Frame", "InvenSimulatorStatFrameRightDropDown", self.attributesFrame, "UIDropDownMenuTemplate")
	self.attributesFrame.right.dropdown.id = "right"
	self.attributesFrame.right.dropdown:EnableMouse(true)
	self.attributesFrame.right.dropdown:SetPoint("BOTTOMLEFT", self.attributesFrame.right, "TOPLEFT", -17, -8)
	self.attributesFrame.right.dropdown:SetScript("OnShow", dropdownOnShow)
	UIDropDownMenu_Initialize(self.attributesFrame.right.dropdown, dropdownInitialize)
	UIDropDownMenu_SetSelectedValue(self.attributesFrame.right.dropdown, self.db.right)
	UIDropDownMenu_SetWidth(self.attributesFrame.right.dropdown, 99)
	UIDropDownMenu_JustifyText(self.attributesFrame.right.dropdown, "LEFT")
	self.receiveFrame = CreateFrame("Frame", nil, self)
	self.receiveFrame:SetPoint("TOPLEFT", self.attributesFrame.left.dropdown, "TOPLEFT", 16, 0)
	self.receiveFrame:SetPoint("BOTTOMRIGHT", self.attributesFrame, "BOTTOMRIGHT", 0, -10)
	self.receiveFrame:EnableMouse(true)
	self.receiveFrame:SetFrameLevel(InvenSimulatorStatFrameRightDropDownButton:GetFrameLevel() + 1)
	self.receiveFrame:Hide()
	self.receiveFrame:SetScript("OnEnter", frameOnEnter)
	self.receiveFrame:SetScript("OnLeave", frameOnLeave)
	self.receiveFrame:SetScript("OnMouseUp", frameOnMouseDown)
	self.receiveFrame:SetScript("OnReceiveDrag", frameOnReceiveDrag)
	local function OnClickShowHelmCloak(self)
		InvenSimulatorUI.db[self.key] = not InvenSimulatorUI.db[self.key]
		PlaySound(InvenSimulatorUI.db[self.key] and "igMainMenuOptionCheckBoxOn" or "igMainMenuOptionCheckBoxOff")
		self:SetChecked(InvenSimulatorUI.db[self.key])
		InvenSimulatorUI:ModelUpdate()
	end
	self.showHelm = CreateFrame("CheckButton", "InvenSimulatorUIShowHelm", self, "InterfaceOptionsCheckButtonTemplate")
	InvenSimulatorUIShowHelmText:SetText("투구 보이기")
	self.showHelm.key = "showHelm"
	self.showHelm:SetChecked(self.db.showHelm)
	self.showHelm:SetScript("OnClick", OnClickShowHelmCloak)
	self.showHelm:SetPoint("TOPLEFT", self.slots[9], "BOTTOMLEFT", 0, -2)
	self.showHelm:SetScale(0.8)
	self.showCloak = CreateFrame("CheckButton", "InvenSimulatorUIShowCloak", self, "InterfaceOptionsCheckButtonTemplate")
	InvenSimulatorUIShowCloakText:SetText("망토 보이기")
	self.showCloak.key = "showCloak"
	self.showCloak:SetChecked(self.db.showCloak)
	self.showCloak:SetScript("OnClick", OnClickShowHelmCloak)
	self.showCloak:SetPoint("TOPLEFT", self.showHelm, "BOTTOMLEFT", 0, 9)
	self.showCloak:SetScale(0.8)
	self.tradeSkillButton1 = CreateFrame("Button", "InvenSimulatorUITradeSkill1", self, "UIPanelButtonTemplate")
	self.tradeSkillButton1:SetID(1)
	self.tradeSkillButton1:SetWidth(60)
	self.tradeSkillButton1:SetHeight(20)
	self.tradeSkillButton1:SetScale(0.9)
	if self.db.tradeSkill[1] == nil or self.db.tradeSkill[1] == "" or self.db.tradeSkill[1] == "없음" then
		self.tradeSkillButton1:SetText("전문기술1")
	else
		self.tradeSkillButton1:SetText(self.db.tradeSkill[1])
	end
	self.tradeSkillButton1:SetPoint("TOPRIGHT", self.slots[14], "BOTTOMRIGHT", 2, 0)
	self.tradeSkillButton2 = CreateFrame("Button", "InvenSimulatorUITradeSkill2", self, "UIPanelButtonTemplate")
	self.tradeSkillButton2:SetID(2)
	self.tradeSkillButton2:SetWidth(60)
	self.tradeSkillButton2:SetHeight(20)
	self.tradeSkillButton2:SetScale(0.9)
	if self.db.tradeSkill[2] == nil or self.db.tradeSkill[2] == "" or self.db.tradeSkill[2] == "없음" then
		self.tradeSkillButton2:SetText("전문기술2")
	else
		self.tradeSkillButton2:SetText(self.db.tradeSkill[2])
	end
	self.tradeSkillButton2:SetPoint("TOPRIGHT", self.tradeSkillButton1, "BOTTOMRIGHT", 0, 1)
	local function tradeSkillButtonOnClick(self)
		InvenSimulatorUI:OpenTradeSkillMenu(self)
	end
	self.tradeSkillButton1:SetScript("OnClick", tradeSkillButtonOnClick)
	self.tradeSkillButton2:SetScript("OnClick", tradeSkillButtonOnClick)
	self.talentButton = CreateFrame("Button", nil, self, "UIPanelButtonTemplate")
	self.talentButton:SetWidth(60)
	self.talentButton:SetHeight(22)
	self.talentButton:SetText("특성/문양")
	self.talentButton:SetPoint("TOPRIGHT", -6, -38)
	self.talentButton:SetScript("OnClick", function()
		if InvenSimulatorTalentFrame:IsShown() then
			InvenSimulatorTalentFrame:Hide()
		else
			InvenSimulatorTalentFrame:Show()
		end
	end)
	self.copyItem = CreateFrame("Button", nil, self, "UIPanelButtonTemplate")
	self.copyItem:SetWidth(110)
	self.copyItem:SetHeight(22)
	self.copyItem:SetText("현재 장비 가져오기")
	self.copyItem:SetPoint("RIGHT", self.talentButton, "LEFT", 2, 0)
	self.copyItem:SetScript("OnClick", function()
		for i = 1, 19 do
			InvenSimulatorCharDB.items[i] = nil
		end
		InvenSimulatorCharDB.ammo = LIS:GetItemID(GetInventoryItemLink("player", 0))
		for i = 1, 19 do
			InvenSimulatorUI:SetItem(i, GetInventoryItemLink("player", i), nil, nil)
		end
		InvenSimulatorUI:ModelUpdate()
		InvenSimulatorUI:ScanItem()
	end)
	self.reflashButton = CreateFrame("Button", nil, self, "UIPanelButtonTemplate")
	self.reflashButton:SetWidth(60)
	self.reflashButton:SetHeight(22)
	self.reflashButton:SetText("새로 고침")
	self.reflashButton:SetPoint("RIGHT", self.copyItem, "LEFT", 2, 0)
	self.reflashButton:SetScript("OnClick", function()
		InvenSimulatorUI:ModelUpdate()
		InvenSimulatorUI:ScanItem()
	end)
	self.profileButton = CreateFrame("Button", nil, self, "UIPanelButtonTemplate")
	self.profileButton:SetWidth(50)
	self.profileButton:SetHeight(22)
	self.profileButton:SetText("프로필")
	self.profileButton:SetPoint("RIGHT", self.reflashButton, "LEFT", 2, 0)
	self.profileButton:SetScript("OnClick", function(self)
		InvenSimulatorUI:OpenProfileMenu(self)
	end)
	self.statLinkButton = CreateFrame("Button", nil, self, "UIPanelButtonTemplate")
	self.statLinkButton:SetWidth(22)
	self.statLinkButton:SetHeight(22)
	self.statLinkButton:SetText("▶")
	self.statLinkButton:SetPoint("BOTTOMRIGHT", self.talentButton, "TOPRIGHT", 0, -4)
	self.statLinkButton:SetScript("OnClick", function()
		InvenSimulatorUI:ShowStatLink()
	end)
	self:RegisterEvent("CURSOR_UPDATE")
	self:CreateBuffFrame()

	self.openSaveItemFrameButton = CreateFrame("Button", "InvenSimulatorUIOpenSaveItemFrame", self, "UIPanelButtonTemplate")
	self.openSaveItemFrameButton:SetWidth(80)
	self.openSaveItemFrameButton:SetHeight(20)
	self.openSaveItemFrameButton:SetScale(0.9)
	self.openSaveItemFrameButton:SetText("아이템 저장소")
	self.openSaveItemFrameButton:SetPoint("LEFT", self.buffFrame.removeAllButton, "RIGHT", -3, 0)
	self.openSaveItemFrameButton:SetScript("OnClick", function()
		if InvenSimulatorSaveItemFrame:IsShown() then
			InvenSimulatorSaveItemFrame:Hide()
		else
			InvenSimulatorUI:ShowTop(InvenSimulatorSaveItemFrame)
		end
	end)

	self.openOtherCharItem = CreateFrame("Button", "InvenSimulatorUIOpenOtherCharFrame", self, "UIPanelButtonTemplate")
	self.openOtherCharItem:SetFrameLevel(self.showCloak:GetFrameLevel() + 1)
	self.openOtherCharItem:SetWidth(80)
	self.openOtherCharItem:SetHeight(20)
	self.openOtherCharItem:SetScale(0.9)
	self.openOtherCharItem:SetText("다른 캐릭터")
	self.openOtherCharItem:SetPoint("RIGHT", self.buffFrame.removeAllButton, "LEFT", 3, 0)
	self.openOtherCharItem:SetScript("OnClick", function()
		if InvenSimulatorOtherCharFrame:IsShown() then
			InvenSimulatorOtherCharFrame:Hide()
		else
			InvenSimulatorUI:ShowTop(InvenSimulatorOtherCharFrame)
		end
	end)
	self.openOtherCharItem:Disable()
	for _ in pairs(InvenSimulatorSaveDB) do
		self.openOtherCharItem:Enable()
		break
	end
	tinsert(UISpecialFrames, "InvenSimulatorUI")
end

function InvenSimulatorUI:ShowStatTooltip()
	if self.statName and InvenSimulatorUI.tooltipTable[self.statName] then
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
		GameTooltip:ClearLines()
		if type(InvenSimulatorUI.tooltipTable[self.statName]) == "table" then
			local t = InvenSimulatorUI.tooltipTable[self.statName]
			if self.delta then
				GameTooltip:AddDoubleLine(t[1], self.delta, 1, 1, 1, 1, 1, 1)
			else
				GameTooltip:AddLine(t[1], 1, 1, 1)
			end
			for i = 2, #t, 2 do
				if t[i + 1] and t[i + 1] ~= "" then
					GameTooltip:AddDoubleLine(t[i], t[i + 1], nil, nil, nil, nil, nil, nil, 1)
				else
					GameTooltip:AddLine(t[i], nil, nil, nil, 1)
				end
			end
		else
			GameTooltip:SetText(InvenSimulatorUI.tooltipTable[self.statName])
		end
		if self.statName == "주문 공격력" then
			for i, school in ipairs(InvenSimulatorUI.spellSchools) do
				GameTooltip:AddDoubleLine(school, ("%d"):format(InvenSimulatorUI.specTable[school.." 주문 공격력"] or InvenSimulatorUI.specTable["주문 공격력"] or 0))
				GameTooltip:AddTexture("Interface\\PaperDollInfoFrame\\SpellSchoolIcon"..(i + 1))
			end
		elseif self.statName == "극대화율" then
			for i, school in ipairs(InvenSimulatorUI.spellSchools) do
				GameTooltip:AddDoubleLine(school, ("%.2f%%"):format(InvenSimulatorUI.specTable[school.." 주문 극대화율"] or InvenSimulatorUI.specTable["극대화율"] or 0))
				GameTooltip:AddTexture("Interface\\PaperDollInfoFrame\\SpellSchoolIcon"..(i + 1))
			end

		end
	end
	GameTooltip:Show()
end

function InvenSimulatorUI:UpdateStatList(id)
	local f = self.attributesFrame[id]
	local list = self.statDetailList[self.db[id]]
	local cv, ov, nv, dv, dv2, nv1, nv2, pattern
	if not list then
		self.db[id] = "기본 능력치"
		list = self.statDetailList[self.db[id]]
	end
	for i = 1, 6 do
		if list[i] then
			f[i].label:SetText((self.statReplaceValue[list[i]] or list[i])..":")
			if list[i] == "공격력" then
				if self.specTable["주장비 최소 공격력"] < 100 and self.specTable["주장비 최대 공격력"] < 100 then
					f[i].text:SetFormattedText("%d - %d", self.specTable["주장비 최소 공격력"], self.specTable["주장비 최대 공격력"])
				else
					f[i].text:SetFormattedText("%d-%d", self.specTable["주장비 최소 공격력"], self.specTable["주장비 최대 공격력"])
				end
			elseif list[i] == "원거리 공격력" then
				if self.specTable["원거리 장비 최소 공격력"] == nil then
					f[i].text:SetText("-")
				elseif self.specTable["원거리 장비 최소 공격력"] < 100 and self.specTable["원거리 장비 최대 공격력"] < 100 then
					f[i].text:SetFormattedText("%d - %d", self.specTable["원거리 장비 최소 공격력"], self.specTable["원거리 장비 최대 공격력"])
				else
					f[i].text:SetFormattedText("%d-%d", self.specTable["원거리 장비 최소 공격력"], self.specTable["원거리 장비 최대 공격력"])
				end
			elseif list[i] == "속도" then
				if self.specTable["보조장비 공격 속도"] then
					f[i].text:SetFormattedText("%.2f / %.2f", self.specTable["주장비 공격 속도"], self.specTable["보조장비 공격 속도"])
				else
					f[i].text:SetFormattedText("%.2f", self.specTable["주장비 공격 속도"])
				end
			elseif list[i] == "원거리 속도" then
				if self.specTable["원거리 장비 공격 속도"] then
					f[i].text:SetFormattedText("%.2f", self.specTable["원거리 장비 공격 속도"])
				else
					f[i].text:SetText("-")
				end
			elseif list[i] == "치명타율" or list[i] == "원거리 치명타율" or list[i] == "극대화율" or list[i] == "회피율" or list[i] == "무기 막기" or list[i] == "방패 막기" then
				f[i].text:SetFormattedText("%.2f%%", self.specTable[list[i]] or 0)
			elseif list[i] == "숙련" then
				if self.specTable["숙련2"] then
					f[i].text:SetFormattedText("%d / %d", self.specTable[list[i]], self.specTable["숙련2"])
				else
					f[i].text:SetFormattedText("%d", self.specTable[list[i]])
				end
			elseif list[i] == "5초당 마나 회복량" then
				if UnitPowerMax("player", 0) > 0 then
					f[i].text:SetFormattedText("%d", self.specTable[list[i]] or 0)
				else
					f[i].text:SetText("-")
				end
			else
				f[i].text:SetFormattedText("%d", self.specTable[list[i]] or 0)
			end
			f[i].statName = list[i]
			if not self.tooltipTable[list[i]] and f[i].text:GetText() ~= "-" then
				self.tooltipTable[list[i]] = { ("|cffffffff%s %s|r"):format(self.statReplaceValue[list[i]] or list[i], f[i].text:GetText()) }
			end
			if self.currentStatValues[list[i]] then
				pattern = self.statPattern[list[i]] or "%d"
				if type(self.currentStatValues[list[i]]) == "function" then
					cv, ov = self.currentStatValues[list[i]]()
				else
					cv, ov = self.currentStatValues[list[i]], nil
				end
				nv = (f[i].text:GetText() or "")..""
				if nv == "" or nv == "-" then
					f[i].delta = nil
				elseif nv:find("(.+)/(.+)") then
					nv1, nv2 = nv:match("(.+)/(.+)")
					dv = cv and (tonumber(nv1:gsub("%%", "") or 0) - tonumber((pattern:format(cv)):gsub("%%", "") or 0)) or 0
					dv2 = ov and (tonumber(nv2:gsub("%%", "") or 0) - tonumber((pattern:format(ov)):gsub("%%", "") or 0)) or 0
					if list[i]:find("속도") then
						if dv > 0 then
							f[i].delta = "|cffff7272+"..pattern:format(dv).."|r / "
							f[i].text:SetText(f[i].text:GetText():gsub("(.+)/(.+)", "|cffff7272%1|r/%2"))
						elseif dv < 0 then
							f[i].delta = "|cff00ff00"..pattern:format(dv).."|r / "
							f[i].text:SetText(f[i].text:GetText():gsub("(.+)/(.+)", "|cff00ff00%1|r/%2"))
						else
							f[i].delta = "0 / "
						end
						if dv2 > 0 then
							f[i].delta = f[i].delta.."|cffff7272+"..pattern:format(dv2)
							f[i].text:SetText(f[i].text:GetText():gsub("(.+)/(.+)", "%1/|cffff7272%2"))
						elseif dv2 < 0 then
							f[i].delta = f[i].delta.."|cff00ff00"..pattern:format(dv2)
							f[i].text:SetText(f[i].text:GetText():gsub("(.+)/(.+)", "%1/|cff00ff00%2"))
						elseif f[i].delta == "0 / " then
							f[i].delta = nil
						end
					else
						if dv > 0 then
							f[i].delta = "|cff00ff00+"..pattern:format(dv).."|r / "
							f[i].text:SetText(f[i].text:GetText():gsub("(.+)/(.+)", "|cff00ff00%1|r/%2"))
						elseif dv < 0 then
							f[i].delta = "|cffff7272"..pattern:format(dv).."|r / "
							f[i].text:SetText(f[i].text:GetText():gsub("(.+)/(.+)", "|cffff7272%1|r/%2"))
						else
							f[i].delta = "0 / "
						end
						if dv2 > 0 then
							f[i].delta = f[i].delta.."|cff00ff00+"..pattern:format(dv2)
							f[i].text:SetText(f[i].text:GetText():gsub("(.+)/(.+)", "%1/|cff00ff00%2"))
						elseif dv2 < 0 then
							f[i].delta = f[i].delta.."|cffff7272"..pattern:format(dv2)
							f[i].text:SetText(f[i].text:GetText():gsub("(.+)/(.+)", "%1/|cffff7272%2"))
						elseif f[i].delta == "0 / " then
							f[i].delta = nil
						end
					end
				elseif nv:find("(.+)-(.+)") then
					if list[i] == "공격력" then
						dv = (self.specTable["주장비 최소 공격력"] + self.specTable["주장비 최대 공격력"]) / 2 / self.specTable["주장비 공격 속도"] - cv
					elseif list[i] == "원거리" then
						dv = (self.specTable["원거리 장비 최소 공격력"] + self.specTable["원거리 장비 최대 공격력"]) / 2 / self.specTable["원거리 장비 공격 속도"] - cv
					else
						dv = nil
					end
					if dv and abs(dv) > 0.25 then
						if dv > 0 then
							f[i].text:SetText(f[i].text:GetText():gsub("(.+)-(.+)", "|cff00ff00%1|r-|cff00ff00%2"))
						else
							f[i].text:SetText(f[i].text:GetText():gsub("(.+)-(.+)", "|cffff7272%1|r-|cffff7272%2"))
						end
					end
					f[i].delta = nil
				else
					cv = pattern:format(cv)
					dv = tonumber(nv:gsub("%%", "") or 0) - tonumber(cv:gsub("%%", "") or 0)
					if dv == 0 then
						f[i].delta = nil
					elseif list[i]:find("속도") and not list[i]:find("가속도") then
						if dv > 0 then
							f[i].delta = "|cffff7272+"..pattern:format(dv)
							f[i].text:SetText("|cffff7272"..f[i].text:GetText())
						else
							f[i].delta = "|cff00ff00"..pattern:format(dv)
							f[i].text:SetText("|cff00ff00"..f[i].text:GetText())
						end
					elseif dv > 0 then
						f[i].delta = "|cff00ff00+"..pattern:format(dv)
						f[i].text:SetText("|cff00ff00"..f[i].text:GetText())
					else
						f[i].delta = "|cffff7272"..pattern:format(dv)
						f[i].text:SetText("|cffff7272"..f[i].text:GetText())
					end
				end
			else
				f[i].delta = nil
			end
		else
			f[i].label:SetText("")
			f[i].text:SetText("")
			f[i].statName = nil
			f[i].deltaValue, f[i].deltaUnit, f[i].deltaPattern = 0, nil, nil
		end
	end
end

function InvenSimulatorUI:ModelUpdate()
	self.modelFrame:Undress()
	if self.db.items[1] and self.db.showHelm then
		self.modelFrame:TryOn(self.db.items[1])
	end
	for i = 2, 14 do
		if self.db.items[i] and IsDressableItem(self.db.items[i]) then
			self.modelFrame:TryOn(self.db.items[i])
		end
	end
	if self.db.items[15] and self.db.showCloak then
		self.modelFrame:TryOn(self.db.items[15])
	end
	local w1 = self.db.items[16] and select(9, GetItemInfo(self.db.items[16])) or nil
	local w2 = self.db.items[17] and select(9, GetItemInfo(self.db.items[17])) or nil
	if w1 and w2 then
		if self.db.items[16] == self.db.items[17] then
			self.modelFrame:TryOn(self.db.items[16])
			self.modelFrame:TryOn(self.db.items[17])
		elseif w1 == "INVTYPE_2HWEAPON" and w2 == "INVTYPE_2HWEAPON" then
			self.modelFrame:TryOn(self.db.items[16])
			self.modelFrame:TryOn(self.db.items[17])
		elseif w1 == "INVTYPE_WEAPONMAINHAND" and w2 == "INVTYPE_WEAPON" then
			self.modelFrame:TryOn(self.db.items[16])
			self.modelFrame:TryOn(self.db.items[17])
			self.modelFrame:TryOn(self.db.items[17])
			self.modelFrame:TryOn(self.db.items[16])
		elseif w1 == "INVTYPE_WEAPON" and w2 == "INVTYPE_WEAPON" then
			self.modelFrame:TryOn(self.db.items[16])
			self.modelFrame:TryOn(self.db.items[16])
			self.modelFrame:TryOn(self.db.items[17])
		else
			self.modelFrame:TryOn(self.db.items[16])
			self.modelFrame:TryOn(self.db.items[17])
		end
	elseif w1 then
		self.modelFrame:TryOn(self.db.items[16])
	elseif w2 then
		self.modelFrame:TryOn(self.db.items[17])
	end
	if self.db.items[19] then
		self.modelFrame:TryOn(self.db.items[19])
	end
end

function InvenSimulatorUI:EquipItem(slot, link)
	if equipableLink == link then
		equipableLink = nil
		if slot > 0 and slot < 20 and equipableSlot[slot] == true then
			self:SetItem(slot, link, nil, true)
			self:ModelUpdate()
		else
			slot = 20
			for p in pairs(equipableSlot) do
				slot = min(p, slot)
				if self.db.items[p] == nil then
					slot = p
					break
				end
			end
			if slot < 20 then
				self:SetItem(slot, link, nil, true)
				self:ModelUpdate()
			end
		end
	end
	self.receiveFrame:Hide()
end

function InvenSimulatorUI:SlotHighlighUpdate(equipLoc, link)
	if equipLoc and link then
		equipableLink = link
		if self:IsEquipItem(link) then
			self.isUniqueItem = self:IsUniqueItem(link)
			self.isHighlightSlot = true
			for i = 1, 19 do
				if self.slotsEquipLoc[i][equipLoc] then
					equipableSlot[i] = true
					self.slots[i]:LockHighlight()
				else
					equipableSlot[i] = nil
					self.slots[i]:UnlockHighlight()
				end
			end
			if self.isUniqueItem then
				link = LIS:GetItemID(link)
				if self.isUniqueItem == "INVTYPE_FINGER" then
					if LIS:GetItemID(self.db.items[11]) == link then
						equipableSlot[12] = nil
						self.slots[12]:UnlockHighlight()
					elseif LIS:GetItemID(self.db.items[12]) == link then
						equipableSlot[11] = nil
						self.slots[11]:UnlockHighlight()
					end
				elseif self.isUniqueItem == "INVTYPE_TRINKET" then
					if LIS:GetItemID(self.db.items[13]) == link then
						equipableSlot[14] = nil
						self.slots[14]:UnlockHighlight()
					elseif LIS:GetItemID(self.db.items[14]) == link then
						equipableSlot[13] = nil
						self.slots[13]:UnlockHighlight()
					elseif equipableLink:find("다크문 카드: 위대함") then
						if self.db.items[13] and self.db.items[13]:find("다크문 카드: 위대함") then
							equipableSlot[14] = nil
							self.slots[14]:UnlockHighlight()
						elseif self.db.items[14] and self.db.items[14]:find("다크문 카드: 위대함") then
							equipableSlot[14] = nil
							self.slots[14]:UnlockHighlight()
						end
					end
				elseif self.isUniqueItem == "INVTYPE_WEAPON" or self.isUniqueItem == "INVTYPE_2HWEAPON" then
					if LIS:GetItemID(self.db.items[16]) == link then
						equipableSlot[17] = nil
						self.slots[17]:UnlockHighlight()
					elseif LIS:GetItemID(self.db.items[17]) == link then
						equipableSlot[16] = nil
						self.slots[16]:UnlockHighlight()
					end
				end
			end
			return true
		end
	end
	return nil
end

function InvenSimulatorUI:GetEquipableSlot(slot, link)
	return equipableSlot[slot]
end

function InvenSimulatorUI:HasShield()
	if self.db.items[17] and select(9, GetItemInfo(self.db.items[17])) == "INVTYPE_SHIELD" then
		return true
	else
		return nil
	end
end

function InvenSimulatorUI:CURSOR_UPDATE()
	if self:IsShown() then
		if GetCursorInfo() then
			self.receiveFrame:Show()
			cursorItemLink = self:GetCursorItemLink()
			if cursorItemLink then
				cursorType = select(2, self:IsEquipItem(cursorItemLink))
				if self:SlotHighlighUpdate(cursorType, cursorItemLink) then
					return
				end
			end
		elseif self.isFakeDragging and self.fakeCursor.link then
			self.receiveFrame:Show()
			cursorType = select(2, self:IsEquipItem(self.fakeCursor.link))
			if self:SlotHighlighUpdate(cursorType, self.fakeCursor.link) then
				return
			end
		else
			self.receiveFrame:Hide()
		end
	else
		self.receiveFrame:Hide()
	end
	self.isUniqueItem = nil
	if self.isHighlightSlot then
		self.isHighlightSlot = nil
		for i = 1, 19 do
			self.slots[i]:UnlockHighlight()
		end
	end
end

function InvenSimulatorUI:SetItem(id, link, first, run)
	if self.slots[id] then
		if link then
			link = self:FixItemLink(link, id)
			if link == nil then
				return self:SetItem(id, nil, first, run)
			end
			if id == 16 and self.db.items[17] then
				if select(9, GetItemInfo(link)) == "INVTYPE_2HWEAPON" then
					if self.class == "전사" and self:GetTalentPoint("티탄의 손아귀") == 1 then
						if self.db.items[17] then
							if select(9, GetItemInfo(self.db.items[17])) == "INVTYPE_SHIELD" then
								if not first then
									self:SetItem(17, nil, nil, true)
								end
							elseif select(7, GetItemInfo(link)) == "장창류" then
								if not first then
									self:SetItem(17, nil, nil, true)
								end
							end
						end
					elseif self.db.items[17] then
						if not first then
							self:SetItem(17, nil, nil, true)
						end
					end
				end
			elseif id == 17 and self.db.items[16] then
				if select(7, GetItemInfo(link)) == "장창류" then
					self:SetItem(16, link, nil, nil)
					return self:SetItem(17, nil, first, run)
				elseif select(9, GetItemInfo(self.db.items[16])) == "INVTYPE_2HWEAPON" then
					if select(9, GetItemInfo(link)) == "INVTYPE_SHIELD" or select(9, GetItemInfo(link)) == "INVTYPE_HOLDABLE" then
						self:SetItem(16, nil, nil, nil)
					elseif self.class == "전사" and self:GetTalentPoint("티탄의 손아귀") == 0 then
						self:SetItem(16, nil, nil, nil)
					end
				elseif self.class == "주술사" and self:GetTalentPoint("쌍수 무기") == 0 then
					if select(9, GetItemInfo(link)) == "INVTYPE_WEAPON" or select(9, GetItemInfo(link)) == "INVTYPE_WEAPONOFFHAND" then
						return self:SetItem(17, nil, first, run)
					end
				end
			end
			self.slots[id].icon:SetTexture(GetItemIcon(link))
			if first or self.db.items[id] == link then
				run = nil
			else
				run = true
				self.db.items[id] = link
				self.db.itemsQuality[id] = select(3, GetItemInfo(link))
			end
			if self.db.itemsQuality[id] and self.db.itemsQuality[id] > 1 then
				self.slots[id].border:SetVertexColor(unpack(self.qualityColor[self.db.itemsQuality[id]]))
				self.slots[id].border:Show()
			else
				self.slots[id].border:Hide()
			end
			if self.itemEnchantingFrame and self.itemEnchantingFrame.openSlot == id then
				self.itemEnchantingFrame:SetItem(link)
			end
		else
			self.slots[id].icon:SetTexture(self.slots[id].backgroundTextureName)
			self.slots[id].border:Hide()
			if first then
				run = nil
			else
				run = true
				self.db.items[id] = nil
				self.db.itemsQuality[id] = nil
			end
			if self.itemEnchantingFrame and self.itemEnchantingFrame.openSlot == id then
				self.itemEnchantingFrame:Hide()
			end
		end
		if id == 18 then
			self:ToggleAmmoSlot()
		end
		if run then
			self:ScanItem()
		end
	end
end

function InvenSimulatorUI:ToggleAmmoSlot()
	if self.ammoSlot then
		if self.db.items[18] and LIS:GetItemID(self.db.items[18]) ~= 34334 then
			local ranged = select(7, GetItemInfo(self.db.items[18]))
			if ranged == "활류" or ranged == "총기류" or ranged == "석궁류" then
				self.ammoSlot:Show()
				self:TransmuteAmmo()
				self.ammoSlot.icon:SetTexture(self.db.ammo and GetItemIcon(self.db.ammo) or self.ammoSlot.backgroundTextureName)
				return
			end
		end
		self.ammoSlot:Hide()
	end
end

function InvenSimulatorUI:IsEquipItem(link)
	if link and link:find("item:") then
		if self:HasTradeSkill(self:IsTradeSkillOnly(link)) then
			itemSubType, _, itemEquipLoc = select(7, GetItemInfo(link))
			if itemSubType and itemEquipLoc and InvenSimulatorUI.itemSubTypes[itemSubType] then
				for i = 1, 19 do
					if InvenSimulatorUI.slotsEquipLoc[i][itemEquipLoc] then
						link = LIS:GetItemID(link)
						if raceClassItemCache[link] == true then
							return itemSubType, itemEquipLoc
						elseif raceClassItemCache[link] == false then
							return nil, nil
						else
							local text, r, g, b
							raceCheck, classCheck, uniqueCheck = true, true, nil
							tooltip:SetOwner(UIParent, "ANCHOR_NONE")
							tooltip:SetHyperlink("item:"..link)
							for i = 2, 17 do
								text, r, g, b = tooltip:GetLineText(i)
								if text then
									if text:find("직업: ") then
										if not(r > 0.9 and g > 0.9 and b > 0.9) then
											classCheck = nil
										end
									elseif text:find("종족: ") then
										if not(r > 0.9 and g > 0.9 and b > 0.9) then
											raceCheck = nil
										end
									end
									if text == "고유 아이템" or text == "고유 장착 아이템" then
										uniqueCheck = true
									end
								end
							end
							if itemEquipLoc == "INVTYPE_FINGER" or itemEquipLoc == "INVTYPE_TRINKET" or itemEquipLoc == "INVTYPE_WEAPON" or itemEquipLoc == "INVTYPE_2HWEAPON" then
								if uniqueCheck then
									uniqueItemCache[link] = true
								else
									uniqueItemCache[link] = false
								end
							end
							if raceCheck and classCheck then
								raceClassItemCache[link] = true
								return itemSubType, itemEquipLoc
							else
								raceClassItemCache[link] = false
								return nil, nil
							end
						end
					end
				end
			end
		end
	end
	return nil, nil
end

function InvenSimulatorUI:IsUniqueItem(link)
	if link and link:find("item:") then
		local equipLoc = select(9, GetItemInfo(link))
		if equipLoc == "INVTYPE_FINGER" or equipLoc == "INVTYPE_TRINKET" or equipLoc == "INVTYPE_WEAPON" or equipLoc == "INVTYPE_2HWEAPON" then
			local itemid = LIS:GetItemID(link)
			if uniqueItemCache[itemid] == true then
				return equipLoc
			elseif uniqueItemCache[itemid] == false then
				return nil
			else
				tooltip:SetOwner(UIParent, "ANCHOR_NONE")
				tooltip:SetHyperlink(link)
				for i = 2, 4 do
					if tooltip:GetLineText(i) == "고유 아이템" or tooltip:GetLineText(i) == "고유 장착 아이템" then
						uniqueItemCache[itemid] = true
						return equipLoc
					end
				end
				uniqueItemCache[itemid] = false
			end
		end
	end
	return nil
end

function InvenSimulatorUI:GetSlotItemName(slot)
	slot = slot and self.db.items[slot]
	if type(slot) == "string" then
		return ("%s%s|r"):format(slot:sub(1, 10), slot:match("|h%[(.+)%]"))
	end
end

function InvenSimulatorUI:ApplyFakeDrag()
	self.fakeCursor = CreateFrame("Frame", nil, UIParent)
	self.fakeCursor:Hide()
	self.fakeCursor:SetFrameStrata("DIALOG")
	self.fakeCursor:SetToplevel(true)
	self.fakeCursor:SetWidth(32)
	self.fakeCursor:SetHeight(32)
	self.fakeCursor.icon = self.fakeCursor:CreateTexture(nil, "ARTWORK")
	self.fakeCursor.icon:SetAllPoints()
	self.fakeCursor.arrow = self.fakeCursor:CreateTexture(nil, "OVERLAY")
	self.fakeCursor.arrow:SetTexture("Interface\\CURSOR\\Item")
	self.fakeCursor.arrow:SetAllPoints()
	self.fakeCursor.anchor = CreateFrame("GameTooltip", "InvenSimulatorFakeCursorAnchor", UIParent, "GameTooltipTemplate")
	self.fakeCursor.anchor:SetClampedToScreen(nil)
	self.fakeCursor.anchor:Hide()
	self.fakeCursor:SetPoint("TOPLEFT", self.fakeCursor.anchor, "BOTTOM")
	self.fakeCursor:SetScript("OnShow", function(self)
		self.anchor:SetOwner(UIParent, "ANCHOR_CURSOR")
		self.anchor:ClearLines()
		self.anchor:AddLine("InvenSimulator")
		self.anchor:Show()
		self.anchor:SetAlpha(0)
		self.icon:SetTexture(GetItemIcon(self.link))
		InvenSimulatorUI.isUniqueItem = InvenSimulatorUI:IsUniqueItem(InvenSimulatorUI.fakeCursor.link)
		SetCursor("NONE")
	end)
	self.fakeCursor:SetScript("OnHide", function(self)
		InvenSimulatorUI.isFakeDragging = nil
		InvenSimulatorUI.isUniqueItem = nil
		self.link = nil
		self.anchor:Hide()
		ResetCursor()
	end)
	local ignoreFrame = { "^ChatFrame(%d+)", "UIParent", "WorldFrame", "^InvenSimulator(.+)" }
	local enableHook = {}
	local editTooltip = {}
	local function onDragStartItem()
		if InvenSimulatorUI:IsShown() and not InvenSimulatorUI.isFakeDragging and InvenSimulatorUI:IsEquipItem(InvenSimulatorUI.fakeCursor.link) then
			InvenSimulatorUI.isFakeDragging = true
			InvenSimulatorUI.fakeCursor:Show()
		end
	end
	local function onDragStopItem()
		if InvenSimulatorUI.isFakeDragging then
			InvenSimulatorUI.isFakeDragging = nil
			if InvenSimulatorUI.enterSlot then
				if InvenSimulatorUI.slots[InvenSimulatorUI.enterSlot] then
					InvenSimulatorUI.slots[InvenSimulatorUI.enterSlot].preventClick = true
				end
				InvenSimulatorUI:EquipItem(InvenSimulatorUI.enterSlot, InvenSimulatorUI.fakeCursor.link)
			elseif InvenSimulatorUI.enterParent then
				InvenSimulatorUI:EquipItem(0, InvenSimulatorUI.fakeCursor.link)
			elseif GetMouseFocus() and GetMouseFocus():GetName() and GetMouseFocus():GetName():find("^InvenSimulatorSaveItemFrame") then
				InvenSimulatorSaveItemFrame:SaveItem(InvenSimulatorUI.fakeCursor.link, true)
			end
			InvenSimulatorUI.fakeCursor:Hide()
		end
	end
	local function onTooltipSetItem(self)
		if self == GameTooltip and InvenSimulatorUI:IsShown() and not InvenSimulatorUI.isFakeDragging then
			local parent, anchor = self:GetOwner()
			if parent then
				local setTooltipLink = nil
				if enableHook[parent] then
					setTooltipLink = true
					if editTooltip[parent] then
						InvenSimulatorUI:EditTooltip(self, parent:GetID())
					end
				elseif parent:GetName() and anchor ~= "ANCHOR_NONE" and anchor ~= "ANCHOR_CURSOR" then
					if not parent:GetScript("OnDragStart") and not parent:GetScript("OnDragStop") then
						anchor = parent:GetName()
						if anchor:find("^InvenSimulatorUI(.+)Slot$") then
							return InvenSimulatorUI:EditTooltip(self, parent:GetID())
						elseif anchor:find("^InvenSimulatorItemListFrameButton(%d+)$") or anchor:find("^InvenSimulatorSaveItemFrameItemButton(%d+)$") or anchor:find("^InvenSimulatorOtherCharFrameSlot(%d+)$") then
							InvenSimulatorUI:EditTooltip(self, parent:GetID())
							editTooltip[parent] = true
						else
							for _, fn in ipairs(ignoreFrame) do
								if fn == anchor or (fn:find("++") and anchor:find(fn)) then
									return
								end
							end
						end
						parent:RegisterForDrag("LeftButton")
						parent:SetScript("OnDragStart", onDragStartItem)
						parent:SetScript("OnDragStop", onDragStopItem)
						enableHook[parent] = true
						setTooltipLink = true
					elseif (parent:GetName()):find("ExaminerItemButton(.+)Slot") then
						parent:HookScript("OnDragStart", function(self)
							if not (Examiner:ValidateUnit() and UnitIsUnit(Examiner.unit, "player")) then
								onDragStartItem()
							end
						end)
						parent:SetScript("OnDragStop", onDragStopItem)
						enableHook[parent] = true
						setTooltipLink = true
					end
				end
				if setTooltipLink then
					InvenSimulatorUI.fakeCursor.link = select(2, self:GetItem())
				else
					InvenSimulatorUI.fakeCursor.link = nil
				end
			end
		end
	end
	if GameTooltip:GetScript("OnTooltipSetItem") then
		GameTooltip:HookScript("OnTooltipSetItem", onTooltipSetItem)
	else
		GameTooltip:SetScript("OnTooltipSetItem", onTooltipSetItem)
	end
	GameTooltip:HookScript("OnHide", function() GameTooltip_ICC_Texture:Hide() end)
	local function onHyperlinkDragStart(self)
		if InvenSimulatorUI.chatLink then
			if not GetItemInfo(InvenSimulatorUI.chatLink) then
				InvenSimulatorFakeCursorAnchor:SetOwner(UIParent, "ANCHOR_NONE")
				InvenSimulatorFakeCursorAnchor:SetHyperlink(InvenSimulatorUI.chatLink)
				InvenSimulatorFakeCursorAnchor:Show()
			end
			InvenSimulatorUI.fakeCursor.link = InvenSimulatorUI.chatLink
			InvenSimulatorUI.chatLink = nil
			onDragStartItem()
		end
	end
	local function onHyperlinkEnter(self, button, link)
		if type(link) == "string" and link:find("item:") and not InvenSimulatorUI.isFakeDragging then
			button = GetMouseFocus()
			if button then
				if button:GetObjectType() == "Button" and button:GetName() == nil then
					InvenSimulatorUI.chatLink = link
					button:RegisterForDrag("LeftButton")
					button:SetScript("OnDragStart", onHyperlinkDragStart)
				else
					InvenSimulatorUI.chatLink = nil
				end
			else
				InvenSimulatorUI.chatLink = nil
			end
		end
	end
	local function onHyperlinkLeave()
		InvenSimulatorUI.chatLink = nil
	end
	for i = 1, NUM_CHAT_WINDOWS do
		_G["ChatFrame"..i]:HookScript("OnHyperlinkEnter", onHyperlinkEnter)
		_G["ChatFrame"..i]:HookScript("OnHyperlinkLeave", onHyperlinkLeave)
	end
	self.fakeCursor.anchor:SetScript("OnUpdate", function()
		if IsMouseButtonDown() then
			SetCursor("NONE")
		elseif InvenSimulatorUI.isFakeDragging then
			onDragStopItem()
			InvenSimulatorUI:CURSOR_UPDATE()
		end
	end)
end

function InvenSimulatorUI:InitClassItemType()
	if self.class == "전사" then
		self.maxArmor = "판금"
		self.itemSubTypes = { ["천"] = true, ["가죽"] = true, ["사슬"] = true, ["판금"] = true, ["기타"] = true, ["퀘스트"] = true, ["활류"] = true, ["총기류"] = true, ["석궁류"] = true, ["투척 무기류"] = true, ["방패"] = true, ["양손 도검류"] = true, ["양손 둔기류"] = true, ["양손 도끼류"] = true, ["장창류"] = true, ["한손 도검류"] = true, ["한손 둔기류"] = true, ["한손 도끼류"] = true, ["단검류"] = true, ["장착 무기류"] = true }
		self.slotsEquipLoc[17] = { ["INVTYPE_SHIELD"] = true, ["INVTYPE_WEAPON"] = true, ["INVTYPE_WEAPONOFFHAND"] = true, ["INVTYPE_2HWEAPON"] = true }
		self.slotsEquipLoc[18] = { ["INVTYPE_RANGED"] = true, ["INVTYPE_RANGEDRIGHT"] = true, ["INVTYPE_THROWN"] = true }
	elseif self.class == "도적" then
		self.maxArmor = "가죽"
		self.itemSubTypes = { ["천"] = true, ["가죽"] = true, ["기타"] = true, ["퀘스트"] = true, ["활류"] = true, ["총기류"] = true, ["석궁류"] = true, ["투척 무기류"] = true, ["한손 도검류"] = true, ["한손 둔기류"] = true, ["단검류"] = true, ["장착 무기류"] = true, ["한손 도끼류"] = true }
		self.slotsEquipLoc[16]["INVTYPE_2HWEAPON"] = nil
		self.slotsEquipLoc[17] = { ["INVTYPE_WEAPON"] = true, ["INVTYPE_WEAPONOFFHAND"] = true }
		self.slotsEquipLoc[18] = { ["INVTYPE_RANGED"] = true, ["INVTYPE_RANGEDRIGHT"] = true, ["INVTYPE_THROWN"] = true }
	elseif self.class == "사제" then
		self.maxArmor = "천"
		self.itemSubTypes = { ["천"] = true, ["기타"] = true, ["퀘스트"] = true, ["마법봉류"] = true, ["한손 둔기류"] = true, ["단검류"] = true, ["지팡이류"] = true }
		self.slotsEquipLoc[17] = { ["INVTYPE_HOLDABLE"] = true }
		self.slotsEquipLoc[18] = { ["INVTYPE_RANGED"] = true, ["INVTYPE_RANGEDRIGHT"] = true }
	elseif self.class == "마법사" then
		self.maxArmor = "천"
		self.itemSubTypes = { ["천"] = true, ["기타"] = true, ["퀘스트"] = true, ["마법봉류"] = true, ["한손 도검류"] = true, ["단검류"] = true, ["지팡이류"] = true }
		self.slotsEquipLoc[17] = { ["INVTYPE_HOLDABLE"] = true }
		self.slotsEquipLoc[18] = { ["INVTYPE_RANGED"] = true, ["INVTYPE_RANGEDRIGHT"] = true }
	elseif self.class == "흑마법사" then
		self.maxArmor = "천"
		self.itemSubTypes = { ["천"] = true, ["기타"] = true, ["퀘스트"] = true, ["마법봉류"] = true, ["한손 도검류"] = true, ["단검류"] = true, ["지팡이류"] = true }
		self.slotsEquipLoc[17] = { ["INVTYPE_HOLDABLE"] = true }
		self.slotsEquipLoc[18] = { ["INVTYPE_RANGED"] = true, ["INVTYPE_RANGEDRIGHT"] = true }
	elseif self.class == "사냥꾼" then
		self.maxArmor = "사슬"
		self.itemSubTypes = { ["천"] = true, ["가죽"] = true, ["사슬"] = true, ["기타"] = true, ["퀘스트"] = true, ["활류"] = true, ["총기류"] = true, ["석궁류"] = true, ["투척 무기류"] = true, ["한손 도검류"] = true, ["한손 도끼류"] = true, ["단검류"] = true, ["장착 무기류"] = true, ["지팡이류"] = true, ["양손 도검류"] = true, ["양손 도끼류"] = true, ["장창류"] = true }
		self.slotsEquipLoc[17] = { ["INVTYPE_WEAPON"] = true, ["INVTYPE_WEAPONOFFHAND"] = true }
		self.slotsEquipLoc[18] = { ["INVTYPE_RANGED"] = true, ["INVTYPE_RANGEDRIGHT"] = true, ["INVTYPE_THROWN"] = true }
	elseif self.class == "드루이드" then
		self.maxArmor = "가죽"
		self.itemSubTypes = { ["천"] = true, ["가죽"] = true, ["기타"] = true, ["퀘스트"] = true, ["우상"] = true, ["한손 둔기류"] = true, ["단검류"] = true, ["장착 무기류"] = true, ["지팡이류"] = true, ["양손 둔기류"] = true, ["장창류"] = true }
		self.slotsEquipLoc[17] = { ["INVTYPE_HOLDABLE"] = true }
		self.slotsEquipLoc[18] = { ["INVTYPE_RELIC"] = true }
	elseif self.class == "주술사" then
		self.maxArmor = "사슬"
		self.itemSubTypes = { ["천"] = true, ["가죽"] = true, ["사슬"] = true, ["기타"] = true, ["퀘스트"] = true, ["토템"] = true, ["방패"] = true, ["한손 둔기류"] = true, ["한손 도끼류"] = true, ["단검류"] = true, ["장착 무기류"] = true, ["양손 둔기류"] = true, ["양손 도끼류"] = true, ["지팡이류"] = true }
		self.slotsEquipLoc[17] = { ["INVTYPE_SHIELD"] = true, ["INVTYPE_WEAPON"] = true, ["INVTYPE_WEAPONOFFHAND"] = true, ["INVTYPE_HOLDABLE"] = true }
		self.slotsEquipLoc[18] = { ["INVTYPE_RELIC"] = true }
	elseif self.class == "성기사" then
		self.maxArmor = "판금"
		self.itemSubTypes = { ["천"] = true, ["가죽"] = true, ["사슬"] = true, ["판금"] = true, ["기타"] = true, ["퀘스트"] = true, ["성서"] = true, ["방패"] = true, ["한손 도검류"] = true, ["한손 둔기류"] = true, ["한손 도끼류"] = true, ["양손 도검류"] = true, ["양손 둔기류"] = true, ["양손 도끼류"] = true, ["장창류"] = true }
		self.slotsEquipLoc[17] = { ["INVTYPE_SHIELD"] = true }
		self.slotsEquipLoc[18] = { ["INVTYPE_RELIC"] = true }
	elseif self.class == "죽음의 기사" then
		self.maxArmor = "판금"
		self.itemSubTypes = { ["천"] = true, ["가죽"] = true, ["사슬"] = true, ["판금"] = true, ["기타"] = true, ["퀘스트"] = true, ["인장"] = true,  ["한손 도검류"] = true, ["한손 둔기류"] = true, ["한손 도끼류"] = true, ["양손 도검류"] = true, ["양손 둔기류"] = true, ["양손 도끼류"] = true, ["장창류"] = true }
		self.slotsEquipLoc[17] = { ["INVTYPE_WEAPON"] = true, ["INVTYPE_WEAPONOFFHAND"] = true }
		self.slotsEquipLoc[18] = { ["INVTYPE_RELIC"] = true }
	end
end