/**
 * Autocompleter.Request
 *
 * http://digitarald.de/project/autocompleter/
 *
 * @version		1.1.2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */

Autocompleter.Request = new Class({

	Extends: Autocompleter,

	options: {/*
		indicator: null,
		indicatorClass: null,
		onRequest: $empty,
		onComplete: $empty,*/
		postData: {},
		ajaxOptions: {},
		postVar: 'value'

	},

	query: function(){
		var data = $unlink(this.options.postData) || {};
		data[this.options.postVar] = this.queryValue;
		var indicator = $(this.options.indicator);
		if (indicator) indicator.setStyle('display', '');
		var cls = this.options.indicatorClass;
		if (cls) this.element.addClass(cls);
		this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
		this.request.send({'data': data});
	},

	/**
	 * queryResponse - abstract
	 *
	 * Inherated classes have to extend this function and use this.parent()
	 */
	queryResponse: function() {
		var indicator = $(this.options.indicator);
		if (indicator) indicator.setStyle('display', 'none');
		var cls = this.options.indicatorClass;
		if (cls) this.element.removeClass(cls);
		return this.fireEvent('onComplete', [this.element, this.request]);
	}

});

Autocompleter.Request.JSON = new Class({

    Extends: Autocompleter.Request,

    initialize: function (el, url, options) {
        this.parent(el, options);
        this.request = new Request.JSON($merge({
            'url': url,
            'link': 'cancel',
            'update': this.choices
        }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
    },

    /* This will actually use JSONP from jquery */
    query: function () {

        var data = $unlink(this.options.postData) || {};
        data[this.options.postVar] = this.queryValue;
        var indicator = $(this.options.indicator);
        if (indicator) indicator.setStyle('display', '');
        var cls = this.options.indicatorClass;
        if (cls) this.element.addClass(cls);
        this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);

        // construct a list of parameters
        var me = this;
        var params = '?p_lang=' + me.encodeForJson(data.p_lang) + '&product=' + me.encodeForJson(data.product) + '&value=' + me.encodeForJson(data.value) + '&jsonCallback=?';
        jq.getJSON('http://www.cheaptickets.nl/autocomplete.cfm' + params, function (data) {
            // build html string
            var rawHtml = '';
            for (var i = 0; i < data.auto.length; i++) {
                var item = data.auto[i];
                rawHtml += '<li>';
                rawHtml += "<span id='autocomplete_label'>" + item.l + "</span>";
                rawHtml += "<span id='autocomplete_code' class='hdn'>" + item.c + "</span>";
                rawHtml += "<span id='autocomplete_continent' class='hdn'>" + item.o + "</span>";
                rawHtml += '</li>';
            }

            // write to the autocomplete box
            me.choices.innerHTML = rawHtml;

            // call response function
            me.queryResponse('', data);
        });

    },

    queryResponse: function (response) {
        this.parent();

        if (!arguments[1] || !arguments[1].auto.length) {
            this.hideChoices();
        } else {
            this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice || function (choice) {
                var value = choice.innerHTML;
                choice.inputValue = value;
                this.addChoiceEvents(choice.set('html', this.markQueryValue(value)));
            }, this);
            this.showChoices();
        }

        //this.update(response);
    },

    encodeForJson: function (txt) {
        return encodeURIComponent(txt);
    }

});

Autocompleter.Request.HTML = new Class({

	Extends: Autocompleter.Request,

	initialize: function(el, url, options) {
		this.parent(el, options);
		this.request = new Request.HTML($merge({
			'url': url,
			'link': 'cancel',
			'update': this.choices
		}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
	},

	queryResponse: function(tree, elements) {
		this.parent();
		if (!elements || !elements.length) {
			this.hideChoices();
		} else {
			this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice || function(choice) {
				var value = choice.innerHTML;
				choice.inputValue = value;
				this.addChoiceEvents(choice.set('html', this.markQueryValue(value)));
			}, this);
			this.showChoices();
		}

	}

});

/* compatibility */

Autocompleter.Ajax = {
	Base: Autocompleter.Request,
	Json: Autocompleter.Request.JSON,
	Xhtml: Autocompleter.Request.HTML
};

