AllCheckbox = Class.create();
AllCheckboxGroups = {};
AllCheckbox.prototype = {
  initialize: function(element, group_name) {
		this.checkboxes = [];
		this.groupStateChangeListeners = [];
		this.element = $(element);
    
		
		Event.observe(element,'click', this.synchronizeChildren.bind(this));
		
		AllCheckboxGroups[group_name] = this;
	},
	
	synchronizeChildren: function() {
	  if (this.element.checked) { this.checkChildren(); } else {	this.uncheckChildren(); }		
	},
	
	checkChildren: function() {
		this.checkboxes.each(function(checkbox) { checkbox.checked = true; });
		this.fireGroupStateChanged();
	},
	
	uncheckChildren: function() {
		this.checkboxes.each(function(checkbox) { checkbox.checked = false; });
		this.fireGroupStateChanged();
	},
	
	allChildrenChecked: function() {
		if (this.checkboxes.length == 0) {
			return false;
		}
		return this.checkboxes.all(function(checkbox) { return checkbox.checked; });
	},
	
	anyChildrenChecked: function() {
		return this.checkboxes.any(function(checkbox) { return checkbox.checked; });
	},
	
	addGroupStateChangeListener: function(listener) {
		this.groupStateChangeListeners.push(listener);
	},
	
	fireGroupStateChanged: function() {
		this.groupStateChangeListeners.each(function(listener) {
			listener();
		})
	},
	
	synchronizeSelfWithChildren: function() {
		this.element.checked = this.allChildrenChecked();
		this.fireGroupStateChanged();
	}
};

AllCheckboxChild = Class.create();
AllCheckboxChild.prototype = {
  initialize: function(element, group_name) {
	  this.element = $(element);
		this.parent = AllCheckboxGroups[group_name];
		this.parent.checkboxes.push($(element));
		Event.observe(element,'click', this.synchronizeParent.bind(this));
	},
	
	synchronizeParent: function() {
		this.parent.synchronizeSelfWithChildren();
	}		
};

