/**
 * Take a normal <select> and turn it into a Twitch-stylized dropdown that has the markup:
 *
 * <div class="dropdown">
 *   <span></span>
 *   <select>
 *     <option></option>
 *     ...
 *     <option></option>
 *   </select>
 * </div>
 *
 * The given <select> must pass $('select').data('dropdownify-type').match(/month|day|year/)
 */

(function ($) {
  var capitalize = function (string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  };

  var getLabel = function (el) {
    var $el = $(el);
    var currentVal = $el.val();
    if (!currentVal) return $el.data('dropdownify-label') || capitalize($el.data('dropdownify-type'));

    return $el.find('option').filter(function () {
      return currentVal === $(this).attr('value');
    }).first().text();
  };

  // to get around fact that an empty string causes label span to collapse, causing graphical glitch
  var ensureOneSpace = function (str) {
    return str || "&nbsp;";
  };

  $.extend($.fn, {
    dropdownify: function () {
      $(this).each(function () {
        var $parent = $(this).parent();
        if (!$(this).is("select") || !$(this).data('dropdownify-type') || $parent.hasClass('dropdown')) {
          return;
        }

        var $dropdown = $('<div class="dropdown ' + $(this).data('dropdownify-type') + '_contain"><span>' +
          ensureOneSpace(getLabel(this)) + '</span></div>')
        .append(this)
        .on('change', function () {
          // Use native JS to get selectValue because Zepto does not support $("option:selected")
          var select = $('select', this).get(0);
          var selectValue = ensureOneSpace($(select.options[select.selectedIndex]).text());
          $('span:first-child', this).html(selectValue);
        })
        .on('focus', 'select', function () {
          $(this).parent().addClass('active_dropdown');
        })
        .on('blur', 'select', function () {
          $(this).parent().removeClass('active_dropdown');
        });

        $parent.append($dropdown);
      });
    }
  });
})(window.jQuery);
