/*
Manages multiple groups of checkboxes that have a select-all checkbox.
This script needs only be included once per page, no matter how many groups
are to be supported.

Keeps an array of checkbox 'groups'.  Each group is an array where the 0th
element is a select-all checkbox and the remaining elements are its children.

A checkbox group is created by calling checkboxGroups.createGroup, passing an
array of checkbox ids where the 0th id is for the select-all checkbox, the rest
are for its children.

This script adds a function to the onclick event to each checkbox so that:
- when the select-all checkbox is clicked, all child checkboxes in its group
  take the same value
- when a child checkbox is clicked, the select-all checkbox is updated so that
  it is checked only if all the child checkboxes are checked
- any pre-existing onclick function of any checkbox is still called.
  
(The preservation of pre-existing onclick functions is acheived by storing them
 in a hash table keyed on checkbox id, and calling from the new functions.)
*/

var checkboxGroups = {
    groups : new Array,

    origFunctions : new Array,
    
    createGroup : function(checkboxIds) {
        if (checkboxIds.length < 2) return;
        var group = new Array;
        for (var i = 0; i < checkboxIds.length; i++) {
            var element = document.getElementById(checkboxIds[i]);
	    	if (element != null && element.type == "checkbox") {
	   			if (element.onclick) {
	   			    checkboxGroups.origFunctions[element.id] = element.onclick;
    	   			element.onclick = function(event) {checkboxGroups.checkboxClicked(this); checkboxGroups.origFunctions[this.id](event);};
	   			} else {
    	   			element.onclick = function(event) {checkboxGroups.checkboxClicked(this);};
    	   		}
                group[group.length] = element;
            }
        }
        this.groups[this.groups.length] = group;
        this.updateSelectAllFromChildren(group);
    },
    
    checkboxClicked : function(checkbox) {
        var group;
        var checkboxIndex = -1;
        a: for (var i = 0; i < this.groups.length; i++) {
            group = this.groups[i];
            for (var j = 0; j < group.length; j++) {
                if (group[j] == checkbox) {
                    checkboxIndex = j;
                    break a;
                }
            }
        }
        if (checkboxIndex < 0) {
            return;
        } else if (checkboxIndex == 0) {
            for (var i = 1; i < group.length; i++) {
                group[i].checked = group[0].checked;
            }
        } else {
            this.updateSelectAllFromChildren(group);
        }
    },
    
    updateSelectAllFromChildren : function(group) {
        var i = 1;
        for (; i < group.length; i++) {
            if (!group[i].checked) break;
        }
        group[0].checked = (i == group.length);
    }
}

