if (document.getElementById && document.getElementsByTagName && document.createTextNode) 
	window.onload = initWordCount;

function initWordCount() {
	for($i = 0; $i < document.getElementsByTagName("textarea").length; $i++) {
		var thisarea = document.getElementsByTagName("textarea")[$i];
		var textareaID = thisarea.id;
		var spanID = textareaID + "_count";
		thisarea.setAttribute("onkeyup", "countwords('" + textareaID + "', '" + spanID + "', 'y')");
		var newwordsp = document.createElement("div");
		var target = thisarea.parentNode;
		target.insertBefore(newwordsp, target.firstChild);
		newwordsp.className = "counter";
		var newcountspan = document.createElement("span");
		newwordsp.appendChild(newcountspan);
		newcountspan.setAttribute("ID", spanID);
		newwordsp.innerHTML += "&nbsp;Words";
		countwords(textareaID, spanID, "y");
	}	
}

function countwords(textareaID, destinationID, striphtml) {
  var txt = document.getElementById(textareaID).value;
  if (striphtml == "y") txt = txt.replace(/(<([^>]+)>)/ig,""); //strip HTML
  txt = txt.replace(/\s*((\S+\s*)*)/, "$1"); //ltrim
  txt = txt.replace(/((\s*\S+)*)\s*/, "$1"); //rtrim
  document.getElementById(destinationID).innerHTML = txt.match(/^ *$/) ? 0 : txt.split(/\s+/g).length;
}
