// A snippet designed to be used with my FixedTaxonomyTagSelectMultiple
// widget, to select multiple tags from a pre-determined collection
//
// Writen by Oz for the threecouncils project on 16 April 2010

var tagselect;

(function ($) {
    tagselect = function() {
        // In short, fetch all select options, generate 'tags' from them,
        // then attach events to tags such that clicking will immediately
        // update the options of the select element
        var select = $('select.tagselect'),
            options = select.children(),
            proxy = $('<div class="tagselect-container" />');

        if(select.hasClass('is_pretty')) return; // don't do twice...
    
        select.after(proxy).css('display', 'none');
        
        options.each(function () {
            var tag = $('<a class="tag" />');
    
            if ($(this).attr('selected')) {
                tag.addClass('selected');
            }
    
            tag
                .html($(this).html())
                .data('select_value', $(this).attr('value'))
                .bind('click', function () {
                    var option_selector = "option[value='" + $(this).data('select_value') + "']",
                        option = options.filter(option_selector);
                    if ($(this).hasClass('selected')) {
                        option.attr('selected', false);
                        $(this).removeClass('selected');
                    } else {
                        option.attr('selected', true)
                        $(this).addClass('selected');
                    }
                });
                    
            proxy.append(tag);
    
        });
        select.addClass('is_pretty');
    };
    $(document).ready(function(){ tagselect(); });

})(window.django && django.jQuery || jQuery);





