// https://github.com/SrcFlux/jquery-nameBadges/blob/master/jquery.nameBadges.js
// customized by mailbeez

(function ($) {
    $.fn.nameBadge = function (options) {
        var settings = $.extend({
            border: {
                color: '#ddd',
                width: 3
            },
            colors: ['#a3a948', '#edb92e', '#f85931', '#ce1836', '#009989'],
            text: '#fff',
            size: 72,
            margin: 5,
            middlename: true,
            uppercase: false
        }, options);
        return this.each(function () {

            var elementText = $(this).data('name');

            if (elementText === undefined) {
                var elementText = $(this).text().trim();
                $(this).data('name', elementText.trim());
            }

            var initialLetters = elementText.match(settings.middlename ? /\b(\w)/g : /^\w|\b\w(?=\S+$)/g);

            if (initialLetters == null) {
                var initials = "-";
            } else {
                var initials = initialLetters.join('');

            }

            $(this).text(initials);


            // uppercase unicode
            // A 65
            // Z 90
            ucMin = 65;
            ucMax = 90;

            val1 = Math.min(ucMax, initials.toUpperCase().charCodeAt(0));
            num2 = Math.max(ucMin, elementText.toUpperCase().charCodeAt(Math.floor(elementText.length/2)));
            if (num2 != 'NaN') {
                val2 = Math.min(ucMax, num2);
                // val = Math.max(val1, val2);
                val = val1 + val2;
                normalized = (val - (ucMin + ucMin)) / ((ucMax + ucMax) - (ucMin + ucMin));
            } else {
                val = val1;
                normalized = (val - (ucMin )) / ((ucMax ) - (ucMin ));
            }


            // normalized = (x-Math.min(x))/(Math.max(x)-Math.min(x))


            $(this).css({
                'color': settings.text,
                'background-color': settings.colors[Math.floor(normalized * settings.colors.length)],
                'border': settings.border.width + 'px solid ' + settings.border.color,
                'display': 'inline-block',
                'font-family': 'Arial, \'Helvetica Neue\', Helvetica, sans-serif',
                'font-size': settings.size * 0.4,
                'border-radius': settings.size + 'px',
                'width': settings.size + 'px',
                'height': settings.size + 'px',
                'line-height': settings.size + 'px',
                'margin': settings.margin + 'px',
                'text-align': 'center',
                'text-transform': settings.uppercase ? 'uppercase' : ''
            });
        });
    };
}(jQuery));