//ex: init_scroll_obj($('.scroll-div-container'));

function init_scroll_obj(obj) {
    var SETTINGS = {
        navBarTravelling: false,
        navBarTravelDirection: '', //left|right
        navBarTravelDistance: 200
    };

    // Out advancer buttons
    var left_arrow = obj[0].querySelector('.scroll-div-left-arrow');
    var right_arrow = obj[0].querySelector('.scroll-div-right-arrow');
    // the indicator
    var active_item = obj[0].querySelector('.scroll-div-active-item');

    var scrollable_div = obj[0].querySelector('.scroll-div-scrollable');
    var contents_div = obj[0].querySelector('.scroll-div-contents');

    scrollable_div.setAttribute('data-overflowing', determineOverflow(contents_div, scrollable_div));

    // Set the indicator
    if (scrollable_div.querySelector('.scroll-div-item[aria-selected=\'true\']') != null)
        moveIndicator(scrollable_div.querySelector('[aria-selected=\'true\']')/*, colours[0]*/);

    // Handle the scroll of the horizontal container
    var last_known_scroll_position = 0;
    var ticking = false;
    function doSomething(scroll_pos) {
        scrollable_div.setAttribute('data-overflowing', determineOverflow(contents_div, scrollable_div));
    }

    scrollable_div.addEventListener('scroll', function (e) {
        last_known_scroll_position = window.scrollY;
        if (!ticking) {
            window.requestAnimationFrame(function () {
                doSomething(last_known_scroll_position);
                ticking = false;
            });
        }
        ticking = true;
    });

    if (left_arrow != null) {
        left_arrow.addEventListener('click', function () {
            // If in the middle of a move return
            if (SETTINGS.navBarTravelling === true)
                return;
            // If we have content overflowing both sides or on the left
            if (determineOverflow(contents_div, scrollable_div) === 'left' || determineOverflow(contents_div, scrollable_div) === 'both') {
                // Find how far this panel has been scrolled
                var availableScrollLeft = scrollable_div.scrollLeft;
                // If the space available is less than two lots of our desired distance, just move the whole amount
                // otherwise, move by the amount in the settings
                if (availableScrollLeft < SETTINGS.navBarTravelDistance * 2)
                    contents_div.style.transform = 'translateX(' + availableScrollLeft + 'px)';
                else
                    contents_div.style.transform = 'translateX(' + SETTINGS.navBarTravelDistance + 'px)';
                // We do want a transition (this is set in CSS) when moving so remove the class that would prevent that
                contents_div.classList.remove('scroll-div-contents-no-transition');
                // Update our settings
                SETTINGS.navBarTravelDirection = 'left';
                SETTINGS.navBarTravelling = true;
            }
            // Now update the attribute in the DOM
            scrollable_div.setAttribute('data-overflowing', determineOverflow(contents_div, scrollable_div));
        });
    }

    if (right_arrow != null) {
        right_arrow.addEventListener('click', function () {
            // If in the middle of a move return
            if (SETTINGS.navBarTravelling === true)
                return;
            // If we have content overflowing both sides or on the right
            if (determineOverflow(contents_div, scrollable_div) === 'right' || determineOverflow(contents_div, scrollable_div) === 'both') {
                // Get the right edge of the container and content
                var navBarRightEdge = contents_div.getBoundingClientRect().right;
                var navBarScrollerRightEdge = scrollable_div.getBoundingClientRect().right;
                // Now we know how much space we have available to scroll
                var availableScrollRight = Math.floor(navBarRightEdge - navBarScrollerRightEdge);
                // If the space available is less than two lots of our desired distance, just move the whole amount
                // otherwise, move by the amount in the settings
                if (availableScrollRight < SETTINGS.navBarTravelDistance * 2)
                    contents_div.style.transform = 'translateX(-' + availableScrollRight + 'px)';
                else
                    contents_div.style.transform = 'translateX(-' + SETTINGS.navBarTravelDistance + 'px)';
                // We do want a transition (this is set in CSS) when moving so remove the class that would prevent that
                contents_div.classList.remove('scroll-div-contents-no-transition');
                // Update our settings
                SETTINGS.navBarTravelDirection = 'right';
                SETTINGS.navBarTravelling = true;
            }
            // Now update the attribute in the DOM
            scrollable_div.setAttribute('data-overflowing', determineOverflow(contents_div, scrollable_div));
        });
    }

    contents_div.addEventListener('transitionend', function () {
        // get the value of the transform, apply that to the current scroll position (so get the scroll pos first) and then remove the transform
        var styleOfTransform = window.getComputedStyle(contents_div, null);
        var tr = styleOfTransform.getPropertyValue('-webkit-transform') || styleOfTransform.getPropertyValue('transform');
        // If there is no transition we want to default to 0 and not null
        var amount = Math.abs(parseInt(tr.split(',')[4]) || 0);
        contents_div.style.transform = 'none';
        contents_div.classList.add('scroll-div-contents-no-transition');
        // Now lets set the scroll position
        if (SETTINGS.navBarTravelDirection === 'left')
            scrollable_div.scrollLeft = scrollable_div.scrollLeft - amount;
        else
            scrollable_div.scrollLeft = scrollable_div.scrollLeft + amount;
        SETTINGS.navBarTravelling = false;
    }, false);

    // Handle setting the currently active link
    contents_div.addEventListener('click', function (e) {
        var links = [].slice.call(contents_div.querySelectorAll('.scroll-div-item'));
        links.forEach(function (item) {
            item.setAttribute('aria-selected', 'false');
        });
        e.target.setAttribute('aria-selected', 'true');
        // Pass the clicked item and it's colour to the move indicator function
        moveIndicator(e.target/*, colours[links.indexOf(e.target)]*/);
    });

    // var count = 0;
    function moveIndicator(item) {
        if (active_item == null)
            return;
        var textPosition = item.getBoundingClientRect();
        var container = contents_div.getBoundingClientRect().left;
        var distance = textPosition.left - container;
        var scroll = contents_div.scrollLeft;
        active_item.style.transform = 'translateX(' + (distance + scroll) + 'px) scaleX(' + textPosition.width * 0.01 + ')';
        // count = count += 100;
        // active_item.style.transform = 'translateX(' + count + 'px)';
        //if (color)
        active_item.style.backgroundColor = '#867100';
        //}
    }

    function determineOverflow(content, container) {
        var containerMetrics = container.getBoundingClientRect();
        var containerMetricsRight = Math.floor(containerMetrics.right);
        var containerMetricsLeft = Math.floor(containerMetrics.left);
        var contentMetrics = content.getBoundingClientRect();
        var contentMetricsRight = Math.floor(contentMetrics.right);
        var contentMetricsLeft = Math.floor(contentMetrics.left);
        if (containerMetricsLeft > contentMetricsLeft && containerMetricsRight < contentMetricsRight) {
            return 'both';
        } else if (contentMetricsLeft < containerMetricsLeft) {
            return 'left';
        } else if (contentMetricsRight > containerMetricsRight) {
            return 'right';
        } else
            return 'none';
    }

}


/**
 * @fileoverview dragscroll - scroll area by dragging
 * @version 0.0.8
 * 
 * @license MIT, see http://github.com/asvd/dragscroll
 * @copyright 2015 asvd <heliosframework@gmail.com> 
 * 
 * Add the dragscroll class to a scrollable element
 * If you add or remove the dragscroll class dynamically, invoke dragscroll.reset() to update the listeners.
 * You can also add the nochilddrag attribute to a scrollable element, which will only enable drag-scrolling 
 * for an element itself, but not for its subchildren.
 */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['exports'], factory)
    } else if (typeof exports !== 'undefined') {
        factory(exports)
    } else {
        factory((root.dragscroll = {}))
    }
}(this, function (exports) {
    var _window = window;
    var _document = document;
    var mousemove = 'mousemove';
    var mouseup = 'mouseup';
    var mousedown = 'mousedown';
    var EventListener = 'EventListener';
    var addEventListener = 'add' + EventListener;
    var removeEventListener = 'remove' + EventListener;
    var newScrollX, newScrollY;
    var dragged = [];
    var reset = function (i, el) {
        for (i = 0; i < dragged.length; ) {
            el = dragged[i++];
            el = el.container || el;
            el[removeEventListener](mousedown, el.md, 0);
            _window[removeEventListener](mouseup, el.mu, 0);
            _window[removeEventListener](mousemove, el.mm, 0)
        }
        dragged = [].slice.call(_document.getElementsByClassName('dragscroll'));
        for (i = 0; i < dragged.length; ) {
            (function (el, lastClientX, lastClientY, pushed, scroller, cont) {
                //
                (cont = el.container || el)[addEventListener](mousedown/*touchstart*/, cont.md = function (e) {
                    if (!el.hasAttribute('nochilddrag') || _document.elementFromPoint(e.pageX, e.pageY) == cont) {
                        pushed = 1;
                        lastClientX = e.clientX;
                        lastClientY = e.clientY;
                        el.setAttribute('data-start-clientX', lastClientX);
                        el.setAttribute('data-start-clientY', lastClientY);
                        e.preventDefault();
                    }
                }, 0);
                //
                _window[addEventListener](mouseup/*touchend*/, cont.mu = function () {
                    pushed = 0;
                    //added by bilal
                    //here if scroll is small then remove class directly to be able to fire click else wait ms. to remove it
                    var amountX = lastClientX - el.getAttribute('data-start-clientX');
                    var amountY = lastClientY - el.getAttribute('data-start-clientY');
                    if (!isNaN(amountX) && !isNaN(amountY) && Math.abs(amountX) < 5 && Math.abs(amountY) < 5)
                        el.classList.remove("dragscroll-inprogress");
                    else
                        setTimeout(function () {
                            el.classList.remove("dragscroll-inprogress");
                        }, 30);
                }, 0);
                //
                _window[addEventListener](mousemove, cont.mm = function (e) {
                    if (pushed) {
                        //added by bilal
                        el.classList.add("dragscroll-inprogress");
                        (scroller = el.scroller || el).scrollLeft -= newScrollX = (-lastClientX + (lastClientX = e.clientX));
                        scroller.scrollTop -= newScrollY = (-lastClientY + (lastClientY = e.clientY));
                        if (el == _document.body) {
                            (scroller = _document.documentElement).scrollLeft -= newScrollX;
                            scroller.scrollTop -= newScrollY
                        }
                    }
                }, 0);
            })(dragged[i++]);
        }
    };
    if (_document.readyState == 'complete')
        reset();
    else
        _window[addEventListener]('load', reset, 0);
    exports.reset = reset
}));


//
function init_swipe_obj(obj, tmp_optns) {
    obj.each(function () {
        var el = $(this);
        //we clone it since object send by reference so if we change here it will change by the main variable we send
        var optns = (tmp_optns == undefined || tmp_optns == '' || tmp_optns == false || tmp_optns == null) ? {} : Object.create(tmp_optns);
        var dflt_optns = {
            margin_px: 5, //type: right, left, top, bottom
            scroll_ft: function (type, amount_px) {}
        };
        dflt_optns = $.extend(true, {}, dflt_optns, optns);
        var is_pushed = 0;
        el.on('mousedown touchstart', function (e) {
            is_pushed = 1;
            el.attr('data-start-clientX', (e.type == 'touchstart' ? e.originalEvent.touches[0].clientX : e.clientX));
            el.attr('data-start-clientY', (e.type == 'touchstart' ? e.originalEvent.touches[0].clientY : e.clientY));
        });
        //
        $(window).on('mouseup touchend', function (e) {
            if (is_pushed == 1) {   //since here mouse up on windows we make this check
                is_pushed = 0;
                //here if scroll is small then defined margin pixel then it is not scroll just click
                var amountX = (e.type == 'touchend' ? e.originalEvent.changedTouches[0].clientX : e.clientX) - el.attr('data-start-clientX');
                var amountY = (e.type == 'touchend' ? e.originalEvent.changedTouches[0].clientY : e.clientY) - el.attr('data-start-clientY');
                if (!isNaN(amountX) && Math.abs(amountX) > dflt_optns.margin_px) {
                    if (el.css('direction') == 'rtl')
                        dflt_optns.scroll_ft((amountX > 0 ? 'left' : 'right'), amountX);
                    else
                        dflt_optns.scroll_ft((amountX > 0 ? 'right' : 'left'), amountX);
                }
                if (!isNaN(amountY) && Math.abs(amountY) > dflt_optns.margin_px)
                    dflt_optns.scroll_ft((amountY > 0 ? 'bottom' : 'top'), amountY);
            }
        });
    });
}
