
function toggleOptionSelection(select, label) {
  //alert("toggleOptionSelection");

  if (select.selectedIndex > -1) {
    // need to deselect
    select.selectedIndex = -1;
  }
  else {
    // need to select 
    for (x = 0; x < select.options.length; x++) 
      select.options[x].selected = true;
  }

  toggleLabelText(select, label);
}

function toggleLabelText(select, label) {
  //alert("toggleLabelText");

  if (select.options.length == 0 || (select.options.length == 1 && select.options[0].value == ''))
    updateElementHtmlById(label, '');
  else {
    numSelected = getSelectedCount(select);
    if (numSelected > 0)    
      updateElementHtmlById(label, 'Clear All');
    else
      updateElementHtmlById(label, 'Select All');
  } 
}

function getSelectedCount(selectBox) {
  var count = 0;
  if (selectBox != null) {
    if (selectBox.multiple) {
      if (selectBox.options != null) {
        for (var i = 0; i < selectBox.options.length; i++) {
          if (selectBox.options[i] != null && selectBox.options[i].selected) {
            count++;
          }
        }
      }
    }
    else {
      if (selectBox.selectedIndex > 0 || 
          (selectBox.selectedIndex == 0 && selectBox.options[0].value != "")) {
        count = 1;
      }
    }
  }
  return count;
}

function updateElementHtmlById(elementId, newHtml) {
  var el = document.getElementById(elementId); 
  if (el != null) {
    el.innerHTML = newHtml;
  }
}

