/*
 * Simple jquery module to allow collapsing parts of the HTML page.
 */
(function($) {
    var options = {};
    var default_options = {
	'min_elements': 10,
	'header': '.collapsible_header',
	'holder': '.collapsible_content',
	'elements': 'tr',
	'collapsed_class': 'collapsed',
	'expanded_class': 'expanded'
    };


    function make_default_options(opts) {
	/* Copy default options to the options dictionnary. */
        if (typeof(opts) == 'undefined') {
            opts = {};
        }
	
        for (key in default_options) {
            if (typeof(opts[key]) == 'undefined') {
                opts[key] = default_options[key];
            }
        }

	options = opts;
    };

    $.fn._next_with_class = function(cl) {
	/* Finds the next element with a given class */
	if (this.length == 0) {
	    return this;
	}
	
	el = $(this[0]).next();
	while (el.length > 0 && !el.hasClass(cl)) {
	    el = el.next();
	}
	return el;
    };

    $.fn.collapsible = function(opts) {
	make_default_options(opts);

	return this.each(function() {
	    var nb_elements = $(this).find(options['holder'] + ' ' + options['elements']).length;
	    if (nb_elements < options['min_elements']) {
		/* Not enough elements, we do not do anything */
		return;
	    }

	    $(this).find(options['holder']).hide();
	    $(this).find(options['header']).addClass(options['collapsed_class']);

	    $(this).find(options['header']).click(function(e) {
		e.preventDefault();
		var content = $(this)._next_with_class(options['holder']);
		if ($(this).hasClass(options['collapsed_class'])) {
		    content.show();
		}
		else {
		    content.hide();
		}

		$(this).toggleClass(options['expanded_class']);
		$(this).toggleClass(options['collapsed_class']);
	    });
	});
    };
})(jQuery);
