CheckboxesCollection = Class.create({
  initialize: function(container, hidden_list, separator)
  {
    this.separator = ','
    if(typeof separator !== 'undefined')
      this.separator = separator;
    this.hidden_list = hidden_list;
    this.onAllClick = this.allClick.bindAsEventListener(this);
    this.allField = container.select('.all-field')[0];
    this.allField.observe('click', this.onAllClick);
    this.onFormSubmit = this.formSubmit.bindAsEventListener(this);
    document.observe('form:submit', this.onFormSubmit);
    this.checkboxes = container.select('.checkbox-field');
    this.selected_count = this.checkboxes.length;
    this.onCheckboxClick = this.checkboxClick.bindAsEventListener(this);
    this.checkboxes.invoke('observe', 'click', this.onCheckboxClick);
  },
  allClick: function(event)
  {
    var checked = event.element().checked;
    this.checkboxes.each(function(e){
      e.checked = checked;
    });
    this.selected_count = checked?this.checkboxes.length:0;
  },
  checkboxClick: function(event)
  {
    var checked = event.element().checked;
    if(checked)
      this.selected_count += 1;
    else
      this.selected_count -= 1;
    
    this.allField.checked = (this.selected_count == this.checkboxes.length);
  },
  formSubmit: function(event)
  {
    if(this.allField.checked)
    {
      this.hidden_list.setValue(this.separator);
      return;
    }
    var listValue = this.checkboxes.findAll(function(e){
      return e.checked;
    }).map(function(e){ 
      return e.getValue()
    }).join(this.separator);   
    this.hidden_list.setValue(listValue);
  }
});