/**
 * jquery.row-sync.js
 *
 * A plugin to sync elements' heights within a table-like structure.
 *
 * Usage:
 * rowSync(rowSelector, itemsPerRow, [syncSelector, [setCallback, [reduceCallback]]])
 * 
 * Example:
 * $('ul.items').rowSync('>li', 4, 'h3');
 * 
 * Will sync all h3's per 4 li elements to the same height. h3 is a jquery selector, so you can use
 * complex selectors too. You can supply an array of selectors to sync heights per child selectors
 * within the cell, e.g.:
 *
 * $('ul.items').rowSync('>li', 4, ['h3', 'p']);
 * 
 * With no selector given as a third argument, the li's are individually synced in height.
 *
 * An optional fourth and fifth argument are available to change the behaviour, e.g. use an animation
 * to change the height (with setCallback), or use an alternate method of determining the height
 * (reduceCallback)
 * 
 * @copyright Zicht Online <http://zicht.nl>
 * @author Gerard van Helden <gerard@zicht.nl>
 */

;(function($){
    $.tabularGroup = function(parentElement, childSelector, itemsPerRow) {
        var table = [];
        var cellIndex = 0;
        var row = [];
        $(childSelector, parentElement).each(function(j, c) {
            row.push(c);
            if(cellIndex++ % itemsPerRow == itemsPerRow -1) {
                table.push(row);
                row = [];
            }
        });
        if(row.length) {
            table.push(row);
        }
        return table;
    }

    function getMaxHeight(elements) {
        var max = -1;
        $(elements).each(function() {
            max = Math.max($(this).height(), max);
        });
        return max;
    }

    function setHeight(elements, value) {
        $(elements).css('height', value);
    }

    $.fn.extend({
        'rowSync': function (childSelector, itemsPerRow, syncSelectors, setCallback, reduceCallback) {
            setCallback = setCallback || setHeight;
            reduceCallback = reduceCallback || getMaxHeight;

            if(typeof syncSelectors == 'string') {
                syncSelectors = [syncSelectors];
            } else if(typeof syncSelectors == 'undefined') {
                syncSelectors = [''];
            }

            $(this).each(function(i, e){
                var table = $.tabularGroup(e, childSelector, itemsPerRow);

                $.each(table, function(x){
                    $.each(syncSelectors, function(syncIndex, syncSelector) {
                        var cells;
                        if(syncSelector == '') {
                            cells = $(table[x]);
                        } else {
                            cells = $(syncSelector, table[x]);
                        }
                        setCallback(cells, reduceCallback(cells));
                    });
                });
            });

            return this;
        }
    });
})(jQuery);
    

