/*
Script: 		comboBoo.js
License:		MIT-style license.
Credits:		Bruno Torrinha - www.torrinha.com
				Kaz de Groot - www.peerendedigitalesupermarkt.nl - modified for more bettar general usage
				Mootools framework - mootools.net.
*/

var comboBoo = new Class({

	initialize: function(el, options){
		this.setOptions(options);
		this.oldCombo = $(el);
		this.build($(el));
	},

	build: function(el){
		if ($('comboBoo-' + el.name))
		{
			$('comboBoo-' + el.name).remove();
			$('comboBoo-choices-' + el.name).remove();
			el.setStyle('display','');
		}
		this.bOpen = false;
		
		var className = el.className;
		var pos = el.getPosition();
		
		this.comboLink = new Element('a', {'class': className + '-label', 'id': 'comboBoo-' + el.name})
			.setHTML(el.options[el.options.selectedIndex].text)
			.injectInside(el.parentNode);
			
		el.setStyle('display', 'none');
		
		this.comboList = new Element('ul', {'class': className + '-list', 'id': 'comboBoo-choices-' + el.name})
			.setStyles({display: 'none'})
			.addEvent('mouseleave', function() {
				if (!this.bOpen) {
					this.setStyle('display', 'none');
				}
		}).injectInside(document.body);
		
		this.comboLink
			.addEvent('click', function() {this.click();}.bind(this))

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

	click: function() {
		if (this.bOpen) {
			this.bOpen = false;
			this.comboList.setStyle('display', 'none');
		}else{
			this.bOpen = true;
			var pos = this.comboLink.getPosition();
			this.comboList.setStyles({'display': '', 'top':pos.y,'left':pos.x});
		}
	},

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

	choiceSelect: function(el) {
		this.comboLink.setHTML(el.getText());
		this.comboList.setStyle('display', 'none');
		this.bOpen = false;
		this.oldCombo.selectedIndex = el.optId;
		this.oldCombo.fireEvent('change');
	},

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