--[[

	Status Mod 2

]]

-- Configuration variables
local MilitaryTime = 0;		-- set this to something other than nil to use 24-hour display
local OffsetHour = 0;			-- this is the hour offset applied to server time
local OffsetMinute = 0;			-- this is the minute offset applied to server time
local ShowSeconds = 0;			-- set this to 1 to enable timestamping of seconds
local HideExp = 0;				-- set this to 1 to hide xp
local HideDura = 0;
local HideClock = 0;
local HideGold = 0;

-- Constants
STATSMOD2_UPDATE_RATE = 0.1;

local StatsMod2_PopupOnMouseOver = true;

-- Local variables

local TotalTimePlayed = 0;
local LevelTimePlayed = 0;
local SessionTimePlayed = 0;
local ElapsedSinceLastPlayedMessage = 0;
local NeedPlayedMessage = 1;

local localInitialXP;
local localSessionXP = 0;
local localRolloverXP = 0;

local localHealthSecondTimer = 0;
local localInitialHealth;
local localHealthPerSecond;
local localManaSecondTimer = 0;
local localInitialMana;
local localManaPerSecond;

local localInCombat;
local localTravelTime = 0;
local localTravelDist = 0;

local localSpeed = 0;
local localSpeedDist = 0;
local localSpeedTime = 0;

-- added by max for seconds
local SecondCount = 0;
local LastMinute = 0;
local CurrentSecond = 0;
local InitialRun = 1;
local UpdateTime = 0; 

-- added by sarf for money
local StatsMod2_ShowMoney = 0;
local localMoneyOld = nil;
local localMoneyIncreases = 0;

-- added by Arbi for durability
local localBagupdate = nil
local localCurrPercent = 0;
local StatsMod2_Armor_value = 0;
local StatsMod2_Armor_max = 0;
local StatsMod2_Armor_cost = 0;

local DurStatus_Slots = {
	{ name = INVTYPE_HEAD, slot = "Head" },
	{ name = INVTYPE_SHOULDER, slot = "Shoulder" },
	{ name = INVTYPE_CHEST, slot = "Chest" },
	{ name = INVTYPE_WAIST, slot = "Waist" },
	{ name = INVTYPE_LEGS, slot = "Legs" },
	{ name = INVTYPE_FEET, slot = "Feet" },
	{ name = INVTYPE_WRIST, slot = "Wrist" },
	{ name = INVTYPE_HAND, slot = "Hands" },
	{ name = INVTYPE_WEAPONMAINHAND, slot = "MainHand" },
	{ name = INVTYPE_WEAPONOFFHAND, slot = "SecondaryHand" },
	{ name = INVTYPE_RANGED, slot = "Ranged" },
	{ name = INVENTORY_TOOLTIP },
}

-- Local functions
local function StatsMod2_ResetHealth()
	localHealthSecondTimer = 0;
	localInitialHealth = UnitHealth("player");
end

local function StatsMod2_ResetMana()
	localManaSecondTimer = 0;
	localInitialMana = UnitMana("player");
end

-- Callback functions
function ToggleStatsMod2()
	if( StatsMod2Frame:IsVisible() ) then
		HideUIPanel(StatsMod2Frame);
	else
		ShowUIPanel(StatsMod2Frame);
	end
end

function StatsMod2_Display(toggle)
	if ( toggle == 1 ) then 
		StatsMod2Frame:Show();
	else
		StatsMod2Frame:Hide();
	end
end

function ResetClockPosition(setval, checked)
	StatsMod2Frame:ClearAllPoints();
	StatsMod2Frame:SetPoint("TOP", "UIParent", "TOP", 0, 0);
end

function ClockFormat(checked)
	MilitaryTime = checked;
end
function ClockHideExp(checked)
	HideExp = checked;
end

function ClockOffset(checked,value)
	local offset = value;
	if( OffsetHour > 0 ) then
		OffsetHour = math.floor(offset);
	else
		OffsetHour = math.ceil(offset);
	end
	OffsetMinute = (value - OffsetHour) * 60;
end

-- added 2005-01-13 by arys
function ClockRoundTravelSpeed(checked)
	StatsMod2_RoundTravelSpeed = checked;
end

function DuraEnable(toggle)
	if ( toggle == 1 ) then
		HideDura = 0;
		StatsMod2FrameDurButton:Show();
	else
		HideDura = 1;
		StatsMod2FrameDurButton:Hide();
	end
	StatsMod2_InitElements();
end

function ClockEnable(toggle)
	if ( toggle == 1 ) then
		HideClock = 0;
		StatsMod2FrameClockButton:Show();
	else
		HideClock = 1;
		StatsMod2FrameClockButton:Hide();
	end
	StatsMod2_InitElements();
end

function GoldEnable(toggle)
	if ( toggle == 1 ) then
		HideGold = 0;
		StatsMod2FrameGoldButton:Show();
		StatsMod2FrameSilverButton:Show();
		StatsMod2FrameCopperButton:Show();
	else
		HideGold = 1;
		StatsMod2FrameGoldButton:Hide();
		StatsMod2FrameSilverButton:Hide();
		StatsMod2FrameCopperButton:Hide();
	end
	StatsMod2_InitElements();
end

function StatsMod2_DisableLegacy()
	if ( ( StatsModFrame and StatsModFrame:IsShown() ) or ( StatsModCashFrame and StatsModCashFrame:IsShown() ) ) then
		Cosmos_SetCVar("COS_STATSMOD_ENABLE_X", 0);
		Cosmos_SetCVar("COS_STATSMOD_CASH_ENABLE_X", 0);
		StatsModDisplay(0);
		StatsModCashToggle(0);
	end
	if ( ClockFrame and ClockFrame:IsShown() ) then
		Cosmos_SetCVar("COS_CLOCK_ENABLE_X", 0);
		ClockDisplay(0);
	end
end

function StatsMod2_RegisterCosmosOptions()
	if( Cosmos_RegisterConfiguration ~= nil ) then
		Cosmos_RegisterConfiguration("COS_STMOD2",
			"SECTION",
			STMOD2_OPTION_HEADER,
			STMOD2_OPTION_HEADER_INFO
		);
		Cosmos_RegisterConfiguration("COS_STMOD2_GENERAL_SECTION",
			"SEPARATOR",
			STMOD2_OPTION_GENERAL_HEADER,
			STMOD2_OPTION_GENERAL_HEADER_INFO
			);
		Cosmos_RegisterConfiguration("COS_STMOD2_ENABLE",
			"CHECKBOX",
			STMOD2_OPTION_ENABLE, 
			STMOD2_OPTION_ENABLE_INFO,
			StatsMod2_Display,
			1,
			0
		);
		Cosmos_RegisterConfiguration("COS_STMOD2_RESET_POSITION",
			"BUTTON",
			STMOD2_OPTION_RESET_POSITION,
			STMOD2_OPTION_RESET_POSITION_INFO,
			ResetClockPosition,
			0,
			0,
			0,
			0,
			STMOD2_OPTION_RESET_POSITION_NAME
			);
		Cosmos_RegisterConfiguration("COS_STMOD2_CLOCK_SECTION",
			"SEPARATOR",
			STMOD2_OPTION_CLOCK_HEADER,
			STMOD2_OPTION_CLOCK_HEADER_INFO
			);
		Cosmos_RegisterConfiguration("COS_STMOD2_CLOCK_ENABLE",
			"CHECKBOX",
			STMOD2_CLOCK_OPTION_ENABLE,
			STMOD2_CLOCK_OPTION_ENABLE_INFO,
			ClockEnable,
			1,
			0
		);
		Cosmos_RegisterConfiguration("COS_STMOD2_CLOCK_SECONDS_ENABLE",
			"CHECKBOX",
			STMOD2_CLOCK_OPTION_SECONDS,
			STMOD2_CLOCK_OPTION_SECONDS_INFO,
			StatsMod2_DisplaySeconds,
			0,
			0
		);
		Cosmos_RegisterConfiguration("COS_STMOD2_CLOCK_MONEY",
			"CHECKBOX",
			STMOD2_CLOCK_OPTION_MONEY,
			STMOD2_CLOCK_OPTION_MONEY_INFO,
			StatsMod2_ToggleDisplayMoney,
			0,
			0
		);
		Cosmos_RegisterConfiguration("COS_STMOD2_CLOCK_OFFSET",
			"SLIDER",
			STMOD2_CLOCK_OPTION_TIME_OFFSET,
			STMOD2_CLOCK_OPTION_TIME_OFFSET_INFO,
			ClockOffset,
			0,
			0,
			-12,
			12,
			STMOD2_CLOCK_OPTION_TIME_OFFSET_SLID_1,
			0.5,
			1,
			STMOD2_CLOCK_OPTION_TIME_OFFSET_SLID_2,
			1
			);
		Cosmos_RegisterConfiguration("COS_STMOD2_CLOCK_TWENTYFOUR_HOURS",
			"CHECKBOX",
			STMOD2_CLOCK_OPTION_TWENTYFOUR_HOURS,
			STMOD2_CLOCK_OPTION_TWENTYFOUR_HOURS_INFO,
			ClockFormat,
			0,
			1
			);
		Cosmos_RegisterConfiguration("COS_STMOD2_CLOCK_HIDE_EXP",
			"CHECKBOX",
			STMOD2_CLOCK_OPTION_HIDE_EXP,
			STMOD2_CLOCK_OPTION_HIDE_EXP_INFO,
			ClockHideExp,
			0,
			1
		);
		Cosmos_RegisterConfiguration("COS_STMOD2_CLOCK_RESET_DATA",
			"BUTTON",
			STMOD2_CLOCK_OPTION_RESET_DATA,
			STMOD2_CLOCK_OPTION_RESET_DATA_INFO,
			StatsMod2_ResetData,
			0,
			0,
			0,
			0,
			STMOD2_CLOCK_OPTION_RESET_DATA_NAME
		);
		Cosmos_RegisterConfiguration(
			"COS_STMOD2_CLOCK_POPUPONMOUSEOVER",
			"CHECKBOX",
			STMOD2_CLOCK_OPTION_POPUPONMOUSEOVER, 
			STMOD2_CLOCK_OPTION_POPUPONMOUSEOVER_INFO,
			ClockPopupOnMouseOver,
			1,
			1
		);
		Cosmos_RegisterConfiguration("COS_STMOD2_DURA_SECTION",
			"SEPARATOR",
			STMOD2_OPTION_DURA_HEADER,
			STMOD2_OPTION_DURA_HEADER_INFO
		);
		Cosmos_RegisterConfiguration("COS_STMOD2_DURA_ENABLE",
			"CHECKBOX",
			STMOD2_OPTION_DURA_ENABLE,
			STMOD2_OPTION_DURA_ENABLE_INFO,
			DuraEnable,
			1,
			0
		);
		Cosmos_RegisterConfiguration("COS_STMOD2_GOLD_SECTION",
			"SEPARATOR",
			STMOD2_OPTION_GOLD_HEADER,
			STMOD2_OPTION_GOLD_HEADER_INFO
		);
		Cosmos_RegisterConfiguration("COS_STMOD2_GOLD_ENABLE",
			"CHECKBOX",
			STMOD2_OPTION_GOLD_ENABLE,
			STMOD2_OPTION_GOLD_ENABLE_INFO,
			GoldEnable,
			1,
			0
		);
	end
end

function StatsMod2_InitElements()
	if ( HideDura == 0 and HideClock == 1 and HideGold == 0 ) then
		StatsMod2Frame:Show();
		StatsMod2Frame:SetWidth(220);
		StatsMod2FrameGoldButtonText:ClearAllPoints();
		StatsMod2FrameGoldButtonText:SetPoint("TOPLEFT", StatsMod2FrameDurButton, 70, 2);
		StatsMod2_SortMoney();
	elseif ( HideDura == 0 and HideClock == 0 and HideGold == 1 ) then
		StatsMod2Frame:Show();
		StatsMod2Frame:SetWidth(170);
		StatsMod2FrameClockButton:ClearAllPoints();
		StatsMod2FrameClockButton:SetPoint("TOPLEFT", StatsMod2FrameDurButton, 80, 0);
	elseif ( HideDura == 0 and HideClock == 1 and HideGold == 1 ) then
		StatsMod2Frame:Show();
		StatsMod2Frame:SetWidth(95);
	elseif ( HideDura == 0 and HideClock == 0 and HideGold == 1 ) then
		StatsMod2Frame:Show();
		StatsMod2Frame:SetWidth(165);
		StatsMod2FrameClockButton:ClearAllPoints();
		StatsMod2FrameClockButton:SetPoint("TOPLEFT", StatsMod2FrameDurButton, 80, 0);
	elseif ( HideDura == 1 and HideClock == 0 and HideGold == 0 ) then
		StatsMod2Frame:Show();
		StatsMod2Frame:SetWidth(210);
		StatsMod2FrameClockButton:ClearAllPoints();
		StatsMod2FrameClockButton:SetPoint("TOPLEFT", StatsMod2Frame, 10, -9);
		StatsMod2FrameGoldButtonText:ClearAllPoints();
		StatsMod2FrameGoldButtonText:SetPoint("TOPLEFT", StatsMod2FrameClockButton, 60, 2);
		StatsMod2_SortMoney();
	elseif ( HideDura == 1 and HideClock == 1 and HideGold == 0 ) then
		StatsMod2Frame:Show();
		StatsMod2Frame:SetWidth(150);
		StatsMod2FrameGoldButtonText:ClearAllPoints();
		StatsMod2FrameGoldButtonText:SetPoint("TOPLEFT", StatsMod2Frame, 10, -7);
		StatsMod2_SortMoney();
	elseif ( HideDura == 1 and HideClock == 0 and HideGold == 1 ) then
		StatsMod2Frame:Show();
		StatsMod2Frame:SetWidth(120);
		StatsMod2FrameClockButton:ClearAllPoints();
		StatsMod2FrameClockButton:SetPoint("TOPLEFT", StatsMod2Frame, 30, -9);
	elseif ( HideDura == 1 and HideClock == 1 and HideGold == 1 ) then
		StatsMod2Frame:Hide();
	else
		StatsMod2Frame:Show();
		StatsMod2Frame:SetWidth(290);
		StatsMod2FrameClockButton:ClearAllPoints();
		StatsMod2FrameClockButton:SetPoint("TOPLEFT", StatsMod2FrameDurButton, 80, 0);
		StatsMod2FrameGoldButtonText:ClearAllPoints();
		StatsMod2FrameGoldButtonText:SetPoint("TOPLEFT", StatsMod2FrameClockButton, 60, 2);
		StatsMod2_SortMoney();
		localBagupdate = 0;
	end
end

function StatsMod2_SortMoney()
	StatsMod2FrameSilverButtonText:ClearAllPoints();
	StatsMod2FrameSilverButtonText:SetPoint("TOPLEFT", StatsMod2FrameGoldButtonIcon, 0, 2);
	StatsMod2FrameCopperButtonText:ClearAllPoints();
	StatsMod2FrameCopperButtonText:SetPoint("TOPLEFT", StatsMod2FrameSilverButtonIcon, 0, 1);
end

-- OnFoo functions
function StatsMod2_OnLoad()
	this:RegisterEvent("UPDATE_INVENTORY_ALERTS"); --update inventory
	this:RegisterEvent("VARIABLES_LOADED");
	this:RegisterEvent("PLAYER_MONEY");
	this:RegisterEvent("TIME_PLAYED_MSG");
	this:RegisterEvent("PLAYER_LEVEL_UP");
	this:RegisterEvent("PLAYER_ENTERING_WORLD");
	this:RegisterEvent("PLAYER_XP_UPDATE");
	this:RegisterEvent("UNIT_HEALTH");
	this:RegisterEvent("UNIT_MANA");
	this:RegisterEvent("PLAYER_ENTER_COMBAT");
	this:RegisterEvent("PLAYER_LEAVE_COMBAT");
	this:RegisterEvent("PLAYER_DEAD");--bagupdate
	this:RegisterEvent("PLAYER_UNGHOST"); --bagupdate
	this:RegisterEvent("PLAYER_REGEN_ENABLED");---bagupdate
	this:RegisterEvent("UNIT_INVENTORY_CHANGED"); --update inventory
	this:RegisterEvent("MERCHANT_SHOW");
	this:RegisterEvent("MERCHANT_CLOSED");
	
	StatsMod2Frame.TimeSinceLastUpdate = 0;
	
	StatsMod2_DisableLegacy();
	StatsMod2_RegisterCosmosOptions();
	
	if ( Chronos ) then
		Chronos.afterInit(StatsMod2_RetrieveCurrentMoneyOnStart);
	end
end

function StatsMod2_OnUpdate(arg1)
	StatsMod2_ShowSeconds_DoUpdate(arg1);
	SessionTimePlayed = SessionTimePlayed + arg1;
	ElapsedSinceLastPlayedMessage = ElapsedSinceLastPlayedMessage + arg1;
	localHealthSecondTimer = localHealthSecondTimer + arg1;
	localManaSecondTimer = localManaSecondTimer + arg1;
	
	if( localHealthSecondTimer >= 1 and localInitialHealth ) then
		if( UnitHealth("player") < UnitHealthMax("player") ) then
			local hps = UnitHealth("player") - localInitialHealth;
			if( hps > 0 ) then
				localHealthPerSecond = hps / localHealthSecondTimer;
			end
		end
		StatsMod2_ResetHealth();
	end
	
	if( localManaSecondTimer >= 1 and localInitialMana ) then
		if( UnitMana("player") < UnitManaMax("player") ) then
			local mps = UnitMana("player") - localInitialMana;
			if( mps > 0 ) then
				localManaPerSecond = mps / localManaSecondTimer;
			end
		end
		StatsMod2_ResetMana();
	end
	
	StatsMod2Frame.TimeSinceLastUpdate = StatsMod2Frame.TimeSinceLastUpdate + arg1;
	if( StatsMod2Frame.TimeSinceLastUpdate > STATSMOD2_UPDATE_RATE ) then
		StatsMod2_DisplayMoney();
		StatsMod2FrameClockButtonText:SetText(StatsMod2_GetTimeText());
		StatsMod2Frame.TimeSinceLastUpdate = 0;
	end
	
	--BAG_UPDATE
	if(localBagupdate) then
		--update the lapse
		localBagupdate = localBagupdate - arg1;

		--check if the timer ran out
		if ( localBagupdate <= 0 ) then
			StatsMod2_BagUpdate();
			localBagupdate = nil;
		end
	end
end

function StatsMod2_OnEvent()
	if (event == "VARIABLES_LOADED") then
		StatsMod2_BagUpdate();
	end
	if( event == "PLAYER_MONEY" ) then
		StatsMod2_UpdateMoney();
		--StatsMod2_CheckTenThousand();
		return;
	end
	if (event == "PLAYER_ENTERING_WORLD") then
		--StatsMod2_CheckTenThousand();
		this:RegisterEvent("UPDATE_INVENTORY_ALERTS");
		return;
	end

	if (event == "PLAYER_LEAVING_WORLD") then
		this:UnregisterEvent("UPDATE_INVENTORY_ALERTS");
		return;
	end
	if (event == "PLAYER_ENTERING_WORLD" or event == "UPDATE_INVENTORY_ALERTS" or event == "PLAYER_REGEN_ENABLED" 
			or event == "PLAYER_UNGHOST" or event == "PLAYER_DEAD" 
			or (CanMerchantRepair() and event == "PLAYER_MONEY") 
			or (event == "UNIT_INVENTORY_CHANGED" and arg1 == "player")) then
		if (HideDura == 1) then
			return;
		end
		if((CanMerchantRepair() and localCurrPercent < 100) or event == "PLAYER_REGEN_ENABLED" or event == "UNIT_INVENTORY_CHANGED") then
			if (event == "PLAYER_MONEY" or event == "PLAYER_REGEN_ENABLED" or event == "UNIT_INVENTORY_CHANGED") then
				localBagupdate = .5;
			else
				localBagupdate = 0;
			end
		else
			localBagupdate = 5;
		end
	end
	if (event == "MERCHANT_SHOW") then
		localBagupdate = 0;
	elseif (event == "MERCHANT_CLOSED") then
		localBagupdate = 1;
	end
	if( event == "TIME_PLAYED_MSG" ) then
		TotalTimePlayed = arg1;
		LevelTimePlayed = arg2;
		ElapsedSinceLastPlayedMessage = 0;
		NeedPlayedMessage = 0;
		
	-- Sync up all of the times to the session time; this makes
	-- the tooltip look nicer as everything changes all at once
	local fraction = SessionTimePlayed - floor(SessionTimePlayed);
		TotalTimePlayed = floor(TotalTimePlayed) + fraction;
		LevelTimePlayed = floor(LevelTimePlayed) + fraction;

		if( GameTooltip:IsOwned(this) ) then
			StatsMod2_SetTooltip();
		end
	elseif( event == "PLAYER_LEVEL_UP" ) then
		LevelTimePlayed = SessionTimePlayed - floor(SessionTimePlayed);
		localRolloverXP = localSessionXP;
		localInitialXP = 0;
		if( GameTooltip:IsOwned(this) ) then
			StatsMod2_SetTooltip();
		end
	elseif( event == "PLAYER_ENTERING_WORLD" ) then
		if( not localInitialXP ) then
			localInitialXP = UnitXP("player");
		end
		StatsMod2_ResetHealth();
		StatsMod2_ResetMana();
	elseif( event == "PLAYER_XP_UPDATE" ) then
		if( localInitialXP ) then
			localSessionXP = UnitXP("player") - localInitialXP + localRolloverXP;
		end
	elseif( event == "UNIT_HEALTH" ) then
		if( arg1 == "player" ) then
			if( not localInitialHealth or UnitHealth("player") - localInitialHealth < 0 ) then
				StatsMod2_ResetHealth();
			end
		end
	elseif( event == "UNIT_MANA" ) then
		if( arg1 == "player" ) then
			if( not localInitialMana or UnitMana("player") - localInitialMana < 0 ) then
				StatsMod2_ResetMana();
			end
		end
	elseif( event == "PLAYER_ENTER_COMBAT" ) then
		localInCombat = 1;
	elseif( event == "PLAYER_LEAVE_COMBAT" ) then
		localInCombat = nil;
	end
end

function ClockPopupOnMouseOver(toggle)
	if ( toggle == 1 ) then
		StatsMod2_PopupOnMouseOver = true;
	else
		StatsMod2_PopupOnMouseOver = false;
	end
--	RegisterForSave("StatsMod2_PopupOnMouseOver");
end

function StatsMod2_ClockText_OnLoad()
	this:RegisterForClicks("LeftButtonUp", "RightButtonUp");
end

function StatsMod2_OpenUpTooltip()
	if( NeedPlayedMessage == 1 ) then
		RequestTimePlayed();
	end
	GameTooltip:SetOwner(StatsMod2Frame, "ANCHOR_BOTTOMRIGHT");
	StatsMod2_SetTooltip();
end

function StatsMod2_OnEnter()
	if ( StatsMod2_PopupOnMouseOver ) then
		StatsMod2_OpenUpTooltip();
	end
end

function StatsMod2_OnLeave()
	if ( GameTooltip:IsOwned(StatsMod2Frame) ) then
		GameTooltip:Hide();
	end
end

function StatsMod2_ClockText_OnClick(button)
	if ( not StatsMod2_PopupOnMouseOver ) then
		StatsMod2_ClockText_OpenUpTooltip();
	end
end


function StatsMod2_SetClockTooltipPoint()
 	-- Figured out the scale system.. it shows the scale between the object and the UIParent
	local x,y = StatsMod2Frame:GetCenter();
	local screenWidth = UIParent:GetWidth();
	local screenHeight = UIParent:GetHeight();
	local scale = StatsMod2Frame:GetEffectiveScale();
	local setX = 0;
	if (x~=nil and y~=nil and screenWidth>0 and screenHeight>0) then
		x = x * scale;
		y = y * scale;
		local anchorPoint = "";
		local relativePoint = "";
		if (y <= (screenHeight * (1/2))) then
			anchorPoint = "BOTTOM";
			relativePoint = "TOP";
		else
			anchorPoint = "TOP";
			relativePoint = "BOTTOM";
		end
		if (x <= (screenWidth * (1/2))) then
			anchorPoint = anchorPoint.."LEFT";
			relativePoint = relativePoint.."LEFT";
			if ((StatsMod2Frame:GetLeft() * scale) < 0) then
				setX = -(StatsMod2Frame:GetLeft() * scale);
			end
		else
			anchorPoint = anchorPoint.."RIGHT";
			relativePoint = relativePoint.."RIGHT";
			if ((StatsMod2Frame:GetRight() * scale) > screenWidth) then
				setX = screenWidth - (StatsMod2Frame:GetRight() * scale);
			end
		end
		
		if (anchorPoint == "") then
			anchorPoint = "TOPLEFT";
		end
		
		if (relativePoint == "") then
			anchorPoint = "BOTTOMLEFT";
		end
		
		-- added 2005-01-13 by arys
		-- makes clock tooltip scale correctly
		GameTooltip:SetScale(this:GetScale());
		GameTooltip:ClearAllPoints();
		GameTooltip:SetPoint(anchorPoint, StatsMod2Frame:GetName(), relativePoint, setX / GameTooltip:GetEffectiveScale(), 0);

	end
end

-- Helper functions
function StatsMod2_GetTimeText()
	local hour, minute = GetGameTime();
	local pm;

	hour = hour + OffsetHour;
	minute = minute + OffsetMinute;
	if( minute > 59 ) then
		minute = minute - 60;
		hour = hour + 1;
	elseif( minute < 0 ) then
		minute = 60 + minute;
		hour = hour - 1;
	end
	if( hour > 23 ) then
		hour = hour - 24;
	elseif( hour < 0 ) then
		hour = 24 + hour;
	end

	if( MilitaryTime == 1 ) then
		if( ( ShowSeconds == 1 ) ) then
			return date("%H:%M:%S", time() + (OffsetHour*60+OffsetMinute)*60 );
		else
			return format(TEXT(STMOD2_CLOCK_TIME_TWENTYFOURHOURS), hour, minute);
		end
	else
		if( hour >= 12 ) then
			pm = 1;
			hour = hour - 12;
		else
			pm = 0;
		end
		if( hour == 0 ) then
			hour = 12;
		end
		if( pm == 1 ) then
			if( ( ShowSeconds == 1 ) )  then
				return date("%I:%M:%S %p", time() + (OffsetHour*60+OffsetMinute)*60 );
			else
				return format(TEXT(TIME_TWELVEHOURPM), hour, minute);
			end
		else
			if( ( ShowSeconds == 1 ) ) then
				return date("%I:%M:%S %p", time() + (OffsetHour*60+OffsetMinute)*60 );
			else
				return format(TEXT(TIME_TWELVEHOURAM), hour, minute);
			end
		end
	end
end

local function StatsMod2_FormatPart(fmt, val)
	local part;

	part = format(TEXT(fmt), val);
	if( val ~= 1 ) then
		part = part..TEXT(STMOD2_CLOCK_PART_PLURAL);
	end

	return part;
end

function StatsMod2_FormatTime(time)
	local d, h, m, s;
	local text = "";
	local skip = 1;

	d, h, m, s = ChatFrame_TimeBreakDown(time);
	if( d > 0 ) then
		text = text..StatsMod2_FormatPart(STMOD2_CLOCK_TIME_DAY, d)..", ";
		skip = 0;
	end
	if( (skip == 0) or (h > 0) ) then
		text = text..StatsMod2_FormatPart(STMOD2_CLOCK_TIME_HOUR, h)..", ";
		skip = 0;
	end
	if( (skip == 0) or (m > 0) ) then
		text = text..StatsMod2_FormatPart(STMOD2_CLOCK_TIME_MINUTE, m)..", ";
		skip = 0;
	end
	if( (skip == 0) or (s > 0) ) then
		text = text..StatsMod2_FormatPart(STMOD2_CLOCK_TIME_SECOND, s);
	end

	return text;
end

function StatsMod2_SetTooltip()
	local total, level, session;
	local xpPerHourLevel, xpPerHourSession;
	local xpTotal, xpCurrent, xpToLevel;
	local text;

	total = format(TEXT(TIME_PLAYED_TOTAL), StatsMod2_FormatTime(TotalTimePlayed + ElapsedSinceLastPlayedMessage));
	level = format(TEXT(TIME_PLAYED_LEVEL), StatsMod2_FormatTime(LevelTimePlayed + ElapsedSinceLastPlayedMessage));
	session = format(TEXT(TIME_PLAYED_SESSION), StatsMod2_FormatTime(SessionTimePlayed));

	if( NeedPlayedMessage == 1 ) then
		text = session;
	else
		text = total.."\n"..level.."\n"..session;
	end

	if(HideExp ~= 1 and UnitLevel('player') ~= MAX_PLAYER_LEVEL) then
		if( (LevelTimePlayed + ElapsedSinceLastPlayedMessage > 0) or SessionTimePlayed > 0 ) then
			text = text.."\n";
		end
		if( LevelTimePlayed + ElapsedSinceLastPlayedMessage > 0 ) then
			xpPerHourLevel = UnitXP("player") / ((LevelTimePlayed + ElapsedSinceLastPlayedMessage) / 3600);
			text = text.."\n"..format(TEXT(EXP_PER_HOUR_LEVEL), xpPerHourLevel);
		else
			xpPerHourLevel = 0;
		end
		if( SessionTimePlayed > 0 ) then
			xpPerHourSession = localSessionXP / (SessionTimePlayed / 3600);
			text = text.."\n"..format(TEXT(EXP_PER_HOUR_SESSION), xpPerHourSession);
		else
			xpPerHourSession = 0;
		end
		
		xpTotal = UnitXPMax("player");
		xpCurrent = UnitXP("player");
		if( xpCurrent < xpTotal ) then
			xpToLevel = xpTotal - xpCurrent;
			text = text.."\n"..format(TEXT(EXP_TO_LEVEL), xpToLevel, (xpToLevel / xpTotal) * 100);
			if( xpPerHourLevel > 0 ) then
				text = text.."\n"..format(TEXT(TIME_TO_LEVEL_LEVEL), StatsMod2_FormatTime((xpToLevel / xpPerHourLevel) * 3600));
			else
				text = text.."\n"..format(TEXT(TIME_TO_LEVEL_LEVEL), TEXT(TIME_INFINITE));
			end
			if( xpPerHourSession > 0 ) then
				text = text.."\n"..format(TEXT(TIME_TO_LEVEL_SESSION), StatsMod2_FormatTime((xpToLevel / xpPerHourSession) * 3600));
			else
				text = text.."\n"..format(TEXT(TIME_TO_LEVEL_SESSION), TEXT(TIME_INFINITE));
			end
		end
	end

	if( localHealthPerSecond or localManaPerSecond ) then
		text = text.."\n";
	end
	if( localHealthPerSecond ) then
		text = text.."\n"..format(TEXT(HEALTH_PER_SECOND), localHealthPerSecond);
	end
	if( localManaPerSecond ) then
		text = text.."\n"..format(TEXT(MANA_PER_SECOND), localManaPerSecond);
	end
	
	if ( StatsMod2_ShowMoney ) and ( StatsMod2_ShowMoney == 1 ) then
		text = text.."\n\n"..StatsMod2_GetMoneyGainAsString();
	end
	
	GameTooltip:SetText(text);
	--Fix the tooltip position
	StatsMod2_SetClockTooltipPoint();	
end

-- added by popular demand by sarf
function StatsMod2_ResetData()
	TotalTimePlayed = 0;
	LevelTimePlayed = 0;
	SessionTimePlayed = 0;
	ElapsedSinceLastPlayedMessage = 0;
	NeedPlayedMessage = 1;

	localInitialXP = UnitXP("player");
	localSessionXP = 0;
	localRolloverXP = 0;

	localHealthSecondTimer = 0;
	localInitialHealth = UnitHealth("player");
	localHealthPerSecond = nil;
	localManaSecondTimer = 0;
	localInitialMana = UnitMana("player");
	localManaPerSecond = nil;
	localMoneyIncreases = 0;

	localInCombat = nil;
	localSpeed = 0;
	localSpeedDist = 0;
	localSpeedTime = 0;
end


-- added as per Bhaeraus request by sarf

function StatsMod2_ToggleDisplayMoney(toggle)
	if ( toggle == 1 ) then
		StatsMod2_ShowMoney = 1;
	else
		StatsMod2_ShowMoney = 0;
	end
end


function StatsMod2_GetMoneyGainAsString()
	local formatStr = TEXT(STMOD2_CLOCK_MONEY);
	local valueStr = TEXT(STMOD2_CLOCK_MONEY_UNAVAILABLE);
	if ( localMoneyIncreases > 0 ) and ( SessionTimePlayed > 0 ) then
		local moneyFormat = TEXT(STMOD2_CLOCK_MONEY_PER_HOUR);
		local moneyGain = math.floor((localMoneyIncreases/SessionTimePlayed)*3600);
		if ( true ) then
			moneyFormat = TEXT(STMOD2_CLOCK_MONEY_PER_HOUR);
			moneyGain = math.floor((localMoneyIncreases/SessionTimePlayed)*3600);
		else
			moneyFormat = TEXT(STMOD2_CLOCK_MONEY_PER_MINUTE);
			moneyGain = math.floor((localMoneyIncreases/SessionTimePlayed)*60);
		end
		valueStr = format(moneyFormat, StatsMod2_GetMoneyAsString(moneyGain));
	end
	return format(formatStr, valueStr);
end

function StatsMod2_GetCurrencyString(currencyType)
	local name = "STMOD2_CLOCK_MONEY_";
	if ( currencyType == "gold" ) then
		name = name.."GOLD";
	end
	if ( currencyType == "silver" ) then
		name = name.."SILVER";
	end
	if ( currencyType == "copper" ) then
		name = name.."COPPER";
	end
	if ( not StatsMod2_UseBigCurrencyDescriptions) or ( StatsMod2_UseBigCurrencyDescriptions ~= 1 ) then
		name = name.."_SHORT";
	end
	return getglobal(name);
end

function StatsMod2_GetMoneyAsString(amount)
	local gold = math.floor(amount / COPPER_PER_GOLD);
	amount = amount - gold * COPPER_PER_GOLD;
	local silver = math.floor(amount / COPPER_PER_SILVER);
	amount = amount - silver * COPPER_PER_SILVER;
	local copper = amount;
	local str = "";
	if ( gold > 0 ) then
		str = str..format(StatsMod2_GetCurrencyString("gold"), gold);
		if ( silver > 0 ) or ( copper > 0 ) then
			str = str..TEXT(STMOD2_CLOCK_MONEY_SEPERATOR);
		end
	end
	if ( silver > 0 ) then
		str = str..format(StatsMod2_GetCurrencyString("silver"), silver);
		if ( copper > 0 ) then
			str = str..TEXT(STMOD2_CLOCK_MONEY_SEPERATOR);
		end
	end
	if ( copper > 0 ) then
		str = str..format(StatsMod2_GetCurrencyString("copper"), copper);
	end
	return str;
end

function StatsMod2_RetrieveCurrentMoneyOnStart()
	if ( not StatsMod2_UpdateMoney() ) then
		if ( Chronos ) then
			Chronos.scheduleByName("STMOD2_CLOCK_RETRIEVE_MONEY", 5, StatsMod2_RetrieveCurrentMoneyOnStart);
		end
	end
end

function StatsMod2_UpdateMoney()
	local currentMoney = GetMoney();
	if ( not currentMoney ) then
		return false;
	end
	if ( localMoneyOld ) then
		local diff = currentMoney-localMoneyOld;
		if ( diff > 0 ) then
			localMoneyIncreases = localMoneyIncreases + diff;
		end
	end
	localMoneyOld = currentMoney;
	if ( not localMoneyOld ) then
		return false;
	else
		return true;
	end
end

function StatsMod2_CheckTenThousand()
	local currentMoney = GetMoney();
	if (string.len(currentMoney) > 8) then
		StatsMod2Frame:SetWidth(280);
		StatsMod2FrameGoldButtonText:ClearAllPoints();
		StatsMod2FrameGoldButtonText:SetPoint("TOPLEFT", StatsMod2Frame, 145, -7);
		StatsMod2FrameSilverButtonText:ClearAllPoints();
		StatsMod2FrameSilverButtonText:SetPoint("TOPLEFT", StatsMod2Frame, 185, -7);
		StatsMod2FrameCopperButtonText:ClearAllPoints();
		StatsMod2FrameCopperButtonText:SetPoint("TOPLEFT", StatsMod2Frame, 218, -7);
	else
		StatsMod2Frame:SetWidth(270);
		StatsMod2FrameGoldButtonText:ClearAllPoints();
		StatsMod2FrameGoldButtonText:SetPoint("TOPLEFT", StatsMod2Frame, 140, -7);
		StatsMod2FrameSilverButtonText:ClearAllPoints();
		StatsMod2FrameSilverButtonText:SetPoint("TOPLEFT", StatsMod2Frame, 180, -7);
		StatsMod2FrameCopperButtonText:ClearAllPoints();
		StatsMod2FrameCopperButtonText:SetPoint("TOPLEFT", StatsMod2Frame, 213, -7);
	end
end

--- added 2005-01-13 by arys
function StatsMod2_DisplaySeconds(toggle)
	if ( toggle == 1 ) then
		ShowSeconds = 1;
		InitialRun = 1;
	else
		ShowSeconds = 0;
	end
end
  

function StatsMod2_ShowSeconds_DoUpdate(elapsed)
    local DoUpdate = 0;
    if ( ShowSeconds ) and ( ShowSeconds >= 1 ) then

		CurrentSecond = CurrentSecond + elapsed;
		if( InitialRun == 1 ) then
			local CurrentHour, CurrentMinute = GetGameTime();
			LastMinute = CurrentMinute;
			InitialRun = 2;
		end
	
		if( CurrentSecond >= 1 ) then
			CurrentSecond = CurrentSecond - 1;
			SecondCount = SecondCount + 1;
			
			if( SecondCount >= 60 ) then
				SecondCount = 0;
				DoUpdate = 1;
			end
			
			if ( DoUpdate == 1 ) then
				if ( not updateTime ) then 
					updateTime = 0;
				end
				-- fractions of seconds are lost every time the game lags,
				-- this should keep track of that.
				local CurrentTime = GetTime();
				local SecondOffset = ((CurrentTime - 60) - updateTime)/2;
				CurrentSecond = SecondOffset;
				updateTime = CurrentTime;
				DoUpdate = 0;
			end
			
			if( InitialRun == 2 ) then
				local CurrentHour, CurrentMinute = GetGameTime();
				if( CurrentMinute ~= LastMinute ) then
					updateTime = GetTime();
					SecondCount = 1;
					InitialRun = 0;
					LastMinute = CurrentMinute;
				end
			end
		end
	end
end

--- Cash display functions

function StatsMod2_DisplayMoney()
	local money = (GetMoney() - GetCursorMoney() - GetPlayerTradeMoney());
	local gold, silver, copper = StatsMod2_ShowGSC(money);
	
	StatsMod2FrameGoldButtonText:SetText(gold);
	StatsMod2FrameSilverButtonText:SetText(silver);
	StatsMod2FrameCopperButtonText:SetText(copper);
end

--- Show Gold Silver Copper Type
function StatsMod2_ShowGSC(money)
	local curMoney = money;
	local gType = 0;
	local sType = 0;
	local cType = 0;

	gType = curMoney / 10000;
	sType = (curMoney - (gType * 10000)) / 100;
	cType = (curMoney - (gType * 10000) - (sType * 100));

	gType = floor(curMoney / (10000));
	sType = floor((curMoney - (gType * 10000)) / 100);
	cType = mod(curMoney, 100);

	return gType, sType, cType;
end

-- Tick display function

function StatsMod2_UnitPowerType()
	local type = UnitPowerType("player");
	if ( type and type == 0 ) then
		type = MANA;
	else
		type = nil;
	end
	return type;
end

-- Durability function

function StatsMod2_BagUpdate()
	--ARMOR
	StatsMod2_Armor_value = 0;
	StatsMod2_Armor_max = 0;
	StatsMod2_Armor_cost = 0;

	for i = 1, 11 do

		local value, max, cost = StatsMod2_Dura_GetStatus(i);

		if (value ~= nil) then
			StatsMod2_Armor_value = StatsMod2_Armor_value + value;
			StatsMod2_Armor_max = StatsMod2_Armor_max + max;
			StatsMod2_Armor_cost = StatsMod2_Armor_cost + cost;
		end

	end


	--update the percentage
	StatsMod2_Dura_UpdatePercent();
end

function StatsMod2_Dura_GetStatus(index)
	local val = 0;
	local max = 0;
	local cost = 0;
	local hasItem, repairCost

	STMOD2TT:SetOwner(WorldFrame, "ANCHOR_NONE");

	local slotName = DurStatus_Slots[index].slot .. "Slot";
	local id = GetInventorySlotInfo(slotName);
	local lHasItem, _, lRepairCost = STMOD2TT:SetInventoryItem("player", id);
	hasItem = lHasItem;
	repairCost = lRepairCost;

	if (hasItem) then
		if (repairCost) then
			cost = repairCost;
		end

		for i = 1, 30 do
			local field = getglobal("STMOD2TTTextLeft" .. i);
			if (field ~= nil) then
				local text = field:GetText();
				if (text) then
					-- find durability
					local _, _, f_val, f_max = string.find(text, STMOD2_DURA_TEXTCHK);

					if (f_val) then
						val = tonumber(f_val);
						max = tonumber(f_max);
					end
				end
			end

		end

	end

	STMOD2TT:Hide();
	return val, max, cost;

end

function StatsMod2_Dura_GetStatusPercent(val, max)
	if (max > 0) then
		return (val / max);
	end
	return 1.0;
end

function StatsMod2_Dura_UpdatePercent()
	local green = GREEN_FONT_COLOR;
	local yellow = NORMAL_FONT_COLOR;
	local red = RED_FONT_COLOR;

	local percent = StatsMod2_Dura_GetStatusPercent(StatsMod2_Armor_value, StatsMod2_Armor_max);

	local color = {};

	if (percent == 1.0) then
		color = green;
	elseif (percent == 0.5) then
		color = yellow;
	elseif (percent == 0.0) then
		color = red;
	elseif (percent > 0.5) then
		local pct = (1.0 - percent) * 2;
		color.r =(yellow.r - green.r)*pct + green.r;
		color.g = (yellow.g - green.g)*pct + green.g;
		color.b = (yellow.b - green.b)*pct + green.b;
	elseif (percent < 0.5) then
		local pct = (0.5 - percent) * 2;
		color.r = (red.r - yellow.r)*pct + yellow.r;
		color.g = (red.g - yellow.g)*pct + yellow.g;
		color.b = (red.b - yellow.b)*pct + yellow.b;
	end

	--make sure we don't go overboard
	if( floor(percent*100) > 100) then percent = 100; else percent = floor(percent*100); end

	localCurrPercent = percent;

	StatsMod2FrameDurButtonText:SetText(STMOD2_DURA_TEXT..percent.."%");
	StatsMod2FrameDurButtonText:SetTextColor(color.r, color.g, color.b);

end

function StatsMod2_Dura_ShowTooltip()
	GameTooltip:SetOwner(StatsMod2FrameClockButton, "ANCHOR_BOTTOMLEFT");
	GameTooltip:AddLine(STMOD2_REPAIRCOST_TEXT, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b);
	if ( StatsMod2_Armor_cost == 0 ) then
		GameTooltip:AddLine(NONE, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b);
	else
		SetTooltipMoney(GameTooltip, StatsMod2_Armor_cost);
	end
	GameTooltip:Show();
end