/* jQuery MaxLength for INPUT and TEXTAREA fields v1.1
* Updated: Modernized and optimized for better browser support.
* Author: JavaScript Kit at http://www.javascriptkit.com/
* Updated for modern best practices.
*/

var thresholdcolors = [
    ['20%', 'darkred'],
    ['10%', 'red']
]; // [chars_left_in_pct, CSS color to apply to output]

// Sort thresholdcolors by percentage, ascending
thresholdcolors.sort(function (a, b) {
    return parseInt(a[0]) - parseInt(b[0]);
});

// Keycodes that are not checked when the limit is reached (backspace, enter, shift, ctrl, alt)
var uncheckedkeycodes = /^(8|13|16|17|18)$/;

function setformfieldsize($fields, optsize, optoutputdiv) {
    $fields.each(function () {
        var $field = $(this);
        // Get max character limit from attribute or passed option
        var maxsize = optsize || parseInt($field.attr('data-maxsize'), 10);
        $field.data('maxsize', maxsize);

        var statusdivid = optoutputdiv || $field.attr('data-output');
        var $statusdiv = $('#' + statusdivid);

        // Check if status output div exists and store reference
        $field.data('$statusdiv', $statusdiv.length === 1 ? $statusdiv : null);

        // Attach keypress and keyup event handlers
        $field.off('keypress.restrict').on('keypress.restrict', function (e) {
            restrictInput($field, e);
        });

        $field.off('keyup.show').on('keyup.show', function () {
            showLimit($field);
        });

        // Show initial character limit status
        showLimit($field);
    });
}

function restrictInput($field, e) {
    var keyunicode = e.charCode || e.keyCode;
    if (!uncheckedkeycodes.test(keyunicode)) {
        if ($field.val().length >= $field.data('maxsize')) {
            e.preventDefault ? e.preventDefault() : (e.returnValue = false); // Prevent input if max length reached
            return false;
        }
    }
}

function showLimit($field) {
    var maxsize = $field.data('maxsize');
    var text = $field.val();
    if (text.length > maxsize) {
        $field.val(text.substring(0, maxsize)); // Trim excess characters if exceeded
    }

    var $statusdiv = $field.data('$statusdiv');
    if ($statusdiv) {
        // Update character count display
        $statusdiv.html(text.length).css('color', '');

        // Calculate percentage of remaining characters and apply color threshold
        var pctremaining = ((maxsize - text.length) / maxsize) * 100;
        for (var i = 0; i < thresholdcolors.length; i++) {
            if (pctremaining <= parseInt(thresholdcolors[i][0], 10)) {
                $statusdiv.css('color', thresholdcolors[i][1]);
                break;
            }
        }
    }
}

// On DOM ready
jQuery(document).ready(function ($) {
    var $targetfields = $("input[data-maxsize], textarea[data-maxsize]"); // Select inputs and textareas with 'data-maxsize' attribute
    setformfieldsize($targetfields);
});