// Displays a popup with current character length of the selected text object
// and the max characters allowed for that text object.
// Popup automatically hides itself after a set amount of time.
function updateCharCount(txtObj, max, min, force) {
	if(min == null) min = 0;
	
	var init = false;
	var force = force == null ? false : force;
	var showMax = max > 0;
	var showMin = min > 0;
	var length = txtObj.value.length;
	var className = "low";
	
	if(showMax) {
		// Find the relevant class to indicate current length status.
		var low = max / 2;
		if(length > low && length < max) className = "mid";
		if(length >= max) className = "max";

		// Restrict the user's input to the max characters allowed.
		if(force && length > max){
			txtObj.value = txtObj.value.substr(0, max);
			length = max;
		}
	}

	// Overwrite class name if min being used
	if(showMin) {
		if(length < min) className = "max";
	}
	
	// Create the popup if it hasn't already been done.
	if(txtObj.charCounter == null) {
		var container = document.createElement("div");
		container.style.position = "absolute";
		container.className = "charCounter";
		
		var span = document.createElement("span");	
		container.appendChild(span);
		
		var displayText = " /";
		if(showMin) {
			displayText += " min " + min;
			if(showMax) displayText += ",";
		}
		if(showMax) {
			displayText += " max " + max;
		}
		
		container.appendChild(document.createTextNode(displayText));	
		txtObj.parentNode.appendChild(container);
		
		txtObj.charCounter = container;
		txtObj.countObj = span;
		init = true;
	}
	
	// Set the new values of the popup
	var countObj = txtObj.countObj;
	var currentWidth = countObj.offsetWidth;	
	countObj.className = className;	
	countObj.innerHTML = length;
	
	// Show the popup.
	var container = countObj.parentNode;
	container.style.display = 'block';
	
	var position = Utilities.getPositionedOffset(txtObj);
	
	// Correct popup's current position if the width has changed
	if(init || currentWidth != countObj.offsetWidth)
		container.style.left = position.x + txtObj.offsetWidth - container.offsetWidth + 'px';
	
	// Popup can be pushed up/down from other javascripts so we constantly have to reposition the popup
	container.style.top = position.y - container.offsetHeight + 1 + 'px';
	
	// Reset the 'hide popup' timer if it has already been set
	if(container.timerId != null)
		clearTimeout(container.timerId);

	// Set the new 'hide popup' timer
	container.timerId = setTimeout(function() { container.style.display = 'none'; }, 2500);
}