--[[
--	//////////////////////////////////////////////
--	Variables Init
--	//////////////////////////////////////////////
]]
local rpgoCP_VERSION		= "1.212";
local rpgoCP_PROVIDER		= "rpgo (edits by Wulfson)";
local rpgoCP_PROFILEDB		= "1.2";
local rpgoCP_TITLE			= "CharacterItems";
local rpgoCPdebug 			= nil;		-- [1|nil] enable debugging
--	//////////////////////////////////////////////
if(not rpgoColorTitle) then rpgoColorTitle = "909090"; end
if(not rpgoColorGreen) then rpgoColorGreen = "00cc00"; end
if(not rpgoColorRed)   then rpgoColorRed   = "ff0000"; end
myProfile = {};
myProfile[GetCVar("realmName")] = {} ;
RegisterForSave("myProfile");
rpgoCPpref = {};
rpgoCPpref["Enabled"]			= 1;
rpgoCPpref["GetEquipment"]		= 1;	-- get equipment?
rpgoCPpref["GetInventory"]		= 1;	-- get inventory?
rpgoCPpref["GetBank"]			= 1;	-- get bank?
rpgoCPpref["HTML_Tooltips"]		= 1;	-- make html tooltips (non-array format) - separate lines with <br>

-- uncomment to rpgoCPpref in sv.lua
--RegisterForSave("rpgoCPpref");
-- or save rpgoCP_ENABLED
rpgoCP_ENABLED = rpgoCPpref["Enabled"];
RegisterForSave("rpgoCP_ENABLED");
--	//////////////////////////////////////////////
local rpgoCPlock = nil;
local rpgoCPplayer = nil;
local rpgoCPserver = nil;
local rpgoCPstate = {};
--	//////////////////////////////////////////////
local bagFirst = 0;
local bagLast = 4;
local bankTimeWait = 3;
local bankFirst = 5;
local bankLast = 10;
local equipmentCount = 19;
local timePlayed = -1;
local timeLevelPlayed = -1;

-- array of inventory slot names
Profile_slots = {
  "Head",          -- 1
  "Neck",          -- 2
  "Shoulder",      -- 3
  "Shirt",         -- 4
  "Chest",         -- 5
  "Waist",         -- 6
  "Legs",          -- 7
  "Feet",          -- 8
  "Wrist",         -- 9
  "Hands",         -- 10
  "Finger0",       -- 11
  "Finger1",       -- 12
  "Trinket0",      -- 13
  "Trinket1",      -- 14
  "Back",          -- 15
  "MainHand",      -- 16
  "SecondaryHand", -- 17
  "Ranged",        -- 18
  "Tabard",        -- 19
};

--[[//////////////////////////////////////////////
--	rpgoCP Core Functions
--    OnLoad,LoadVar,RegisterEvents,InitState,OnEvent
--	////////////////////////////////////////////]]

--[[// OnLoad
--	////////////////////////////////////////////]]
function rpgoCP_OnLoad()
	rpgoCP_InitState();
	this:RegisterEvent("VARIABLES_LOADED");
	SLASH_RPGOCP1 = "/ci";
	SLASH_RPGOCP2 = "/profiler";
	SlashCmdList["RPGOCP"] = rpgoCP_ChatCommand;
	DEFAULT_CHAT_FRAME:AddMessage(rpgo_ColorizeTitle(rpgoCP_PROVIDER,rpgoCP_TITLE).." [v" .. rpgoCP_VERSION .. "] loaded.");
	rpgoCP_debug(rpgo_ColorizeTitle(rpgoCP_PROVIDER,rpgoCP_TITLE).." running in DEBUG MODE.");
end

--[[// LoadVar
--	////////////////////////////////////////////]]
function rpgoCP_LoadVar()
	rpgoCPpref["Enabled"] = rpgoCP_ENABLED;
	rpgoCP_RegisterEvents();
	rpgoCPstate["LoadedVar"] = 1;
	rpgoCPplayer = UnitName("player");
	rpgoCPserver = GetCVar("realmName");
	rpgoCP_InitProfile();
end

--[[// RegisterEvents
--	////////////////////////////////////////////]]
function rpgoCP_RegisterEvents()
	local flagMode=0;
	if(rpgoCPpref["Enabled"]==1) then
		flagMode=1;
	end
	if(flagMode==1) then
		rpgoCP_debug("     RegisterEvents");
		rpgoCPframe:RegisterEvent("PLAYER_ENTERING_WORLD");
		rpgoCPframe:RegisterEvent("PLAYER_LEVEL_UP");
		rpgoCPframe:RegisterEvent("TIME_PLAYED_MSG");
		rpgoCPframe:RegisterEvent("BANKFRAME_CLOSED");
		rpgoCPframe:RegisterEvent("MAIL_CLOSED");
		rpgoCPframe:RegisterEvent("MERCHANT_CLOSED");
	else
		rpgoCP_debug("     UnregisterEvent");
		rpgoCPframe:UnregisterEvent("PLAYER_ENTERING_WORLD");
		rpgoCPframe:UnregisterEvent("PLAYER_LEVEL_UP");
		rpgoCPframe:UnregisterEvent("TIME_PLAYED_MSG");
		rpgoCPframe:UnregisterEvent("BANKFRAME_CLOSED");
		rpgoCPframe:UnregisterEvent("MAIL_CLOSED");
		rpgoCPframe:UnregisterEvent("MERCHANT_CLOSED");
	end
	flagMode=nil;
end

--[[// InitState
--	////////////////////////////////////////////]]
function rpgoCP_InitState(arg)
	rpgoCPstate={};
	rpgoCPstate["Loaded"]=nil;
	rpgoCPstate["LoadedVar"]=arg;
	rpgoCPstate["Equipment"]=0;
	rpgoCPstate["EquipmentScan"]=0;
	rpgoCPstate["Guild"]=nil;
	rpgoCPstate["GuildNum"]=nil;
	rpgoCPstate["Inventory"]={};
	rpgoCPstate["Bank"]={};
	rpgoCPstate["BankTime"]=0;
end

--[[// OnEvent
--	////////////////////////////////////////////]]
function rpgoCP_OnEvent(event,arg1,arg2,arg3,arg4,arg5)
	if(rpgoDebugArg) then rpgoDebugArg("CP",event,arg1,arg2,arg3,arg4,arg5); end
	if(event=="VARIABLES_LOADED") then
		rpgoCP_LoadVar();
		return;
	end
	if(rpgoCPpref["Enabled"]==0) then return; end
	if(event=="TIME_PLAYED_MSG") then
		return;
	elseif(event=="PLAYER_ENTERING_WORLD") then
		rpgoCP_LoadProfile();
		return;
	end

	if(not rpgoCPlock and rpgoCPplayer) then
		rpgoCPlock = 1;
		if(not rpgoCPstate["Loaded"]) then
			rpgoCP_LoadProfile();
		end
		if(event=="BANKFRAME_CLOSED") then
			rpgoCP_GetBank();
			rpgoCP_GetEquipment();
			rpgoCP_GetInventory();
		elseif(event=="MAIL_CLOSED") then
			rpgoCP_GetEquipment();
			rpgoCP_GetInventory();
		elseif(event=="MERCHANT_CLOSED") then
			rpgoCP_GetEquipment();
			rpgoCP_GetInventory();
		elseif(event=="PLAYER_LEVEL_UP") then
			rpgoCP_LoadProfile();
		end
		rpgoCPlock = nil;
	end
end

--[[// OnClick
--	////////////////////////////////////////////]]
function rpgoCP_OnClick()
	if(rpgoCPpref["Enabled"]==0) then return; end
	if(not rpgoCPlock) then
		rpgoCPlock = 1;
		rpgoCP_ForceExport();
		rpgoCPlock = nil;
	end
	rpgoCP_Show();
end

--[[// OnHide
--	////////////////////////////////////////////]]
function rpgoCP_OnHide()
	if(rpgoCPpref["Enabled"]==0) then return; end
	rpgoCP_InitProfile();
	rpgoCP_LoadProfile();
	rpgoCP_UpdateProfile();
end

--[[// OverLoaded functions are bad, but force till
--     PLAYER_QUITTING/PLAYER_LEAVING_WORLD
--     PetAbandon - to grab drop of pet
--	////////////////////////////////////////////]]
rpgoOldQuit = Quit;
function Quit()
	rpgoCP_UpdateProfile();
	RequestTimePlayed();
	return rpgoOldQuit();
end

rpgoOldLogout = Logout;
function Logout()
	rpgoCP_UpdateProfile();
	RequestTimePlayed();
	return rpgoOldLogout();
end

--[[// ChatCommand
--	////////////////////////////////////////////]]
function rpgoCP_ChatCommand(msg)
	if (msg) then
		msg = string.lower(msg);
		if (msg == "off") then
			rpgoCP_Toggle(0);
			return;
		elseif (msg == "on") then
			rpgoCP_Toggle(1);
			return;
		elseif (msg == "show") then
			rpgoCP_Show();
			return;
		elseif (msg == "export") then
			rpgoCP_ForceExport();
			return;
		elseif (msg == "debug") then
			rpgoCP_Debug();
			return;
		elseif (msg == "purge char") then
			rpgoCP_Purge("char");
			return;
		elseif (msg == "purge server") then
			rpgoCP_Purge("server");
			return;
		elseif (msg == "purge all") then
			rpgoCP_Purge("all");
			return;
		end
	end
	DEFAULT_CHAT_FRAME:AddMessage(rpgo_ColorizeTitle(rpgoCP_PROVIDER,rpgoCP_TITLE).." Usage [v" .. rpgoCP_VERSION .. "]");
	DEFAULT_CHAT_FRAME:AddMessage("   /ci          -- This Message");
	DEFAULT_CHAT_FRAME:AddMessage("   /ci on       -- Turns CharacterItems on");
	DEFAULT_CHAT_FRAME:AddMessage("   /ci off      -- Turns CharacterItems off");
	DEFAULT_CHAT_FRAME:AddMessage("   /ci export");
	DEFAULT_CHAT_FRAME:AddMessage("   /ci show");
	DEFAULT_CHAT_FRAME:AddMessage("   /ci purge [all|server|char]");
	if( rpgoCPpref["Enabled"] == 1) then
		DEFAULT_CHAT_FRAME:AddMessage(rpgo_ColorizeTitle(rpgoCP_PROVIDER,rpgoCP_TITLE)..": currently "..rpgo_ColorizeMsg(rpgoColorGreen,"enabled"));
	else
		DEFAULT_CHAT_FRAME:AddMessage(rpgo_ColorizeTitle(rpgoCP_PROVIDER,rpgoCP_TITLE)..": currently "..rpgo_ColorizeMsg(rpgoColorRed,"disabled"));
	end
end

--[[// Toggle
--	////////////////////////////////////////////]]
function rpgoCP_Toggle(toggle)
	if (toggle == 1) then
		rpgoCP_InitState(1);
		rpgoCPpref["Enabled"]=1;
		rpgoCP_RegisterEvents(rpgoCPpref["Enabled"]);
		if (not rpgoCPplayer or rpgoCPserver) then
			rpgoCPplayer = UnitName("player");
			rpgoCPserver = GetCVar("realmName");
		end
		if (not rpgoCPstate["Loaded"]) then
			PaperDollFrame_SetDamage();
			PaperDollFrame_SetRangedDamage();
			rpgoCP_InitProfile();
			RequestTimePlayed();
		end
		DEFAULT_CHAT_FRAME:AddMessage(rpgo_ColorizeTitle(rpgoCP_PROVIDER,rpgoCP_TITLE)..": "..rpgo_ColorizeMsg(rpgoColorGreen,"enabled"));
	else
		rpgoCPstate = nil;
		rpgoCPpref["Enabled"] = 0;
		rpgoCP_RegisterEvents(rpgoCPpref["Enabled"]);
		DEFAULT_CHAT_FRAME:AddMessage(rpgo_ColorizeTitle(rpgoCP_PROVIDER,rpgoCP_TITLE)..": "..rpgo_ColorizeMsg(rpgoColorRed,"disabled"));
	end
	rpgoCP_ENABLED = rpgoCPpref["Enabled"];
--	if ( (rpgoCPpref["Enabled"] == 0) and myProfile[rpgoCPserver] ) then
--		myProfile[rpgoCPserver][rpgoCPplayer] = nil;
--	end
end

--[[// Debug
--	////////////////////////////////////////////]]
function rpgoCP_Debug()
	if (rpgoCPdebug) then
		rpgoCPdebug = nil;
	else
		rpgoCPdebug = 1;
		rpgoCP_debug("Debug Mode: enabled");
	end
end

--[[// Show
--	////////////////////////////////////////////]]
function rpgoCP_Show()
	if( rpgoCPpref["Enabled"] == 1) then
		if(rpgoCPplayer and rpgoCPstate["Loaded"]) then
			local msg = "";
			local item=nil;
			local count=0;
			DEFAULT_CHAT_FRAME:AddMessage(rpgo_ColorizeTitle(rpgoCP_PROVIDER,rpgoCP_TITLE)..":  character info scanned this session");

				msg="Profile for: " .. rpgoCPplayer .. "@" .. rpgoCPserver;
			DEFAULT_CHAT_FRAME:AddMessage("    "..msg);
			
				msg="Guild Info:  ";
				if(rpgoCPstate["Guild"] == 0) then
					msg=msg.."not in a guild";
				elseif(rpgoCPstate["Guild"]) then
					if(myProfile[rpgoCPserver][rpgoCPplayer]["Guild"]["GuildName"]) then
						msg=msg..myProfile[rpgoCPserver][rpgoCPplayer]["Guild"]["GuildName"];
					else
						msg=msg..rpgo_ColorizeMsg(rpgoColorRed," not scanned1");
					end
				else
					msg=msg..rpgo_ColorizeMsg(rpgoColorRed," not scanned2");
				end
			DEFAULT_CHAT_FRAME:AddMessage("    " .. msg);
			
				msg = "";
				msg = msg .. "  Equipment:"..rpgoCPstate["Equipment"].."/"..equipmentCount;
			DEFAULT_CHAT_FRAME:AddMessage("  " .. msg);

				count=0;
				msg = "Inventory:";
				for item in rpgoCPstate["Inventory"] do
					msg = msg .. " Bag" .. item..":"..rpgoCPstate["Inventory"][item]["inv"].."/"..rpgoCPstate["Inventory"][item]["slot"];
					count=count+1;
				end
				if(count==0) then
					msg=msg..rpgo_ColorizeMsg(rpgoColorRed," not scanned")..".   to scan: open your bank or 'character info'";
				end
			DEFAULT_CHAT_FRAME:AddMessage("    " .. msg);
			
				count=0;
				msg = "Bank:";
				for item in rpgoCPstate["Bank"] do
					msg = msg .. " Bag" .. item .. ":".. rpgoCPstate["Bank"][item]["inv"].."/"..rpgoCPstate["Bank"][item]["slot"];
					count=count+1;
				end
				if(count==0) then
					msg=msg..rpgo_ColorizeMsg(rpgoColorRed," not scanned")..".   to scan: open your bank (May have scanned, this is buggy)";
				end
			DEFAULT_CHAT_FRAME:AddMessage("    " .. msg);
			
		else
			DEFAULT_CHAT_FRAME:AddMessage(rpgo_ColorizeTitle(rpgoCP_PROVIDER,rpgoCP_TITLE)..": "..rpgo_ColorizeMsg(rpgoColorRed," no character scanned"));
		end
	else
		DEFAULT_CHAT_FRAME:AddMessage(rpgo_ColorizeTitle(rpgoCP_PROVIDER,rpgoCP_TITLE)..": currently "..rpgo_ColorizeMsg(rpgoColorRed,"disabled"));
	end
end

--[[//////////////////////////////////////////////
--	InitProfile
--	////////////////////////////////////////////]]
function rpgoCP_InitProfile()
	if ( not myProfile ) then
		myProfile = {};
	end
	if ( not myProfile[rpgoCPserver] ) then
		myProfile[rpgoCPserver] = {};
	end
	if ( not myProfile[rpgoCPserver][rpgoCPplayer] ) then
		myProfile[rpgoCPserver][rpgoCPplayer] = {};
	end
end

--[[//////////////////////////////////////////////
--	LoadProfile
--	////////////////////////////////////////////]]
function rpgoCP_LoadProfile()
	if(myProfile[rpgoCPserver][rpgoCPplayer]["ProfilerProvider"]) then
		myProfile[rpgoCPserver][rpgoCPplayer]["ProfilerProvider"]=nil;
	end

	local myGold,mySilver,myCopper = rpgoGetMoney();
	myProfile[rpgoCPserver][rpgoCPplayer]["Money"] = {};
	myProfile[rpgoCPserver][rpgoCPplayer]["Money"]["Gold"] = myGold;
	myProfile[rpgoCPserver][rpgoCPplayer]["Money"]["Silver"] = mySilver;
	myProfile[rpgoCPserver][rpgoCPplayer]["Money"]["Copper"] = myCopper;

	rpgoCP_GetGuild();
	rpgoCP_UpdateDate();
	rpgoCPstate["Loaded"] = 1;
end

--[[//////////////////////////////////////////////
--	UpdateProfile
--	////////////////////////////////////////////]]
function rpgoCP_UpdateProfile()
	rpgoCP_GetGuild(force);
	rpgoCP_GetEquipment();
	rpgoCP_GetInventory();
	rpgoCP_UpdateDate();
end

--[[//////////////////////////////////////////////
--	ForceExport
--	////////////////////////////////////////////]]
function rpgoCP_ForceExport()
	if(rpgoCPpref["Enabled"]==0) then return; end
	local bankStateTemp = rpgoCPstate["Bank"];
	rpgoCP_InitState(1);
	rpgoCPstate["Bank"] = bankStateTemp;
	rpgoCP_InitProfile();
	rpgoCP_LoadProfile();
	rpgoCP_UpdateProfile();
end

--[[//////////////////////////////////////////////
--	Purge
--	////////////////////////////////////////////]]
function rpgoCP_Purge(arg1)
	if(arg1 and arg1 == "char") then
		myProfile[rpgoCPserver][rpgoCPplayer] = {};
	elseif(arg1 and arg1 == "server") then
		myProfile[rpgoCPserver] = {};
	elseif(arg1 and arg1 == "all") then
		myProfile = {};
	end
	rpgoCP_InitState(1);
end

--[[//////////////////////////////////////////////
--	rpgoCP Extract functions
--	////////////////////////////////////////////]]
function rpgoCP_GetGuild(force)
	local isGuildMember = IsInGuild();
	if(not isGuildMember) then
		rpgoCPstate["Guild"] = 0;
	else
		local guildNumMembers = GetNumGuildMembers();
		if(force or not rpgoCPstate["Guild"] or rpgoCPstate["GuildNum"] ~= guildNumMembers) then
			myProfile[rpgoCPserver][rpgoCPplayer]["Guild"] = {} ;
			local tmpGuildName,tmpGuildTitle,tmpGuildRank = GetGuildInfo("player");
			if(tmpGuildName) then
				myProfile[rpgoCPserver][rpgoCPplayer]["Guild"]["GuildName"] = tmpGuildName;
				rpgoCPstate["Guild"] = 1;
				rpgoCPstate["GuildNum"] = guildNumMembers;
			end
		end
	end
end

function rpgoCP_GetEquipment(force)
	if( rpgoCPpref["GetEquipment"] ) then
		if( force or rpgoCPstate["Equipment"]==0 or rpgoCPstate["Equipment"]~=rpgoCPstate["EquipmentScan"] ) then
			local link;
			local texture;
			rpgoCPstate["Equipment"]=0;
			rpgoCPstate["EquipmentScan"]=0;
			myProfile[rpgoCPserver][rpgoCPplayer]["Equipment"] = {};
			for index,slot in Profile_slots do
				link = GetInventoryItemLink("player", index);
				texture = GetInventoryItemTexture("player", index);
				if(link) then
					for color, item, name in string.gfind(link, "|c(%x+)|Hitem:(%d+:%d+:%d+:%d+)|h%[(.-)%]|h|r") do
						if( color~="" and item~="" and name~="" ) then
							myProfile[rpgoCPserver][rpgoCPplayer]["Equipment"][slot] = { };
							myProfile[rpgoCPserver][rpgoCPplayer]["Equipment"][slot]["Texture"] = texture;
							myProfile[rpgoCPserver][rpgoCPplayer]["Equipment"][slot]["Color"] = color;
							myProfile[rpgoCPserver][rpgoCPplayer]["Equipment"][slot]["Name"] = name;
							ProfileHiddenTooltip:SetInventoryItem("player", index);
							myProfile[rpgoCPserver][rpgoCPplayer]["Equipment"][slot]["Tooltip"] = strTooltip();
							rpgoCPstate["EquipmentScan"]=rpgoCPstate["EquipmentScan"]+1;
						end
					end
					rpgoCPstate["Equipment"]=rpgoCPstate["Equipment"]+1;
				end
			end
		end
	end
end

function rpgoCP_GetInventory()
	if( rpgoCPpref["GetInventory"] ) then
		local playerSlotSkew=19;
		local bag;
		if(not myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]) then
			myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"] = {};
			rpgoCPstate["Inventory"]={};
		end
		for bag=0,4 do
			local bagname, link, texture, color, item, itemname;
			bagname=GetBagName(bag);
			link=GetInventoryItemLink("player", (bag+playerSlotSkew));
			texture = GetInventoryItemTexture("player", (bag+playerSlotSkew));
			if(bag==0) then
				item=bagname;
				link="["..bagname.."]";
				color="ffffffff";
				texture="Interface\\Buttons\\Button-Backpack-Up";
				ProfileHiddenTooltip:SetText(bagname);
			elseif(link) then
				color,item,itemname=rpgoCP_GetItemInfo(link);
				ProfileHiddenTooltip:SetInventoryItem("player",(bag+playerSlotSkew))
			end
			if( color and item and bagname ) then
				local bagContentsTemp=nil;
				if(myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag] and myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Contents"]) then
					bagContentsTemp = myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Contents"];
				end
				myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag] = {};
				myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Name"]=bagname;
				myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Slots"]=GetContainerNumSlots(bag);
				myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Color"]=color;
				myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Texture"]=texture;
				myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Tooltip"] = strTooltip();
				myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Contents"]=bagContentsTemp;
				bagContentsTemp = nil;
				rpgoCP_GetBagItems(bag);
			else
				myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]=nil;
			end
		end
	elseif ( myProfile[rpgoCPserver][rpgoCPplayer] ) then
		myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"] = nil;
		rpgoCPstate["Inventory"]={};
	end
end

function rpgoCP_GetBank()
	if( rpgoCPpref["GetBank"]) then
		if( rpgoCPstate["BankTime"] < GetTime()-bankTimeWait) then
			if(not myProfile[rpgoCPserver][rpgoCPplayer]["Bank"]) then
				myProfile[rpgoCPserver][rpgoCPplayer]["Bank"]={};
				rpgoCPstate["Bank"]={};
			end
			local bagnum=0;
			local bagContentsTemp=nil;
			if(myProfile[rpgoCPserver][rpgoCPplayer]["Bank"]["Contents"]) then
				bagContentsTemp=myProfile[rpgoCPserver][rpgoCPplayer]["Bank"]["Contents"];
			end
			if(not rpgoCPstate["Bank"][bagnum] or not rpgoCPstate["Bank"][bagnum]["key"] or rpgoCPstate["Bank"][bagnum]["key"]~=rpgoCP_GetBagKey(BANK_CONTAINER)) then
				myProfile[rpgoCPserver][rpgoCPplayer]["Bank"]["Contents"] = rpgoCP_GetBankBagItems(0,0);
			else
				myProfile[rpgoCPserver][rpgoCPplayer]["Bank"]["Contents"]=bagContentsTemp;
				bagContentsTemp=nil;
			end
			local bag, size, slot, link;
			for bag=bankFirst,bankLast do
				bagnum = bag-4;
				bagName = "Bag" .. bagnum;
				link = GetContainerItemLink(BANK_CONTAINER, (bag+20));
				texture, itemCount, locked, quality = GetContainerItemInfo(BANK_CONTAINER, (bag+20));
				if(link) then
					color, item, bagname=rpgoCP_GetItemInfo(link);
					if( color~="" and item~="" and bagname~="" ) then
						bagContentsTemp=nil;
						if(myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName] and myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName]["Contents"]) then
							bagContentsTemp=myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName]["Contents"];
						end
						myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName] = {};
						myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName]["Name"] = bagname;
						myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName]["Slots"] = GetContainerNumSlots(bag);
						myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName]["Texture"] = texture;
						myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName]["Color"] = color;
						ProfileHiddenTooltip:SetHyperlink("item:" .. item);
						myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName]["Tooltip"] = strTooltip();
						if(not rpgoCPstate["Bank"][bagnum] or not rpgoCPstate["Bank"][bagnum]["key"] or rpgoCPstate["Bank"][bagnum]["key"]~=rpgoCP_GetBagKey(bag)) then
							myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName]["Contents"]=rpgoCP_GetBankBagItems(bag,bagnum);
						else
							myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName]["Contents"]=bagContentsTemp;
							bagContentsTemp=nil;
						end
					end
				else
					rpgoCPstate["Bank"][bagnum]=nil;
					myProfile[rpgoCPserver][rpgoCPplayer]["Bank"][bagName]=nil;
				end
			end
			rpgoCPstate["BankTime"]=GetTime();
		end
	elseif ( myProfile[rpgoCPserver][rpgoCPplayer] ) then
		myProfile[rpgoCPserver][rpgoCPplayer]["Bank"] = nil;
		rpgoCPstate["Bank"]={};
	end
end

function rpgoCP_GetBagItems(bag)
	if(not rpgoCPstate["Inventory"][bag] or not rpgoCPstate["Inventory"][bag]["key"] or rpgoCPstate["Inventory"][bag]["key"]~=rpgoCP_GetBagKey(bag)) then
		rpgoCPstate["Inventory"][bag]={};
		rpgoCPstate["Inventory"][bag]["inv"]=0;
		rpgoCPstate["Inventory"][bag]["slot"]=0;
		rpgoCPstate["Inventory"][bag]["key"]=0;
		local key=0;
		local slot, strings, str, texture, itemCount, locked, quality, link, color, item, name;
		myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Contents"] = {};
		for slot=1,GetContainerNumSlots(bag) do
			ProfileHiddenTooltip:SetBagItem(bag, slot);
			texture, itemCount, locked, quality = GetContainerItemInfo(bag,slot);
			link = GetContainerItemLink(bag, slot);
			if(link) then
				color,item,itemname=rpgoCP_GetItemInfo(link);
				if( color~="" and item~="" and itemname~="" ) then
					myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Contents"][slot] = {};
					myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Contents"][slot]["Tooltip"] = strTooltip();
					myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Contents"][slot]["Texture"] = texture;
					myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Contents"][slot]["Quantity"] = itemCount;
					myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Contents"][slot]["Name"] = itemname;
					myProfile[rpgoCPserver][rpgoCPplayer]["Inventory"]["Bag" .. bag]["Contents"][slot]["Color"] = color;
					key=key+rpgoCP_CalcItemKey(itemCount,quality,slot);
				end
				rpgoCPstate["Inventory"][bag]["inv"]=rpgoCPstate["Inventory"][bag]["inv"]+1;
			end
			rpgoCPstate["Inventory"][bag]["slot"]=rpgoCPstate["Inventory"][bag]["slot"]+1;
		end
		rpgoCPstate["Inventory"][bag]["key"]=key;
	end
end

function rpgoCP_GetBankBagItems(bag,bagnum)
	local bagContents = {};
	local key=0;
	if(bag==0) then
		bagContainer=BANK_CONTAINER;
	else
		bagContainer=bag;
	end
	rpgoCPstate["Bank"][bagnum]={};
	rpgoCPstate["Bank"][bagnum]["slot"]=0;
	rpgoCPstate["Bank"][bagnum]["inv"]=0;
	rpgoCPstate["Bank"][bagnum]["key"]=0;
	for slot=1, GetContainerNumSlots(bagContainer) do
		local link = GetContainerItemLink(bagContainer, slot);
		local texture, itemCount, locked, quality = GetContainerItemInfo(bagContainer,slot);
		if( link ) then
			color, item, name=rpgoCP_GetItemInfo(link);
			if( color~="" and item~="" and name~="" ) then
				bagContents[slot] = {};
				bagContents[slot]["Texture"] = texture;
				bagContents[slot]["Quantity"] = itemCount;
				bagContents[slot]["Name"] = name;
				bagContents[slot]["Color"] = color;
				if(bag==0) then
					ProfileHiddenTooltip:SetHyperlink("item:" .. item);
				else
					ProfileHiddenTooltip:SetBagItem(bag, slot);
				end
				bagContents[slot]["Tooltip"] = strTooltip();
				key=key+rpgoCP_CalcItemKey(itemCount,quality,slot);
			end
			rpgoCPstate["Bank"][bagnum]["inv"] = rpgoCPstate["Bank"][bagnum]["inv"]+1;
		end
		rpgoCPstate["Bank"][bagnum]["slot"] = rpgoCPstate["Bank"][bagnum]["slot"]+1;
	end
	rpgoCPstate["Bank"][bagnum]["key"]=key;
	return bagContents;
end

function rpgoCP_UpdateDate()
	myProfile[rpgoCPserver][rpgoCPplayer]["DateUpdated"] = date();
end

--[[//////////////////////////////////////////////
--	general functions
--	////////////////////////////////////////////]]
function rpgoCP_GetBagKey(bag)
	local key=0;
	local slot,texture,itemCount,locked,quality;
	for slot = 1,GetContainerNumSlots(bag) do
		texture,itemCount,locked,quality = GetContainerItemInfo(bag,slot);
		if(itemCount and quality) then
			key=key+rpgoCP_CalcItemKey(itemCount,quality,slot);
		end
	end
	return(key);
end

function rpgoCP_GetItemInfo(link)
	local c,i,n;
	if(link) then
		for c,i,n in string.gfind(link, "|c(%x+)|Hitem:(%d+:%d+:%d+:%d+)|h%[(.-)%]|h|r") do
			return c,i,n ;
		end
	else
		return c,i,n ;
	end
end

function rpgoCP_CalcItemKey(c,q,s)
	return((c*q)+s);
end

function rpgoGetMoney()
	local money = GetMoney();
	local gold,silver,copper;
	local CopperPerGold = COPPER_PER_SILVER * SILVER_PER_GOLD;
	gold = floor(money/CopperPerGold);
		money=mod(money,CopperPerGold);
	silver = floor(money/COPPER_PER_SILVER);
		money=mod(money,CopperPerGold);
	copper = mod(money,COPPER_PER_SILVER);
	return gold,silver,copper
end

function strTooltip()
	local strings = ScanTooltip("ProfileHiddenTooltip");
	local str = {};
	local htmlstr = nil;
	for i=1, getn(strings) do
		if (not strings[i].right) then
			strings[i].right = "";
		else
			strings[i].right = "\t" .. strings[i].right;
		end
		str[i] = string.gsub(string.gsub(strings[i].left .. strings[i].right, "\n", "<br>"), "\r", "");
		if ( htmlstr ) then
			htmlstr = htmlstr .. "<br>" .. strings[i].left .. strings[i].right;
		else
			htmlstr = strings[i].left .. strings[i].right;
		end
	end
	--ClearTooltip("ProfileHiddenTooltip");
	ProfileHiddenTooltip:ClearLines();
	if ( rpgoCPpref["HTML_Tooltips"] and htmlstr ) then
		return string.gsub(string.gsub(htmlstr, "\n", "<br>"), "\r", "");
	else
		return str;
	end
end

-- From CosmosCommonFunctions.lua
-- Clears a tooltip for usage.
function ClearTooltip(TooltipNameBase)
	for i=1, 15, 1 do
		getglobal(TooltipNameBase.."TextLeft"..i):SetText("");
		getglobal(TooltipNameBase.."TextRight"..i):SetText("");
	end
end

-- From CosmosCommonFunctions.lua
-- Gets all lines out of a tooltip.
function ScanTooltip(TooltipNameBase)
	if ( TooltipNameBase == nil ) then
		TooltipNameBase = "ProfileHiddenTooltip";
	end

	local strings = {};
	for idx = 1, 20 do
		local textLeft = nil;
		local textRight = nil;
		ttext = getglobal(TooltipNameBase.."TextLeft"..idx);
		if(ttext and ttext:IsVisible() and ttext:GetText() ~= nil)
		then
			textLeft = ttext:GetText();
		end
		ttext = getglobal(TooltipNameBase.."TextRight"..idx);
		if(ttext and ttext:IsVisible() and ttext:GetText() ~= nil)
		then
			textRight = ttext:GetText();
		end
		if (textLeft or textRight)
		then
			strings[idx] = {};
			strings[idx].left = textLeft;
			strings[idx].right = textRight;
		end
	end
	return strings;
end

if (not fixnilempty) then
	fixnilempty = function(...)
	  for i=1, arg.n, 1 do
	    if(not arg[i]) then
	      arg[i] = "";
	    end
	  end
	  return arg;
	end
end

function round(x)
  if(x - math.floor(x) > 0.5) then
    x = x + 0.5;
  end
  return math.floor(x);
end

--[[//////////////////////////////////////////////
--	general rpgo functions
--	////////////////////////////////////////////]]
-- USAGE: rpgoCP_debug(msg)
function rpgoCP_debug(msg)
	if (rpgoCPdebug) then
		if(rpgoDebug) then rpgoDebug("CP",msg);
		else DEFAULT_CHAT_FRAME:AddMessage("rpgoCP: [" .. msg .. "]",1,0,0); end
	end
end
-- USAGE: rpgo_ColorizeTitle(provider,title)
if (not rpgo_ColorizeTitle) then rpgo_ColorizeTitle=function(provider,title) if(provider and title) then return rpgo_ColorizeMsg(rpgoColorTitle,provider.."-"..title); end end end
-- USAGE: rpgo_ColorizeMsg(color,msg)
if (not rpgo_ColorizeMsg) then rpgo_ColorizeMsg=function(color,msg) if(color and msg) then return "|cff"..color..msg.."|r"; end end end
