
jQuery.fn.collapse = function (options) {
	var show_text = '<span class="collapsible_show_hide"> - Click to show</span>';
	var hide_text = '<span class="collapsible_show_hide"> - Click to hide</span>';
	return this.each(function (index, element) {
		// TODO: this needs looking at...the bug is that this doesn't collapse 2nd level fieldsets if there are more than 1 collapsible fieldset with sub collapsible fieldsets...haven't tried 3rd or deeper levels - GC will look into this but not an issue at the moment
		$('> legend:first', element).click(function() {
			var fieldset = $(element);
			if (fieldset.hasClass('collapsible_collapsed')) {
				fieldset.removeClass('collapsible_collapsed');
				fieldset.children().not('legend,script').show('fast');
				$(this).find('.collapsible_show_hide').html(" - Click to hide");
				
			} else {
				fieldset.addClass('collapsible_collapsed');
				fieldset.children().not('legend,script').each(function () {
					$(this).hide('fast', function () {
						$(this).css('display', 'none');
					});
				});
				$(this).find('.collapsible_show_hide').html(" - Click to show");
				
			}
		});
		
		// Initial state
		if ($(element).hasClass('collapsible_collapsed') || $(element).hasClass('collapsible_collapsed_slow')) {
			if ($(element).hasClass('collapsible_collapsed_slow')) {
				$(element).children().not('legend,script').hide('slow');
			} else {
				$(element).children().not('legend,script').hide();
			}
			
			$('> legend:first', element).html(
				$('> legend:first', element).html().replace(hide_text, '')
				+ show_text
			);
		} else {
			$('> legend:first', element).html(
				$('> legend:first', element).html().replace(show_text, '')
				+ hide_text
			);
		}
	});
};

