var maxCharsOldOnload = window.onload;
window.onload = function()
{
    if (typeof maxCharsOldOnload == 'function')
    {
         maxCharsOldOnload();
    }

    window.maxCharsInstance = new maxCharsScript();
    maxCharsInstance.init();
}


var maxCharsScript = function()
{
    this.classPrefix = 'maxChars';
    this.charsLeftSuffix = 'CharsLeft';
    this.areas = [];
}


maxCharsScript.prototype.init = function()
{
    this.initTextAreas();
}

maxCharsScript.prototype.initTextAreas = function()
{
    var textAreas = document.getElementsByTagName('textArea');
    var script = this;

    for (var i=0; i<textAreas.length; i++)
    {

        var textArea = textAreas[i];
        var className = textArea.className;
        if (!className)
        {
            continue;
        }

        var id = textArea.id;
        if (!id)
        {
            return;
        }

        var charsLeftBox = document.getElementById( id.concat(this.charsLeftSuffix) )
        if (!charsLeftBox)
        {
            return;
        }

        var maxChars = null;
        classNames = className.split(' ');
        for (var j=0; j < classNames.length; j++ )
        {
            if (classNames[j].substring(0, this.classPrefix.length) != this.classPrefix)
            {
                continue;
            }
            var valuePart = classNames[j].substring( this.classPrefix.length );
            if (!valuePart.match(/^\d+$/))
            {
                continue;
            }
            maxChars = parseInt( valuePart );
        }

        if (!maxChars)
        {
            continue;
        }

        textArea.maxChars = maxChars;
        textArea.charsLeftBox = charsLeftBox;


        textArea.textAreaChanged = function()
        {
            script.textAreaChanged( this );
        }

        textArea.onchange         = textArea.textAreaChanged;
        textArea.onkeypress       = textArea.textAreaChanged;
        textArea.onkeyup          = textArea.textAreaChanged;
        textArea.onclick          = textArea.textAreaChanged;
        textArea.onpropertychange = textArea.textAreaChanged;

        textArea.textAreaChanged();
    }


}

maxCharsScript.prototype.textAreaChanged = function( textArea )
{
    if (
        (!textArea.maxChars)
        ||
        (!textArea.charsLeftBox)
    )
    {
        return false;
    }

    var symbolsLeft = textArea.maxChars - textArea.value.length;
    if (symbolsLeft < 0)
    {
        textArea.value = textArea.value.substring(0, textArea.maxChars);
    }

    this.updateCharsLeft( textArea );
    return true;

}


maxCharsScript.prototype.updateCharsLeft = function( textArea )
{
    if (
        (!textArea.maxChars)
        ||
        (!textArea.charsLeftBox)
    )
    {
        return false;
    }


    textArea.charsLeft = textArea.maxChars - textArea.value.length;
    textArea.charsLeftBox.innerHTML = textArea.charsLeft;
    return;
}
