// Typekit
try{Typekit.load();}catch(e){}

/**
 * Based on scrollable dropdown solution from http://css-tricks.com/long-dropdowns-solution/
 */
$(function(){
    $(".dropdown > li").hover(function() {
        var verticalOffset = 100; // how much additional space reserve for dropdown
        // cache values, so they're not recalculated onmousemove
        var $container = $(this);
        var $list = $container.find("ul");
        var listPaddingTop = parseInt($list.css("padding-top"), 10);
        var listOuterWidth = $list.outerWidth();
        var listOuterHeight = $list.outerHeight();
        
        var maxHeight = $(window).height() - verticalOffset - listPaddingTop;
        var multiplier = listOuterHeight / maxHeight;
        
        $list
            .show()
            .css({
                // using clip instead of overflow to prevent cutting list item with flexible width
                clip: "rect(" + listPaddingTop + "px " + listOuterWidth + "px " + maxHeight + "px 0)"
        });
        // don't do any animation if list shorter than max
        if (multiplier > 1) {
            $container.mousemove(function(e) {
                var offset = $container.offset();
                var relativeY = (e.pageY - offset.top - listPaddingTop) * multiplier;
                var top = -relativeY + listPaddingTop;
                var clipTop = -top + listPaddingTop;
                var clipBottom = -top + maxHeight;
                var clipHeight = maxHeight - listPaddingTop;
                var clippedBottomHeight = (listOuterHeight + top - clipHeight - listPaddingTop);
                if (relativeY > listPaddingTop
                    && clippedBottomHeight >= 0) {
                    $list.css({
                        top: top,
                        clip: "rect(" + clipTop + "px " + listOuterWidth + "px " + clipBottom + "px 0)"
                    });
                };
                if (clippedBottomHeight < 0) {
                    // final values
                    var finalTop = -(listOuterHeight - clipHeight - listPaddingTop);
                    var finalClipTop = -finalTop + listPaddingTop;
                    var finalClipBottom = -finalTop + maxHeight;
                    $list.css({
                        top: finalTop,
                        clip: "rect(" + finalClipTop + "px " + listOuterWidth + "px " + finalClipBottom + "px 0)"
                    });
                }
            });
        }
    }, function() {
        // put things back to normal
        $(this).find("ul")
            .css({
                top: 0,
                clip: "auto"})
            .hide();
    });
    
    // Ensure that mousemove is not triggered with old context
    $(window).resize(function(e) {
        $(".dropdown > li").unbind("mousemove");
    });
});
