﻿// 2006 Rob Chandanais (http://bluerobot.com)

function TextSizeWatcher()
{
	var tickLength = 1000/10; // milliseconds
	var ticksToMatch = 5;
	var ticksLeftToMatch = 0;
	var lastSize = 0;
	var pending = false;
	var testBox = null;
	var ticker = null;
	var running = false;
	
	this.action = null;
	
	this.start = function()
	{
		if (!running)
		{
			running = true;
			testBox = createTestBox();
			document.body.appendChild(testBox);
			lastSize = testBox.offsetHeight;
			ticker = window.setInterval(bind(checkTextHeight,this), tickLength);
		}
	}
	
	this.stop = function()
	{
		if (running)
		{
			running = false;
			window.clearInterval(ticker);
		}
	}
	
	function createTestBox()
	{
		var x = document.createElement('div');
		x.innerHTML = "X";
		x.style.position = "absolute";
		x.style.left = "0px";
		x.style.top = "0";
		x.style.fontSize = "xx-large";
		return x;
	}
	
	function checkTextHeight()
	{
		var current = testBox.offsetHeight;
		var changed = (current != lastSize);
		
		if (changed)
		{
			pending = true;
			lastSize = current;
			ticksLeftToMatch = ticksToMatch-1;
		}
		
		if (pending)
		{
			if (ticksLeftToMatch > 0)
			{
				ticksLeftToMatch--;
			}
			else
			{
				doAction(this.action);
				pending = false;
			}
		}
	}
	
	function doAction(theAction)
	{
		if (theAction)
		{
			theAction();
		}
	}
	
	function bind(method, obj)
	{
		return function()
		{
			return method.apply(obj);
		}
	}
}


function trace(message)
{
	alert(message);
}