;(function($) {
/* The tv2alignListElements plugin takes a HTML list, ol or ul, traverse
 * its list items, and align their heights, so that the elements will align
 * nicely next to each others.
 *
 * It works by setting a height on the elements, so the list elements should
 * be floated block-elements.
 *
 * The list element should have a TV 2 css container type set, .con-[1-12],
 * and the list item elements should have a TV 2 col type set, .col-[1-12].
 * If not, it will do nothing to the list, and the plugin will just return
 * the input unchanged.
 *
 * This is not the best solution in the world, but it works in our supported
 * browsers.
 *
 * NB: This plugin requires the Array Chunk extension.
 *
 * Example of usage:
 * - $('ol.blog-authors').tv2alignListElements();
 */
$.fn.tv2alignListElements = function(options) {

    return this.each(function() {
        /* container is an ol, or an ul. */
        var $container = $(this);

        /* - return container if it is not an ol, or an ul. */
        var tag = $container[0].tagName.toLowerCase();
        if(tag != 'ol' && tag != 'ul') return $container;

        /* Get the width of the container,
         * - return the container if none */
        var li = $('li:first',$container)[0],
            cons = /con-([0-9]*)/.exec($container[0].className),
            cols = /col-([0-9]*)/.exec(li.className);

        if(cons && cons[1] && cols && cols[1]){
            cons = cons[1]; cols = cols[1];
        }
        else
            return $container;

        /* sanitiy check on the cols to con ratio, if not sane, do nothing */
        if(cons % cols == 0){
            /* find the chunk size-divide them into rows, and align height */
            var chunkSize = cons/cols;

            $($.chunk($('> li', $container), chunkSize)).each(function(){
                var tallest = 0;
                $(this).each(function(){
                    var current = $(this).height();
                    tallest = current > tallest ? current : tallest;
                }).height(tallest);
            });
        }

        return $container;
    });
};

})(jQuery);
