/*
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}).setStyles({top: pos.top+'px', left: pos.left+'px', width: pos.width+'px'}).inject(document.body).setHTML(el.options[el.options.selectedIndex].text);
		this.comboList = new Element('ul', {'class': this.options.className + '-list', 'id': 'choices-' + el.name}).setStyles({display: 'none', top: pos.top+'px', left: pos.left+'px', width: pos.width + 33+'px'}).injectAfter(this.comboLink);
		this.fx={cmbLink: this.comboLink.effect('background-color', {duration: 150}).start('#FFF'),
					cmbList: this.comboList.effect('opacity', {duration: 150}).start(0)}

		this.addComboLinkEvents(this.comboLink);

		this.build(el);
		
		el.setStyle('display', 'none');
		el.setStyle('height', '1px');
		el.setStyle('border', '0px');
		this.comboList.setStyle('display', '');
		
	},

	build: function(el){
		for(i = 0; i < el.length; i++) {
			var el2 = new Element('li', {'id': i}).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('#FFF');
	},

	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('#FFF');
		this.fx.cmbList.start(0);
		this.comboLink.setHTML(el.getText());
		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);