/*
	Author: Jeremy Espinosa
	Filename: characterCounter.js
	Description: Counting charater inside an input or textarea and can display how many characters left to show
	Dependencies:
		- jQuery
	How to use:
		1. The input/textarea must have a js-character-counter class
		2. Must have these following attribute:
			- data-character-max = max character that can accept by the input/textarea
			- data-character-display = the targetted element where the count will display
	Sample HTML:
		<input type="text" class="js-character-counter" data-character-max="100" data-character-display="#js-character-display">
		
		<div id="js-character-display"></div>
*/

;(function($) {
    'use strict'

    B2C.characterCounter = {
        init: function(option) {
            this._default = {
                target: '.js-character-counter',
                characterMax: 100,
                characterDisplay: '#js-character-display'
            }

            this._option = $.extend(true, this._default, option)

            if (!$(this._option.target).length) return

            this.domCache()
            this.onloadCharacterCount()
            this.eventHandler()
        },

        domCache: function() {
            this.$target = $(this._option.target)
        },

        eventHandler: function() {
            const self = this

            this.$target.on('keydown keyup', function(e) {
                // update character count on each key typed
                self.updateCharacterCount(this)
            })
        },

        onloadCharacterCount: function() {
            const self = this

            this.$target.each(function() {
                let characterMax =
                        $(this).data('character-max') ||
                        self._option.characterMax,
                    characterDisplay =
                        $(this).data('character-display') ||
                        self._option.characterDisplay

                // to set max character length can be input
                $(this).prop('maxlength', characterMax)
                // render the number of character maximum length
                $(characterDisplay).text(characterMax)
            })
        },

        updateCharacterCount: function(element) {
            let $element = $(element),
                $characterDisplay = $($element.data('character-display')),
                characterMax = $element.data('character-max'),
                characterCount = $element.val().length,
                characterCalc = characterMax - characterCount

            if (characterCalc >= 0) {
                $characterDisplay.text(characterCalc)
            }
        }
    }

    const defaultCharacterCounter = Object.create(B2C.characterCounter)

    defaultCharacterCounter.init()
})(jQuery)
