/******************************************************
author: DAroo, darooo7@interia.pl
do not remove this comment! (nie usuwać tego komentarza!)
******************************************************/

// configuration
var sTextAreaId = "area_content"; //id of the <textarea/>
var sIdP = "chars"; // id of the <p/>

var iMaxLength = 500; // comment length
var sInfor = "Chars left: "; //description
var iWarningChars = 50; // warning chars amount
var sWarning = "yellow"; // warning color
var sCritical = "red"; // 0 chars color
// configuration end
function replaceP(sText) {
	var oNewDesc = document.createElement("p");		
	oNewDesc.setAttribute("id", sIdP);
	var oText = document.createTextNode(sText);
	oNewDesc.appendChild(oText);
	var oDesc = document.getElementById(sIdP);
	oDesc.parentNode.replaceChild(oNewDesc, oDesc);
	return oNewDesc;
};
function checkChars(oTextbox) {
	var iDiff = iMaxLength - oTextbox.value.length;
	if(iDiff > iWarningChars) {
		replaceP(sInfor + iDiff.toString())
	} else if(iDiff <= iWarningChars && iDiff > 0) {
		var oNewDesc = replaceP(sInfor);
		var oSpan = document.createElement("span");
		oSpan.style.color = sWarning;
		oText = document.createTextNode(iDiff);
		oSpan.appendChild(oText);
		oNewDesc.appendChild(oSpan);
	} else if(iDiff <= 0){
		if(iDiff < 0) {
			sNewTextbox = oTextbox.value.slice(0, iMaxLength);
			oTextbox.value = sNewTextbox;
		}
		var oNewDesc = replaceP(sInfor);
		var oSpan = document.createElement("span");
		oSpan.style.color = sCritical;
		oText = document.createTextNode(0);
		oSpan.appendChild(oText);
		oNewDesc.appendChild(oSpan);		
	}	
};

EventUtil.addEventHandler(window, "load", loadScript);

function loadScript() {
	var oTextbox = document.getElementById(sTextAreaId);
	checkChars(oTextbox);
	oTextbox.onkeydown = function() { checkChars(this); }
	oTextbox.onkeyup = function() { checkChars(this); }
	document.onmouseover = function() { 
		checkChars(oTextbox);
	}
	// comments in cms
	var oBbcodeHide = document.getElementById("bbcode_hide");
	oBbcodeHide.style.display = "block";
};