var Regions = Class.create({
  initialize: function(element) {
    this.element = $(element);

    this.findInputs('north', Regions.north);
    this.findInputs('south', Regions.south);

    var hr = new Element('hr');
    this.element.insert({top: hr});

    this.addInput('South Island', this.south);
    this.addInput('North Island', this.north);
    this.addInput('All of New Zealand', [this.north, this.south].flatten());
  },

  findInputs: function(name, values) {
    var inputs = [];

    this.element.select('input').findAll(function(input) {
      var label = input.up('label');

      if (label) {
        var text = '';

        if (label.innerText) {
          text = label.innerText;
        } else {
          text = label.textContent;
        }

        text = text.strip();

        if (values.indexOf(text) > -1) {
          inputs.push(input);
        }
      }
    });

    this[name] = inputs;
  },

  addInput: function(name, inputs) {
    var p = new Element('p');
    var label = new Element('label');
    var input = new Element('input', {'type': 'checkbox'});

    label.appendChild(input);
    label.insert({'bottom': '&nbsp;' + name});
    p.insert(label);

    this.element.insert({'top': p});

    input.observe('click', function(e) {
      inputs.each(function(chk) {
        chk.checked = input.checked;
      });
    });

    inputs.each(function(chk) {
      chk.observe('click', function(e) {
        this.checkInput(input, inputs);
      }.bindAsEventListener(this));
    }.bind(this));
  },

  checkInput: function(input, inputs) {
    input.checked = inputs.all(function(chk) {
      return chk.checked;
    });
  }
});

Regions.north = [
  'Northland',
  'Auckland',
  'Coromandel',
  'Waikato',
  'Bay of Plenty',
  'East Coast',
  'Central Plateau',
  'Hawkes Bay',
  'Taranaki',
  'Manawatu - Wanganui',
  'Wairarapa',
  'Wellington'];

Regions.south = [
  'Nelson',
  'Marlborough',
  'West Coast',
  'Canterbury',
  'Otago',
  'Fiordland',
  'Southland'];

//$(document).observe('dom:loaded', function() {
//  $$('.regions').each(function(regions) {
//    new Regions(regions);
//  });
//});