-- -----------------------------------------------------------------
-- File: MyInventory.lua
--
-- Purpose: Functions for MyInventory WoW Window.
-- 
-- Author: Ramble - May, 2005
--         Svarten - MyInventory origional author.
--		   独孤傲雪 - MyInventroyView author
-- Credits: 
--   Sarf, for the original concept.
--   Telo, for LootLink which I love.
--   Kaitlin, for showing me how a good code should look.
--   Pan and Nirre, for testing Svarten's corrupt code during development.
-- -----------------------------------------------------------------
-- Vim command: :% s/^.* -LITE\({\_.\{-}}-LITE\)\=\(\s*-->\)\=$/
-- RegExp to remove Lite stuff: ^.* -LITE\({\_.\{-}}-LITE\)\=\(\s*-->\)\=$
-- This removes all lines ending in -LITE
--
-- And All Lines with a -LITE{ Starting line ended with 
-- this at the end }-LITE
-- 
-- Also will work in XML so <!-- -LITE{
-- This works too
-- }-LITE -->
MyInventoryDEBUG                = 0;
---==================================
--[[ 对外接口: 
函数: MyInventory_RegisterButton
	参数1 - 需要添加的button的名字
	参数2 - Button上显示的文字
	参数3 - Button的长度(Width)
	参数4 - 鼠标进入时显示的文字
	参数5 - 对应OnClick事件的函数
	...	  - 其他参数
]]
local MY_INVENTORY_REGISTER_BUTTONS = {};	-- 保存所有的注册的Buttons
local MyInventoryRegisterLastButton;		-- 上次一个注册入的按钮
--===================================

-- Global declarations {{{
-----------------------
-- Saved Configuration  
-----------------------
MyInventoryProfile = {}
MyInventroyViewProfile = {};
local PlayerName = nil;
-----------------------
-- Local Configuration
-----------------------
-- Constants {{{
MYINVENTORY_MAX_ID              = 160;
MYINVENTORY_COLUMNS_MIN         =   2;
MYINVENTORY_COLUMNS_MAX         =  18;

MYINVENTORY_TOP_HEIGHT          =  20;
MYINVENTORY_BOTTOM_HEIGHT       =  16;

MYINVENTORY_FIRST_ITEM_OFFSET_X =   8;
MYINVENTORY_FIRST_ITEM_OFFSET_Y = -28;
MYINVENTORY_ITEM_OFFSET_X       =  39;
MYINVENTORY_ITEM_OFFSET_Y       = -39;

MYINVENTORY_ITEM_COLOR = {	
	[0] = { r = 0.8, g = 0.8, b = 0.8, a = 0.8},
	[1] = { r = 0.5, g = 0.5, b = 0.5, a = 0.8},
	[2] = { r = 0, g = 1.0, b = 0, a = 0.8},
	[3] = { r = 0, g = 0.0, b = 1.0, a = 0.8},
	[4] = { r = 0.5, g = 0, b = 1.0, a = 0.8},
	[5] = { r = 1.0, g = 0, b = 0, a = 0.8},
	[6] = { r = 1.0, g = 0.5, b = 0, a = 0.8},
	[9] = { r = 1, g = 1, b = 0, a = 0.6 },
};

MyInventory_Loaded              = nil;
MyInventory_Initialized         = nil;
--}}}
-- Saved Between sessions:These are also the defaults
MyInventoryColumns              = 8;

MyInventoryReplaceBags          = 1;
MyInventoryGraphics             = 1; -- -LITE
MyInventoryHighlightItems       = 1;
MyInventoryHighlightBags        = 1;
MyInventoryFreeze               = 0;
-- Keep the window from closing with Close
-- These options are on the MI Window itself.
MyInventoryLock                 = 0; -- Lock the window in place
MyInventoryBagView              = 0;
--Visibility
MyInventoryCount                = 1;
MyInventoryBackground           = 1;
MyInventoryShowTitle            = 1;
MyInventoryCash                 = 1;
MyInventoryButtons              = 1;
MyInventoryAIOIStyle            = 0;
MyInventoryItemBorder           = 1;
MyInventoryScale                = 1; --tonumber(GetCVar("uiscale"));

-- Hooked functions {{{
MyInventory_Saved_ToggleBag                        = nil;
MyInventory_Saved_OpenBag                          = nil;
MyInventory_Saved_CloseBag                         = nil;
MyInventory_Saved_ToggleBackpack                   = nil;
MyInventory_Saved_CloseBackpack                    = nil;
MyInventory_Saved_OpenBackpack                     = nil;
MyInventory_Saved_OpenAllBags                      = nil;
MyInventory_Saved_CloseAllBags                     = nil;
MyInventory_Saved_BackpackButton_OnClick           = nil;
MyInventory_Saved_LootFrame_OnShow                 = nil;
-- }}}
-- }}}
local isHooked = false;
local PlayerMoney, isPlayerTab;
MyInventory_Enabled = nil;
MyInventory_Count = "%d/%d";

-- Loading {{{
function MyInventoryFrame_OnLoad()
end
--========================================================================
-- Initialilze
--========================================================================
function MyInventory_InitializeProfile()
	if MyInventory_Initialized == true then
		return
	end
	if ( UnitName('player') ) then
		PlayerName = UnitName('player').."|"..MyInventory_Trim(GetCVar("realmName"));
		MyInventory_LoadSettings();
		MyInventory_Initialized = true;
		MyInventoryFrame_UpdateLook();
		MyInventory_SetFreeze();
	end
end --}}}
--=========================================================================
-- 载入当前玩家配置
--=========================================================================
function MyInventory_LoadSettings() --{{{
	if ( MyInventoryProfile[PlayerName] == nil ) then
		MyInventoryProfile[PlayerName] = {};
	end
	local MI_SoD = MyInventory_SavedOrDefault;
	MyInventoryColumns        = MI_SoD("Columns");
	MyInventoryReplaceBags    = MI_SoD("ReplaceBags");
--	MyInventoryFreeze         = MI_SoD("Freeze");
	MyInventoryLock           = MI_SoD("Lock");
	MyInventoryHighlightItems = MI_SoD("HighlightItems");
	MyInventoryHighlightBags  = MI_SoD("HighlightBags");
	MyInventoryBagView        = 0; -- Disabled by Sharak@BigFoot
	MyInventoryGraphics       = MI_SoD("Graphics"); -- -LITE
	MyInventoryBackground     = MI_SoD("Background");
	MyInventoryCount          = MI_SoD("Count");
	MyInventoryShowTitle      = MI_SoD("ShowTitle");
	MyInventoryCash           = MI_SoD("Cash");
	MyInventoryButtons        = MI_SoD("Buttons");
	MyInventoryScale          = MI_SoD("Scale");
	MyInventoryAIOIStyle      = MI_SoD("AIOIStyle");
	MyInventoryItemBorder     = MI_SoD("ItemBorder");

	MyInventory_SetScale(tonumber(MyInventoryScale));
end -- }}}
--========================================================================
-- 函数：MyInventory_SavedOrDefault
-- 功能：获得当前或缺省配置
-- 参数：varname - [输入] 配置名
-- 返回：MyInventoryProfile[PlayerName][varname] - 配置值
--========================================================================
function MyInventory_SavedOrDefault(varname) -- {{{
	if PlayerName == nil or varname == nil then
		MyInventory_DEBUG("ERR: nil value");
		return nil;
	end
	if MyInventoryProfile[PlayerName][varname] == nil then -- Setting not set
		MyInventoryProfile[PlayerName][varname] = getglobal("MyInventory"..varname); -- Load Default
	end
	return MyInventoryProfile[PlayerName][varname];  -- Return Setting.
end -- }}}
--========================================================================
-- 注册事件和命令
--========================================================================
local MInvertory_Eventer = BLibrary("BEvent");
MInvertory_Eventer:Init{
	name = "MyInventory",
	func = function()
		SlashCmdList["MYINVENTORYSLASHMAIN"] = MyInventory_ChatCommandHandler;
		SLASH_MYINVENTORYSLASHMAIN1 = "/myinventory";
		SLASH_MYINVENTORYSLASHMAIN2 = "/mi";
		MInvertory_Eventer:RegisterEvent("UNIT_NAME_UPDATE", MyInventoryFrame_OnEvent);

		if (UnitName('player')) then
			local playerName = UnitName('player').."|"..MyInventory_Trim(GetCVar("realmName"));
			if (MyInventoryProfile[playerName]) then
				if (not MyInventoryProfile[playerName]["Version"]) then
					MyInventoryProfile[playerName]["Version"] = 1.46;

					MyInventory_ResetPosition();
				else
					if (MyInventoryProfile[playerName]["Version"] < 1.46) then
						MyInventoryProfile[playerName]["Version"] = 1.46;

						MyInventory_ResetPosition();
					end
				end
			end
		end
	end
}
--========================================================================
-- 注册入MyAddon
--========================================================================
function MyInventory_MyAddonsRegister() -- {{{
	if (myAddOnsFrame) then
		myAddOnsList.MyInventory = {
			name = MYINVENTORY_MYADDON_NAME,
			description = MYINVENTORY_MYADDON_DESCRIPTION,
			version = MYINVENTORY_MYADDON_VERSION,
			category = MYADDONS_CATEGORY_INVENTORY,
			frame = "MyInventoryFrame",
			optionsframe = "MyInventoryOptionsFrame"
		};
	end
end -- }}}
-- }}}
--=======================================================================
-- hook functions
--=======================================================================
-- Hooks functions. {{{
local hooker = BLibrary("BHook");
function MyInventory_Setup_Hooks(toggle) -- {{{	
	if ( toggle and not MyInventory_Enabled ) then
		hooker:Hook("ToggleBag", MyInventory_ToggleBag);
		hooker:Hook("CloseBag", MyInventory_CloseBag);
		hooker:Hook("OpenBag", MyInventory_OpenBag);
		hooker:Hook("OpenAllBags", MyInventory_OpenAllBags);
		hooker:Hook("CloseAllBags", MyInventory_CloseAllBags);
		hooker:Hook("ToggleBackpack", MyInventory_ToggleBackpack);
		hooker:Hook("CloseBackpack", MyInventory_CloseBackpack);
		hooker:Hook("OpenBackpack", MyInventory_OpenBackpack);		
		if (not isHooked) then
			hooksecurefunc("LootFrame_OnShow", MyInventory_LootFrame_OnShow);
		end
		MInvertory_Eventer:RegisterEvent("BAG_UPDATE", MyInventoryFrame_OnEvent);
		MInvertory_Eventer:RegisterEvent("BAG_UPDATE_COOLDOWN", MyInventoryFrame_OnEvent);
		MInvertory_Eventer:RegisterEvent("ITEM_LOCK_CHANGED", MyInventoryFrame_OnEvent);
		MInvertory_Eventer:RegisterEvent("UPDATE_INVENTORY_ALERTS", MyInventoryFrame_OnEvent);
		MInvertory_Eventer:RegisterEvent("PLAYER_MONEY", MyInventoryFrame_UpdateMoney);--MoneyFrame_Update("MyBank_MoneyFrameTotal", totalMoney);
	elseif ( MyInventory_Enabled ) then
		hooker:Unhook("ToggleBag");
		hooker:Unhook("CloseBag");
		hooker:Unhook("OpenBag");
		hooker:Unhook("OpenAllBags");
		hooker:Unhook("CloseAllBags");
		hooker:Unhook("ToggleBackpack");
		hooker:Unhook("CloseBackpack");
		hooker:Unhook("OpenBackpack");
		
		MInvertory_Eventer:UnregisterAllEvent();
		MInvertory_Eventer:RegisterEvent("UNIT_NAME_UPDATE", MyInventoryFrame_OnEvent);
	end
end -- }}}

function MyInventoryFrame_UpdateMoney()
	PlayerMoney = GetMoney();
	if (isPlayerTab) then
		MoneyFrame_Update("MyInventoryFrameMoneyFrame", PlayerMoney);
	end	
end
-- Does things with the hooked function -- {{{
function MyInventory_LootFrame_OnShow()
	if (MyInventory_Enabled) then
		LootFrame:Raise();
	end	
end
-- }}}
-- Toggling Bags/Backpack {{{
function MyInventory_ShouldOverrideBag(bag)
	if (  (bag >= 0) and (bag <= 4) ) then
		return true;
	else
		return false;
	end
end

function MyInventory_ResetPosition()
	local width = MyInventoryFrame:GetWidth();
	local height = MyInventoryFrame:GetHeight();
	local screen_width = UIParent:GetWidth();
	local screen_height = UIParent:GetHeight();
	local offset_x = (screen_width - width)/2;
	local offset_y = (screen_height - height)/2;
	
	MyInventoryAnchorFrame:ClearAllPoints();
	MyInventoryAnchorFrame:SetPoint("TOPLEFT", UIParent, "TOPLEFT", offset_x, -offset_y);
end

function MyInventory_Toggle(switch)
	if (switch) then
		MyInventory_Setup_Hooks(1);
		MyInventory_Loaded = true;
		MyInventory_InitializeProfile();

		MyInventory_Enabled = 1;

		MIStealBackpackButton:Show();
		MIStealItBag0Slot:Show();
		MIStealItBag1Slot:Show();
		MIStealItBag2Slot:Show();
		MIStealItBag3Slot:Show();

		MIStealBackpackButton:GetParent():EnableMouse(0);
		MIStealItBag0Slot:GetParent():EnableMouse(0);
		MIStealItBag1Slot:GetParent():EnableMouse(0);
		MIStealItBag2Slot:GetParent():EnableMouse(0);
		MIStealItBag3Slot:GetParent():EnableMouse(0);
	else
		MyInventory_Setup_Hooks(nil);
		MyInventory_Loaded = false;					

		MIStealBackpackButton:Hide();
		MIStealItBag0Slot:Hide();
		MIStealItBag1Slot:Hide();
		MIStealItBag2Slot:Hide();
		MIStealItBag3Slot:Hide();


		MIStealBackpackButton:GetParent():EnableMouse(1);
		MIStealItBag0Slot:GetParent():EnableMouse(1);
		MIStealItBag1Slot:GetParent():EnableMouse(1);
		MIStealItBag2Slot:GetParent():EnableMouse(1);
		MIStealItBag3Slot:GetParent():EnableMouse(1);

		MyInventory_Enabled = nil;
	end

end

function MyInventory_ToggleBackpack(origfunc)
	MyInventory_DEBUG("ToggleBackpack called");
	if ((MyInventoryReplaceBags == 1) and MyInventory_ShouldOverrideBag(0)) then
		ToggleMyInventoryFrame();
		return;
	end
	origfunc()
end

function MyInventory_ToggleBag(origfunc, bag)
	MyInventory_DEBUG("ToggleBag"..bag.." called");
	if ((MyInventoryReplaceBags == 1) and MyInventory_ShouldOverrideBag(bag)) then
		ToggleMyInventoryFrame();
		return;
	else
		origfunc(bag);
	end
end

function MyInventory_OpenBackpack(origfunc)
	MyInventory_DEBUG("Open Backpack called");
	if ( MyInventoryReplaceBags == 1 ) then  
		OpenMyInventoryFrame();
		return;
	end
	origfunc() -- original function
end

function MyInventory_CloseBackpack(origfunc)
	MyInventory_DEBUG("Close Backpack called");
	if ( MyInventoryReplaceBags == 1 and MyInventory_ShouldOverrideBag(0)) then
		if ( MyInventoryFreeze == 0) then
			CloseMyInventoryFrame();
		end
		return;
	end
	MyInventory_DEBUG("Default close");
	origfunc() -- Default close
end
--=============================================================================
-- 禁止开启单个背包
--=============================================================================
function MyInventory_CloseBag(origfunc, bag)
	MyInventory_DEBUG("Close Bag"..bag.." called");
	if ((MyInventoryReplaceBags == 1) and MyInventory_ShouldOverrideBag(bag)) then
		return;
	else
		origfunc(bag);
	end
end

function MyInventory_OpenBag(origfunc, bag)
	if ((MyInventoryReplaceBags == 1) and MyInventory_ShouldOverrideBag(bag)) then
		return;
	else
		origfunc(bag)
	end
end
--=============================================================================
-- 开启所有背包
--=============================================================================
function MyInventory_OpenAllBags(origfunc, forceOpen)
	MyInventory_DEBUG("Open All Bags Called");
	if ((MyInventoryReplaceBags == 1)) then
		MyInventory_DEBUG("Replacing function");
		-- OK, first determine if All bags are open, and if they are then close instead ::((
		local bagsOpen=0;
		local totalbags=0;
		for i=0,4 do
			if GetContainerNumSlots(i) > 0 then
				totalbags=totalbags+1;
				if MyInventoryFrame:IsVisible() and MyInventory_ShouldOverrideBag(i) then
					bagsOpen = bagsOpen+1;
				end
			end
		end
		for i=1,NUM_CONTAINER_FRAMES,1 do
			local containerFrame = getglobal("ContainerFrame"..i);
			if containerFrame:IsVisible() then
				bagsOpen=bagsOpen+1;
			end
		end
		if totalbags==bagsOpen and not forceOpen then
			CloseAllBags(1);
		else
			OpenMyInventoryFrame();	-- 开启背包整合
			for i=0,4 do
				if not MyInventory_ShouldOverrideBag(i) then
					MyInventory_DEBUG("Opening bag "..i);
					OpenBag(i);	-- 开启其他背包，ie：银行背包
				end
			end
		end
		return;
	else
		origfunc(forceOpen);
	end
end
--=============================================================================
-- 关闭所有背包
--=============================================================================
function MyInventory_CloseAllBags(origfunc, force)
	MyInventory_DEBUG("Close All Bags Called");
	if ((MyInventoryReplaceBags == 1)) then
		MyInventory_DEBUG("Replacing function");
		CloseMyInventoryFrame();
		for i=0,4 do
			if not MyInventory_ShouldOverrideBag(i) then
				CloseBag(i);
			end
		end
		return
	else
		origfunc(arg);
	end
end
-- }}}
-- }}}
--=============================================================================
-- Options {{{
--=============================================================================
-- Slash commands {{{快捷命令
function MyInventory_ChatCommandHandler(msg) -- {{{

	if ( ( not msg ) or ( strlen(msg) <= 0 ) ) then
		MyInventory_Print(MYINVENTORY_CHAT_COMMAND_USAGE);
		return;
	end
	
	local commandName, params = MyInventory_Extract_NextParameter(msg);
  
	if ( ( commandName ) and ( strlen(commandName) > 0 ) ) then
		commandName = string.lower(commandName);
	else
		commandName = "";
	end
 
	if ( (strfind(commandName, "show")) or (strfind(commandName, "toggle")) ) then
		ToggleMyInventoryFrame();
	elseif ( strfind(commandName, "config") or strfind(commandName, "option") ) then
		ShowUIPanel(MyInventoryOptionsFrame);
	elseif ( strfind(commandName, "replace") ) then
		MyInventory_Toggle_Option("ReplaceBags");
	elseif ( strfind(commandName, "freeze") ) then
		MyInventory_Toggle_Option("Freeze");
	elseif ( strfind(commandName, "aioi") ) then
		MyInventory_Toggle_Option("AIOIStyle", nil, nil, 1);
	elseif ( strfind(commandName, "lock") ) then
		MyInventory_Toggle_Option("Lock",nil,nil,1);
	elseif ( strfind(commandName, "cash") or strfind(commandName, "money")) then
		MyInventory_Toggle_Option("Cash",nil,nil,1);
	elseif ( strfind(commandName, "button") ) then
		MyInventory_Toggle_Option("Buttons",nil,nil,1);
	elseif ( strfind(commandName, "title") ) then
		MyInventory_Toggle_Option("ShowTitle",nil,nil,1);
	elseif ( strfind(commandName, "count") or strfind(commandName, "slot")) then
		MyInventory_Toggle_Option("Count",nil,nil,1);
	elseif ( strfind(commandName, "graphic") or strfind(commandName, "art") ) then -- -LITE
		MyInventory_Toggle_Option("Graphics",nil,nil,1); -- -LITE
	elseif ( strfind(commandName, "back") ) then
		MyInventory_Toggle_Option("Background",nil,nil,1);
	elseif ( strfind(commandName, "bagview") ) then
		MyInventory_Toggle_Option("BagView",nil,nil,1);
	elseif ( strfind(commandName, "quality") ) then
		MyInventory_Toggle_Option("ItemBorder",nil,nil,1);
	elseif ( strfind(commandName, "col") ) then
		cols, params = MyInventory_Extract_NextParameter(params);
		if cols then
			MyInventoryFrame_SetColumns(cols);
		end
	elseif ( strfind(commandName, "scale") ) then
		scale, params = MyInventory_Extract_NextParameter(params);
		if tonumber(scale) and tonumber(scale) >= 0.5 and tonumber(scale) <= 1.5 then
			MyInventory_SetScale(scale);
		else
			MyInventory_Print(MYINVENTORY_MSG_SCALE..MyInventoryScale);
		end
	elseif ( strfind(commandName, "resetpos") ) then
		MyInventory_ResetPosition();
	else
		MyInventory_Print(MYINVENTORY_CHAT_COMMAND_USAGE);
		return;
	end
end -- }}}
function MyInventory_Extract_NextParameter(msg) -- {{{
	local params = msg;
	local command = params;
	local index = strfind(command, " ");
	if ( index ) then
		command = strsub(command, 1, index-1);
		params = strsub(params, index+1);
	else
		params = "";
	end
	return command, params;
end -- }}}
-- }}}
--=============================================================================
-- 切换
--=============================================================================
function MyInventory_Toggle_Option(option, value, quiet, updateLook) -- {{{
	if value == nil then
		if getglobal("MyInventory"..option) == 1 then
			value = 0;
		else
			value = 1;
		end
	end
	setglobal("MyInventory"..option, value);
	MyInventoryProfile[PlayerName][option] = value;
	-- 在聊天窗口显示文字，很讨厌
	if not quiet or  quiet ~= 1 then
		local chat_message;
		local globalName = "MYINVENTORY_CHAT_"..string.upper(option);
		if value == 0 then
			globalName = globalName.."OFF";
		else
			globalName = globalName.."ON";
		end
		chat_message = getglobal(globalName);
		if ( chat_message ) then
			MyInventory_Print(MYINVENTORY_CHAT_PREFIX..chat_message);
		else
			MyInventory_DEBUG("ERROR: No global "..globalName);
		end
	end
	if MyInventoryBagView == 1 and MyInventoryColumns < 5 then
		MyInventoryFrame_SetColumns(5);
	end
	if updateLook and updateLook == 1 then
		MyInventoryFrame_UpdateLook();
	end
	if option=="Freeze" then
		MyInventory_SetFreeze()
	elseif option=="ReplaceBags" then
		MyInventory_SetReplace();
	elseif option=="Graphics" then -- -LITE
		MyInventoryFrame_Update(); -- -LITE
	elseif option=="ItemBorder" then
		MyInventoryFrame_Update();
	end
end -- }}}
--===========================================================================
-- 是否设置为系统特殊frame
--===========================================================================
function MyInventory_SetFreeze() -- {{{
	if MyInventoryFreeze == 0 then
		tinsert(UISpecialFrames, "MyInventoryFrame"); -- Esc Closes Inventory 
	else
		for key, value in pairs(UISpecialFrames) do
			if value == "MyInventoryFrame" then
				table.remove(UISpecialFrames, key);
			end
		end
	end
end -- }}}
--===========================================================================
-- 替换系统的背包
--===========================================================================
function MyInventory_SetReplace() -- {{{
	if MyInventoryReplaceBags==1 then
		for i=0,4 do
			MyInventory_DEBUG("replacing bag "..i);
			for j=1,NUM_CONTAINER_FRAMES,1 do
				local containerFrame = getglobal("ContainerFrame"..j);
				if containerFrame:GetID() == i then
					containerFrame:Hide();
				end
			end
		end
	end
end -- }}}
--==========================================================================
-- 设置缩放
--==========================================================================
function MyInventory_SetScale(scale) -- {{{
	local myscale = tonumber(scale);
	if ( not myscale ) then
		myscale = 1;
	end
	MyInventoryFrame:SetScale(myscale);

	if ( SellValue_Enable ) then
		InvList_Button:SetScale(myscale);
	end

	if ( SellValue_Enable ) then
		InvQuery_Button:SetScale(myscale);
	end

	MyInventory_Toggle_Option("Scale", myscale, 1);
end -- }}}
--=============================================================================
-- 设置每行的格数，最少为5格
--=============================================================================
function MyInventoryFrame_SetColumns(col) -- {{{
	if ( type(col) ~= "number" ) then
		col = tonumber(col);
	end
	if (type(col) ~= "number" or col == 0) then
		return
	end
	if MyInventoryBagView == 1 and col < 5 then
		col = 5;
	end
	if ( ( col >= MYINVENTORY_COLUMNS_MIN ) and ( col <= MYINVENTORY_COLUMNS_MAX ) ) then
		MyInventoryColumns = col;
		MyInventoryProfile[PlayerName].Columns = MyInventoryColumns;
		MyInventoryFrame_UpdateLook();
	end
end -- }}}
-- }}}

-- Text related functions. {{{
function MyInventory_Trim (s) -- {{{
	return (string.gsub(s, "^%s*(.-)%s*$", "%1"));
end --}}}
function MyInventory_Print(msg,r,g,b,frame,id,unknown4th) -- {{{
	--if ( Print ) then
	--	Print(msg, r, g, b, frame, id, unknown4th);
	--	return;
	--end
	if(unknown4th) then
		local temp = id;
		id = unknown4th;
		unknown4th = id;
	end
	
	if (not r) then r = 1.0; end
	if (not g) then g = 1.0; end
	if (not b) then b = 1.0; end
	if not frame then
		if DEFAULT_CHAT_FRAME then
			frame = DEFAULT_CHAT_FRAME
		else
			MyInventory_DEBUG("quitting print");
			return
		end
	end
	if type(msg) == "table" then
		for key, value in pairs(msg) do
			frame:AddMessage(value, r, g, b,id,unknown4th);
		end
	else
		frame:AddMessage(msg, r, g, b,id,unknown4th);
	end
end  -- }}}
function MyInventory_DEBUG(msg) --{{{
	-- If Debug is not set, just skip it.
	if ( not MyInventoryDEBUG or MyInventoryDEBUG == 0 ) then
		return;
	end
	
	msg = "*** DEBUG(MyInventory): "..msg;
	if ( DEFAULT_CHAT_FRAME ) then 
		DEFAULT_CHAT_FRAME:AddMessage(msg, 1.0, 1.0, 0.0);
	end
end -- }}}
-- }}}
--============================================================================
-- 显示/隐藏
--============================================================================
-- Toggle Frame {{{
function ToggleMyInventoryFrame() -- {{{
	if ( MyInventoryFrame:IsVisible() ) then
		CloseMyInventoryFrame();
	else
		OpenMyInventoryFrame();
	end
end -- }}}
--============================================================================
-- 隐藏
--============================================================================
function CloseMyInventoryFrame() -- {{{
	if ( MyInventoryFrame:IsVisible() ) then
		MyInventoryFrame:Hide();
	end
	MyInventory_UpdateBagState();
end --}}}
--============================================================================
-- 显示
--============================================================================
function OpenMyInventoryFrame() -- {{{
	MyInventoryFrame_UpdateLookIfNeeded();
	MyInventoryFrame:Show();
	MyInventory_UpdateBagState();

	MyInventoryFrame_SetViewType(1);
	MyInventoryFrame_UpdateButtonsVisibility();
	MyInventoryFrame_UpdateViewByType(1);

	if (not BigFoot_IsFramePlacedByUser(MyInventoryAnchorFrame)) then
		MyInventory_ResetPosition();
	end
end --}}}
-- }}}
--============================================================================
-- 判断背包是否处于开启状态
--============================================================================
-- Update Bag State: Setting Checks {{{
function MyInventory_IsBagOpen(id) -- {{{
	local formatStr = "ContainerFrame%d";
	local frame = nil;
	for i = 1, NUM_CONTAINER_FRAMES do
		frame = getglobal(format(formatStr, i));
		if ( ( frame ) and ( frame:IsVisible() ) and ( frame:GetID() == id ) ) then
			return true;
		end
	end
	return false;
end --}}}
--===========================================================================
-- 
--===========================================================================
function MyInventory_GetBagState(toggle) -- {{{
	if ( ( toggle == true ) or ( toggle == 1 ) ) then
		return 1;
	else
		return 0;
	end
end -- }}}
--===========================================================================
-- 
--===========================================================================
function MyInventory_UpdateBagState() -- {{{
	local visible = MyInventoryFrame:IsVisible();
	MainMenuBarBackpackButton:SetChecked(MyInventory_GetBagState(visible or MyInventory_IsBagOpen(0)));
	MyInventoryBackpackButton:SetChecked(MyInventory_GetBagState(visible));
	local bagButton = nil;
	local mibagButton1 = nil
	local mibagButton2 = nil
	local formatStr = "CharacterBag%dSlot";
	local formatStr2= "MyInventoBag%dSlot";

	for i = 0, 3 do 
		bagButton   = getglobal(format(formatStr, i));
		mibagButton2 = getglobal(format(formatStr2, i)); 
		if ( bagButton ) then
			bagButton:SetChecked(MyInventory_GetBagState(visible or MyInventory_IsBagOpen(i+1)));
			mibagButton2:SetChecked(MyInventory_GetBagState(visible));
		end
	end
end -- }}}
-- }}}
--=============================================================================
--
--=============================================================================
-- Frame Events {{{
function MyInventoryFrame_OnEvent() -- {{{	
	if not MyInventory_Loaded then
		return
	end
	if ( event == "UNIT_NAME_UPDATE" and arg1 == "player" and UnitName("player") ~= UNKNOWNOBJECT) then
		MyInventory_InitializeProfile();
		PlayerMoney = GetMoney();	-- 初始化
	end
	if PlayerName == nil then 
		return
	end
	if ( event == "BAG_UPDATE" ) then
		if ( this:IsVisible() ) then
			MyInventory_DEBUG("BAG_UPDATE Event fired.");
			MyInventoryFrame_Update(MyInventoryFrame);
		end
	elseif ( event == "ITEM_LOCK_CHANGED" or event == "BAG_UPDATE_COOLDOWN" or event == "UPDATE_INVENTORY_ALERTS" ) then
		if ( this:IsVisible() ) then
			MyInventoryFrame_Update(MyInventoryFrame);
		end
	end
end -- }}}
--=============================================================================
--
--=============================================================================
function MyInventoryFrame_OnHide() -- {{{
	PlaySound("igBackPackClose");
	MyInventory_UpdateBagState();
	if ( SellValue_Enable ) then
		MyInventoryFrame_HideButtons();
	end

	-- 有时候，我们可能正在拖动的时候关闭背包。
	-- 所以在隐藏的时候需要调用StopMovingOrSizing防止这样的事情发生。
	this:StopMovingOrSizing();
	MyInventoryAnchorFrame:StopMovingOrSizing();
end -- }}}
function MyInventoryFrame_OnShow() -- {{{
	if MyInventory_Initialized == false then
		MyInventoryFrame:Hide();
		return;
	end
	MyInventoryFrame_Update(MyInventoryFrame);
	PlaySound("igBackPackOpen");
	MyInventoryFrame:ClearAllPoints();
	MyInventoryFrame:SetPoint("TOPLEFT", "MyInventoryAnchorFrame", "TOPLEFT");
	local pScale = MyInventoryFrame:GetParent():GetScale();
	MyInventoryFrame:SetScale(MyInventoryScale);

	if ( SellValue_Enable ) then
		if ( MyInventoryFrame:IsVisible() and MyInventoryGraphics == 1 and MyInventoryBagView == 0 ) then
			InvList_Button:SetPoint("TOPLEFT", MyInventoryFrame:GetName(), "TOPRIGHT", -140, -28);
			InvList_Button:SetFrameLevel(this:GetFrameLevel()+1);
			InvList_Button:SetScale(MyInventoryFrame:GetScale());
			InvQuery_Button:SetFrameLevel(this:GetFrameLevel()+1);
			InvQuery_Button:SetScale(MyInventoryFrame:GetScale());
		end
	end

	MyInventoryFrame_UpdateButtonsVisibility();
end -- }}}

function MyInventoryFrame_StartResizing()
	ResizingX, ResizingY = GetCursorPosition();
	ResizingCols = MyInventoryColumns;

	BigFoot_DelayCall(MyInventoryFrame_OnResizing, 0.2);
end

function MyInventoryFrame_OnResizing()
	if (ResizingX and ResizingY) then
		local x, y = GetCursorPosition();
		local offsetX = x - ResizingX;
		local offsetY = y - ResizingY;

		local cols = math.floor(math.floor(offsetX + 0.5) / 32);
		local final_cols = ResizingCols + cols;
		if (final_cols > 18) then
			final_cols = 18;
		elseif (final_cols < 2) then
			final_cols = 2;
		end

		MyInventoryFrame_SetColumns(final_cols);
		MyInventoryFrame_UpdateLook(MyInventory_GetBagsTotalSlots());
		MyInventoryFrame_UpdateViewByType(MyInventoryFrame_GetViewType());

		BigFoot_DelayCall(MyInventoryFrame_OnResizing, 0.2);
	end
end

function MyInventoryFrame_StopResizing()
	ResizingX = nil;
	ResizingY = nil;
end

function MyInventoryFrame_OnMouseDown(arg1) -- {{{
	if ( arg1 == "LeftButton" ) then
		if ( MyInventoryLock == 0 ) then
			-- this:StartMoving();
			MyInventoryAnchorFrame:StartMoving();
		else
			MyInventory_Print("MyInventory is locked and can not move...");
		end
	end
end -- }}}
function MyInventoryFrame_OnMouseUp(arg1) -- {{{
	if ( arg1 == "LeftButton" ) then
		this:StopMovingOrSizing();
		MyInventoryAnchorFrame:StopMovingOrSizing();
	end
end -- }}}
-- }}}
-- Bag Button Events {{{

function MyInventory_Backpack_OnEnter() -- {{{
	GameTooltip:SetOwner(this,"ANCHOR_LEFT");
	GameTooltip:SetText(TEXT(BACKPACK_TOOLTIP),1.0,1.0,1.0);
	local keyBinding = GetBindingKey("TOGGLEBACKPACK");
	if ( keyBinding ) then
		GameTooltip:AppendText(" "..NORMAL_FONT_COLOR_CODE.."("..keyBinding..")"..FONT_COLOR_CODE_CLOSE);
	end
	MyInventory_HighlightBagItems(0);
end -- }}}

function MyInventory_Backpack_OnLeave() -- {{{
	GameTooltip:Hide();
	MyInventory_HighlightBagItems(0,1);
end -- }}}

function MyInventory_BagButton_OnEnter() -- {{{
	GameTooltip:SetOwner(this,"ANCHOR_LEFT");
	if GameTooltip:SetInventoryItem("player", this:GetID()) then
		local bindingkey = GetBindingKey("TOGGLEBAG"..(4-(this:GetID()-CharacterBag0Slot:GetID())));
		if bindingkey then
			GameTooltip:AppendText(" "..NORMAL_FONT_COLOR_CODE.."("..bindingkey..")"..FONT_COLOR_CODE_CLOSE);
		end
		MyInventory_HighlightBagItems(1+this:GetID()-MyInventoBag0Slot:GetID());
	else
		GameTooltip:SetText(TEXT(EQUIP_CONTAINER),1.0,1.0,1.0);
	end
end -- }}}
function MyInventory_BagButton_OnLeave() -- {{{
   this.updateTooltip = nil;
   GameTooltip:Hide();
   ResetCursor();
	local bagID = 1+this:GetID()-MyInventoBag0Slot:GetID();
	MyInventory_HighlightBagItems(bagID, 1);
end -- }}}

function MyInventory_BagButton_OnClick(isMMB) -- {{{
	--local index = tonumber(strsub(this:GetName(), 13, 13))+2;
	local bagID = 1+this:GetID()-MyInventoBag0Slot:GetID();
	if not PutItemInBag(this:GetID()) then
		ToggleBag(bagID);
	end
end -- }}}
function MyInventory_Backpack_OnClick(isMMB) -- {{{
	if not PutItemInBackpack() then
		ToggleBackpack();
	end
end -- }}}
function MyInventory_BagButton_OnDragStart() -- {{{
	--BagSlotButton_OnDrag();
	PickupBagFromSlot(this:GetID());
	PlaySound("BAGMENUBUTTONPRESS");
end -- }}}
function MyInventory_BagButton_OnReceiveDrag() -- {{{
	PutItemInBag(this:GetID());
end -- }}}
-- }}}

-- Highlighting {{{
--=============================================================================
-- 高亮背包里的物品
--=============================================================================
function MyInventory_HighlightBagItems(bagID, off) -- {{{
	if MyInventoryHighlightItems == 0 then
		return
	end
	local found;
	local itemButton;
	for i = 1,MYINVENTORY_MAX_ID do
		local bag, slot;
		itemButton = getglobal("MyInventoryFrameItem"..i);
		bag = itemButton:GetParent():GetID();		
		if bag == bagID then
			found = true;
			if off and off == 1 then
				itemButton:UnlockHighlight();
			else
				itemButton:LockHighlight();
			end
		else
			if found then 
				break;
			end
		end
	end
end -- }}}
--===========================================================================
-- 高亮物品所在的背包
--===========================================================================
function MyInventory_HighlightItemBag(bagID, off) -- {{{
	if MyInventoryHighlightBags == 0 then
		return
	end
	local BagButton1, BagButton2;
	if bagID == 0 then
		BagButton1= getglobal("MyInventoryBackpackButton");
		BagButton2= getglobal("MainMenuBarBackpackButton");
	else
		BagButton1= getglobal("MyInventoBag"..(bagID-1).."Slot");
		BagButton2= getglobal("CharacterBag"..(bagID-1).."Slot");
	end
	if off then
		BagButton1:UnlockHighlight();
		BagButton2:UnlockHighlight();
	else
		BagButton1:LockHighlight();
		BagButton2:LockHighlight();
	end
end -- }}}
-- }}}

-- Update Visuals, toggled options {{{
-- Update Look {{{
--=============================================================================
-- 背包总格数不同时UpdateLook
--=============================================================================
function MyInventoryFrame_UpdateLookIfNeeded(name, slots) -- {{{
	local slots = slots or MyInventory_GetBagsTotalSlots();
	if ( ( not MyInventoryFrame.size ) or ( slots ~= MyInventoryFrame.size ) ) then
		MyInventoryFrame_UpdateLook(name, slots);
	end
end -- }}}
---------------------
-- 调整背包外观
---------------------
function MyInventoryFrame_UpdateLook(pname, frameSize, name) -- {{{
	--local frameSize = MyInventory_GetBagsTotalSlots();
	local frameSize = frameSize or MyInventory_GetBagsReplacingSlots();
	local player, realm;
	if (pname) then
		player, realm = strmatch(pname, "(.+)|(.+)");
	end	
	MyInventoryTitle_Update(player, realm);  -- Update Title
	MyInventory_SetLock();		-- Set Lock Icon
	MyInventory_ShowButtons();  -- Show or Hide Buttons
	
	MyInventoryFrame.size = frameSize;	
	
	local name = name or MyInventoryFrame:GetName();
	-- Update Size Anchor to bottom right
	-- 列数, 行数
	local columns, rows = MyInventoryColumns, ceil(frameSize / MyInventoryColumns);
	-- 高度, 宽度
	local height, width = MyInventoryFrame_GetAppropriateHeight(rows), MyInventoryFrame_GetAppropriateWidth(columns);

	MyInventoryFrame:SetHeight(height);
	MyInventoryFrame:SetWidth(width);
	MyInventoryFrame:ClearAllPoints();
	MyInventoryFrame:SetPoint("TOPLEFT", MyInventoryAnchorFrame, "TOPLEFT", 0, 0);

	MyInventory_SetGraphics(); -- Turn on or Off Blizzard Graphics
	-- Border	
	local First_Y = -6 ;
	-- Title
	local show = false
	if MyInventoryGraphics == 1 then -- -LITE{
		show = true;
	end -- }-LITE
	if MyInventoryShowTitle==1 or MyInventoryButtons == 1 or show then
		First_Y = First_Y - MYINVENTORY_TOP_HEIGHT;
	end
	-- BagButtons
	MyInventoryBagButtonsBar:ClearAllPoints();
	-- -LITE{
	if MyInventoryGraphics == 1 then
		if MyInventoryColumns == 5 then
			First_Y = First_Y + MYINVENTORY_ITEM_OFFSET_Y;
			MyInventoryBagButtonsBar:SetPoint("TOP", "MyInventoryFrame", "TOP", 0, First_Y);
		else
			MyInventoryBagButtonsBar:SetPoint("TOP", "MyInventoryFrame", "TOP", 20, First_Y);
			First_Y = First_Y + MYINVENTORY_ITEM_OFFSET_Y;
		end
	else
		-- }-LITE
		MyInventoryBagButtonsBar:SetPoint("TOP", "MyInventoryFrame", "TOP", 0, First_Y);
	end -- -LITE
	
	if MyInventoryBagView == 1 then
		if MyInventoryGraphics == 0 or MyInventoryColumns == 5 then -- -LITE
			First_Y = First_Y + MYINVENTORY_ITEM_OFFSET_Y;
		end -- -LITE
		MyInventoryBagButtonsBar:Show();
	else
		MyInventoryBagButtonsBar:Hide();
	end
	-- SellValue
	if ( SellValue_Enable ) then
		if ( MyInventoryFrame:IsVisible() and MyInventoryGraphics == 1 and MyInventoryBagView == 0 ) then
			InvList_Button:SetPoint("TOPLEFT", MyInventoryFrame:GetName(), "TOPRIGHT", -140, -28);
			InvList_Button:SetFrameLevel(MyInventoryFrame:GetFrameLevel()+1);
			InvList_Button:SetScale(MyInventoryFrame:GetScale());
			InvQuery_Button:SetFrameLevel(MyInventoryFrame:GetFrameLevel()+1);
			InvQuery_Button:SetScale(MyInventoryFrame:GetScale());
		end
	end

	MyInventoryFrame_UpdateButtonsVisibility();

	local curCol;
	if MyInventoryAIOIStyle==1 then
		curCol=columns-(mod(frameSize, columns)-1);
		if curCol>columns then 
			curCol=curCol-columns;
		end
	else
		curCol=1;
	end
	local curRow=1;
	for j=1, frameSize, 1 do
		local itemButton = getglobal(name.."Item"..j);
		--itemButton:SetID(j);					-- this ID must be change
		-- Set first button
		itemButton:ClearAllPoints();
		local dx, dy, baseframe;
		if ( j == 1 ) then
			baseframe = "MyInventoryFrame";
			if MyInventoryAIOIStyle == 1 then
				dx = (curCol-1)*MYINVENTORY_ITEM_OFFSET_X + MYINVENTORY_FIRST_ITEM_OFFSET_X;
				dy =    First_Y;
			else
				dx = MYINVENTORY_FIRST_ITEM_OFFSET_X;
				dy = First_Y;
			end
		else
			if ( mod((curCol+j-2), columns) == 0 ) then
				baseframe = "MyInventoryFrame";
				dx = MYINVENTORY_FIRST_ITEM_OFFSET_X;
				dy = First_Y + MYINVENTORY_ITEM_OFFSET_Y*curRow;
				curRow=curRow+1;
			else
				baseframe = name.."Item"..(j - 1);
				dy = 0;
				dx = MYINVENTORY_ITEM_OFFSET_X;
			end
		end
		itemButton:SetPoint("TOPLEFT", baseframe, "TOPLEFT", dx, dy);
		
		itemButton:Show();
	end
	-- 隐藏多于的button
	local button = nil;
	for i = frameSize+1, MYINVENTORY_MAX_ID do
		button = getglobal(name .. "Item"..i);
		if ( button ) then
			button:Hide();
		end
	end
end -- }}}
-- }}}
-- Get Height and Width {{{
function MyInventoryFrame_GetAppropriateHeight(rows) -- {{{
	-- Border 6 on top, 6 on bottom
	-- First row is 28 pixels down.
	-- BASE_HEIGHT = 44
	if MyInventoryGraphics == 1 then -- -LITE{
		rows = rows+1; 
	end -- }-LITE
	if MyInventoryBagView == 1 then
		if MyInventoryGraphics == 0 or MyInventoryColumns == 5 then -- -LITE
			rows = rows+1;
		end -- -LITE
	end
	local height = 12;
	if MyInventoryButtons==1 or MyInventoryShowTitle==1 or MyInventoryGraphics == 1 then
		height = height + MYINVENTORY_TOP_HEIGHT;
	end
	if (MyInventoryCash==1) or (MyInventoryCount > -1)  then
		height = height + MYINVENTORY_BOTTOM_HEIGHT;
	end
	height = height + (-MYINVENTORY_ITEM_OFFSET_Y) * rows; -- 39*rows
  return height;
end -- }}}

function MyInventoryFrame_GetAppropriateWidth(cols) -- {{{
	return 12 + ( MYINVENTORY_ITEM_OFFSET_X * cols ); -- 39*cols
end -- }}}
-- }}}
-- Get Bag Slots {{{
--============================================================================
-- 获得背包格数
--============================================================================
function MyInventory_GetBagsTotalSlots() -- {{{
	local slots = 0;
	for bag = 0, 4 do
		slots = slots + GetContainerNumSlots(bag);
	end
	return slots;
end -- }}}
--=============================================================================
-- 获得背包的总格数
--=============================================================================
function MyInventory_GetBagsReplacingSlots() -- {{{
	local slots = 0;
	for bag = 0, 4 do
		if MyInventory_ShouldOverrideBag(bag) then
			slots = slots + GetContainerNumSlots(bag);
		end
	end
	return slots;
end  -- }}}


function MyInventoryTitle_Update(player, realm) -- {{{
	if MyInventoryCash == 1 then
		MyInventoryFrameMoneyFrame:Show();
	else
		MyInventoryFrameMoneyFrame:Hide();
	end
	MyInventorySlots_Update();
	if MyInventoryShowTitle == 0 then
		if MyInventoryGraphics == 0 then -- -LITE
			MyInventoryFrameName:Hide();
			return;
		end -- -LITE
	end
	MyInventoryFrameName:Show();
	--{{ 修改这里
	if ( UnitName('player') ) then
		local player = player or UnitName('player');
		local realm = realm or MyInventory_Trim(GetCVar("realmName"));		
	--}}
		if (MyInventoryColumns < 5 ) then
			MyInventoryFrameName:SetText(MYINVENTORY_TITLE);
		elseif (MyInventoryColumns < 7 ) then
			if MyInventoryGraphics == 1 then -- -LITE
				MyInventoryFrameName:SetText(MYINVENTORY_TITLE); -- -LITE
			else -- -LITE
				MyInventoryFrameName:SetText(format(MYINVENTORY_TITLE_S, player));
			end -- -LITE
		else
			if MyInventoryGraphics == 1 and MyInventoryColumns < 9 then -- -LITE
				MyInventoryFrameName:SetText(format(MYINVENTORY_TITLE_S, player)); -- -LITE
			else -- -LITE
				MyInventoryFrameName:SetText(format(MYINVENTORY_TITLE_SS,player, realm));
			end -- -LITE
		end
		MyInventoryFrameName:SetTextColor(1.0, 1.0, 1.0);			
	end
end -- }}}

function MyInventorySlots_Update() -- {{{
	local i, j, totalSlots= 0, 0, 0;
	local takenSlots = 0;
	
	for i = 0, 4 do
		local slots = GetContainerNumSlots(i)
		if MyInventory_ShouldOverrideBag(i) then 
			totalSlots = totalSlots + slots;
			for j = 1, slots do
				if GetContainerItemInfo(i,j) then
					takenSlots=takenSlots + 1;
				end
			end
		end
	end
	
	if MyInventoryCount == 0 then
		MyInventoryFrameSlots:Show();
		MyInventoryFrameSlots:SetText(format(MYINVENTORY_SLOTS_DD, (totalSlots-takenSlots),totalSlots));
	elseif MyInventoryCount == 1 then
		MyInventoryFrameSlots:Show();
		MyInventoryFrameSlots:SetText(format(MYINVENTORY_SLOTS_DD, (takenSlots),totalSlots));
	else
		MyInventoryFrameSlots:Hide();
	end
end -- }}}

function MyInventory_SetLock() -- {{{
	if MyInventoryLock == 1 then
		MILockNormalTexture:SetTexture("Interface\\AddOns\\MyInventory\\Skin\\LockButton-Locked-Up");
	else
		MILockNormalTexture:SetTexture("Interface\\AddOns\\MyInventory\\Skin\\LockButton-Unlocked-Up");
	end
	MyInventoryFrame:EnableMouse(1-MyInventoryLock);
end -- }}}

function MyInventory_ShowButtons() -- {{{
	local show = false;
	if MyInventoryGraphics == 1 then -- -LITE{
		show = true 
	end -- }-LITE
	if MyInventoryButtons == 1 or show then
		MyInventoryFrameCloseButton:Show();
		MyInventoryFrameLockButton:Show();
		MyInventoryFrameHideBagsButton:Show();
	else
		MyInventoryFrameCloseButton:Hide();
		MyInventoryFrameLockButton:Hide();
		MyInventoryFrameHideBagsButton:Hide();
	end
end -- }}}
function MyInventory_SetGraphics() -- {{{
	-- -LITE{
	if MyInventoryGraphics == 1 then
		MyInventoryFrame:SetBackdropColor(0,0,0,0);
		MyInventoryFrame:SetBackdropBorderColor(0,0,0,0);
		
		MyInventoryFramePortrait:Show();
		MyInventoryFrameTextureTopLeft:Show();
		MyInventoryFrameTextureTopCenter:Show();
		MyInventoryFrameTextureTopRight:Show();
		MyInventoryFrameTextureLeft:Show();
		MyInventoryFrameTextureCenter:Show();
		MyInventoryFrameTextureRight:Show();
		MyInventoryFrameTextureBottomLeft:Show();
		MyInventoryFrameTextureBottomCenter:Show();
		MyInventoryFrameTextureBottomRight:Show();
		MyInventoryFrameName:ClearAllPoints();
		MyInventoryFrameName:SetPoint("TOPLEFT", "MyInventoryFrame", "TOPLEFT", 70, -8);
		MyInventoryFrameCloseButton:ClearAllPoints();
		MyInventoryFrameCloseButton:SetPoint("TOPRIGHT", "MyInventoryFrame", "TOPRIGHT", 10, 0);
	else	-- }-LITE
		
		if MyInventoryBackground==1 then
			MyInventoryFrame:SetBackdropColor(0,0,0,1.0);
			MyInventoryFrame:SetBackdropBorderColor(1,1,1,1.0);
		else
			MyInventoryFrame:SetBackdropColor(0,0,0,0);
			MyInventoryFrame:SetBackdropBorderColor(1,1,1,0);
		end
			
		MyInventoryFramePortrait:Hide();
		MyInventoryFrameTextureTopLeft:Hide();
		MyInventoryFrameTextureTopCenter:Hide();
		MyInventoryFrameTextureTopRight:Hide();
		MyInventoryFrameTextureLeft:Hide();
		MyInventoryFrameTextureCenter:Hide();
		MyInventoryFrameTextureRight:Hide();
		MyInventoryFrameTextureBottomLeft:Hide();
		MyInventoryFrameTextureBottomCenter:Hide();
		MyInventoryFrameTextureBottomRight:Hide();
		MyInventoryFrameName:ClearAllPoints();
		MyInventoryFrameName:SetPoint("TOPLEFT", "MyInventoryFrame", "TOPLEFT", 5, -6);
		MyInventoryFrameCloseButton:ClearAllPoints();
		MyInventoryFrameCloseButton:SetPoint("TOPRIGHT", "MyInventoryFrame", "TOPRIGHT", 2, 2);
	end -- -LITE
end -- }}}
-- }}}

function MyInventoryFrame_Update(frame, force) --- {{{
	if (not frame) then
		frame = getglobal("MyInventoryFrame");
	end

	if (not frame or not frame:IsVisible()) then
		return;
	end

	MyInventoryFrame_UpdateLookIfNeeded();
	local name = frame:GetName();
	local index = 0;
	MyInventorySlots_Update();
	local altbag=0; -- Even or odd bag
	for bag=0, 4 do
		if MyInventory_ShouldOverrideBag(bag) and GetContainerNumSlots(bag)>0 then 
			altbag=math.abs(altbag-1); -- Even or odd (couting the replaced ones only)
			
			local special_bag = nil;
			local bag_obj;
			if (bag > 0) then			
				bag_obj = getglobal("MyInventoBag"..(bag-1).."Slot");
			end			
			if (bag_obj) then
				local link = GetInventoryItemLink("player", bag_obj:GetID());
				if (link) then
					local _,_,_,_,_,_,bag_type =  GetItemInfo(link);
					if (bag_type and (
						bag_type == MYINVENTORY_AMMO		or 
						bag_type == MYINVENTORY_SOUL_BAG	or 
						bag_type == MYINVENTORY_HERB_BAG	or
						bag_type == MYINVENTORY_ENCH_BAG	or
						bag_type == MYINVENTORY_MINING_SACK or
						bag_type == MYINVENTORY_GEM_BAG		or
						bag_type == MYINVENTORY_ENGI_BAG	or
						bag_type == MYINVENTORY_QUIVER)) then	

						special_bag = 1;
					end
				end
				
			end

			local itemButton, texture, itemCount, locked, quality, readable, link, itemStack;			
			for slot=1, GetContainerNumSlots(bag) do
				itemStack = 0;
				index = index + 1;
				local itemButton = getglobal(name.."Item"..index);
				texture, itemCount, locked, quality, readable = GetContainerItemInfo(bag, slot);
				--itemButton.bagIndex = bag; itemButton.itemIndex = slot;	
				link = GetContainerItemLink(bag, slot) or "";	-- I can't sure the bad result!
				_, _, _, _, _, _, _, itemStack = GetItemInfo(link);
				itemButton:SetParent(getglobal("MyInventoryFrameBag"..bag));							
				itemButton:SetID(slot);
				-- Save the slot and bag, MUCH easier then looking it up every time.
				if not texture and MyInventoryGraphics==1 then -- -LITE{
					SetItemButtonTexture(itemButton, "Interface\\AddOns\\MyInventory\\Skin\\blank");
				else -- }-LITE
					SetItemButtonTexture(itemButton, texture);
				end -- -LITE
				SetItemButtonCount(itemButton, itemCount);
				SetItemButtonDesaturated(itemButton, locked, 0.5, 0.5, 0.5);
				--getglobal(itemButton:GetName() .. "Count"):ClearAllPoints();
				--getglobal(itemButton:GetName() .. "Count"):SetPoint("BOTTOMRIGHT", itemButton, "BOTTOMRIGHT", -1, 2);
				--if (itemCount and itemStack and itemCount>0 and itemStack>0 and itemStack<100) then					
				--	getglobal(itemButton:GetName() .. "Count"):SetText(format(MyInventory_Count, itemCount, itemStack));					
				--end				
				local color, highlightBorder;
				if (MyInventoryItemBorder == 1) and  ( quality and quality >= 2 ) then					
					color = MYINVENTORY_ITEM_COLOR[quality] or {["r"]=0.5, ["g"]=0.5, ["b"]=0.5};
					highlightBorder = true;					
				end
				
				if (highlightBorder) then
					getglobal(itemButton:GetName().."Border"):Show();
					getglobal(itemButton:GetName().."Border"):SetVertexColor(color.r, color.g, color.b, 0.8);
				else
					if (special_bag and MyInventoryItemBorder == 1) then
						getglobal(itemButton:GetName().."Border"):Show();
						getglobal(itemButton:GetName().."Border"):SetVertexColor(1.0, 1.0, 0.0, 0.6);
					else
						getglobal(itemButton:GetName().."Border"):Hide();
					end
				end

				if ( texture ) then
					local cooldown = getglobal(itemButton:GetName().."Cooldown");
					local start, duration, enable = GetContainerItemCooldown(bag, slot);
					CooldownFrame_SetTimer(cooldown, start, duration, enable);
					if ( duration > 0 and enable == 0 ) then
						SetItemButtonTextureVertexColor(itemButton, 0.4, 0.4, 0.4);
					end
				else
					getglobal(name.."Item"..index.."Cooldown"):Hide();
				end

				itemButton.readable = readable;
				local showSell = nil;
				if ( GameTooltip:IsOwned(itemButton) ) then
					if ( texture ) then
						local hasCooldown, repairCost = GameTooltip:SetBagItem(bag, slot);
						if ( hasCooldown ) then
							itemButton.updateTooltip = TOOLTIP_UPDATE_TIME;
						else
							itemButton.updateTooltip = nil;
						end
						if ( InRepairMode() and (repairCost > 0) ) then
							GameTooltip:AddLine(TEXT(REPAIR_COST), "", 1, 1, 1);
							SetTooltipMoney(GameTooltip, repairCost);
							GameTooltip:Show();
						elseif ( MerchantFrame:IsVisible() and not locked) then
							showSell = 1;
						end
					else
						GameTooltip:Hide();    
					end
					if ( showSell ) then
						ShowContainerSellCursor(bag, slot);
					elseif ( readable ) then    
						ShowInspectCursor();
					else      
						ResetCursor();
					end 
				end
			end
		end
	end
end -- }}}

-- alt+left to trade item
local function MI_PostClick(arg1)
	if (IsAltKeyDown() and arg1 == "LeftButton") then
		local bag, slot = this:GetParent():GetID(), this:GetID();
		if (bag and slot and TradeFrame:IsShown()) then
			PickupContainerItem(bag, slot);		
			if (CursorHasItem()) then
				TradeFrame_OnMouseUp();
			end
		end
	end
end

hooksecurefunc("ContainerFrameItemButton_OnModifiedClick", MI_PostClick);
------------------------------------------------------------------------------------
--[[
MyInventory_GetBagsReplacingSlots
MyInventoryFrame_UpdateLook
MyInventoryTitle_Update
]]
--------------------------------------------------------------------------------------
-- Begin MyInventory View
---------------------------------------------------------------------------------------
--MyInventroyViewProfile = {};
--local PlayerName = nil;
MYINVENTORYBAGS = {0, 1, 2, 3, 4};
local function print(msg)
	msg = "|cff00ff00" ..MYINVENTORY_CHAT_PREFIX .. "|r" .. msg;

	ChatFrame1:AddMessage(msg, 1.0, 1.0, 1.0);
end

function SaveInventoryInfo()
	local index = 1;
	local link, hyperlink;	
	MyInventroyViewProfile[PlayerName] = {};
	MyInventroyViewProfile[PlayerName]['info'] = {};
	for k, bag in ipairs(MYINVENTORYBAGS) do		
		local special_bag = nil;
		local bag_obj = (bag > 0) and getglobal("MyInventoBag"..(bag-1).."Slot") or nil;
		
		if (bag_obj) then
			local link = GetInventoryItemLink("player", bag_obj:GetID());
			if (link) then
				local _,_,_,_,_,_,bag_type =  GetItemInfo(link);
				if (bag_type and (
					bag_type == MYINVENTORY_AMMO		or 
					bag_type == MYINVENTORY_SOUL_BAG	or 
					bag_type == MYINVENTORY_HERB_BAG	or
					bag_type == MYINVENTORY_ENCH_BAG	or
					bag_type == MYINVENTORY_MINING_SACK or
					bag_type == MYINVENTORY_GEM_BAG		or
					bag_type == MYINVENTORY_ENGI_BAG	or
					bag_type == MYINVENTORY_QUIVER)) then	

					special_bag = 9;
				end
			end		
		end
		
		local texture, itemCount, locked, quality, readable;
		for slot=1, GetContainerNumSlots(bag) do
			texture, itemCount, locked, quality, readable = GetContainerItemInfo(bag, slot);
			link = GetContainerItemLink(bag, slot) or "";
			hyperlink = strmatch(link, "|c%x*|H(item:.*)|h%[.-%]|h|r")
			if (hyperlink and itemCount) then
				MyInventroyViewProfile[PlayerName]['info'][index] = format("%s`%d`%d", hyperlink, itemCount, special_bag or quality or 0);
			end
			index = index + 1;
		end
	end
	MyInventroyViewProfile[PlayerName]['nums'] = index-1;
	MyInventroyViewProfile[PlayerName]['money'] = GetMoney();
end

hooksecurefunc("Logout", SaveInventoryInfo);
hooksecurefunc("Quit", SaveInventoryInfo);
-- MyInventoryViewDropDown --
local checkedPlayer;
function MyInventoryViewDropClick(value)
	local value = value or this.value;	
	checkedPlayer = value;
	if (value and MyInventroyViewProfile[value]) then
		local playerInfo = MyInventroyViewProfile[value];
		BDropDownMenu_SetSelectedValue(MyInventoryViewDropDown, value);
		MyInventoryViewUpdate(value, playerInfo);		
	else
		print("Error! None infomation about this player");
	end
end

function MyInventoryViewUpdate(player, playerInfo)	
	if (playerInfo) then
		local _, bName, itemButton, texture, itemCount, quality, link, hyperlink;
		local takenSlots = 0;
		for i=1, playerInfo.nums do
			bName = format("MyInventroyViewItem%d", i);
			itemButton = getglobal(bName);
			if (not itemButton) then
				itemButton = CreateFrame("Button", bName, MyInventoryViewDropDown, "ItemButtonTemplate");
				itemButton.Border = itemButton:CreateTexture("", "OVERLAY");
				itemButton.Border:SetWidth(64);
				itemButton.Border:SetHeight(64);
				itemButton.Border:SetPoint("CENTER", itemButton, "CENTER", 0, 0);				
				itemButton.Border:SetTexture("Interface\\AddOns\\MyInventory\\Skin\\Border");
				itemButton:SetScript("OnEnter", function(self)
					if (this.link) then
						GameTooltip:SetOwner(this,"ANCHOR_RIGHT");
						GameTooltip:SetHyperlink(this.link);
						GameTooltip:Show();
					end					
				end);
				itemButton:SetScript("OnLeave", function(self)
					GameTooltip:Hide();
				end);
			end
			if (playerInfo.info[i]) then
				hyperlink, itemCount, quality = strmatch(playerInfo.info[i], "(.*)`(.*)`(.*)");
				itemButton.link = hyperlink;
				_, _, _, _, _, _, _, _, _, texture = GetItemInfo(hyperlink);
				SetItemButtonTexture(itemButton, texture);
				SetItemButtonCount(itemButton, itemCount+0);
				local color;				
				quality = quality + 0;
				
				if ((MyInventoryItemBorder == 1) and  ( quality and quality >= 2)) then					
					color = MYINVENTORY_ITEM_COLOR[quality] or {["r"]=0.5, ["g"]=0.5, ["b"]=0.5, ["a"] = 0.8};
					itemButton.Border:SetVertexColor(color.r, color.g, color.b, color.a);
					itemButton.Border:Show();
				else
					itemButton.Border:Hide();
				end
				takenSlots = takenSlots + 1;
			else
				SetItemButtonCount(itemButton, 0);
				if MyInventoryGraphics==1 then 
					SetItemButtonTexture(itemButton, "Interface\\AddOns\\MyInventory\\Skin\\blank");				
				end
				itemButton.Border:Hide();
			end
		end
		-- 刷新外观显示
		MyInventoryFrame_UpdateLook(player, playerInfo.nums, "MyInventroyView");
		-- 刷新格式数显示
		if MyInventoryCount == 0 then
			MyInventoryFrameSlots:Show();
			MyInventoryFrameSlots:SetText(format(MYINVENTORY_SLOTS_DD, (playerInfo.nums-takenSlots),playerInfo.nums));
		elseif MyInventoryCount == 1 then
			MyInventoryFrameSlots:Show();
			MyInventoryFrameSlots:SetText(format(MYINVENTORY_SLOTS_DD, (takenSlots),playerInfo.nums));
		else
			MyInventoryFrameSlots:Hide();
		end
		-- 刷新金钱显示
		MoneyFrame_Update("MyInventoryFrameMoneyFrame", playerInfo.money);		
		-- hide other button
		local i = playerInfo.nums + 1;
		while (getglobal("MyInventroyViewItem" .. i)) do
			getglobal("MyInventroyViewItem" .. i):Hide();
			i = i +1;
		end
	end
end

function MyInventoryFrame_IsProfileStored()
	for key, value in pairs(MyInventroyViewProfile) do
		local thisRealmPlayers = strmatch(key, "|(.+)");
		if ( #(MyInventroyViewProfile[key]) > 0 or MyInventroyViewProfile[key].money ) then
			if (thisRealmPlayers == MyInventory_Trim(GetCVar("realmName")) and key ~= PlayerName) then
				return true;
			end
		end
	end

	return false;
end

function MyInventoryViewDropDown_Initialize()
	local selectedValue = BDropDownMenu_GetSelectedValue(MyInventoryViewDropDown);
	local info, first;
	for key, value in pairs(MyInventroyViewProfile) do
		local thisRealmPlayers = strmatch(key, "|(.+)");		
		if ( #(MyInventroyViewProfile[key]) > 0 or MyInventroyViewProfile[key].money ) then
			if (thisRealmPlayers == MyInventory_Trim(GetCVar("realmName")) and key ~= PlayerName) then
				info = {};
				info.text = strmatch(key,"(.+)|.+");
				info.value = key;
				info.func = MyInventoryViewDropClick;
				if (selectedValue) then
					if ( selectedValue == info.value ) then
						info.checked = 1;
					else
						info.checked = nil;
					end
				elseif (not first) then
					MyInventoryViewDropClick(key);
					info.checked = 1;
					first = true;
				end				
				BDropDownMenu_AddButton(info);
			end
		end
	end
end

function MyInventoryViewDropDown_OnLoad()
	BDropDownMenu_Initialize(this, MyInventoryViewDropDown_Initialize);	
	MyBankDropDown.tooltip =  MYINVENTORY_TOOLTIP_PLAYER;	
end

function MyInventoryFrame_GetViewType()
	return MyInventoryFrame.viewType;
end

function MyInventoryFrame_SetViewType(type)
	MyInventoryFrame.viewType = type;
end

function MyInventoryFrame_IsInvListButtonShown()
	if (not SellValue_Enable) then
		return false;
	end

	if (not MyInventoryFrame:IsVisible()) then
		return false;
	end

	if (MyInventoryFrame_GetViewType() == 1) then
		return true;
	else
		return false;
	end
end

function MyInventoryFrame_IsInvQueryButtonShown()
	if (not SellValue_Enable) then
		return false;
	end

	if (MyInventoryFrame_GetViewType() == 1) then
		return true;
	else
		return false;
	end
end

function MyInventoryFrame_IsPackupButtonShown()
	if (not SellValue_Enable) then
		return false;
	end

	if (MyInventoryFrame_GetViewType() == 1) then
		return true;
	else
		return false;
	end
end

function MyInventoryFrame_HideButtons()
	InvList_Button:Hide();
	InvQuery_Button:Hide();
end

function MyInventoryFrame_UpdateButtonsVisibility()
	if (not MyInventoryFrame:IsVisible()) then
		return;
	end
	if (SellValue_Enable) then	-- 确认开启了物品售价
		if (MyInventoryFrame_IsInvListButtonShown()) then
			InvList_Button:Show();
		else
			InvList_Button:Hide();
		end
	
		if (MyInventoryFrame_IsInvQueryButtonShown()) then
			InvQuery_Button:Show();
		else
			InvQuery_Button:Hide();
		end
	end
	local button = getglobal("PUI_Button_1");
	if (button) then
		if (MyInventoryFrame_IsPackupButtonShown()) then
			button:Show();
		else
			button:Hide();
		end
	end

	if (MyInventoryFrame_EnableViewOther and MyInventoryFrame_IsProfileStored()) then
		MyInventoryFramePlayerTab:Show();		
		MyInventoryFrameViewTab:Show();
	else
		MyInventoryFrameViewTab:Hide();
		MyInventoryFrameViewTab:Hide();
	end
end

function MyInventory_ToggleViewOther(switch)
	if (switch) then
		MyInventoryFrame_EnableViewOther = true;
	else
		MyInventoryFrame_EnableViewOther = false;
	end	

	MyInventoryFrame_UpdateButtonsVisibility();
end

function MyInventoryFrame_TabOnClick()
	local id = this:GetID();
	if (id == 1 and MyInventoryFrame_GetViewType() ~= 1) then	-- 整合背包
		MyInventoryFrame_UpdateViewByType(1);
		MyInventoryFrame_SetViewType(1);
		
	elseif (id == 2 and MyInventoryFrame_GetViewType() ~= 2) then
		MyInventoryFrame_UpdateViewByType(2);
		MyInventoryFrame_SetViewType(2);		
	end

	MyInventoryFrame_UpdateButtonsVisibility();
end

function MyInventoryFrame_UpdateViewByType(type)
	if (type == 1) then
		isPlayerTab = true;
		MyInventoryFrameBag0:Show();
		MyInventoryFrameBag1:Show();
		MyInventoryFrameBag2:Show();
		MyInventoryFrameBag3:Show();
		MyInventoryFrameBag4:Show();
		MyInventoryViewDropDown:Hide();	
		
		MyInventoryFramePlayerTab:LockHighlight();		
		MyInventoryFrameViewTab:UnlockHighlight();

		MyInventoryFrame_Update();
		if (IsAddOnLoaded("PackUpInventory") and MyInventory_GetRegisterButton("MyInventoryFramePack")) then
			MyInventory_GetRegisterButton("MyInventoryFramePack"):Show();
		end
		if (PlayerMoney) then	
			MoneyFrame_Update("MyInventoryFrameMoneyFrame", PlayerMoney);
		end
	else
		isPlayerTab = false;
		MyInventoryFrameBag0:Hide();
		MyInventoryFrameBag1:Hide();
		MyInventoryFrameBag2:Hide();
		MyInventoryFrameBag3:Hide();
		MyInventoryFrameBag4:Hide();
		MyInventoryViewDropDown:Show();

		MyInventoryFramePlayerTab:UnlockHighlight();		
		MyInventoryFrameViewTab:LockHighlight();
		if (IsAddOnLoaded("PackUpInventory") and MyInventory_GetRegisterButton("MyInventoryFramePack")) then
			MyInventory_GetRegisterButton("MyInventoryFramePack"):Hide();
		end
		MyInventoryViewDropClick(checkedPlayer)
	end
end

function MyInventroyAjustDropDown()	
	BDropDownMenu_SetWidth(94);	
end
--==================
-- API 
--==================
function MyInventory_RegisterButton(name, text, width, tooltip, func, arg1)
	local n = #(MY_INVENTORY_REGISTER_BUTTONS) + 1;
	local name = name and tostring(name) or format("MyInventroyRegisterButton%d", n);
	local text = text and tostring(text) or "";
	local width = type(width) == "number" and width or 90;
	local func = type(func) == "function" and func or function() end;
	
	local button = MY_INVENTORY_REGISTER_BUTTONS[name];
	if (not button) then
		button = CreateFrame("Button", nil, MyInventoryFrame, "UIPanelButtonTemplate");	
		button:SetHeight(26);
		button:SetText(text);
		button:SetWidth(width);
		button:SetScript("OnClick", function()
			func(arg1);
		end);
		if (tooltip and type(tooltip) == "string") then
			button:SetScript("OnEnter", function(self)
				GameTooltip:SetOwner(self, "ANCHOR_TOPRIGHT");
				GameTooltip:SetText(format("|cffffffff%s|r", text));
				GameTooltip:AddLine(tooltip);
				GameTooltip:Show();
			end);
			button:SetScript("OnLeave", function(self)
				GameTooltip:Hide();
			end);
		end
		
		if (n <= 1) then -- exactly, n == 1
			button:SetPoint("TOPRIGHT", MyInventoryFrame, "TOPRIGHT", -5, -32);
		else
			button:SetPoint("RIGHT", MyInventoryRegisterLastButton, "RIGHT", -2, 0);
		end
		MyInventoryRegisterLastButton = button;
		MY_INVENTORY_REGISTER_BUTTONS[name] = button;
	end	
	return button;
end
--------------------
-- 通过名字获得Button的句柄
--------------------
function MyInventory_GetRegisterButton(name)
	if (MY_INVENTORY_REGISTER_BUTTONS[name]) then		
		return MY_INVENTORY_REGISTER_BUTTONS[name];
	else
		return false;
	end
end