// ** Selected Content List:
// Called from the add/remove buttons.
function add_remove_selections(choices, selections, sort) {

	var c = document.getElementById(choices);
	var s = document.getElementById(selections);
									
	// Add selected elements to list box
	for (var x = 0; x < c.options.length; x++) {
		if (c.options[x].selected) {
			s.options[s.options.length] = new Option(c.options[x].text, c.options[x].value);
		}
	}
	
	// Backwards loop to remove content from the list box
	for (var x = c.options.length - 1; x >= 0; x--) {
		if (c.options[x].selected) {
			c.options[x] = null;
		}
	}
	
	sort_options(c, sort);
	sort_options(s, sort);
}

// Sorts the options list box
function sort_options(list, sort) {

	var items = list.options.length;
	var arrTemp = new Array(items);
	
	for (var i = 0; i < items; i++) {
		arrTemp[i] = new Option(list.options[i].text, list.options[i].value);
	}
	
	if (sort == 'text') {
		arrTemp.sort(sort_by_option_text);
	} else {
		arrTemp.sort(sort_by_option_value);
	}	
	
	for (var i = 0; i < items; i++) {
		list.options[i] = new Option(arrTemp[i].text, arrTemp[i].value);
	}
	
}

// Criteria used to determine how to sort the options
function sort_by_option_text(a, b) {
	if (a.text > b.text) {
		return  1; 
	} else if (a.text < b.text) {
		return -1; 
	} else { 
		return  0; 
	}
}
function sort_by_option_value(a, b) {
	if (a.value > b.value) {
		return  1; 
	} else if (a.value < b.value) {
		return -1; 
	} else { 
		return  0; 
	}
}

// Selects select list box for on submit
function select_listbox_items(elements) {
	
	var arrLBoxes = elements.split(',');
	var e;
	
	for (a = 0; a < arrLBoxes.length; a++) {
		e = document.getElementById(arrLBoxes[a]);
		for (var x = 0; x < e.options.length; x++) {
			e.options[x].selected = true;
		}
	}
}

// ** Clear Content from the Selected Content List:
// Called from the >> << button.
function clear_selections(choices, selections) {

	var c = document.getElementById(choices);
	var s = document.getElementById(selections);
	
	for (var x = 0; x < s.options.length; x++) {
		s.options[x].selected = true;
	}
	
	add_remove_selections(selections, choices);
}
