// Add the default callBack-handler:
Widget.addCallBack("ColorPicker", function(params) {
	// Add the widget to the DatePicker handler:
	Widget.getClass("ColorPicker").addWidget(params.widgetId);
});

/**
 * The color picker static class.
 * 
 * @version 2010-02-07
 * @author <a href="mailto:r.tennapel@griponservice.nl?SUBJECT=ColorPicker script.js">R. ten Napel, ing.</a>
 **/
function ColorPicker() {}

ColorPicker.widgets = Array();
ColorPicker.handlers = Array();

/**
 * Add a widget to the list of ColorPicker widgets to be handled when a color is selected. If the ID is already
 * stored, it won't be added.
 * 
 * @param widgetId			The widget ID of the widget to handle.
 * 
 * @return					The index of the widget ID.
 **/
ColorPicker.addWidget = function(widgetId) {
	// Retrieve the index of the given widget:
	var i = this.widgets.indexOf(widgetId);
	
	// If no index, add the widget and handler array:
	if (i == -1) {
		this.widgets.add(widgetId);
		this.handlers.add(Array());
		
		i = this.widgets.length - 1;
	}
	
	return i;
};

/**
 * Add a handler to the list. If a widget ID already exists, it'll be used.
 * 
 * @param widgetId			The widget ID of the widget to handler.
 * @param handler			The handler corresponding to the widget.
 **/
ColorPicker.addHandler = function(widgetId, handler) {
	// Add the widget and retrieve it's index:
	var i = this.addWidget(widgetId);
	
	// If the widget exists add the handler:
	this.handlers[i].add(handler);
};

/**
 * Select a color, update this widget and all the widgets in the handler.
 * 
 * @param widgetId			The ID of the ColorPicker widget that triggers the selection.
 * @param color				The color that is selected.
 * @param update			The ID of the input element to update it's value.
 **/
ColorPicker.selectColor = function(widgetId, color, update) {
	// Retrieve the right handlers which belong to the given widget:
	var i = this.widgets.indexOf(widgetId);
	
	// Add widget if not yet exists:
	if (i == -1) {
		i = this.addWidget(widgetId);
	}
	
	// Call each handler:
	var handlers = this.handlers[i];
	for (var j = 0; j < handlers.length; j++) {
		handlers[j].apply(this, new Array(color));
	}
	
	// Update the input element's value:
	if (update != null) {
		$(update).$().value = color;
	}
	
	// Refresh the widget:
	new Widget($(widgetId).$().parentNode, "ColorPicker").refresh("widgetId=" + widgetId + "&color=" + color);
};

//Store the ColorPicker static JS class:
Widget.addClass("ColorPicker", ColorPicker);
