
var InvitationsManager = Class.create({
	initialize: function(buttonAdd,buttonRemove,inputField){
		this.buttonAdd = buttonAdd;
		this.buttonRemove = buttonRemove;
		this.inputField = inputField;
		$(buttonAdd).observe("click",this.addRemote.bind(this));
		$(buttonRemove).observe("click",this.removeRemote.bind(this));
		$(inputField).observe("keypress", this.keyPressHandler.bindAsEventListener(this));
	},
	select: function(event){
		var item = event.element();
		if(item.hasClassName('selected')){
			item.removeClassName('selected');
		} else {
			item.addClassName('selected');
		}
	},
	removeRemote: function() {
		var itemsToRemove = $('invitationList').select('div.selected');
		var emailList = itemsToRemove.pluck('id');
		AddCriteriaJS.removeInvitations(emailList,this.remove.bind(this));
	},
	remove: function() {
		var itemsToRemove = $('invitationList').select('div.selected');
		itemsToRemove.invoke('remove');
	}, 
	keyPressHandler: function(event){
		switch(event.keyCode){
			case Event.KEY_RETURN:
				this.addRemote();
				event.stop();
				return false;
		}
	},
	addRemote: function(){
		var value = $(this.inputField).value;
		AddCriteriaJS.addInvitation(value,function(success){
			if(success){
				this.add(value);
			}
		}.bind(this));
	},
	add: function(email) {
		var elem = new Element('div',
			{	'class':'dynamicListItem',
				'style':'display:none;height:0px;width:0px;',
				'id':email}).update(email);
		$('invitationList').insert(elem);
		elem.observe('click', this.select.bindAsEventListener());
		elem.appear();
	},
	refreshList: function(){
		AddCriteriaJS.getInvitations(function(emailList){
			this.removeAll();
			emailList.each(this.add.bind(this));
		});
	},
	removeAll: function(){
		var itemsToRemove = $('invitationList').select('div.dynamicListItem');
		itemsToRemove.invoke('remove');
	}
});

Event.observe(window,'load', function(){
	new InvitationsManager('inviteButton','removeInvitationButton','emailAddress')});
