/** @file
 * 
 *
 */
(function($){

    var debug = function(msg){};

    if ( window.console && window.console.log ) {
        debug = function(msg) {
            window.console.log(msg);
        };
    }

    /**
     * Create a section wrapper element.
     */
    function createWrapper(html, theClass, element){
        debug('Begining new section w/ class = ' + theClass);

        // Section wrapper
        var $sect = $(html);
        if (theClass) {
            $sect.addClass(theClass);
        }
        
        // Header wrapper
        if ( element ) {
            var $head = $('<div class="hd"></div>');
            $head.append(element);
            $sect.append($head);
        }

        // Body wrapper
        var $body = $('<div class="bd"></div>');
        $sect.append($body);

        return $sect
    }

    $.fn.sectionate = function(args){
        var opt = $.extend({}, $.fn.sectionate.defaults, args);

        var sect = "<"+opt.wholeElement +">" + "</"+opt.wholeElement+">";
        var sectClass = opt.wholeClass;

        return this.each(function(){
            var $this = $(this);
            var $kids = $this.children();

            // Create the first wrapper
            var $sect = false;
            var $body = $sect;

            // Process the children
            for ( i=0; i < $kids.length; i++ ) {
                if ( $($kids[i]).is(opt.headSelector) ) {
                    if ( $sect ) 
                        $sect.insertBefore($kids[i]);
                    $sect = createWrapper(sect, sectClass, $kids[i]);
                    $body = $('.bd', $sect);
                } else {
                    if ( ! $sect ) {
                        $sect = createWrapper(sect, sectClass);
                        $body = $('.bd', $sect);
                    }
                    $body.append($kids[i]);
                }
            }

            // 
            if ( $kids.length > 0 ) {
                $this.append($sect);
            }
        });
    };

    $.fn.sectionate.defaults = 
        { 'headSelector': 'h1,h2,h3'
        , 'headElement': 'div'
        , 'bodyElement': 'div'
        , 'wholeElement': 'div'
        , 'headClass': 'hd'
        , 'bodyClass': 'bd'
        , 'wholeClass': 'section'
        };
})(jQuery);
