/*
Script: 		comboBoo.js
License:		MIT-style license.
Credits:		Bruno Torrinha - www.torrinha.com
				Mootools framework - mootools.net.
*/

var comboBoo = new Class({
	options: {
		className: 'comboBoo'
	},

	initialize: function(el, options){
		this.setOptions(options);
		this.oldCombo = $(el);
		this.bOpen = false;
		var pos = el.getCoordinates();
		this.comboLink = new Element('a', {'class': this.options.className + '-label', 'id': el.name}).inject('select_labor').setHTML(el.options[el.options.selectedIndex].text);
		this.comboList = new Element('ul', {'class': this.options.className + '-list', 'id': 'choices-' + el.name}).setStyles({display: 'none'}).injectAfter(this.comboLink);
		this.fx={cmbLink: this.comboLink.effect('background-color', {duration: 150}).start('#000'),
					cmbList: this.comboList.effect('opacity', {duration: 150}).start(0)}

		this.addComboLinkEvents(this.comboLink);

		this.build(el);
//		el.setStyle('display', 'none');
		this.comboList.setStyle('display', '');
	},

	build: function(el){
		for(i = 0; i < el.length; i++) {
			var el2 = new Element('li', {'id': el[i].value}).setHTML(el.options[i].text);
			this.addChoiceEvents(el2).injectInside(this.comboList);
		};
	},

	click: function(el) {
		if (this.bOpen) {
			this.bOpen = false;
			this.fx.cmbList.start(0);
		}else{
			this.bOpen = true;
			this.fx.cmbList.start(1);
		}
	},

	comboOver: function() {
		if (!this.bOpen) this.fx.cmbLink.start('#600');
	},

	comboOut: function(el) {
		if (!this.bOpen) this.fx.cmbLink.start('#000');
	},

	choiceOver: function(el) {
		if (this.selected) this.selected.removeClass('choice-selected');
		this.selected = el.addClass('choice-selected');
	},

	choiceSelect: function(el) {
		this.bOpen = false;
		this.fx.cmbLink.start('#000');
		this.fx.cmbList.start(0);
		this.comboLink.setHTML(el.getText());
		$('tipo_conv').value = el.id;
		this.oldCombo.selectedIndex = el.id;
	},

	addComboLinkEvents: function(el) {
		return el.addEvents({
			click: this.click.bind(this, [el]), 
			mouseover: this.comboOver.bind(this, [el]), 
			mouseleave: this.comboOut.bind(this, [el])
		});
	},

	addChoiceEvents: function(el) {
		return el.addEvents({
			mouseover: this.choiceOver.bind(this, [el]),
			mousedown: this.choiceSelect.bind(this, [el])
		});
	}
});

comboBoo.implement(new Events, new Options);
