/* Responsive product header javascript.

   @file        product-header.en.js
   @author      marionm
   ========================================================================== */

$(document).ready(function() {
    // set variables
    var _ph = '#_product-header',
        _phHeight = 42,
        _phLandingHeight = 55;

    // proceed only if product header is present
    if ($(_ph).length > 0) {

/* ==========================================================================
   mobile nav
   ========================================================================== */

        // show mobile nav
        var _showMobileNav = function() {
            // determine if mobile nav is open
            if ($('#_product-name').hasClass('open')) {
                // mobile nav is already open; close it
                _hideMobileNav();
            } else {
                // mobile nav is closed; open it
                $('#_product-name').addClass('open');

                // reposition backdrop
                var _backdropOffset = document.getElementById('_product-header').offsetTop + _phHeight;
                $('#_product-backdrop').css('top', _backdropOffset+'px').css('height', $('body').outerHeight(true) - _backdropOffset);

                // show backdrop
                $('#_product-backdrop').show();
            }
        }

        // hide mobile nav
        var _hideMobileNav = function() {
            // close mobile nav
            $('#_product-name').removeClass('open');

            // hide backdrop
            $('#_product-backdrop').hide();
        }

        // show click events
        $('#_product-name, #_product-mobile, #_product-mobile svg').on('click', function(e) {
            // determine which nav action to do
            var width = (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) ? document.documentElement.clientWidth : window.innerWidth;
            if (width <= 600) {
                // page is narrow, show mobile nav
                _showMobileNav();
            } else {
                // page is wide, go to url
                window.location = $('#_product-name h1').data('url');
            }
        });

        // hide click events
        $('#_product-mobile ul, #_product-backdrop').on('click', _hideMobileNav);

        // scroll to hide mobile nav
        $(window).on('scroll', _hideMobileNav);

        // fix iOS link double click bug
        $('#_product-mobile a').on('click', function() {
            window.location = $(this).attr('href');
        });

/* ==========================================================================
   subnavs
   ========================================================================== */

        // open a specific subnav
        var _showSubnavs = function(t) {
            // hide more nav
            _hideMoreNav();

            // open subnav
            $(t).toggleClass('open').children('._product-is-subnav').toggleClass('hide');
        }

        // close all subnavs
        var _hideSubnavs = function() {
            $('#_product-nav ._product-has-subnav').removeClass('open');
            $('#_product-nav ._product-is-subnav').addClass('hide');
        }

        // ignore empty anchor tags on subnav triggers
        $('#_product-nav ._product-has-subnav > a').on('click', function(e) {
            e.preventDefault();
        });

        // scroll or click outside area to hide subnavs
        $(window).on('click scroll', _hideSubnavs);

        // toggle subnavs on click
        $('#_product-nav ._product-has-subnav').on('click', function(e) {
            // override window click event above
            e.stopPropagation();

            // determine if a specific subnav is open
            if ($(this).hasClass('open')) {
                // subnav is open; close them all
                _hideSubnavs();
            } else {
                // subnav is closed; close others and open this one
                _hideSubnavs();
                _showSubnavs(this);
            }
        });

/* ==========================================================================
   more nav
   ========================================================================== */

        // show more nav
        var _showMoreNav = function(e) {
            // override window click event
            e.stopPropagation();

            // hide subnavs
            _hideSubnavs();

            // determine if more nav is open
            if ($('#_product-more').hasClass('open')) {
                // more nav is open; close it
                _hideMoreNav();
            } else {
                // more nav is closed; open it
                $('#_product-more').addClass('open');
            }
        }

        // hide more nav
        var _hideMoreNav = function() {
            $('#_product-more').removeClass('open');
        }

        // reset more nav
        var _resetMoreNav = function() {
            // hide more nav and all it's items
            $('#_product-more').removeClass('open');
            $('#_product-more, #_product-more ul li').addClass('hide').removeClass('match');

            // reset width of product nav so it may be centered on the landing page
            $('#_product-nav').css('width', 'auto');
        }

        // click outside area to hide more nav
        $(window).on('click', function(e) {
            // determine if click target is outside of the more nav container
            if ($(e.target).attr('id') !== '_product-more' || $(e.target).parents('#_product-more').length > 0) {
                // click target confirmed, hide more nav
                _hideMoreNav();
            }
        });

        // hide more nav on scroll
        $(window).on('scroll', _hideMoreNav);

        // toggle more nav on click
        $('#_product-more').on('click', function(e) {
            _showMoreNav(e);
        });

/* ==========================================================================
   assess the nav for situational changes
   ========================================================================== */

        // assess environment to determine how nav should look and behave
        var _assessNav = _throttle(function(e) {
            var _scrollTop = $(window).scrollTop(),
                _offsetTop = document.getElementById('_product-anchor').offsetTop,
                _offsetGlobal = _headerHeight,
                _viewportWidth = (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) ? document.documentElement.clientWidth : window.innerWidth;

/* manage sticky class
   ========================================================================== */

            if ($('html._product-header-landing').length > 0) {
                // wait until the right time to make the product nav sticky
                if (_scrollTop <= 0 || _scrollTop < _offsetTop - _offsetGlobal) {
                    // user has scrolled down but has not yet reached the minimum offset
                    if ($('#_product-header').hasClass('sticky')) $('#_product-header').removeClass('sticky');
                } else {
                    // user has scrolled down past the minimum offset
                    if (!$('#_product-header').hasClass('sticky')) $('#_product-header').addClass('sticky');
                }
            } else {
                // make sticky by default for subpages
                if (!$('#_product-header').hasClass('sticky')) $('#_product-header').addClass('sticky');
            }

/* manage backdrop
   ========================================================================== */

            if (_viewportWidth <= 600) {
                // reposition backdrop
                var _backdropOffset = document.getElementById('_product-header').offsetTop + _phHeight;
                $('#_product-backdrop').css('top', _backdropOffset+'px').css('height', $('body').outerHeight(true) - _backdropOffset);
            }

/* manage global header
   ========================================================================== */

            if ($('#_header').hasClass('_temporarily-scrollable')) {
                // temporarily move product nav off screen
                $('#_product-header').css('top', -100);
            } else {
                // restore top position
                $('#_product-header').css('top', '');
            }

/* manage viewport
   ========================================================================== */

            // determine if more nav should be enabled
            if (_viewportWidth > 600) {
                // hide mobile nav
                _hideMobileNav();

                // reset width of product nav so it may be centered on the landing page
                $('#_product-nav').css('width', 'auto');

                // remove match classes from main nav items
                $('#_product-nav > ul > li.match').removeClass('match');

                // set variables
                var _navRect = $('#_product-nav')[0].getBoundingClientRect(),
                    _navWidth = _navRect.width,
                    _moreRect = $('#_product-end')[0].getBoundingClientRect(),
                    _moreWidth = _moreRect.width,
                    _navItemWidth = 0,
                    i = 0;

                // calculate total width of nav items
                $('#_product-nav > ul > li').each(function() {
                    // get item width
                    var thisRect = $(this)[0].getBoundingClientRect();

                    // add item width to total
                    _navItemWidth += thisRect.width;
                });

                // move nav items to more nav as page size decreases
                if (_navItemWidth > _navWidth - _moreWidth) {
                    // loop through more nav items
                    $('#_product-more ul li').each(function() {
                        // hide items by default
                        $(this).addClass('hide').removeClass('match');

                        // look for text match on main nav
                        var navMatch = $('#_product-nav > ul > li:contains("'+$(this).text().trim()+'")');
                        if (navMatch.length > 0) {
                            // match found, get more details
                            var offset = navMatch.position();
                            if (offset.top > 0) {
                                // offset found, show this item
                                $(this).removeClass('hide').addClass('match');

                                // add match class
                                navMatch.addClass('match');

                                i++;
                            }
                        }

                        // look for text match on subnavs
                        var subnavMatch = $('#_product-nav > ul > li ul li:contains("'+$(this).text().trim()+'")');
                        if (subnavMatch.length > 0) {
                            // match found, get item offset
                            var offset = subnavMatch.parent().parent('li').position();
                            if (offset.top > 0) {
                                // offset found, show this item
                                $(this).removeClass('hide').addClass('match');

                                // add match class
                                subnavMatch.parent().parent('li').addClass('match');

                                i++;
                            }
                        }
                    });

                    // determine what to do based on how many nav items were affected
                    if (i == 0) {
                        // no nav items affected, hide more nav
                        _resetMoreNav();
                    } else {
                        // affected nav items found, show more nav
                        $('#_product-more').removeClass('hide');

                        // adjust width of main nav so it may be centered on the landing page
                        var matchWidth = 0;
                        $('#_product-nav > ul > li').each(function() {
                            // get item details
                            var offset = $(this).position(),
                                rect = $(this)[0].getBoundingClientRect();
                            if (offset.top == 0) {
                                // offset found, add item width to total
                                matchWidth += rect.width;
                            }
                        });

                        // adjust main nav width
                        $('#_product-nav').css('width', matchWidth+'px');
                    }
                } else {
                    // main nav has plenty of room, hide more nav
                    _resetMoreNav();
                }
            } else {
                // main nav is hidden in favor of mobile nav, hide more nav
                _resetMoreNav();
            }

            // re-trigger the resize event when it's finished; ensures the more nav only shows when needed
            // the timeout is absolutely necessary, and it absolutely must be longer than the _assessNav's _throttle function timeout (which is 250ms by default)
            var _resizeTimer;
            $(window).on('resize', function(e) {
                clearTimeout(_resizeTimer);
                _resizeTimer = setTimeout(_assessNav, 300);
            });
        });

        // handle events
        $(window).on('load scroll resize pageshow pagehide', _assessNav);
    }
});