/*
  Autocomplete Hashtags
  Watches the user as they type in attached input. If the "last word"
  of the curent field starts with a # then search/display filtered tags.
  This does some UX checking to ensure no "complete" tags are presented
  and that if they have finished a tag (field ends with whitespace) then
  no results are present
*/
(function($) {
  $.fn.autocompleteHashtag = function () {
    // Blessed #hashtags which are safe to autocomplete on a per-game basis
    var BLESSED = {
      creative: (SiteOptions.creative_communities || '').split(',').map(function (word) {
        return '#' + word;
      })
    };
    // Replace the user's incomplete tag with the full tag
    function setTag($input, tag) {
      var text = $input.val();
      var lastWord = text.trim().split(/\s/).pop();
      $input.val(text.replace(new RegExp(lastWord + '$'), tag) + ' ');
    }
    // Remove current list of blessed tags
    function hideBlessedTags($list) {
      $list.empty().hide();
    }
    // Display list of blessed tags to select from
    function showBlessedTagsFor($list, $input, blessedTags, text) {
      var tags = blessedTags.filter(function (tag) {
        return tag.indexOf(text) === 0 && tag !== text;
      });
      if (!tags.length) {
        return $list.hide();
      }
      var $tags = tags.slice(0, 10).map(function (tag) {
        return $('<li class="balloon__link">' + tag + '</li>')
          .click(function () {
            setTag($input, tag);
            hideBlessedTags($list);
          });
      });
      $list.html($tags).show();
    }
    return $(this).each(function () {
      var $input = $(this);
      var $tagList = $('<ul class="balloon balloon--down balloon--dropmenu full-width"></ul>').hide();
      $input.after($tagList);
      $input.keydown(function (e) {
        var inputVal = $(this).val();
        var lastChar = inputVal.slice(-1);
        var lastWord = inputVal.trim().split(/\s/).pop();
        var channelGame = $('#gameselector_input').val().trim().toLowerCase();
        var blessedTags = BLESSED[channelGame] || [];
        if (lastChar.match(/\s/) || !lastWord || !channelGame || !blessedTags.length) {
          hideBlessedTags($tagList);
        }
        // "enter" key (return) or "tab" key which is cleaned up by jQuery
        else if (e.which === 13 || e.which === 9) {
          e.preventDefault();
          var tags = blessedTags.filter(function (tag) {
            return tag.indexOf(lastWord) === 0;
          });
          if (tags.length === 1) {
            setTag($input, tags[0]);
            hideBlessedTags($tagList);
          }
        }
        else if (lastWord[0] === '#') {
          showBlessedTagsFor($tagList, $input, blessedTags, lastWord);
        }
        else {
          hideBlessedTags($tagList);
        }
      });
    });
  };
})(jQuery);
