define([
  'sandbox',
  './child'
  ], function(sandbox, ChildView){
  var ChildrenListView = sandbox.mvc.View({
    events: {
        "change": "changeSelected"
    },
	  
    initialize: function(){
      this.line = this.$el.find(':first-child');
      this.collection.bind('reset', this.addAll, this);
    },

    render: function() {
      return this;
    },

    addOne: function(child){
      var child = new ChildView({ model: child }).render().el;

      $(child).insertBefore(this.line);
    },

    addAll: function(){
      this.collection.each(this.addOne, this);

      if(this.collection.length > 0) {
	this.$el.children().eq(0).attr('selected', 'selected');
        this.publish(this.collection.at(0));
      }
    },

    changeSelected: function() {  
      var child = this.collection.get(this.$el.val());	    

      this.publish(child);
    },

    publish: function(child) {
      if (child) {
	sandbox.publish("childSelected", child);
      }
    }
  });

  return ChildrenListView;
});
