jQuery(function () {
    'use strict';

    var indexURL = jQuery('link[rel="header_link"]').attr('href');
    if(indexURL && jQuery('header').length) {
        jQuery('header').attr('data-setlocation', indexURL);
    }

    $(document)
        .on('click.themler', ['a', 'form', 'input', 'button', 'textarea'].map(function(tag) { return 'header[data-setlocation] ' + tag; }).join(', '), function (e) {
            // avoid event propagation to clickable header
            e.stopPropagation();
        })
        .on('click.themler', 'header[data-setlocation]', function () {
            var elem = $(this),
                href = elem.data('setlocation');
            window.location.href = href;
        });

    function adminAffix(el) {
        el.off('affix-calc.theme.affix').on('affix-calc.theme.affix', function (e) {
            var offset = 0,
                el = jQuery(this),
                fixAtScreen = jQuery(this).data('fixAtScreen'),
                elOffset = parseInt(el.data('offset'), 10) || 0,
                adminHeight = jQuery('#wpadminbar').outerHeight() || 0;

            if (fixAtScreen === 'top' && elOffset < adminHeight) {
                offset = adminHeight - elOffset;
            }

            e.offset = offset;
        });
    }

    jQuery('body').on('affix-init.theme.affix', function (e, el) {
        if (!el) return;
        adminAffix(el);
    });

    adminAffix(jQuery('[data-fix-at-screen]'));

    $('[data-smooth-scroll] a[href*="#"]').each(function () {
        var href = $(this).attr('href');
        if (href.indexOf(window.location.href) === 0) {
            href = href.replace(window.location.href, '');
            if (href.charAt(0) === '#') {
                $(this).attr('href', href);
            }
        }
    });

    if (window.wpJQuery) {
        window.wpJQuery(document.body).bind('added_to_cart', function () {
            jQuery(document).trigger('force-grid-update');
        });
    }
});

@baseTemplate
