// Made in a singleton-ish style. Defines the class and
// immediately creates the one-and-only instance of it.

sense.ui.widget.Manager = new (Class.create(sense.Base, {
	//Properties
	registry: new Hash(),
	debug: false,

	//Methods
	initialize: function($super, element, options) {
		//Call Parent Constructor
		$super();

		document.observe('dom:loaded', this.initializeWidgets.bind(this));
		document.observe('dom:updated', this.initializeWidgets.bind(this));
	},

	register: function(widgetType){
		if (typeof widgetType == 'string') {
			widgetType = { constructor:widgetType };
		}

		if (!widgetType.selector) widgetType.selector = '.js' + widgetType.constructor;
		if (!widgetType.options) widgetType.options = {};
		
		widgetType.instances = [];

		this.registry.set(widgetType.constructor, widgetType);
	},

	initializeWidgets: function() {
		this.registry.values().each(function(widgetType){

			// If the widget definition .js file has not been loaded, just return.
			if (typeof sense.ui.widget[widgetType.constructor] == 'undefined') return;
			if (this.debug) console.log(widgetType);

			// Iterate through each DOM element matching the selector and pass it into the constructor.
			$$(widgetType.selector).each(function(el){

				// Make sure that we only initialise a widget once.
				if (typeof el[widgetType.constructor] != 'undefined') return;
				if (this.debug) console.log(el);

				if (widgetType.options) {
					var instance = new sense.ui.widget[widgetType.constructor](el, widgetType.options);
				} else {
					var instance = new sense.ui.widget[widgetType.constructor](el);
				}

				el[widgetType.constructor] = instance;
				widgetType.instances.push(instance);

			}.bind(this));

		}.bind(this));
	},
	
	getInstances: function(widgetType) {
		var obj = this.registry.get(widgetType);
		return (obj) ? obj.instances : false;
	}
}))();

// A short-hand reference for ease of use in the console
var uim = sense.ui.widget.Manager;
