$(document).ready( function() {
	$('textarea').each(
		function (){
			var oCntDown = document.getElementById('cnt4'+this.id);
			if(oCntDown){
				var maxLen = oCntDown.innerHTML;
				$(this).keypress(
					function(e){
						if (this.value.length<maxLen) {
							return true;
						}
						keyCode	 = e.keyCode  ? e.keyCode : e.which;
						//alert(keyCode + ' > ' + e.charCode);
						/* Safari crap */
						// special keys codes
						var scCodes = [27, 8, 13, 16, 18, 20, 144, 33, 34, 37, 38, 39, 40, 45, 46];
						window.status = keyCode;
						return scCodes.exists(keyCode) || keyCode > 63000;
						/*if(e.charCode==0) {
							return true;
							//return (keyCode != 13 && keyCode != 8);
						} else {
							return false;
						}*/
					}
				);
				$(this).keyup(
					function() {maxLength(maxLen,this,oCntDown)}
				);
				$(this).blur(
					function() {maxLength(maxLen,this,oCntDown)}
				);
				$(this).click(
					function() {maxLength(maxLen,this,oCntDown)}
				);
				$(this).change(
					function() {maxLength(maxLen,this,oCntDown)}
				);
				maxLength(maxLen,this,oCntDown);
			}
		}
	);
});

function maxLength(maxLen,oArea,oCounter) {
	var cLen = oArea.value.length;
	if(cLen>maxLen) {
		alert(oArea.name+': Your input is too big and will be truncated to '+maxLen+' chars');
		oArea.value = oArea.value.substring(0, maxLen);
		oCounter.innerHTML = maxLen+', remaining '+0;
	} else if(cLen>0) {
		oCounter.innerHTML = maxLen+', remaining '+(maxLen-cLen);
	} else {
		oCounter.innerHTML = maxLen;
	}
}

if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(val, fromIndex) {
		if (typeof(fromIndex) != 'number') fromIndex = 0;
		for (var index = fromIndex,len = this.length; index < len; index++)
			if (this[index] == val) return index;
		return -1;
	}
}
if (!Array.prototype.exists) {
	Array.prototype.exists = function(val, fromIndex) {
		if (typeof(fromIndex) != 'number') fromIndex = 0;
		for (var index = fromIndex,len = this.length; index < len; index++)
			if (this[index] == val) return true;
		return false;
	}
}

