jQuery(document).ready(function(){
	/**
	 * 1. clear the legend text
	 * 2. move the label from the first list element into the legend tag
	 * 3. move and append the selectbox of the first list element into the legend tag
	*/
	jQuery("fieldset.wfSection").each(function( ) {
		jQuery(this).addClass('startclosed')
		jQuery(this).find("legend").empty();
		jQuery(this).find("legend").prepend(jQuery(this).find("div > span > span:first > label"));
		jQuery(this).find("legend").prepend(jQuery(this).find("div > span > span:first > input"));
		jQuery(this).find("div > span > span:first").remove();
		jQuery(this).find("div > span > br:first").remove();
		jQuery(this).find("div > span > br:first").remove();
		if (jQuery(this).find("legend > input[type='checkbox']").is(":checked")) {
			jQuery(this).removeClass('startclosed').addClass('startopened');
		}
	});
	jQuery("fieldset.startopened").collapse( { closed : false } );
	jQuery("fieldset.startclosed").collapse( { closed : true } );
});

jQuery.fn.collapse = function(options) {
	var defaults = {
		closed : false
	}
	settings = jQuery.extend({}, defaults, options);

	return this.each(function() {

		var obj = jQuery(this);
		obj.find("legend:first").addClass('collapsible');
		obj.find("legend:first > input[type='checkbox']").click(function() {

			obj.find("div > ul > li").each(function( ) {
				var liObj = jQuery(this);
				liObj.find("input[type='checkbox']").attr('checked',false).removeAttr("checked");
				var checkboxId = replace('check_', '', liObj.find("input[type='checkbox']").attr("id"));
				var inputObject = jQuery("#" + checkboxId);
				inputObject.val('');
			});

			if (obj.hasClass('collapsed'))
			{
				obj.removeClass('collapsed').addClass('collapsible');
			}
			jQuery(this).removeClass('collapsed');
			obj.children().not('legend').toggle("fast", function() {

				 if (jQuery(this).is(":visible"))
					obj.find("legend:first").addClass('collapsible');
				 else
					obj.addClass('collapsed').find("legend").addClass('collapsed');
			 });
		});
		if (settings.closed) {
			obj.addClass('collapsed').find("legend:first").addClass('collapsed');
			obj.children().not("legend:first").css('display', 'none');
		}
	});
};

// replaces the original replace function and make it work like the php equivalnt
function replace(f, r, s)
{
	var ra = r instanceof Array, sa = s instanceof Array, l = (f = [].concat(f)).length, r = [].concat(r), i = (s = [].concat(s)).length;
	while(j = 0, i--)
		while(s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j < l);
	return sa ? s : s[0];
}

