﻿/*
Silver Earth - columnize multi-level menu
Heavily modified, but based on:

Copyright (c) 2007 Christian yates
christianyates.com
chris [at] christianyates [dot] com
Licensed under the MIT License: 
http://www.opensource.org/licenses/mit-license.php
 
Inspired by work of Ingo Schommer
http://chillu.com/2007/9/30/jquery-columnizelist-plugin
*/
(function ($) {
    $.fn.columnizeList = function (settings) {
        settings = $.extend({
            maxRows: 18,
            columnWidth: 240
        }, settings);

        var chillun = this.children();
        chillun.each(function (i) {
            var list = chillun.eq(i);
            var menu = list.children('ul').first();
            menu.addClass("menu-first-ul");
            var size = $('li', menu).size();
            if (size < settings.maxRows) return; //no need to columnize

            var cols = Math.ceil(size / settings.maxRows);
            var rows = Math.ceil(size / cols);
            var items = menu.children();
            var count = 0;
            var done = 0;

            menu.css('width', (settings.columnWidth * cols) + 'px');
            var ul = null;
            items.each(function (j) {
                var li = items.eq(j);
                count += 1;
                var liul = li.children('ul');
                if (liul.size() > 0) {
                    count += liul.children('li').size();
                }
                if (ul != null) {
                    li.detach();
                    ul.append(li);
                }
                if (count >= rows) {
                    done += 1;
                    menu.after('<ul style="margin-left: ' + (done * settings.columnWidth + 1) + 'px; border-left: none; border-bottom: none; border-right: none;">');
                    ul = menu.next();
                    count = 0;
                }
            });
            if (done > 0) {
                var sibs = list.children('ul');
                var h = 0;
                sibs.each(function (k) {
                    h = Math.max(h, sibs.eq(k).height());
                });
                menu.height(h);
            }
        });
        return;
    };
})(jQuery);

