{% load i18n %}
<input type="text" name="{{name}}_text" id="{{html_id}}_text" value="" {{ extra_attrs }} />
{% if add_link %}
	<a href="{{ add_link }}" class="add-another" id="add_{{ html_id }}" onclick="return showAddAnotherPopup(this);"> <img src="{{ admin_media_prefix }}img/admin/icon_addlink.gif" width="10" height="10" alt="Add Another"></a>
{% endif %}
{% block help %}{# {% if help_text %}<p class="help">{{help_text}}</p>{% endif %} #}{% endblock %}
<div id="{{html_id}}_on_deck" class="results_on_deck"><div>{{current_result|safe}}</div></div>
<input type="hidden" name="{{name}}" id="{{html_id}}" value="{{current_id}}" />
<script type="text/javascript">
jQuery(document).ready(function($){{% block script %}
	$("#{{html_id}}_text").autocomplete('{{lookup_url}}', {
		width: 320,
		formatItem: function(row) { return row[2]; },
		formatResult: function(row) { return row[1]; },
		dataType: "text"
	});
	function receiveResult(event, data) {
		prev = $("#{{html_id}}").val();
		if(prev) {
			kill_{{ func_slug }}(prev);
		}
		$("#{{html_id}}").val(data[0]);
		$("#{{html_id}}_text").val("");
		addKiller_{{ func_slug }}(data[1],data[0]);
		$("#{{html_id}}_on_deck").trigger("added");
	}
	$("#{{html_id}}_text").result(receiveResult);
	function addKiller_{{func_slug}}(repr,id) {
		kill = "<span class='iconic' id='kill_{{ html_id }}'>X</span>	";
		if(repr){
			$( "#{{html_id}}_on_deck" ).empty();
			$( "#{{html_id}}_on_deck" ).append( "<div>" + kill + repr + "</div>");
		} else {
			$( "#{{html_id}}_on_deck > div" ).prepend(kill);
		}
		$("#kill_{{ html_id }}").click(function() { return function(){
			kill_{{func_slug}}();
			$("#{{html_id}}_on_deck").trigger("killed");
		}}() );
	}
	function kill_{{func_slug}}() {
		$("#{{html_id}}").val( '' );
		$( "#{{html_id}}_on_deck" ).children().fadeOut(1.0).remove();
	}
	if($("#{{ html_id }}").val()) { // add X for initial value if any
		addKiller_{{ func_slug }}(null,$("#{{ html_id }}").val());
	}
	$("#{{ html_id }}").bind('didAddPopup',function(event,id,repr) {
		data = Array();
		data[0] = id;
		data[1] = repr;
		receiveResult(null,data);
	});
{% block extra_script %}{% endblock %}
{% endblock %}});
</script>

