﻿jQuery(document).ready(function() {
    var ul1 = jQuery('#footer div.extendedContainer.vertical #footerNavigation ul.level1');
    var ul2 = jQuery('#footer div.extendedContainer.vertical #footerNavigation ul.level2');
    var ul2Heading = jQuery('#footer div.extendedContainer.vertical a.navHeading');
    var custom = jQuery('#footer div.unmanagedContent');

    // important! set width before height, as setting the width may cause wrapping, which affects height.
    setFooterWidth(ul1, ul2, ul2Heading, custom);
    setFooterHeight(ul1, ul2, ul2Heading, custom);

});

function setFooterHeight(ul1, ul2, ul2Heading, custom) {
    // Only alter height if both UL's are visible, it's vertical mode, and the second level is greater than the first
    if (ul2.length > 0 || custom.length > 0) {
        var ul1Height = getUlHeight(ul1);
        var ul2Height = getUlHeight(ul2);
        var ul2HeaderHeight = ul2Heading.outerHeight(true);
        var customHeight = custom.outerHeight(true);

        var increase = (ul2HeaderHeight + ul2Height) > customHeight ? (ul2HeaderHeight + ul2Height) - ul1Height : customHeight - ul1Height;
        if (increase > 0) {
            // need to set the height using the element height (with no padding, border, margin) so cannot use ul1Height
            ul1.height(ul1.height() + increase);
        }
    }
}

function setFooterWidth(ul1, ul2, ul2Heading, custom) {
    // If both uls are visible, then ul2 expands to fit its content (it's absolutely positioned), meaning that it can overlap
    // the dynamic content.
    // Only alter width of 2nd level if both UL's are visible and it's vertical mode and if custom nav is visible. If only the
    // 2nd level is visible, then it is floated, meaning that we don't have an overlap problem.
    if (ul2.length == 0 || ul1.length == 0 || custom.length == 0) {
        return;
    }

    var ul2Left = ul2.offset().left;
    var customLeft = custom.offset().left;
    var width = customLeft - ul2Left;
    ul2.width(width);
    ul2Heading.width(width);
}

function getUlHeight(ul) {
    accumulatedHeight = 0;

    jQuery(ul).each(function(index) {
        accumulatedHeight += jQuery(this).outerHeight(true);
    })

    return accumulatedHeight;
}
