// prototype add
Element._insertionTranslations.into = {
	insert: function(element, node) {
		node.appendChild(element);
	}
};

// v0.2 | 14.09.2007
if (!CD3) var CD3 = {};
CD3.Select = Class.create({
	initialize: function(select){		
		select = $(select);
		
		// get select options
		var options = $A(select.options).collect(function(elem){
		    return { value:	elem.value != null ? elem.value : elem.text, text: elem.text };
		});
		
		var selected 	= options[select.selectedIndex || 0];
		var container	= new Element('span', {className:'dropper'});
		
		select.insert({before: container});
		
		// create elements
		this.name 		= select.name;
		this.container	= container;
		this.link		= new Element('a', {href: 'javascript:;', className: 'drop'}).insert({into:container});
		this.link.observe('click', this.toggle.bind(this));
		this.linkspan	= new Element('span').update(selected.text).insert({into:this.link});		
		this.hidden		= new Element('input', {type: 'hidden', name: this.name, value: selected.value}).insert({into:container});
		this.ul			= new Element('ul').insert({into:container}).hide();

		// create options
		options.each(function(opt){
			var li	= new Element('li')
			li.insert(new Element('a', {href: 'javascript:;'}).update(opt.text));
			li.observe('click', this.select.bind(this, opt));
			li.insert({into:this.ul});
		}.bind(this));
		
		// save mouse for future use
		this.onMouseout = this.mouseout.bindAsEventListener(this);
		
		// delete old select
		Element.remove(select);
	},
	select: function(opt){
		this.linkspan.innerHTML = opt.text;
		this.hidden.value		= opt.value;
		this.hide();
	},
	toggle: function(){
		this[this.ul.visible() ? 'hide' : 'show']();
	},
	show: function(){		
		// this.ul.show();
		new Effect.BlindDown(this.ul, {duration: 0.2});
		this.container.observe('mouseout', this.onMouseout);
	},
	hide: function(){
		// this.ul.hide();
		new Effect.BlindUp(this.ul, {duration: 0.1});
		this.container.stopObserving('mouseout', this.onMouseout);
	},
	mouseout: function(e){
		try {
			var is = Element.descendantOf(e.relatedTarget || e.toElement, this.container);
		} catch(err) {}
		
		if (!is) {
			Event.stop(e);
			this.hide();
		}
	}
});

document.observe('contentloaded', function() {
	$$('select').each(function(select) {
		new CD3.Select(select);
	});
});