
var DropDown = new Class({
	ClassName: 'DropDown',
	Implements: [Options, Events],

	options: {
		className: 'dropdown-menu',
		items: [],
		timeout: 100
	},

	initialize: function(options) {
		this.setOptions(options);
		this.toDOM();
		this.timer = null;
		this.selectItem(0);
		Register.addInstance(this);
		$(document.body).addEvent('click', function() { this.hideMenu() }.bind(this));
	},

	toDOM: function() {
		this.element = new Element('div', { 'class': this.options.className, id: this.options.id||'' });
		if (this.options.label) this.labelSpan = new Element('span', {'class': 'label', text: this.options.label}).inject(this.element);
		this.selText = new Element('p').inject(this.element);
		this.itemList = new Element('ul').inject(this.element).hide();

		this.element.addEvents({
			click:      function(event) { event.stop() },
			mouseenter: function(event) { event.stop(); this.showMenu() }.bind(this),
			mouseleave: function(event) { event.stop(); this.hideWithTimer() }.bind(this)
		});

		this.options.items.each(function(item, index) {
			item.element = new Element('li', { text: item.text });
			item.index = index;
			item.element.addEvents({
				click: function() { this.selectItem(item.index) }.bind(this),
				mouseenter: function() { this.addClass('hover') },
				mouseleave: function() { this.removeClass('hover') }
			});
			this.itemList.grab(item.element);
		}.bind(this));

		this.options.container.grab(this.element);
	},

	showMenu: function() {
		// console.log('showing menu ', this.options.id);
		this.itemList.show();
		this.selText.addClass('open');
		this.clearTimer();
		Register.broadcastMessage({msg:'dropdownMenuOpen', data:this});
	},

	hideMenu: function() {
		// console.log('hiding menu ', this.options.id);
		this.itemList.hide();
		this.selText.removeClass('open');
		this.clearTimer();
	},

	hideWithTimer: function() {
		if (this.timer == null) {
			// console.log('dropdown timer set ', this.options.id);
			this.timer = setTimeout(function(){ this.hideMenu.call(this) }.bind(this), this.options.timeout);
		}
	},

	clearTimer: function() {
		if (this.timer) {
			// console.log('dropdown timer cleared ', this.options.id);
			clearTimeout(this.timer);
			this.timer = null;
		}
	},

	selectItem: function(index) {
		this.selText.set('text', this.options.items[index].text);
		this.itemList.getChildren().removeClass('selected');
		this.itemList.getChildren()[index].addClass('selected');
		this.hideMenu();
		this.fireEvent('itemSelected', [this.options.items[index].value||index]);
	},

	processMessage: function(msg) {
		if (msg.msg == 'dropdownMenuOpen' && msg.data != this) {
			this.hideMenu();
		}
	}
});
