
buildTokens = function(src_text) {
	var tokens = src_text.split('"');
	var real_tokens = [];
	for(var i=0; i<tokens.length; i++) {
		if(tokens[i].length > 0){
			if(i%2 == 0) {
				real_tokens = real_tokens.concat(tokens[i].strip().split(' '));
			} else {
				real_tokens = real_tokens.concat(tokens[i].strip());
			}
		}
	}
	return real_tokens;
}

flatTokens = function(token_arr) {
	var ret = '';
	for(var i=0; i<token_arr.length; i++ ){
		ret+= (token_arr[i].strip().split(' ').length > 1) ? ('"' + token_arr[i].strip() + '"') : (token_arr[i].strip());
		ret+=' ';
	}
	return ret;
}

initTagAutocompleter = function( field_id )
{
	var myAutoCompleter = new Ajax.Autocompleter( field_id, 'tag_choices', "/?op=tag_autocomplete", {
		paramName: "tag",
		minChars: 2,
		fieldId: field_id,
		indicator: 'tag_autocomplete_indicator',
		updateElement: function(el)
		{
			//$(this.fieldId).removeClassName( 'loading' );
			var tkz = buildTokens($(this.fieldId).value);
			tkz.pop();
			tkz = tkz.concat(el.innerHTML);
			$(this.fieldId).value = flatTokens(tkz);
		},
		callback: function(tx, def)
		{
			//tx.addClassName( 'loading' );
			var tkz = buildTokens(tx.value);
			var tkz_item = tkz.pop();
			if( tkz_item.length < 2 ) return false;
			return 'tag=' + tkz_item;
		}
	});

	myAutoCompleter.markPrevious = function()
	{
		if(this.index > 0)
		{
			this.index--;
		}
		else
		{
			this.index = this.entryCount-1;
		}
	};

	myAutoCompleter.markNext = function()
	{
		if(this.index < this.entryCount-1)
		{
			this.index++;
		}
		else
		{
			this.index = 0;
		}
	};

	return myAutoCompleter;
}
