Tauri.WorldsField = Class.create({
	
	box : null,
	list: null,
	current: null,
	field: null,
	
	listBox: null,
	currentText: null,
	
	initialize : function (opts) {
		var t = this, ul, selected = false;
		$H(opts).each(function (p) {
			t[p.key] = p.value;
		});
		this.box = $(this.box);
		this.field = $(this.field);
		this.currentText = (new Element('span'));
		this.box.insert(this.currentText);
		if (!this.list.length) {
			this.currentText.update('---');
			return;
		}
		if (this.list.length > 1) {
			this.listBox = (new Element('div')).hide();
			this.listBox.observe('mouseover', function (ev) {
				Event.stop(ev);
				t.listBox.show();
				return false;
			}).observe('mouseout', function (ev) {
				Event.stop(ev);
				t.listBox.hide();
				return false;
			});
			this.box.observe('mouseover', function (ev) {
				Event.stop(ev);
				t.listBox.show();
				return false;
			}).observe('mouseout', function (ev) {
				Event.stop(ev);
				t.listBox.hide();
				return false;
			});
			this.box.insert(this.listBox);
			ul = new Element('ul');
			this.listBox.insert(ul);
			ul.insert((new Element('li')).addClassName('top'));
			this.list.each(function (item) {
				ul.insert(
					(new Element('li')).
						insert(item[1]).
						observe('click', function (ev) {
							Event.stop(ev);
							t.listBox.hide();
							t.select(item);
							return false;
						})
				);
				if (item[0] == t.current) {
					t.select(item);
					selected = true;
				}
			});
			ul.insert((new Element('li')).addClassName('bottom'));
		}
		if (!selected) {
			this.select(this.list[0]);
		}
		
	},
	
	select : function (item) {
		this.field.value = item[0];
		this.currentText.update(item[1]);
	}
});

Tauri.Worlds = Class.create({
	
	worlds : null,
	fields : null,
	
	initialize : function () {
		this.worlds = $A();
		this.fields = $H();
	},
	
	addWorld : function (id, name) {
		this.worlds.push([id, name]);
	},
	
	addField : function (field, outField, selected) {
		this.fields.set(field, new Tauri.WorldsField({
			box: field, 
			list: this.worlds, 
			current: selected,
			field: outField
		}));
	}
	
});

Tauri.Worlds = new Tauri.Worlds();
