if (!atira) var atira={};

atira.TokensComponent = function(id) {
	this.element = $(id);
	this.values = [];
	this.fieldName;
	this.addBehavior();
}

atira.TokensComponent.prototype = {
	addBehavior : function() {
		var self = this;
		var fields = this.element.select('input');
		fields.each(function(field,index) {
			self.fieldName=field.name;
			self.values[index]=field.value;
			self.addFieldBehavior(field,index);
		});
	},
	
	addFieldBehavior : function(field,index) {
		var self = this;
		field.observe('keydown',function() {
			self.fieldChanged(field,index);
		});
		field.observe('keyup',function() {
			self.fieldChanged(field,index);
		});
		field.observe('keyup',function() {
			self.fieldChanged(field,index);
		});
	},
	
	fieldChanged : function(field,index) {
		if (field.value==this.values[index]) return;
		this.values[index] = field.value;
		if (index==this.values.length-1) {
			this.addNewField();
		}
	},
	
	addNewField : function() {
		var field = new Element('input',{'type':'text','name':this.fieldName,'class':'atira_token'});
		this.element.insert(field);
		this.addFieldBehavior(field,this.values.length);
		this.values.push('');
	}
}


/******************************************** List component ******************************************/

atira.ListComponent = function(id) {
	this.element = $(id);
	this.addBehavior();
}

atira.ListComponent.prototype = {
	addBehavior : function() {
		this.element.select('.atira_list_popup').each(function(node) {
			new atira.ListComponent.PopUp(node);
		});
	}
}

atira.ListComponent.PopUp = function(element) {
	this.element = element;
	this.control = element.select('.atira_list_popup_control')[0];
	this.content = element.select('.atira_list_popup_content')[0];
	this.visible = false;
	this.addBehavior();
}

atira.ListComponent.PopUp.prototype = {
	addBehavior : function() {
		var self = this;
		this.control.observe('click',function(e) {
			if (self.visible) {
				self.hide();
			} else {
				self.show(e);
			}
		});
	},
	show : function(e) {
		this.content.setStyle({display:'block',visibility:'hidden'});
		var contentWidth = this.content.getWidth();
		var controlWidth = this.control.getWidth();
		if (controlWidth>contentWidth) {
			this.content.setStyle({width:(controlWidth-2)+'px'})
		}
		this.content.setStyle({visibility:'visible'});
		var self = this;
		this.hider = function() {self.hide()};
		document.observe('click',this.hider);
		e.stop();
		this.visible = true;
	},
	hide : function() {
		this.content.setStyle({display:'none'});
		document.stopObserving('click',this.hider);
		this.visible = false;
	}
}