﻿Autocompleter.Ajax.Json2 = new Class({

	Extends: Autocompleter.Ajax.Base,

	initialize: function(el, url, options) {
		this.parent(el, options);
		this.request = new Request.JSON($merge({
			'url': url,
			'link': 'cancel'
		}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
	},
	
	setUrl: function(url) {
	    this.request = new Request.JSON($merge({
			'url': url,
			'link': 'cancel'
		}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
	},

	queryResponse: function(response) {
		this.parent();
		this.update(response);
	}

});


/*
 * filter is optional
 */
Autocompleter.initAutocompleter = function(input, service, filter, hint) {
    var dom = $(input);
    if (dom && hint) {
        dom.value = hint;
        dom.addClass('text-hint');
        dom.addEvent('focus', function() { if (this.value == hint) { this.value = ''; this.removeClass('text-hint'); } });
        dom.addEvent('blur', function() { if (this.value == '') { this.value = hint; this.addClass('text-hint'); } });
    }
    var completer2 = new Autocompleter.Ajax.Json2(input, service + (filter ? '?filter=' + filter : ''), {
        'postVar': 'q',
        'injectChoice': function(choice) {
            var el = new Element('li')
				.set('html', this.markQueryValue(choice[0]) + '<br/>')
				.adopt(new Element('span', { 'class': 'autoGray' }).set('html', this.markQueryValue(choice[1])));
            el.inputValue = choice[0];
            this.addChoiceEvents(el).injectInside(this.choices);
        }
    });
    return completer2;
}

Autocompleter.clearOnFocus = function(input, text) {
    var dom = $(input);
    if (dom && dom.value == text)
        dom.value = '';
}
