Global ('Self', nil );
Global ('SelfName', '');

function inTable(tbl, item)
    for key, value in pairs(tbl) do
        if value == item then return key end
    end
    return false
end

function GetCooldown (itemId) 
	local info = avatar.GetItemInfo( itemId );
	local spellInfo = avatar.GetSpellInfo( info.spellId )			
	return spellInfo.cooldownRemainingMs;
end

function Now()
	return common.GetLocalDateTime();
end

function TimeToStr(dt)
	return dt.h..':'..dt.min..':'..dt.s;
end

function WStringToString(WString)
	if (not WString) then return ""; end
	return userMods.FromWString(WString);
end

function GetCooldownString ( msec )
	local out = '';
	local count = SplitTime( msec );
	if count.hours > 1 then
		out =  WStringToString(common.FormatInt( math.ceil( count.hours ), "%d" ))..'h';
	elseif count.minutes > 1 then
		out = WStringToString(common.FormatInt( math.ceil( count.minutes ), "%d" ))..'m';
	else
		out =  WStringToString(common.FormatInt( Round( count.seconds ), "%d" ))..'s';
	end
	
	return out;
end

function SetBackgroundTextureFromItem(widget, itemId )
	local resourceId = avatar.GetItemResourceId( itemId );
	local resourceInfo = avatar.GetItemResourceInfo( resourceId );
	local texture = resourceInfo.image;
	widget:SetBackgroundTexture(texture);
end

function SetButtonCaption ( widget, caption )
	widget:SetVal('button_label', userMods.ToWString(tostring(caption)));
end

function GetItemCount( itemId )
	local info = avatar.GetItemInfo( itemId );
	return info.stackCount;
end

function GetUnitName(id)
	if (not id) then
		return "";
	end
	
	local wStr = object.GetName(id);
	return WStringToString(wStr);
end

function GetItemName ( itemId )
	local valuedObject = avatar.GetItemValuedObject( itemId );
	return WStringToString(valuedObject:GetText());
end

function InitAvatar()
	if Self then 
		return false;
	end 
	
	if not avatar.IsExist() then
		return false;
	end
	
	Self = avatar.GetId();
	SelfName = GetUnitName(Self);
	return true;
end
