<div class="rapid-select {{ id }} data reload-here">
    <input type="hidden" id="{{ id }}" name="{{ name }}" value="{{ value }}" {% for k, v in attrs %} {{ k }} = "{{ v }}" {% endfor %}>
    <ul class="rapid-select-selected">
        {% for e in selected %}
        <li name="{{ e.pk }}">{{ e }} <a class="rapid-select-remove interaction"><span class="fa {{ icon }}"></span></a></li>
        {% endfor %}
    </ul>
    <a class="rapid-select-add interaction"><span class="fa fa-plus">Adicionar</span></a>
</div>
<script>
    function add_ids_to_{{ id }}(source){
        var sel = source.find("table.rapid-object-selector");
        var markers = sel.children("tbody").children("tr.selected").children("td").children("input.rapid-select-id-marker");
        var old_ids = [];
        if($("input#{{ id }}").val()){
            old_ids = $("input#{{ id }}").val().split(",");
        }
        var new_ids = [];
        var new_names = [];
        markers.each(function(){
            if (old_ids.indexOf($(this).val()) < 0){
                new_ids.push($(this).val());
                new_names.push($(this).attr("name"));
            }
        });
        $("input#{{ id }}").val(old_ids.concat(new_ids).join(","));
        var widget_root = $("div.rapid-select.{{ id }}").children("ul.rapid-select-selected")
        for(i = 0; i < new_names.length; i++){
            var li = $("<li>", {id: new_ids[i]}).html(
                new_names[i] + " <a class=\"rapid-select-remove\">" +
                "<span class=\"fa {{ icon }}\"></span></a>");
            widget_root.append(li);
        }
    };
    function add_elements_to_{{ id }}(){
        show_overlay("{{ select_url }}", $("div.rapid-select.{{ id }}").find("a.rapid-select-add"), add_ids_to_{{ id }}, false);
    };
    $(document).ready(function(){
        var d = $("div.rapid-select.{{ id }}")
        d.on("click", ".rapid-select-remove", function(){
            var rem_id = $(this).closest("li").attr("name");
            var old_ids = $("input#{{ id }}").val().split(",");
            for(i = 0; i < old_ids.length; i++){
                if(old_ids[i] = rem_id){
                    old_ids.splice(i, 1);
                    break;
                }
            }
            $("input#{{ id }}").val(old_ids.join(","));
            $(this).closest("li").remove();
        });
        d.find(".rapid-select-add").click(add_elements_to_{{ id }});
    });
</script>