/*
  Copyright 2009 Daniel Arbuckle

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

function mw_setup_item(item) {
    function remove_clicked() {
        item.dispose()
    }

    item.getElements('.many_remove').addEvent('click', remove_clicked);
}

function mw_setup() {
    $$('.many_widget').each(function(w) {
        var template = w.getElement('.many_template').get('html');
        var container = w.getElement('.many_items');
        var items = container.getChildren('.many_item');
        var next_id = items.length;
        var setup_item = mw_setup_item.bind(w);

        function add_clicked() {
            var item = new Element('tr', {'class': 'many_item'});
            container.grab(item);
            item.set('html', template.replace('{$NUMBER$}', next_id, 'g'));
            next_id += 1;
            setup_item(item);
        }

        w.getElement('.many_add').addEvent('click', add_clicked);

        items.each(setup_item);
    });
}

window.addEvent('domready', mw_setup);

