package various.uicomponents;

import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;

public class ComboFieldsetRenderer extends Renderer {

	public final static String SCRIPT = " $.fn.collapse = function(options) {"
			+ "var defaults = {"
			+ "closed : false"
			+ "}"
			+ "settings = $.extend({}, defaults, options);"
			+ "return this.each(function() {"
			+ "var obj = $(this);"
			+ "obj.find('legend').addClass('collapsible').click(function() {"
			+ "if (obj.hasClass('collapsed'))"
			+ "	obj.removeClass('collapsed').addClass('collapsible');"
			+ "$(this).removeClass('collapsed');"
			+ "obj.children().not('legend').toggle('slow', function() {"
			+ "if ($(this).is(':visible'))"
			+ "obj.find('legend').addClass('collapsible');"
			+ "else	obj.addClass('collapsed').find('legend').addClass('collapsed');"
			+ "});" + "});" + "if (settings.closed) {"
			+ "obj.addClass('collapsed').find('legend').addClass('collapsed');"
			+ "obj.children().not('legend').css('display', 'none');" + "}"
			+ "});" + "};";

//	@Override
//	public void decode(FacesContext context, UIComponent _component) {
//		ComboFieldset component = (ComboFieldset) _component;
//		Map<String, String> requestMap = context.getExternalContext()
//				.getRequestParameterMap();
//		String clientId = component.getClientId(context);
//
//		if (requestMap.containsKey(clientId + ComboFieldset.UNROLL_SYMBOL))
//			component.setRolled(true);
//		else
//			component.setRolled(false);
//	}

	@Override
	public void encodeBegin(FacesContext context, UIComponent _component)
			throws IOException {
		ComboFieldset component = (ComboFieldset) _component;
		if (!component.isRendered()) {
			return;
		}

		String clientId = component.getClientId(context);
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement("fieldset", component);
		if (component.isRolled())
			writer.writeAttribute("class", "collapsible", null);
		else
			writer.writeAttribute("class", "startClosed", null);
		writer.writeAttribute("id", clientId, null);
		writer.startElement("legend", component);
		if (component.getLegend() != null)
			writer.write(component.getLegend());
		writer.endElement("legend");
	}

//	@Override
//	public void encodeChildren(FacesContext arg0, UIComponent arg1)
//			throws IOException {
//		super.encodeChildren(arg0, arg1);
//	}

	@Override
	public void encodeEnd(FacesContext context, UIComponent component)
			throws IOException {
		ResponseWriter writer = context.getResponseWriter();
		writer.endElement("fieldset");

	}

	@Override
	public boolean getRendersChildren() {
		return false;

	}

}
