/**
 * @author Darius kruythoff <darius@mangrove.nl>
 */
DualSelect = Class.create({
	/**
	 * Constructor
	 * @param Element The select element
	 * @param {Object} Options
	 */
	initialize: function(selectElement, options){
		this.selectField = $(selectElement);
		this.options = options||{};
		
		// Store all optgroups
		this.optGroups = [];
		
		this.groupField = $(document.createElement('select'));
		this.groupField.addClassName(this.selectField.className);
		this.groupField.removeClassName('dual-select');
		
		if (this.options.startGroup) {
			var groupOption = document.createElement('option');
			groupOption.setAttribute('value',this.optGroups.length);
			groupOption.appendChild(document.createTextNode(this.options.startGroup));
			this.groupField.appendChild(groupOption);
			
			this.optGroups.push({
				label:   this.options.startGroup,
				options: []
			});
		}
		
		this.selectField.select('optgroup').each(function(element){
			var groupOption = document.createElement('option');
			groupOption.setAttribute('value',this.optGroups.length);
			groupOption.appendChild(document.createTextNode(element.readAttribute('label')));
			this.groupField.appendChild(groupOption);
			
			this.optGroups.push({
				label:   element.readAttribute('label'),
				options: element.select('option')
			});
			
			if (element.select('option[selected]').length > 0) {
				groupOption.setAttribute('selected','selected');
			}
		}.bindAsEventListener(this));
		
		this.selectField.up('p').insert({'before':this.groupField.wrap('p')});
		this.updateSelection();
		this.groupField.observe('change', this.updateSelection.bindAsEventListener(this));
	},
	/**
	 * Update the 2nd select with the options from the selected optgroup
	 */
	updateSelection: function(){
		this.selectField.childElements().invoke('remove');
		var options = this.optGroups[this.groupField.getValue()].options;
		if (options.length > 0) {
			options.each(function(opt){this.selectField.insert(opt);}.bindAsEventListener(this));
			this.selectField.show();
		} else {
			this.selectField.hide();
		}
	}
});

var dual_select_rules = {
	'select.dual-select': function() {
		new DualSelect(this,{
			startGroup: ' Alle divisies '
		});
	}
};
Event.addBehavior(dual_select_rules);