{% load i18n %}
<input type="text" name="{{name}}_text" id="{{html_id}}_text" value="{{current_name}}" />
<p id="{{html_id}}_on_deck" class="results_on_deck"></p>
<input type="hidden" name="{{name}}" id="{{html_id}}" value="{{current_ids}}" />
<script type="text/javascript">
jQuery(document).ready(function($){
        function formatItem_{{html_id|cut:"-"}}(row) {
                return row[2];
        }
        function formatResult_{{html_id|cut:"-"}}(row) {
                return row[1];
        }
        $("#{{html_id}}_text").autocomplete('{{lookup_url}}', {
                width: 320,
                multiple: true,
                multipleSeparator: " ",
                scroll: true,
                scrollHeight:  300,
                formatItem: formatItem_{{html_id|cut:"-"}},
                formatResult: formatResult_{{html_id|cut:"-"}},
                dataType: "text",
                highlight: false
        });
        $("#{{html_id}}_text").result(function(event, data, formatted) {
                id = data[0];
                if( $("#{{html_id}}").val().indexOf( "|"+id+"|" ) == -1) {
                        if($("#{{html_id}}").val() == '') {
                                $("#{{html_id}}").val('|');
                        }
                        $("#{{html_id}}").val( $("#{{html_id}}").val() + id + "|");
                        addKiller_{{html_id|cut:"-"}}(data[1],id);
                        $("#{{html_id}}_text").val(''); //can't clear the input field ?
                }
        });
        function addKiller_{{html_id|cut:"-"}}(repr,id) {
                kill = "<span class='iconic' id='kill_" + id + "'>X</span>      ";
                $( "#{{html_id}}_on_deck" ).append("<div id='{{html_id}}_on_deck_" + id +"'>" + kill + repr + " </div>");
                $("#{{html_id}}_on_deck #kill_"+id).click(function(num) { return function(){
                        kill_{{html_id|cut:"-"}}(num);
                        $("#{{html_id}}_on_deck").trigger("killed");//send signal
                }}(id) );
        }
        function kill_{{html_id|cut:"-"}}(id) {
                $("#{{html_id}}").val( $("#{{html_id}}").val().replace( "|" + id + "|", "|" ) );
                $("#{{html_id}}_on_deck_" + id).remove();
        }
        currentRepr = {{current_reprs}};
        currentRepr.forEach(function(its){
                addKiller_{{html_id|cut:"-"}}(its[0],its[1]);
        });
});
</script>

