/*

to attach the script to the text field (or textarea) you have to:
1. the text field has to be in <div> </ div>
2. the text field had the id and name (id = name)
3. after the form run the handler
	createTextLimitWidget(element_name, min_len, max_len);
*/

String.prototype.str_replace = function(srch, rpl) {
	var ar = this.split(srch);
	return ar.join(rpl);
}

function getParent(el) {
	return ((el.parentElement) ? el.parentElement : ((el.parentNode) ? el.parentNode : null));
}

function getElementPosition(elem) {
    var w = elem.offsetWidth;
    var h = elem.offsetHeight;
	
    var l = 0;
    var t = 0;
	
    while (elem)
    {
        l += elem.offsetLeft;
        t += elem.offsetTop;
        elem = elem.offsetParent;
    }
    return {"left":l, "top":t, "width": w, "height":h};
}

function createTextLimitWidget(el, min, max) {
	var el = $(el);
	var counter = $('counter' + el.id);
	if (!counter)
	{
		var parent = getParent(el);
		var counter = document.createElement('div');
		counter.setAttribute('id', 'counter' + el.id);
		counter.className = 'counter';
		parent.appendChild(counter);
		parent.style.position = 'relative';
		counter.style.position = 'absolute';

		if (getElementPosition(el).width > 0) {
			counter.style.left = getElementPosition(el).width - 25 +  'px';
		} else {
			counter.style.left = '360px';
		}
		counter.style.top = '-17px';
		counter.style.height = getElementPosition(el).height + 'px';
	}

	len = max - el.value.str_replace(String.fromCharCode(13), '').length;
	if (len <= 0) {
		el.value = el.value.substr(0, max);
		len = 0;
	}

	el.onkeyup = function () {createTextLimitWidget(el, min, max);}
	el.onchange = function () {createTextLimitWidget(el, min, max);}
	createStat(counter, min, max, len);	
}

function createStat(el, min, max, current) {
	var className = 'number';
	//var cur = (current <= 0) ? current : current;
	var cur = current;
	

	color = '';
	if (cur < 20) {
		color='style="color:#5c0002"'
	}
	if (cur < 10) {
		color='style="color:#dd0d12"'
	}
	
	el.innerHTML = '<span ' + color + ' class=' + className + '>' + cur + '<\/span>';
}
