
(function(jQuery) {
    var globalTags = [];
    var kidsIndex = -1;
    var timer = 1;
    // creates a public function within our private code.
    // tags can either be an array of strings OR
    // array of objects containing a 'tag' attribute
    window.setGlobalTags = function(tags /* array */) {
        globalTags = getTags(tags);
    };

    function getTags(tags) {
        var tag, i, goodTags = [];
        for (i = 0; i < tags.length; i++) {
            tag = tags[i];
            if (typeof tags[i] == 'object') {
                tag = tags[i].tag;
            }
            goodTags.push(tag.toLowerCase());
        }

        return goodTags;
    }

    jQuery.fn.tagSuggest = function(options) {
        var defaults = {
            'matchClass': 'tagMatches',
            'tagContainer': 'div',
            'tagWrap': 'div',
            'sort': true,
            'tags': null,
            'url': null,
            'separator': ' '
        };

        var i, tag, userTags = [], settings = jQuery.extend({}, defaults, options);

        if (settings.tags) {
            userTags = getTags(settings.tags);
        } else {
            userTags = globalTags;
        }

        return this.each(function() {
            var tagsElm = jQuery(this);
            var elm = this;
            var matches, fromTab = false;
            var suggestionsShow = false;
            var workingTags = [];
            var currentTag = { "position": 0, tag: "" };
            var tagMatches = document.createElement(settings.tagContainer);

            function showSuggestions(el, key) {
                workingTags = el.value.split(settings.separator);
                matches = [];
                var i, chosenTags = {}, tagSelected = false;

                // we're looking to complete the tag on currentTag.position (to start with)
                currentTag = { position: currentTags.length - 1, tag: '' };

                for (i = 0; i < currentTags.length; i++) {
                    if (!tagSelected) {
                        currentTag = { position: i, tag: workingTags[i].toLowerCase() };
                        tagSelected = true;
                    }

                    // lookup for filtering out chosen tags
                    chosenTags[currentTags[i].toLowerCase()] = true;
                }
                if (currentTag.tag) {
                    // collect potential tags
                    if (settings.url) {
                        jQuery.ajax({
                            'url': settings.url,
                            'dataType': 'json',
                            'data': { 'tag': currentTag.tag },
                            'async': true, // wait until this is ajax hit is complete before continue
                            'success': function(m) {
                                matches = m;
                                buildMatches();
                            }
                        });

                    } else {
                        for (i = 0; i < userTags.length; i++) {
                            if (userTags[i].indexOf(currentTag.tag) === 0) {
                                matches.push(userTags[i]);
                            }
                        }
                    }


                    if (timer == 1) {
                        setTimeout(function() { if (timer == 1) { tagMatches.html("<div class='stattusText'>Listen bygges</div>") }; }, 1800);
                    }


                } else {
                    hideSuggestions();
                }
            }
            function updateTimer() {
            }

            function ShowText() {
                if (timer == 1) {
                    tagMatches.html("<div class='stattusText'>Listen bygges</div>");
                }
            }

            function buildMatches() {
                timer = 2;
                var html = ''

                for (i = 0; i < matches.length; i++) {
                    var mytitle = matches[i].title.toLowerCase().replace(currentTag.tag.toLowerCase(), "<b>" + currentTag.tag.toLowerCase() + "</b>");
                    html += '<' + settings.tagWrap + ' class="TagSuggestion"><a href="' + matches[i].url + '" title="' + matches[i].title + '"><div class="Title">' + mytitle + '</div><div class="Text">' + matches[i].text + '</div></a></' + settings.tagWrap + '>';
                }

                tagMatches.html(html);


                suggestionsShow = !!(matches.length);
            }
            function hideSuggestions() {
                tagMatches.empty();
                matches = [];
                suggestionsShow = false;
            }

            function setSelection() {
                var v = tagsElm.val();

                if (v == tagsElm.attr('title') && tagsElm.is('.hint')) v = '';

                currentTags = v.split(settings.separator);
                hideSuggestions();
            }


            function handleKeys(ev) {
                fromTab = false;
                var type = ev.type;
                var resetSelection = false;
                var kids = $("." + settings.matchClass).children();
                switch (ev.keyCode) {
                    case 13:
                        {
                            if (kidsIndex != -1) {
                                var ref = $(kids[kidsIndex]).children();
                                window.location.replace(ref.attr('href'));
                            }
                        }
                    case 38:
                        {
                            //added for delay

                            if (ev.keyCode == 38 && ev.type == "keyup") {
                                $(kids).removeClass("hilite");
                                if (kidsIndex > -2)
                                    kidsIndex = kidsIndex - 1;
                                if (kidsIndex > -1)
                                    $(kids[kidsIndex]).addClass("hilite");
                                return true;
                            }
                        }
                    case 40:
                        {

                            if (ev.keyCode == 40 && ev.type == "keyup") {
                                $(kids).removeClass("hilite");
                                if (kidsIndex < kids.length - 1)
                                    kidsIndex = kidsIndex + 1;
                                $(kids[kidsIndex]).addClass("hilite");
                                return true;
                            }

                        }
                    case 18:
                        {
                            return true;
                        }
                    case 32:
                        {
                            setSelection();
                            return true;
                        }
                }

                showSuggestions(this, ev.charCode);
            }


            tagsElm.after(tagMatches).keypress(handleKeys).keyup(handleKeys).blur(function() {
                if (fromTab == true || suggestionsShow) { // tweak to support tab selection for Opera & IE
                    fromTab = false;
                    tagsElm.focus();
                }
            });

            // replace with jQuery version

            tagMatches = jQuery(tagMatches).click(function(ev) {
                //if (ev.target.nodeName == settings.tagWrap.toUpperCase() && jQuery(ev.target).is('.TagSuggestion .Title')) {
                //    chooseTag(ev.target.innerHTML);
                //}
            }).addClass(settings.matchClass);


            // initialise
            setSelection();
        });
    };
})(jQuery);
