/**
 * Autocompleter for use with key - value pairs
 *
 * @package nova
 * @subpackage javascript
 * @author Liquid Edge Solutions
 * @copyright Copyright Liquid Edge Solutions. All rights reserved.
 *///--------------------------------------------------------------------------------
Autocompleter.Request.Hash = new Class({
	Extends: Autocompleter.Request.JSON,
	//--------------------------------------------------------------------------------

	// constructor

	//--------------------------------------------------------------------------------
	initialize: function(el, url, value, options) {
		// init
		this.core = {};
		var nameInput = '__' + el;

		// set additional element properties
		var elInput = $(nameInput);
		elInput.addEvent('change', function() { eval(el + '.validate();'); });
		elInput.set('nosubmit', 'nosubmit');

		// create hidden element
		var elHidden = new Element('input', {
			type: 'hidden',
			id: el,
			name: el,
			value: (value == '' ? 'null' : value)
		});
		elHidden.inject(elInput, 'after');
		this.core.elHidden = $(el);

		// additional post vars
		if ($defined(options.addVar)) {
			options.addVar = $splat(options.addVar);
			options = $extend({
				onRequest: function(element, request, data, options) {
					this.options.addVar.each(function(el) {
						data[el] = $(el).get('value');
					});
				}
			}, options);
		}

		// init options
		options = $extend({
			injectChoice: function(token, index) {
				var choice = new Element('li', {'html': this.markQueryValue(token), 'key': this.core.key_arr[index]});
				choice.inputValue = token;
				this.addChoiceEvents(choice).inject(this.choices);
			},
			onSelection: function(input, selection, currentValue, newValue) {
				this.core.elHidden.set('value', $(selection).get('key'));
			}
		}, options);

		// call parent
		this.parent(nameInput, url, options);
	},
	//--------------------------------------------------------------------------------

	// parent

	//--------------------------------------------------------------------------------
	queryResponse: function(response) {
		this.parent();
		var value_arr = [];
		this.core.key_arr = [];
		$each(response, function(el, index, options) {
			value_arr.push(el);
			this.core.key_arr.push(index);
		}, this);
		this.update(value_arr);
	},
	//--------------------------------------------------------------------------------
	validate: function() {
		var index = this.cached.indexOf(this.element.get('value'));
		if (index === -1) {
			this.element.set('value', '');
			this.core.elHidden.set('value', 'null');
		}
	}
});
//--------------------------------------------------------------------------------