function Field() {
    this.prepareID = function(id) {
        if(!id) {
            return '';
        }
        return id.replace(/\./g, "\\.");
    };

    this.get = function(id) {
        if(!id) {
            return null;
        }
        return $("#" + this.prepareID(id));
    };
}

function AutocompleteField(id, cat, param) {

	var THIS = this;

	this.cat = cat;
	this.param = param;
	this.data = [];
	this.reqSent = false;

	this.match = function(term, response) {
		term = term.toLowerCase();
		var tc = term.length;
		var res = [];
		for(var i = 0, ic = this.data.length; i < ic; ++ i) {
			if(this.data[i].label.substring(0, tc).toLowerCase() == term) {
				res.push(this.data[i]); 
			}
		}
		response(res);
	};

	this.autocomplete = function(request, response) {
		var THIS = this;
		
		if(this.data.length == 0) {

			if(!this.reqSent) {
				this.reqSent = true;

				$.get("/ajax/autocomplete/?cat=" + this.cat + "&param=" + this.param, function(data) {
					THIS.data = data;
					THIS.match(request.term, response);
					THIS.reqSent = false;
				}, 'json');
			}

		} else {
			this.match(request.term, response);
		}
	};
	
	this.get(id).autocomplete({delay: 0, source: function(req, res) {return THIS.autocomplete(req, res);}});
}

AutocompleteField.prototype = new Field();