$(document).ready(function(){
    
    // Generate 3 new columns
    $(".products-dropdown .category-list").after("<div class='category-list product-col generated' /><div class='category-list product-col generated' /><div class='category-list product-col generated' />");
    
    // Distribute the lists between the new generated blocks
    $(".products-dropdown ul.second-level").each(function(idx, el) {
        var targetCol = getTargetColumn();
        
        $(el).prev("h4").remove().appendTo(targetCol);
        $(el).remove().appendTo(targetCol);
    });

    // Remove the original (non-generated) block
    $(".products-dropdown .category-list:not(.generated)").remove();
    
   // Hide the tabs on the product/category pages, if only 1 tab is visible
    if ($(".products div#tabs ul li").length == 1)
        $(".products div#tabs ul").hide();
    
    // Expand the current product
    $(".prod-cats li.current").parents("ul").show();
    
});

function getTargetColumn() {
    
    var smallest;

    $(".products-dropdown .category-list.generated").each(function(idx, el) {
        if (smallest) {            
            if (smallest.find("li").length > $(el).find("li").length)
                smallest = $(el);
        }
        else {
            smallest = $(el);
        }
    });
    
    return smallest;
    
}
