(function ($) {
    $.fn.customScrollableTabs = function () {
        this.each((index, value) => {
            initializeCustomScrollableTavs($(value));
        });
    };

    function initializeCustomScrollableTavs($element) {
        setLastItemPadding($element);
        if ($element.find(".active").length > 0) {
            $element.scrollLeft($element.find(".active").position().left);
        }

        let scrollTreshold = 10;
        let inScroll = false;
        let preventClick = false;
        let startLocationX;
        let StartScrollLocation;

        $element.on("mousedown touchstart", function (e) {
            startLocationX = getPageX(e);
            StartScrollLocation = $element.scrollLeft();
            inScroll = true;
        });

        $element.on("mousemove touchmove", function (e) {
            if (!inScroll) return;

            $element.scrollLeft(StartScrollLocation + (startLocationX - getPageX(e)));
        });

        $element.on("mouseup touchend", function (e) {
            inScroll = false;
            preventClick = Math.abs(startLocationX - getPageX(e)) > scrollTreshold;
        });

        $("body").on("mouseup touchend", function (e) {
            if (!inScroll) return;

            inScroll = false;
            preventClick = Math.abs(startLocationX - getPageX(e)) > scrollTreshold;
        });

        $element.on("click touch", function (e) {
            if (preventClick) e.preventDefault();
        });

        $(window).on("resize", function () {
            setLastItemPadding($element);
        });

        function getPageX(e) {
            if (e.originalEvent.targetTouches && e.originalEvent.targetTouches.length > 0)
                return e.originalEvent.targetTouches[0].pageX;

            if (e.originalEvent.changedTouches && e.originalEvent.changedTouches.length > 0)
                return e.originalEvent.changedTouches[0].pageX;

            return e.pageX;
        }

        function setLastItemPadding($element) {
            let $lastTabItem = $element.find("li").last();
            let $tabbedButtons = $(".buttons-tabbed");
            $lastTabItem.css("padding-right", $tabbedButtons.width() + "px");
        }
    }
}(jQuery));

$(document).ready(function () {
    $(".custom-scrollable-tabs").customScrollableTabs();
});