/*This used to be local to chartron code but is now being used also by one internal form (mass_email)
 * This is why it is now moved to its own file to avoid importing the oui common.js file into cui
 */

/* Select the 'all' option in a multi-select
 * NOTE:  this doesn't select all options, just the one option named 'all'
 * @param select {DOMNode}: An HTML multi-select field
 */
function select_all(select) {
	select.getElement('option.all').selected = true;
}

/* Deselect all options in a multi-select
 * @param select {DOMNode}: An HTML multi-select field
 */
function clear_selection(select) {
	for (var i=0; i<select.options.length; i++) {
		if (select.options[i].selected) select.options[i].selected = false;
	}
		
}

/* Call this when a multi-select field's selection changes
 * @param this_select {DOMNode}: the select field that triggered this event handler
 * @param other_select_id {string}: the id of the correlated multi-select field
 */
function selection_changed(changed_select, other_select_id) {
	var other = $(other_select_id);
	clear_selection(other);
	
	// This coupling is accomplished by using classes on the options in 'other',
	// these classes are the same as the id's of options in 'changed_select'
	
	// For each selected id in the changed selection widget, find options in the
	// other selection widget with a class equal to that id
	for (var i=0; i<changed_select.options.length; i++) {
		var selection = changed_select.options[i];
		if (selection.selected) {			
			// Test if the selected value ends with '_all'
			if (/.*_all$/.exec(selection.value)) {
				select_all(other);
			} else {
				other.getElements('option.' + selection.value).each(function(option) {
					option.selected = true;
				});
			}
		}
	}
	return true;
}
