var charCount = 1;
var maxCharCount = 2000;

function displayRemLength(fieldName) {
	var remField = document.getElementById(fieldName);
    if (remField!=null) {
        remField.innerHTML = (maxCharCount - charCount > 0) ? maxCharCount - charCount : 0;
    }
}

function warnAfterLength(warningLength, fieldName, normalClass, warnClass) {
	var msgField = document.getElementById(fieldName);
    if (maxCharCount - charCount <= warningLength) {
        msgField.className = warnClass;
    }
    else {
        msgField.className = normalClass;
    }
}

// when using JSpell, curField will be a JSpell component. else it will be a field or textarea
function evalEntryLength(curField, maxLimit, discardXtra, errClass, normalClass, isJSpell) {
	maxCharCount = maxLimit;
    if (curField==null)
        return;
	var fieldLength = getCharCount( (isJSpell)?curField.body.innerText:curField.value);
	if (fieldLength > maxLimit) {
		if (errClass != "") {
			curField.className = errClass;
		}
		if (discardXtra) {
			showAllowedLength(curField, maxLimit, isJSpell);
		}
	} else if (normalClass != "") {
		curField.className = normalClass;
	}
}

function getCharCount(curField) {
    if (curField!=null) {
        // can't just do a length because firefox treats carriage return as 1 character but
        // the server treats it as 2 characters
        var temp = new String(curField);
        // this is for IE clients
        while (temp.indexOf('\r\n') >=0) {
            temp = temp.replace('\r\n', '  ');
        }
        //  this is for firefox clients
        while (temp.indexOf('\n') >=0) {
            temp = temp.replace('\n', '  ');
        }
        charCount = temp.length;
        return charCount;
    }
    return 0;
}

function showAllowedLength(curField, maxLimit, isJSpell) {
    if (curField!=null)
    {
        if (isJSpell) {
            curField.body.innerText = curField.body.innerText.substr(0, maxLimit);
            window.status = curField.body.innerText;
        }
        else {
            curField.value = curField.value.substr(0, maxLimit);
            window.status = curField.value;
        }
    }
}