﻿$(document).ready(function() {

    $('.hp_dd ul li ul li.subItem').css('display', 'none');
    $('.hp_dd ul li ul').css('height', 'auto');
    
    $('.main_nav ul li.top').hoverIntent(function() {
        if ($('.hp_dd:visible').size() == 0) {
            $(this).find('.hp_dd').slideDown(400);
        }
        else {
            var link = $(this);
            $('.hp_dd:visible').hide(0, function() {
                link.find('.hp_dd').show();
            });

        }
    },
    function() {
    });

    $('.hp_dd.dropdown').hover(function() { }, function() {
        $('.hp_dd.dropdown').slideUp(400);
    });

    $.each($('.hp_dd ul'), function() {
        var maxHeight = 362;
        var totalHeight = 0;
        var heightIncrement = 0;
        var itemCollection = $(this).find('li');
        var htmlCollection = new Array();
        var htmlInsert = '';
        $.each(itemCollection, function() {
            var cssClass = $(this).attr('class');
            var hasSpacedParent = $(this).parents('div');
            if (cssClass == 'subItem' && hasSpacedParent.attr('class') != 'spaced') {
                //if ($(this).find('a').html().toString().length > 40)
                //    heightIncrement = 50;
                //else
                heightIncrement = 20;
                htmlInsert += '<li class="subItem">' + $(this).html() + '</li>';
            }
            else {
                if (hasSpacedParent.attr('class') == 'spaced')
                    heightIncrement = 90;
                else
                    heightIncrement = 40;
                htmlInsert += '<li>' + $(this).html() + '</li>';
            }
            if ((totalHeight + heightIncrement) >= maxHeight) {
                htmlCollection.push(htmlInsert);
                htmlInsert = '';
                totalHeight = 0;
            }
            else {
                totalHeight += heightIncrement;
            }
        });

        //now add the final html!
        if (htmlInsert != '') htmlCollection.push(htmlInsert);

        var htmlToInsert = '';
        for (index in htmlCollection) {
            htmlToInsert += '<ul>' + htmlCollection[index] + '</ul>';
        }
        $(this).parent().html(htmlToInsert);
    });
});
