/*
	Author: Gab Nucum
	Filename: smoothScroll.js
	Description: Element with scroll effect when clicking.
	Dependencies:
		- jQuery
	How to use:
		1. The element must have a 'js-smooth-scroll' class.
		2. Must have either an attribute of 'href' or 'data-target' to work.
	Sample HTML:
		<ul class="js-position-sticky nav justify-content-center bg-gray">
			<li><a href="#twenty" class="js-smooth-scroll" data-toggle="tab">1920's</a></li>
		</ul>

		<ul class="js-position-sticky nav justify-content-center bg-gray">
			<li><a data-target="#twenty" class="js-smooth-scroll" data-toggle="tab">1920's</a></li>
		</ul>
*/

;(function($) {
    "use strict"

    B2C.smoothScroll = {
        init: function(option) {
            this._default = {
                target: ".js-smooth-scroll",
                navigation: ".js-position-sticky",
                navigationClass: "sticky-heading"
            }

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

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

            this.eventHandler()
            this.stickyPosition()
        },

        eventHandler: function() {
            const self = this

            $(this._option.target).on("click", function(e) {
                self.smoothScroll(self, this)
                e.preventDefault()
            })
        },

        smoothScroll: function(self, element) {
            let dataTarget =
                    $(element).attr("href") || $(element).data("target"),
                offset = $(dataTarget).offset().top,
                height = 55

            if ($(self._option.navigation).length) {
                height = $(self._option.navigation).height()
            }

            $("html, body")
                .stop()
                .animate(
                    {
                        scrollTop: offset - height
                    },
                    1000
                )
        },

        stickyPosition: function() {
            let self = this,
                stickyOffset = $(self._option.navigation).offset().top

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

            $(window).scroll(
                _.debounce(function() {
                    let $sticky = $(self._option.navigation),
                        scroll = $(window).scrollTop()

                    if (scroll >= stickyOffset)
                        $sticky.addClass(self._option.navigationClass)
                    else $sticky.removeClass(self._option.navigationClass)
                }, 100)
            )
        }
    }

    const defaultSmoothScroll = Object.create(B2C.smoothScroll)

    defaultSmoothScroll.init()
})(jQuery)
