var AdminManager = Class.create({
	initialize: function(){
		this.input = $('userFilterInput');
		this.input.observe('keypress',this.userInputKeyHandler.bindAsEventListener(this));
		$('sendNotificationsButton').observe('click',this.sendNotifications.bind(this));
		this.filterTimeout = window.setTimeout(this.fillUserList.bind(this),0);
	},
	addConferenceCreationToken: function(event,user_object){
		AdminController.addConferenceCreationToken(user_object.login,
			function(updated_number){
				dwr.util.setValue("person_num_tokens"+"_"+user_object.id,
								updated_number);
			}
		);
		$('sendNotificationsButton').appear({duration:0.5});
		event.stop();
	},
	removeConferenceCreationToken: function(event,user_object){
		AdminController.removeConferenceCreationToken(user_object.login,
			function(updated_number){
				dwr.util.setValue("person_num_tokens"+"_"+user_object.id,
								updated_number);
			}
		);
		event.stop();
	},
	sendNotifications: function(){
		AdminController.sendNotifications(function(){
			alert("The users have been notified of their new rights.");
		});
	},
	userInputKeyHandler: function(event){
		window.clearTimeout(this.filterTimeout);
		this.filterTimeout = window.setTimeout(
			this.fillUserList.bind(this),1000);
		this.input.pulsate({duration:1.0,from:0.7,pulses:3});
		switch(event.keyCode){
			case Event.KEY_RETURN:
				this.addRemote();
				event.stop();
				return false;
		}
	},
	fillUserList: function(){
		var filter = this.input.value;
		AdminController.getUsersList(filter,function(people){
			$$('#userDynamicList .dynamicListItem').invoke("remove");
			var content;
			var elemName;
			var contentValue;
			var id;
			var person;
			if(people.length > 0){
				$$(".dynamicListPlaceholder").invoke("fade");
			} else {
				$$(".dynamicListPlaceholder").invoke("appear");
			}
			for (var i = 0; i < people.length; i++) {
				person = people[i];
				id = "_"+person.id;
				elemName="person_item_pattern"+id;
 				
 				dwr.util.cloneNode("person_item_pattern", { idSuffix:id });
				dwr.util.setValue("person_name" + id, person.firstName + " " + person.lastName);
				dwr.util.setValue("person_num_tokens"+id,person.numTokens);
				
				$(elemName).removeClassName("dynamicListItemPattern");
				$(elemName).addClassName("dynamicListItem");
				
				$("person_add_token"+id).observe('click',
						this.addConferenceCreationToken.bindAsEventListener(this,person));
				$("person_remove_token"+id).observe('click',
						this.removeConferenceCreationToken.bindAsEventListener(this,person));
				$(elemName).appear();
			}
		}.bind(this) );
	}
});

Event.observe(window,'load',function(e){new AdminManager();});