var CheckboxList = Class.create();
Object.extend(CheckboxList.prototype, {
	initialize: function(group, all, options) {
		this.config = Object.extend({
			blankAll: false
		}, options);
		this.group = $(group);
		this.all = typeof(all) == 'undefined' ? null : $(all);
		this.options = this.findOptions();
		this.registerEvents();
	},

	findOptions: function() {
		return $A(this.group.getElementsByTagName('input')).findAll(
			function(e) {
				return e.getAttribute('type').toLowerCase()
					== 'checkbox';
			}).reject((function(e) {
				return this.all == null ?
					false : e == this.all;
			}).bind(this));
	},

	registerEvents: function() {
		if( this.all == null ) return;
		Event.observe(this.all, 'click',
			this.allClicked.bindAsEventListener(this));
		this.options.each((function(e) {
			Event.observe(e, 'click',
				this.optionClicked.bindAsEventListener(this));
		}).bind(this));
	},

	allClicked: function(event) {
		this.all.checked = this.config.blankAll || this.all.checked;
		this.options.each((function(e) {
			e.checked = this.all.checked && !this.config.blankAll;
		}).bind(this));
	},

	optionClicked: function(event) {
		if( this.config.blankAll )
			this.all.checked = this.isAnySelected() ? false : true;
		else
			this.all.checked = this.isAllSelected();
	},

	isAllSelected: function() {
		return this.options.all(function(e) {return e.checked});
	},

	isAnySelected: function() {
		return this.options.any(function(e) {return e.checked});
	}
});