	
var SecondaryAuthorManager = Class.create({
	lastRef: 0,
	initialize: function(buttonAdd,buttonRemove,inputField){
		this.buttonAdd = buttonAdd;
		this.buttonRemove = buttonRemove;
		this.inputField = inputField;
		$(buttonAdd).observe("click",this.AddSecondaryAuthor.bind(this));
		$(buttonRemove).observe("click",this.RemoveSecondaryAuthor.bind(this));
	    $(inputField).observe("keypress", this.KeyPressHandler.bindAsEventListener(this));
	    this.lastRef = $('secondaryAuthorList').select(".dynamicListItem").size();
	    
	    if (this.lastRef != 0) {
	    	elt = $('secondaryAuthorList').select(".dynamicListItem");
	    	for (var i = 0; i < elt.length; i++) {
	    		elt[i].observe('click', this.SelectSecondaryAuthor.bindAsEventListener());
	    	}
	    }
	},
	SelectSecondaryAuthor: function(event){
		var item = event.element();
		if(item.hasClassName('selected')){
			item.removeClassName('selected');
		} else {
			item.addClassName('selected');
		}
	},
	RemoveSecondaryAuthor: function() {
		var itemsToRemove = $('secondaryAuthorList').select('div.selected');
		// Fade and remove
		itemsToRemove.invoke('fade',{
			afterFinish: function(obj){
				obj.element.remove();
			}
		});
	},
	KeyPressHandler: function(event){
		switch(event.keyCode){
			case Event.KEY_RETURN:
				this.AddSecondaryAuthor();
				event.stop();
				return false;
		}
	},
	AddSecondaryAuthor: function() {
		var ref = this.lastRef++;
		var elemName = "liste["+ref+"]";
		var value = $('newSecondaryAuthorInput').value;
		var hidden = new Element('input',{'id':elemName,'name':elemName,'type':'hidden','value':value});
		var elem = new Element('div',
			{	'class':'dynamicListItem',
				'style':'display:none;height:0px;width:0px;',
				'id':elemName}).update(value).insert(hidden);
		elem.observe('click', this.SelectSecondaryAuthor.bindAsEventListener());
		$('secondaryAuthorList').insert(elem);
		$(this.inputField).clear();
		elem.appear();
	}
});

Event.observe(window,'load', function(){
	new SecondaryAuthorManager('addSecondaryButton','removeSecondaryButton','newSecondaryAuthorInput')});
