// JAVASCRIPT FUNCTION TO LIMIT CHARACTERS PER LINE AND LINE NUMBERS OF TEXT FIELD

cleanUpLine = function (str,limit) { // clean string
 	var clean_pass1 = str;
 	var clean_pass2 = clean_pass1.replace(/\s{2,}/g, ' ');		// compact multiple whitespaces
 	var clean_pass3 = clean_pass2.replace(/^\s+|\s+$/g, '');	// trim whitespaces from beginning or end of string
 	var clean_pass4 = clean_pass3.substring(0,limit);			// trim string
 	return clean_pass4;
}

// number of keywords and keyword length validation
cleanUpList = function (fld) {
 	var charLimit = 22;		// ADJUST: number of characters per line
	 var lineLimit = 4;		// ADJUST: number of lines
 	var cleanList = [];
	 var re1 = /\S/;			// all non-space characters
  var re2 = /[\n\r]/;		// all line breaks
	 var tempList = fld.value.split('\n');
	 for (var i=0; i<tempList.length;i++) {
		  if (re1.test(tempList[i])) { // store filtered lines in an array
  			 var cleanS = cleanUpLine(tempList[i],charLimit);
		  	 cleanList.push(cleanS);
  		}
  }
  for (var j=0; j<tempList.length;j++) {
		  if (tempList[j].length > charLimit && !re2.test(tempList[j].charAt(charLimit))) { 
  		fld.value = cleanList.join('\n'); // restore from array
  		}
	 }
	 if (cleanList.length > lineLimit) {
  		cleanList.pop();	// remove last line
		  fld.value = cleanList.join('\n'); // restore from array
	 }
	 fld.onblur = function () {this.value = cleanList.join('\n');} // onblur - restore from array
}	

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(
  function () {
	var messagearea = document.getElementById('textarea5');
	messagearea.onkeyup =	function () {
		cleanUpList(messagearea);
	}
  }
);
