/*
 * checkall - works on input check boxes. Set "ncbi_checked=1" on
 * a checkbox, and it will work as master for all of the other
 * checkboxes in the group. Its value will also reflect the logical
 * combination of the  slave checkboxes.
 */

var checkall_masters = Object()

function master_clickhandler(e) {
   var theMaster, theForm, theElements, masterChecked
   if (e) {
      theMaster = e.target
   } else if (window.event) {
      theMaster = window.event.srcElement
   }
   theForm = theMaster.form
   theElements = theForm[theMaster.name]
   masterChecked = theMaster.checked

   /* Set all slaves to reflect master */
   for (i = 0; theElements && i < theElements.length; i++) {
      theElements[i].checked = masterChecked
   }
}

/* Master is logical and of all slaves */
function slave_clickhandler(e) {
   var theMaster, theSlave, theForm, theElements, masterChecked
/*   alert("Slave") */
   if (e) {
      theSlave = e.target
   } else if (window.event) {
      theSlave = window.event.srcElement
   }
   theForm = theSlave.form
   theElements = theForm[theSlave.name]
   theMaster = checkall_masters[theSlave.name]

/*   alert("theForm = " + theForm.name + ", theElements: " + theElements.length)  */
   if (theMaster == undefined) {
/*      alert("Form not checkall") */
      return false
   }

   theMaster.checked = true
   for (i = 0; i < theElements.length; i++) {
      thisElement = theElements[i]
      if (thisElement != theMaster) {
         theMaster.checked = theMaster.checked && thisElement.checked
      }
   }
/*   alert("Slave: " + event.target.name)  */
}

function ncbi_init()
{
   /* Initialize master and slave clickhandlers */
   for (i = 0; i < document.forms.length; i++) {
      thisForm = document.forms[i];
      for (j = 0; j < thisForm.elements.length; j++) {
/*        alert("form " + i + ": " + thisForm.name + ", elem" + j + ": " + thisForm.elements[j].name) */
         if (thisForm.elements[j].getAttribute("ncbi_checkall")) {
/*            alert("Checkall " + thisForm.elements[j]); */
            var master = thisForm.elements[j]
            master.onclick = master_clickhandler;
            checkall_masters[master.name] = master
/*	    alert("master of " + master.name) */
            var list = thisForm.elements[master.name]
/*            alert(master.name + " has " + list.length + " elements") */
            for (t = 0; t < list.length; t++) {
               if (list[t] != master) {
                    list[t].onclick = slave_clickhandler
               }
/*               alert("initializing " + master.name + "[" + t + "] = " + thisForm.elements[t].value) */
            }
         }
      }
   }
}

window.onload = ncbi_init
