// Add the default callBack-handler:
Widget.addCallBack("DatePicker", function(params) {
	// Add the widget to the DatePicker handler:
	Widget.getClass("DatePicker").addWidget(params.widgetId);
});

/**
 * The date picker static class.
 * 
 * @version 28-02-2010
 * @author <a href="mailto:r.tennapel@griponservice.nl?SUBJECT=DatePicker script.js">R. ten Napel, ing.</a>
 **/
function DatePicker() {}

DatePicker.widgets = Array();
DatePicker.handlers = Array();

/**
 * Add a widget to the list of DatePicker widgets to be handled when a date 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.
 **/
DatePicker.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.
 **/
DatePicker.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 date, update this widget and all the widgets in the handler.
 * 
 * @param widgetId			The ID of the DatePicker widget that triggers the selection.
 * @param date				The date that is selected.
 * @param update			The ID of the input element to update it's value.
 **/
DatePicker.selectDate = function(widgetId, date, 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(date));
	}
	
	// Update the input element's value:
	if (update != null && update != "") {
		//Debugger.write("$('" + update + "').$().value = " + date);
		
		//alert(update);
		$(update).$().value = date;
	}
	
	// Refresh the widget:
	update = (update != null) ? "&update=" + update : "";
	//Debugger.write("Widget($('" + widgetId + "').$().parentNode, \"DatePicker\").refresh('widgetId=" + widgetId + "&date=" + date + update + ");");
	new Widget($(widgetId).$().parentNode, "DatePicker").refresh("widgetId=" + widgetId + "&date=" + date + update);
};

//Store the DatePicker static JS class:
Widget.addClass("DatePicker", DatePicker);
