$(function() {
    if ($('.columns .menu').length) {
        $('.columns .menu .container').jScrollPane();
        var jscroll = $('.columns .menu .container').data('jsp');
    }
    
    function checkFlyingMenu() {
        var windowScrollTop = $(window).scrollTop();
        if (windowScrollTop > 20) {
            $('.topMenu').css('visibility','hidden');
            $('#flying').show();
            $('#flying .topMenu').css('visibility','visible');
        } else {
            $('.topMenu').css('visibility','visible');
            $('#flying').hide();
        }
        if ($('.columns .menu').length) {
            var menuOffset = $('.columns')[0].offsetTop,
                contentHeight = $('.columns').height(),
                menuHeight = $(window).height()-43;
            if (windowScrollTop+43 > menuOffset) {
                if ((windowScrollTop - menuOffset + menuHeight) > contentHeight  - 73 ) {
                    menuHeight = contentHeight - (windowScrollTop - menuOffset) - 73;
                }
                $('.columns .menu .container').addClass('flying').height(menuHeight);
            } else {
                $('.columns .menu .container').scrollTop(0).removeClass('flying').removeAttr('style');
                $('.jspContainer').height($('.columns .menu ul').height());
            }
            jscroll.reinitialise();
        }
    }
    
    $('.columns .menu li a').click(function() {
        var anchor = $(this).attr('href').split('#')[1],
            anchorSelector = $('a.anchor[id="' + anchor + '"]');
        if (anchorSelector.length) {
            var anchorPosition = anchorSelector.offset().top;
            $('html, body').stop(true,true).animate({scrollTop: anchorPosition}, 500, function() {
                document.location.hash = anchor;
            });
        } else {
            $('html, body').stop(true,true).animate({scrollTop: 0}, 500, function() {
                document.location.hash = "";
            });
        }
        return false; 
    });
    
    $(window).resize(function() {
        checkFlyingMenu();
    });
    
    $(window).scroll(function() { 
        checkFlyingMenu();
    });
    
});

