//set up the RD object
if(!window.RD){
	window.RD = {};
}

if(!RD.XHTML){
	RD.XHTML = {};
}

RD.XHTML.setTextareaMaxLength = function(){
    var vTextAreas = $$(document, "textarea");

    for (var n=0;n<vTextAreas.length;n++) {
        var vMaxLength = vTextAreas[n].getAttribute("maxlength");
		
        if(!vMaxLength && vTextAreas[n].getAttribute("ml")){
            vMaxLength = vTextAreas[n].getAttribute("ml")
            vTextAreas[n].setAttribute("maxlength", vMaxLength);
        }
        if (vMaxLength){
			if(vTextAreas[n].onkeydown){
				 vTextAreas[n]._storedOnKeyDown = vTextAreas[n].onkeydown;
				vTextAreas[n].onkeydown = function(){
					RD.XHTML.checkMaxLength(window.event, this);
					this._storedOnKeyDown();
				}
			}
			else{
				vTextAreas[n].onkeydown = RD.XHTML.checkMaxLength;
			}
			if(vTextAreas[n].onkeyup){
				vTextAreas[n]._storedOnKeyUp = vTextAreas[n].onkeyup;
				vTextAreas[n].onkeyup = function(){
					RD.XHTML.removeExtraText(window.event, this);
					this._storedOnKeyUp();
				}
			}
            else{
				vTextAreas[n].onkeyup = RD.XHTML.removeExtraText;
			}
			
            vTextAreas[n].onkeydown();
        }
    }
}

RD.XHTML.removeExtraText = function(evt, aObject){
	aObject = aObject?aObject:this;
    var vMaxLength = parseInt(aObject.getAttribute("maxlength"), 10);
    var vCurrentLength = aObject.value.length;
    if(vCurrentLength > vMaxLength){
        aObject.value = aObject.value.substr(0, vMaxLength);
    }
}

RD.XHTML.checkMaxLength = function(evt, aObject){
    evt = evt?evt:window.event;
    aObject = aObject?aObject:this;
    var vMaxLength = parseInt(aObject.getAttribute("maxlength"), 10);
    var vCurrentLength = aObject.value.length;
    
    var vAllowKeyDown = true;
    
    
    
    if(evt){
        if((evt.keyCode >= 48 && evt.keyCode <= 90) || (evt.keyCode >= 106 && evt.keyCode <= 222)){
            if(vCurrentLength >= vMaxLength){
                vAllowKeyDown = false;
            }
        }
    }
    else{
        aObject.value = aObject.value.substr(0, vMaxLength);
    }

    return vAllowKeyDown;
}

RD.XHTML.setTextareaMaxLength();