﻿(function ($) {
    $.fn.saturneoTagEditorV1 = function (options) {
        var defaults = {
            separator: '%',
            separatorForJoin: '%',
            items: [],
            itemsString: '',
            className: 'tagEditor',
            tagContainerSuffix: "Container",
            tagListSuffix: "List",
            confirmRemoval: false,
            completeOnSeparator: false,
            completeOnBlur: false,
            readOnly: false
        }

        var options = $.extend(defaults, options);

        return this.each(function (index) {
            var containerId, hiddenTextId;
            var $textBase = $(this), $container, $hiddenText;
            containerId = $textBase.attr("id") + options.tagContainerSuffix;
            hiddenTextId = $textBase.attr("id") + options.tagListSuffix;

            $container = $('#' + containerId);
            $container.empty();

            var isNewTagEditor = true;
            if ($textBase.attr('tagEditor') == 'installed') {
                isNewTagEditor = false;
            }
            $textBase.attr('tagEditor', 'installed');

            // ... hidden field for holding all tags
            $hiddenText = $('#' + hiddenTextId);
            if ($hiddenText.length == 0) {
                $hiddenText = $(document.createElement('input'));
                $hiddenText.attr('type', 'hidden');
                $hiddenText.attr("id", hiddenTextId);
                $hiddenText.attr("name", hiddenTextId);
                $textBase.after($hiddenText);
            }
            $hiddenText.val('');

            // ... add button
            if (isNewTagEditor) {
                $textBase.addClass('tagEditorInput');
                $cmdAdd = $(document.createElement('span'));
                $cmdAdd.addClass('tagEditorAdd');
                $cmdAdd.attr('title', "Ajouter le mot-clé");
                $cmdAdd.html('Ajouter');
                $textBase.after($cmdAdd);
            }

            // ... unordered list for tags
            var $listBase = $(document.createElement('ul'));
            $listBase.attr('class', options.className);
            $container.append($listBase);

            // Process received items
            if (options.items.length == 0) {
                if (options.itemsString.length > 0) {
                    options.items = options.itemsString.split(options.separator);
                }
            }
            for (var i = 0; i < options.items.length; i++) {
                addTag($listBase, jQuery.trim(options.items[i]));
            }

            // Process filled items
            parse();

            // Process all tags
            buildArray();

            // Bind events
            if (isNewTagEditor) {
                $textBase.keypress(handleKeys);
                $textBase.blur(parse);
            }

            //var form = $(this).parents("form");
            //form.submit(function() {
            //    parse();
            //$hiddenText.attr("id", $textBase.attr("id"));
            //$hiddenText.attr("name", $textBase.attr("name"));
            //$textBase.attr("id", $textBase.attr("id") + '_old');
            //$textBase.attr("name", $textBase.attr("name") + '_old');
            //});

            function addTag(listBase, tag) {
                tag = jQuery.trim(tag);
                if (listBase.find('li').filter(
                        function () {
                            return $(this).text() == tag;
                        }).size() > 0) {
                    return;
                }

                var item = $(document.createElement('li'));
                item.text(tag);
                item.attr('title', 'Supprimer "' + tag + '"');

                if (!options.readOnly) {
                    item.click(function () {
                        if (options.confirmRemoval)
                            if (!confirm("Voulez-vous supprimer ce mot-clé ?"))
                                return;

                        item.remove();
                        parse();
                    });
                }

                listBase.append(item);
            }

            function buildArray() {
                var listBase = $container.find('ul:first');
                var itemBase = [];
                var items = $("li", listBase);

                for (var i = 0; i < items.length; i++) {
                    itemBase.push(jQuery.trim($(items[i]).text()));
                }
                $hiddenText.val(itemBase.join(options.separatorForJoin));
            }

            function parse() {
                var listBase = $container.find('ul:first');
                var items = $textBase.val().split(options.separator);

                for (var i = 0; i < items.length; i++) {
                    var trimmedItem = jQuery.trim(items[i]);
                    if (trimmedItem.length > 0)
                        addTag(listBase, trimmedItem);
                }
                $textBase.val("");
                buildArray();
            }

            function handleKeys(ev) {
                var keyCode = (ev.which) ? ev.which : ev.keyCode;

                if (options.completeOnSeparator) {
                    if (String.fromCharCode(keyCode) == options.separator) {
                        parse();
                        return false;
                    }
                }

                switch (keyCode) {
                    case 13:
                        {
                            if (jQuery.trim($textBase.val()) != '') {
                                parse();
                                return false;
                            }
                            return true;
                        }
                }
            }

        }); // each - END
    };
})(jQuery);
