/* public */
function LinkedControlChange(masterControl, linkedControl, showAll, addItems) {
	// Collect all the currently selected linkedControl items for later reselection
	var selectedItems = "";
	for (var i = 0; i < linkedControl.options.length; i++) {
		if (linkedControl.options[i].selected) {
			selectedItems += linkedControl.options[i].value + ",";
		}
	}
	selectedItems = selectedItems.substr(0, selectedItems.length - 1).split(",");

	// Clear the linkedControl list
	for (var i = linkedControl.options.length; i >= 0; i--) {
		linkedControl.options[i] = null;
	}

	// Repopulate the linkedControl list depending on the selected items in the masterControl
	for (var i = 0; i < masterControl.options.length; i++) {
		if (masterControl.options[i].selected) {
			addItems(masterControl.options[i].value, linkedControl);
		}
	}
    
    // If there are too many items selected, javascript can't successfully sort them.
    // As a result of this Firefox and IE hangs and ultimately crashes.
    // The following code is a precaution to prevent that from happeneing. 
    if (linkedControl.options.length > 325)
    {
        alert("You have selected too many sectors, please reduce the number of sectors and try again.");
        return;
	}
	
	// Sort the linkedControl
	SortList(linkedControl);

	if (showAll.length > 0) {
		// Add the 'All' option
		addToListTop(linkedControl, showAll, "");
	}

	// Reselect the linkedControl
	ClearControl(linkedControl);
	for (var i = 0; i < selectedItems.length; i++) {
		for (var j = 0; j < linkedControl.options.length; j++) {
			if (linkedControl.options[j].value == selectedItems[i]) {
				linkedControl.options[j].selected = true;
			}
		}
	}
}

function SortList(list) {
	for (var i = 0; i < (list.length - 1); i++) {
		for (var j = i + 1; j < list.length; j++) {
			if (isLessThan(list.options[j].text, list.options[i].text)) {
				var tempValue = list.options[i].value;
				var tempText  = list.options[i].text;
				list.options[i].value = list.options[j].value;
				list.options[i].text  = list.options[j].text;
				list.options[j].value = tempValue;
				list.options[j].text  = tempText;
			}
		}
	}
}

function ClearControl(ctl) {
	for (var i = 0; i < ctl.options.length; i++) {
		ctl.options[i].selected = false;
	}
}

function SelectControlItem(value, linkedControl) {
	for (var j = 0; j < linkedControl.options.length; j++) {
		if (linkedControl.options[j].value == value) {
			linkedControl.options[j].selected = true;
			break;
		}
	}
}

/* private */
function isOther(name) {	
	if ((String(name).indexOf("Regional") == 0) || (String(name).indexOf("Other") == 0)) {
		return true;
	} else {
		return false;
	}
}

function isLessThan(name1, name2) {
	if (isOther(name1) && !isOther(name2)) {
		return false;
	} else if (!isOther(name1) && isOther(name2)) {
		return true;
	} else {
		return (name1 < name2);
	}
}
