/*
********************************************************
Copyright @ WebOnWebOff.com, by D. Miller
You may reuse this script, on condition that this copyright text is kept
www.WebOnWebOff.com
********************************************************
*/
ylib.namespace('ylib.widget');

ylib.widget.TextCounter=function(textT, numChars, textBefore, textAfter){	
	this.ready=false;
	this.ta=xGetElementById(textT); //text area/textbox	
	if(!isNaN(numChars)){
		this.lim=numChars;
	} else {
		this.lim=0;
	}
	this.tAfter  = xStr(textAfter) ? textAfter : '';
	this.tBefore = xStr(textBefore) ? textBefore : 'Chars left: ';
	this.ta.onchange=this.update;
	this.ta.onkeyup=this.update;
	this.ta.onkeydown=this.prevent;
	this.ta.onkeypress=this.prevent;
	//insert counter element
	var parent = xParent(this.ta, true);	
	var counter = document.createElement('span');
	//add counter	
	if(!parent || !counter){
		return;
	}
	counter.id=textT+'-Counter';
	xDisplay(counter,'block');
	counter.className='TextCounter-Counter';
	xAppendChild(parent,counter);
	
	this.cntr=counter; 
	this.ready=true;
	this.ta.TextCounterObj=this;
	this.update.call(this.ta);	
}
ylib.widget.TextCounter.prototype.update=function(){
	var obj=this.TextCounterObj;	
	if(!obj || !obj.ready) return;
	
	var tVal=obj.ta.value;	
	var lenT=tVal.length;	
	if(lenT>obj.lim){
		obj.ta.value = tVal.substr(0,obj.lim);
		lenT=obj.lim;
	}
	obj.cntr.innerHTML=obj.tBefore+(obj.lim-lenT)+obj.tAfter;
		
}
ylib.widget.TextCounter.prototype.prevent=function(event){

	var obj=this.TextCounterObj;
	if(!obj || !obj.ready) return;
	var T=obj.ta.value;	
	var lenT=T.length;
	var ev=new xEvent(event);
				
	if(ylib.util.isTextChar(ev.keyCode)&&lenT>=obj.lim){
		return false;
	}
	
}