var QuickSearch = Class.create({

	'initialize': function(searchHandlers, activeHandler)
	{
		this.handlers = searchHandlers;
		this.active = activeHandler;
		this.form = $('quick-search');
		this.input = $('searchfield');

		//build default html
		this.quickSearchSwitcher = new Element('ul', {'id': 'quick-search-switcher'});
		this.form.down('fieldset').insert({'top': this.quickSearchSwitcher});
		this.activeLi = this.quickSearchSwitcher.appendChild(new Element('li'));
		this.activeLi.appendChild(new Element('img', {'src': this.handlers[this.active]['handler_icon']}));
		this.options = this.activeLi.appendChild(new Element('ul'));
		for (var i in this.handlers) {
			var option = this.options.appendChild(new Element('li'));
			option.update(this.handlers[i]['handler_title']);
			option.setStyle({
				'backgroundImage': 'url(' + this.handlers[i]['handler_icon'] + ')'
			});
			option.observe('click', this.activateHandler.bindAsEventListener(this, this.handlers[i]['id']));
		}

		this.input.value = this.handlers[this.active]['handler_title'];
		this.input.addClassName('suggestion');

		this.quickSearchSwitcher.observe('click', function(event) {this.quickSearchSwitcher.toggleClassName('open'); event.stop();}.bindAsEventListener(this));
		document.observe('click', function() {if(this.quickSearchSwitcher.hasClassName('open')) {this.quickSearchSwitcher.removeClassName('open');}}.bindAsEventListener(this));
		this.input.observe('focus', this.focusHandler.bindAsEventListener(this));
		this.input.observe('blur', this.blurHandler.bindAsEventListener(this));
		this.form.observe('submit', this.submitHandler.bindAsEventListener(this));
	},

	'activateHandler': function(event, handler)
	{
		this.activeLi.down('img').src = this.handlers[handler]['handler_icon'];
		this.form.action = this.handlers[handler]['handler_url_search'];
		this.quickSearchSwitcher.toggleClassName('open');
		this.input.select();
		this.active = handler;
		event.stop();
	},

	'focusHandler': function()
	{
		if (this.input.value == this.handlers[this.active]['handler_title']) {
			this.input.value = '';
			this.input.removeClassName('suggestion');
		}
	},

	'blurHandler': function()
	{
		if (this.input.value == '') {
			this.input.value = this.handlers[this.active]['handler_title'];
			this.input.addClassName('suggestion');
		}
	},

	'submitHandler': function()
	{
		if (this.input.value == this.handlers[this.active]['handler_title']) {
			this.input.value = '';
		}

		return true;
	}
});
