(function() {

    TextboxList.Ajaxautocomplete = new Class({
        Extends: TextboxList.Autocomplete,
        search: function(bit) {
            if (bit) this.currentInput = bit;
            if (!this.options.queryRemote && !this.values.length) return;
            var search = this.currentInput.getValue()[1];
            if (search.length < this.options.minLength) this.showPlaceholder(this.options.placeholder);
            if (search == this.currentSearch) return;
            this.currentSearch = search;
            this.list.setStyle('display', 'none');
            if (search.length < this.options.minLength) return;

            if (this.options.queryRemote) {
                if (this.searchValues[search]) {
                    this.values = this.searchValues[search];
                    this.showResults(search);
                } else {
                    var data = this.options.remote.extraParams, that = this;
                    if ($type(data) == 'function') data = data.run([], this);
                    data[this.options.remote.param] = search;
                    if (this.currentRequest) this.currentRequest.cancel();
                    var additional;
                    if (this.options.referenceControlId && this.options.referenceControlId != "") {
                        var adPrnt;
                        try {
                            adPrnt = new Function("return " + this.options.referenceControlId)();
                        } catch (pEx) { }
                        if (adPrnt)
                            additional = adPrnt.getValues();
                    }

                    var lUrl;
                    if (!additional)
                        lUrl = this.options.remote.url.replace("[SEARCH]", encodeURIComponent(search.replace(/"/g, "\\\"").toLowerCase() + (this.options.StaticReferenceValue ? "," + this.options.StaticReferenceValue : "")));
                    else
                        lUrl = this.options.remote.url.replace("[SEARCH]", encodeURIComponent(search.replace(/"/g, "\\\"").toLowerCase() + (additional ? "," + additional[0][0] : "")));

                    this.currentRequest = new Request.JSON({ url: lUrl, data: data, onRequest: function() {
                        that.showPlaceholder(that.options.remote.loadPlaceHolder);
                    }, onSuccess: function(data) {
                        that.searchValues[search] = data;
                        that.values = data;
                        /*if (data || !data.length)
                        that.hide();
                        else*/
                        that.showResults(search);
                    }
                    }).send();
                }
            }
            else {
                if (this.values.length) this.showResults(search);
            }
        }


    });


})();