/* 


 */
;
(function($) {
    $.fn.taginput = function(options) {
        options = $.extend({
            url: '',
            topElement: 'topId',
            targetId: 'targetId',
            addButton: 'addId',
            tagFieldName: 'tags'
        }, options);
        return this.each(function() {
            var $this = $(this);
            $this.autocomplete(
                    options.url,
            {
                delay:50,
                minChars:2,
                matchSubset:1,
                matchContains:1,
                cacheLength:10,
                multiple: true,
                autoFill:true,
                extraParams:{
                    excludes: function() {
                        var opts = [];
                        $(options.targetId + ' input ', $(options.topElement)).each(function(pos) {
                            opts[pos] = $(this).val();
                        });
                        return opts;
                    }
                }
            });
            $this.result(function(event, data, formatted) {
                $(options.addButton).click();
            });
            $this.bind("keypress", function(e) {
                if (e.keyCode == 13) {
                    $(options.addButton).click();
                    return false;
                }
            });

            var clicker = function() {
                var value = $this.val().split(",");
                if (value == undefined) {
                    return;
                }
                var i = 0;
                for (i = 0; i < value.length; i++) {
                    var val = $.trim(value[i]);
                    if (val == '' || val == undefined) {
                        continue;
                    }
                    $(options.targetId).append($this.createTag(val, options.tagFieldName));
                }
                $($this).flushCache();
                $($this).val('');
//                return false;
            };
//            $(options.addButton).onclick = clicker;
            $(options.addButton).click(clicker);
        });
    };
    $.fn.nullSafeCreateTag = function(val, tagFieldName) {
        if (val == '' || val == undefined) {
            return null;
        }
        else {
            return $(this).createTag(val, tagFieldName);
        }
    }
    $.fn.createTag = function(value, tagFieldName) {
        var container = $('<span class="selectedTag"></span>');
        container.append("<input name='" + tagFieldName + "' value='" + value + "' type='hidden'/>");
        container.append("<span>" + value + "</span> ");

        container.append("<span class='remove' onclick='$(this).parent().remove()'><img alt='x' src='/aleja/img/closer_blue.png'/></span>");
        return container;
    }
})(jQuery);



