/**
 * Table row alternate style plugin for jQuery
 * Applies a selected css style to alternate table rows.
 *
 * @author Mick Wingert, Visual Jazz
 * @version1.0
 *
 * @param {odd, even}
 * odd: class name for odd <tr> elements {default = "odd"}
 * even: class name for even <tr> elements {default = "even"}
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @example $('table').tableAlt({});
 *
 * @$('table').tableAlt({odd:'alt'});
 *
 * @$('table').tableAlt({odd:'alt', even:'opp'});
 *
 * All the parameters are optional.
 *
 */

(function($) {

    $.fn.tableAlt = function(options) {
        
        var options = $.extend({}, $.fn.tableAlt.defaults, options);
        
        this.each(function(){
            var $this = $(this);
            
            // if there are row spans, get max columns
            var maxColumns = $this.find('tr:has(td[rowspan]):first td').length;

            // if there aren't any rowspans, get the max columns
            if(maxColumns <= 0)
                maxColumns = $this.find('tr:not(td[rowspan]):first td').length;

            // Find and loop each table row, and return the row element that has children
            // that equal the max column count. Apply the css class based on orientation
            if(options.odd.length > 0){
                $this.data('maxColumns', maxColumns).find('tr').filter(function(){
                    var $this = $(this);
                    return $this.children().length == $this.closest('table').data('maxColumns');
                }).filter(':odd').addClass(options.odd);
                
                // If there are rowspan elements, loop through each one, and process the adjoining
                // row elements to add the css class
                $this.find('tr.' + options.odd + ' td[rowspan]').each(function(){
                    $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass(options.odd);
                });
            }
            
            if(options.even.length > 0){
                $this.data('maxColumns', maxColumns).find('tr').filter(function(){
                    var $this = $(this);
                    return $this.children().length == $this.closest('table').data('maxColumns');
                }).filter(':even').addClass(options.even);
                
                // If there are rowspan elements, loop through each one, and process the adjoining
                // row elements to add the css class
                $this.find('tr.' + options.even + ' td[rowspan]').each(function(){
                    $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass(options.even);
                });
            }
        });
    };

    $.fn.tableAlt.defaults = {
        odd: '',
        even: ''
    };

})(jQuery);
