/*
 * (c) 2016 .hausformat
 *
 * This file only contains functions it does not do anything by itself!
 */

;(function () {

    'use strict'

    // import jquery
    var $ = jQuery

    // this is our namespace for all functions
    var hf = {}

    // export 'hf' as a global variable
    window.hf = hf
    
    /**
     * When the $element reaches the offsetTop offset its position is set to 'fixed'.
     *
     * @param {jQuery|string|Element} $element
     * @param {number} offsetTop
     * @param {string} [activeClass='is-sticky']
     */
    hf.stickyElement = function ($element, offsetTop, activeClass) {
        var $clone

        activeClass = activeClass || 'is-sticky'
        $element = jQuery($element)

        function check () {
            if ($clone) {
                unstick()
            } else {
                stick()
            }
        }

        function stick() {
            var top = $element[ 0 ].getBoundingClientRect().top

            if (top <= offsetTop) {
                $clone = $element.clone()
                $clone.hide()
                $clone.insertAfter($element)

                $element.addClass(activeClass)
                $element.css({
                    position: 'fixed',
                    top: ''  + offsetTop + 'px'
                })
            }
        }

        function unstick() {
            $clone.show()

            var top = $clone[ 0 ].getBoundingClientRect().top

            $clone.hide()

            if (top > offsetTop) {
                $clone.remove()
                $clone = null

                $element.removeClass(activeClass)
                $element.css({
                    position: '',
                    top: ''
                })
            }
        }

        $(window).scroll(check)
        check()
    }
})();
