/*
	Author: Thelma Suyam
	Filename: popover.js
	Description: This is to auto expand one lined text on click
	How to use:  
	Note: 
*/
;(function($) {
    'use strict'

    B2C.popover = {
        init: function(option) {
            this._default = {
                openButton: '.js-popover-btn', //dropdown
                target: '.js-popover',
                closeButton: 'js-popover-close',
                container: '.js-popover-container'
            }

            this._option = $.extend({}, this._default, option)

            if (!$(this._option.openButton)) return

            this.onLoad()
            this.eventListener()
        },

        onLoad: function() {
            let self = this
            $(this._option.openButton).each(function() {
                let content = $(this)
                    .closest(self._option.container)
                    .find(self._option.target)
                    .html()

                $(this)
                    .popover({
                        html: true,
                        content: function() {
                            return content
                        }
                    })
                    .on('show.bs.popover', function(e) {
                        $('[rel=popover]')
                            .not(e.target)
                            .popover('destroy')
                        $('.popover').remove()
                    })
            })
        },

        eventListener: function() {
            let self = this

            $(document).on('click', function(e) {
                if ($(e.target).hasClass(self._option.closeButton)) {
                    self.closePopup(self, $(e.target).parents('.popover'))
                } else {
                    $('[data-toggle=popover]').each(function() {
                        if (
                            !$(this).is(e.target) &&
                            $(this).has(e.target).length === 0 &&
                            $('.popover').has(e.target).length === 0
                        ) {
                            $(this).popover('hide')
                        }
                    })
                }
            })
        },

        closePopup: function(self, element) {
            $(element).popover('hide')
        }
    }

    const defaultPopover = Object.create(B2C.popover)

    defaultPopover.init()
})(jQuery)
