{% load i18n staticfiles %}
<h3>{% blocktrans with filter_title=title %} By {{ filter_title }} {% endblocktrans %}</h3>
<ul id="{{ spec.uuid }}" class="das-ajaxlistfilter-search">
    <li><input class="das-search" type="text" field-name="{{ spec.field_name }}" url-kwarg="{{ spec.lookup_kwarg }}" ajax-url="{{ spec.ajax_url }}" placeholder="{{ title }}" /></li>
</ul>
<ul class="das-ajaxlistfilter-remove">
{% for choice in choices %}
    <li{% if choice.selected %} class="selected"{% endif %}>
    {% if choice.query_string %}
        <a href="{{ choice.query_string|iriencode }}" class="inline-deletelink" alt="{{ choice.alt }}" title="{{ choice.alt }}">{{ choice.display }}{% if choice.remove_icon %}
            <span class="inline-deletelink-icon" alt="{{ choice.alt }}" title="{{ choice.alt }}"></span>{% endif %}</a>
    {% else %}
        {{ choice.display }}
    {% endif %}</li>
{% endfor %}
</ul>
<script type="text/javascript">
(function($){
    $(document).ready(function(){
        var timer;
        $('#{{ spec.uuid }} .das-search').keyup(function(){
            var el = $(this);
            var parent = $("#{{ spec.uuid }}");
            
            // Don't bother searching for keypresses that haven't changed
            // the search string.
            var last_val = el.data('last-val');
            if(last_val == el.val()){
                return;
            }
            el.data('last-val', el.val());
            
            if(timer){
                clearTimeout(timer);
            }
            
            timer = setTimeout(function(){
                el.attr('disabled', 'disabled');

                $("li:not(:first-child)", parent).remove();
                
                var progress_message = $('<li/>').addClass('status').text('Searching...').appendTo(parent);
                var progress = setInterval(function(){
                    progress_message.append('.');
                }, 1000);
                
                $.ajax({
                    url: el.attr('ajax-url'),
                    data: {q: el.val()},
                    type: 'GET',
                    dataType: 'json',
                    success: function(data, textStatus, jqXHR){
                        el.removeAttr('disabled');
                        $("li:not(:first-child)", parent).remove();
                        clearInterval(progress);
                        if(data.length){
                            $.each(data, function(i){
                                var li = $('<li/>')
                                    .css('display', 'none')
                                    .appendTo(parent);
                                var label = $('<label />').appendTo(li);
                                $('<input type="checkbox" />')
                                    .attr('value', data[i].key)
                                    .appendTo(label);
                                $('<span />')
                                    .text(data[i].value)
                                    .appendTo(label);
                            });
                            var li = $('<li/>')
                                .css('display', 'none')
                                .appendTo(parent);
                            $('<input type="submit" value="update results" />').appendTo(li).click(function(){
                                var new_parts = $('input:checkbox:checked', parent).map(function(){
                                    return $(this).val();
                                }).get().join(',');
                                var lookup_kwarg = el.attr('url-kwarg');
                                var retrieve_pat = new RegExp("&?"+lookup_kwarg+"=([^&]+)");
                                var existing_matches = retrieve_pat.exec(window.location.href);
                                if(existing_matches){
                                    new_parts = existing_matches[1] + ',' + new_parts;
                                }
                                var remove_pat = new RegExp("&?"+lookup_kwarg+"=[^&]+");
                                var new_url = window.location.href.replace(remove_pat, '')
                                if(new_url.indexOf('?') >= 0){
                                    new_url = new_url + '&';
                                }else{
                                    new_url = new_url + '?';
                                }
                                new_url = new_url + lookup_kwarg + '=' + new_parts;
                                window.location.href = new_url;
                                return false;
                            });
                            $('li', parent).fadeIn();
                        }else{
                            $('<li/>').addClass('status').text('No results').appendTo(parent);
                        }
                        el.focus();
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        // Something bad happened.
                        el.removeAttr('disabled');
                        clearInterval(progress);
                        var parent = $("#{{ spec.uuid }}");
                        $("li:not(:first-child)", parent).remove();
                        $('<li/>')
                            .addClass('status')
                            .text('An error occurred. Please try again later.')
                            .appendTo(parent);
                        el.focus();
                    }
                });
            }, 1000);
        });
    });
})((window.django && window.django.jQuery) || window.jQuery);
</script>