--##########################################################
if(not rpgo) then rpgo={}; end
if(not rpgo.colorTitle) then rpgo.colorTitle="909090"; end
if(not rpgo.colorGreen) then rpgo.colorGreen="00cc00"; end
if(not rpgo.colorRed)   then rpgo.colorRed  ="ff0000"; end

--[function] str
function rpgo.round(num,digit)
	if(not tonumber(num)) then return nil; end
	if(digit==nil) then digit=0; end
--	local shift=10^digit;
--	return floor( num*shift + 0.5 ) / shift;
	local fmt
	if(digit<10) then fmt="%.0"..digit.."f";
	else fmt="%."..digit.."f"; end
	return format(fmt,num);
end

--[function] str
function rpgo.version()
	local version,buildnum,builddate = GetBuildInfo();
	local _,_,vVersion,vMajor,vMinor=string.find(version,"(%d+).(%d+).(%d+)");
	return tonumber(vVersion),tonumber(vMajor),tonumber(vMinor);
end
function rpgo.versionkey()
	local version,buildnum,builddate = GetBuildInfo();
	return strjoin(":", rpgo.GetSystem(),version,buildnum);
end
function rpgo.updateDate(struct)
	if ( not struct["timestamp"] ) then struct["timestamp"]={}; end
	local timestamp = time();
	local currHour,currMinute=GetGameTime();
	struct["timestamp"]["init"]={};
	struct["timestamp"]["init"]["TimeStamp"]=timestamp;
	struct["timestamp"]["init"]["Date"]=date("%Y-%m-%d %H:%M:%S",timestamp);
	struct["timestamp"]["init"]["DateUTC"]=date("!%Y-%m-%d %H:%M:%S",timestamp);
	struct["timestamp"]["init"]["ServerTime"]=format("%02d:%02d",currHour,currMinute);
	struct["timestamp"]["init"]["datakey"]=rpgo.versionkey();
end

function rpgo.date2Epoch(datestr)
	local epoch;
	if(datestr) then
		local _,_,y,m,d,h,n,s=string.find(datestr,"(%d%d%d%d)-(%d%d)-(%d%d) (%d%d):(%d%d):(%d%d)");
		epoch = time( {year=y,month=m,day=d,hour=h,min=n,sec=s} );
	end
	return epoch;
end

--[[########################################################
--## scan functions
--######################################################--]]
--[scanColor] str
function rpgo.scanIconFix(str)
	if(not str) then return str; end
	return table.remove({ strsplit("\\", str) });
end
--[scanIconRaw] str
function rpgo.scanIconRaw(str) return str; end

--[scanColor] str
function rpgo.scanColorFix(str)
	if(not str) then return str; end
	local c;
	_,_,c = string.find(str,"%x%x(%x%x%x%x%x%x)");
	return c
end
--[function] str
function rpgo.scanColorRaw(str) return str; end

--[[########################################################
--## tooltip functions
--######################################################--]]
--[function]
function rpgo.SetTooltip(text)
	if(text) then
		GameTooltip:SetOwner(this,"ANCHOR_BOTTOMRIGHT");
		GameTooltip:SetText(text);
	end
end
--[scanTooltip] tooltipName
function rpgo.ScanTooltip(tooltipName,isHTML)
	tooltipFrame=getglobal(tooltipName);
	local ttTextScan={};
	for idx=1,tooltipFrame:NumLines() do
		local ttTextBuff=nil;
		ttText=getglobal(tooltipName.."TextLeft"..idx);
		if(ttText and ttText:IsShown()) then
			ttTextBuff=ttText:GetText();
			if (ttText) then
				ttTextBuff=string.gsub(ttTextBuff,"\n","<br>");
				ttTextBuff=string.gsub(ttTextBuff,"\r","");
			end
		end
		ttText=getglobal(tooltipName.."TextRight"..idx);
		if(ttText and ttText:IsShown() and ttText:GetText()) then
			ttTextBuff=ttTextBuff.."\t"..ttText:GetText();
		end
		if(ttTextBuff) then table.insert(ttTextScan,ttTextBuff); end
	end
	tooltipFrame:ClearLines();
	if(isHTML) then return table.concat(ttTextScan,"<br>");
	else return ttTextScan; end
end

--[[########################################################
--## item functions
--######################################################--]]
--[function] itemlink
function rpgo.GetItemID(itemlink)
	local item,id,rid;
	if(itemlink) then _,_,item,id,rid=string.find(itemlink,"item:((%d+):%d+:(%d+):%d+:%d+:%d+:%d+:%d+)|"); end
	return item,id,rid;
end
--[function] itemlink
function rpgo.GetItemInfo(itemlink)
	if(itemlink) then
		local itemColor,itemID,itemName,itemLink,itemRarity,itemLevel,itemMinLevel,itemType,itemSubType,itemStackCount,itemEquipLoc,invTexture
		itemName,itemLink,itemRarity,itemLevel,itemMinLevel,itemType,itemSubType,itemStackCount,itemEquipLoc,invTexture = GetItemInfo(itemlink);
		if(itemLink) then
			_,_,itemColor,_,itemID,_=string.find(itemLink,"|c(%x+)|H(item:(%d+:%d+:%d+:%d+:%d+:%d+:%d+:%d+))|h%[(.-)%]|h|r");
		end
		return itemColor,itemLink,itemID,itemName;
	end
	return nil;
end
--[function] tooltip iteminfo
function rpgo.GetItemInfoTT(tooltipName)
	local nTT,cTT,r,g,b;
	if(tooltipName==nil) then tooltipName="rpgoCPtooltip"; end
	ttText=getglobal(tooltipName.."TextLeft1");
	if(ttText) then
		nTT=ttText:GetText();
	end
	if(nTT) then r,g,b=ttText:GetTextColor(); cTT=string.format("ff%02x%02x%02x",r*256,g*256,b*256); end
	return nTT,cTT;
end

--[[########################################################
--## string functions
--######################################################--]]
--[function] str
function rpgo.stripColor(str)
	local function strippingHelper(word) return string.gsub(word,"|c%x%x%x%x%x%x%x%x(.-)|r","%1") end
	if(type(str)=="table") then
		for i=1,table.getn(str),1 do
			str[i]=strippingHelper(str[i]);
		end
	else str=strippingHelper(str); end
	return str;
end
--[function] str
function rpgo.GetSystem()
	local _,_,sys=string.find(GetCVar("realmList"),"^[%a.]-(%a+).%a+.%a+.%a+$");
	if(not sys) then sys="" end return sys;
end
--[function] str
function rpgo.Str2Ary(str)
	local tab={};
	local function S2Ahelper(word) table.insert(tab,word) end
	string.gsub(str,"%w+",S2Ahelper); return tab; end
--[function] str
function rpgo.Str2Abbr(str)
	local abbr='';
	local function S2Ahelper(word) abbr=abbr..string.sub(word,1,1) end
	if not string.find(string.gsub(str,"%w+",S2Ahelper),"%S") then return abbr end end
--[function] arg:key.1,key.n,val.1,val.n
function rpgo.Arg2Tab(...)
	local tab={};
	local split=floor( select("#",...) /2);
	for i=1,split do tab[select(i,...)]=select(i+split,...); end
	return tab; end
--[function] arg:arg.1,arg.n
function rpgo.Arg2Ary(...)
	local tab={};
	for i=1,select("#",...) do tab[i]=select(i,...); end
	return tab; end
--[RegisterEvents] [table]events, [bool]val
function rpgo.RegisterEvents( self, val )
	if (not self or not self.events or not self.FRAME ) then return end
	if( val ) then
		for index,event in pairs(self.events) do
			self.FRAME:RegisterEvent(event); end
	else
		for index,event in pairs(self.events) do
			self.FRAME:UnregisterEvent(event); end
	end
end

--[[########################################################
--## helper functions
--######################################################--]]
--[liteScan] [self.pref.lite]
function rpgo.liteScan(self)
	if(not self or not self.pref or not self.pref.lite) then return false; end
	local msg;
	if(UnitInRaid("player")) then msg="raid";
	elseif(rpgo.isInInstance()) then msg="instance"; end
	if(msg) then
		if(not self.state["_litemsg"]) then
			rpgo.PrintTitle(self,"scan skipped: character is in "..msg);
			self.state["_litemsg"]=true;
		end
		return true;
	end
	return false;
end

--[isInInstance]
function rpgo.isInInstance()
	SetMapToCurrentZone();
	a,b=GetPlayerMapPosition("player");
	if(a==0 and b==0) then return true; else return nil; end end

--[[########################################################
--## Pref functions
--######################################################--]]
--[InitPref] structPref,structDefault
function rpgo.PrefInit(structPref,structDefault)
	for pref,val in pairs(structDefault) do
		if(type(structDefault[pref])=="table") then
			if(not structPref[pref]) then
				structPref[pref]={};
			end
			rpgo.PrefInit(structPref[pref],structDefault[pref]);
		elseif(structPref[pref] == nil) then
			structPref[pref]=val;
		end
	end
end
--[TidyPref] structPref,structDefault
function rpgo.PrefTidy(structPref,structDefault)
	for pref,val in pairs(structPref) do
		if(type(structDefault[pref])=="table") then rpgo.PrefTidy(structPref[pref],structDefault[pref]);
		elseif(structDefault[pref] == nil) then structPref[pref]=nil; end end end
--[function] togglePref
rpgo.TogglePref = function(struct,pref,val)
	local retval=nil;
	if(val and type(var)=="string") then val=string.lower(val); end;
	if(val=="on") then val=true;
	elseif(val=="off") then val=false; end
	if(type(val)=="boolean" and struct[pref]~=val) then
		struct[pref]=val; retval=true;
	else retval=false; end
	return retval
end
--[function] pref
rpgo.PrefColorize = function(pref)
	if(pref) then return rpgo.StringColorize(rpgo.colorGreen,"on|r")
	else return rpgo.StringColorize(rpgo.colorRed,"off|r") end end

--[[########################################################
--## rpgo lib: print functions
--######################################################--]]
--[AssempleHelp] (helpline)
function rpgo.AssempleHelp(helpline)
	local msg; if(type(helpline)=="table") then
		msg="  |cff"..rpgo.colorTitle..helpline[1].."|r     "..helpline[2];
		if(helpline[3]) then msg=msg.."\n     "..helpline[3]; end
		else msg=helpline; end
		return msg; end

--[StringColorize] color,msg
rpgo.StringColorize = function(color,msg)
	if(color and msg) then
		return "|cff"..color..msg.."|r";
	end
end

--[PrintMsg] self,msg
function rpgo.PrintMsg(...)
	if(not select("#",...)) then return end
	DEFAULT_CHAT_FRAME:AddMessage(...);
end

--[PrintTitle] self,msg
function rpgo.PrintTitle(self,msg,title,version)
	if(not self) then return end
	if(not msg or msg==nil) then msg="" else msg=" "..msg end
	local tmsg="";
	if(self["PROVIDER"]) then
		tmsg = self["PROVIDER"];
	end
	if(title and self["TITLE"]) then
		tmsg = tmsg.."-"..self["TITLE"];
	elseif(self["ABBR"]) then
		tmsg = tmsg.."-"..self["ABBR"];
	end
	if(rpgo and rpgo.colorTitle) then
		tmsg = "|cff"..rpgo.colorTitle..tmsg.."|r";
	end
	if(version and self["VERSION"]) then
		tmsg = tmsg.." [v" .. self["VERSION"] .. "]";
	end
	DEFAULT_CHAT_FRAME:AddMessage(tmsg..msg);
end

--[PrintUsage] [self,self.usage]
function rpgo.PrintUsage(self)
	if(self.usage) then
		rpgo.PrintTitle(self,"Usage",true,true);
		for index=1,table.getn(self.usage),1 do
			rpgo.PrintMsg(rpgo.AssempleHelp(self.usage[index]));
		end
	end
end

--[PrintDebug] self,msg
function rpgo.PrintDebug(self,...)
	if(self and self.pref and self.pref.debug) then
		local i;
		local msg={};
		local tmsg="";
		if(self["PROVIDER"]) then
			tmsg = tmsg..self["PROVIDER"];
		end
		if(self["ABBR"]) then
			tmsg = tmsg..self["ABBR"];
		end
		tmsg = tmsg..">"
		if(rpgo and rpgo.colorTitle) then
			tmsg = "|cff"..rpgo.colorTitle..tmsg.."|r";
		end
		for i=1,select("#",...) do msg[i]=select(i,...); end
		if( msg ) then
			tmsg = tmsg .. " ".."[" .. table.concat(msg,":") .. "]";
		end
		if(not RPGODEBUG_FRAME) then
			for i=1,NUM_CHAT_WINDOWS do
				local name,fontSize,r,g,b,alpha,shown,locked,docked = GetChatWindowInfo(i);
				if( name == "debug" ) then
					RPGODEBUG_FRAME = getglobal("ChatFrame"..i);
				end
			end
			if(not RPGODEBUG_FRAME) then RPGODEBUG_FRAME = DEFAULT_CHAT_FRAME end
		end
		RPGODEBUG_FRAME:AddMessage(tmsg,.8,.8,.8);
	end
end
