﻿

jQuery.fn.ulcolumns = function(options) {

    // default settings
    var options = jQuery.extend({
        cols: 4, // Cols
        cClass: 'list', //listclass
        ExtraHeight: 20
    }, options);

    return this.each(function() {


        var height = jQuery(this).height();
        var colHeight = Math.ceil(height / options.cols) + options.ExtraHeight;
        var kids = jQuery(this).children();

        var totHeight = 0;

        var usedHeight = 0;

        var $parent;

        var currentColl = options.cols + 1;


        if (height > 0) {

            for (var i = kids.length - 1; i >= 0; i--) {

                var itemHeight = kids[i].clientHeight;

                if (totHeight == 0 || (totHeight + itemHeight) > colHeight && currentColl > 1) {
                    totHeight = 0;
                    currentColl--;
                    $parent = $('<' + this.nodeName + ' class="' + options.cClass + ' ' + options.cClass + '-' + currentColl + '"></' + this.nodeName + '>');
                    $parent.insertAfter(jQuery(this));

                    colHeight = Math.ceil((height - usedHeight) / currentColl) + options.ExtraHeight;
                }


                if ((totHeight + itemHeight) < colHeight || currentColl == 1 || totHeight == 0) {
                    $parent.prepend(kids[i]);
                    totHeight = totHeight + itemHeight;
                    usedHeight += itemHeight;
                }
            }


            jQuery(this).remove();

        }

    });

};