/**
 * Readabler
 * Web accessibility for Your WordPress site.
 * Exclusively on https://1.envato.market/readabler
 *
 * @encoding        UTF-8
 * @version         2.0.12
 * @copyright       (C) 2018-2025 Merkulove ( https://merkulov.design/ ). All rights reserved.
 * @license         Envato License https://1.envato.market/KYbje
 * @contributors    Dmytro Merkulov (dmitry@merkulov.design)
 * @support         help@merkulov.design
 **/

/*!
Chosen, a Select Box Enhancer for jQuery and Prototype
by Patrick Filler for Harvest, http://getharvest.com

Version 1.7.0
Full source at https://github.com/harvesthq/chosen
Copyright (c) 2011-2017 Harvest http://getharvest.com

MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md
This file is generated by `grunt build`, do not edit it by hand.
*/

(function() {
  "use strict";

  var $, AbstractChosen, Chosen, SelectParser, _ref,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  SelectParser = (function() {
    function SelectParser() {
      this.options_index = 0;
      this.parsed = [];
    }

    SelectParser.prototype.add_node = function(child) {
      if (child.nodeName.toUpperCase() === "OPTGROUP") {
        return this.add_group(child);
      } else {
        return this.add_option(child);
      }
    };

    SelectParser.prototype.add_group = function(group) {
      var group_position, option, _i, _len, _ref, _results;
      group_position = this.parsed.length;
      this.parsed.push({
        array_index: group_position,
        group: true,
        label: this.escapeExpression(group.label),
        title: group.title ? group.title : void 0,
        children: 0,
        disabled: group.disabled,
        classes: group.className
      });
      _ref = group.childNodes;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        option = _ref[_i];
        _results.push(this.add_option(option, group_position, group.disabled));
      }
      return _results;
    };

    SelectParser.prototype.add_option = function(option, group_position, group_disabled) {
      if (option.nodeName.toUpperCase() === "OPTION") {
        if (option.text !== "") {
          if (group_position != null) {
            this.parsed[group_position].children += 1;
          }
          this.parsed.push({
            array_index: this.parsed.length,
            options_index: this.options_index,
            value: option.value,
            text: option.text,
            html: option.innerHTML,
            title: option.title ? option.title : void 0,
            selected: option.selected,
            disabled: group_disabled === true ? group_disabled : option.disabled,
            group_array_index: group_position,
            group_label: group_position != null ? this.parsed[group_position].label : null,
            classes: option.className,
            style: option.style.cssText
          });
        } else {
          this.parsed.push({
            array_index: this.parsed.length,
            options_index: this.options_index,
            empty: true
          });
        }
        return this.options_index += 1;
      }
    };

    SelectParser.prototype.escapeExpression = function(text) {
      var map, unsafe_chars;
      if ((text == null) || text === false) {
        return "";
      }
      if (!/[\&\<\>\"\'\`]/.test(text)) {
        return text;
      }
      map = {
        "<": "&lt;",
        ">": "&gt;",
        '"': "&quot;",
        "'": "&#x27;",
        "`": "&#x60;"
      };
      unsafe_chars = /&(?!\w+;)|[\<\>\"\'\`]/g;
      return text.replace(unsafe_chars, function(chr) {
        return map[chr] || "&amp;";
      });
    };

    return SelectParser;

  })();

  SelectParser.select_to_array = function(select) {
    var child, parser, _i, _len, _ref;
    parser = new SelectParser();
    _ref = select.childNodes;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      child = _ref[_i];
      parser.add_node(child);
    }
    return parser.parsed;
  };

  AbstractChosen = (function() {
    function AbstractChosen(form_field, options) {
      this.form_field = form_field;
      this.options = options != null ? options : {};
      this.label_click_handler = __bind(this.label_click_handler, this );
      if (!AbstractChosen.browser_is_supported()) {
        return;
      }
      this.is_multiple = this.form_field.multiple;
      this.set_default_text();
      this.set_default_values();
      this.setup();
      this.set_up_html();
      this.register_observers();
      this.on_ready();
    }

    AbstractChosen.prototype.set_default_values = function() {
      var _this = this;
      this.click_test_action = function(evt) {
        return _this.test_active_click(evt);
      };
      this.activate_action = function(evt) {
        return _this.activate_field(evt);
      };
      this.active_field = false;
      this.mouse_on_container = false;
      this.results_showing = false;
      this.result_highlighted = null;
      this.is_rtl = this.options.rtl || /\bchosen-rtl\b/.test(this.form_field.className);
      this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false;
      this.disable_search_threshold = this.options.disable_search_threshold || 0;
      this.disable_search = this.options.disable_search || false;
      this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true;
      this.group_search = this.options.group_search != null ? this.options.group_search : true;
      this.search_contains = this.options.search_contains || false;
      this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true;
      this.max_selected_options = this.options.max_selected_options || Infinity;
      this.inherit_select_classes = this.options.inherit_select_classes || false;
      this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true;
      this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true;
      this.include_group_label_in_selected = this.options.include_group_label_in_selected || false;
      this.max_shown_results = this.options.max_shown_results || Number.POSITIVE_INFINITY;
      this.case_sensitive_search = this.options.case_sensitive_search || false;
      return this.hide_results_on_select = this.options.hide_results_on_select != null ? this.options.hide_results_on_select : true;
    };

    AbstractChosen.prototype.set_default_text = function() {
      if (this.form_field.getAttribute("data-placeholder")) {
        this.default_text = this.form_field.getAttribute("data-placeholder");
      } else if (this.is_multiple) {
        this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text;
      } else {
        this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text;
      }
      this.default_text = this.escape_html(this.default_text);
      return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text;
    };

    AbstractChosen.prototype.choice_label = function(item) {
      if (this.include_group_label_in_selected && (item.group_label != null)) {
        return "<b class='group-name'>" + item.group_label + "</b>" + item.html;
      } else {
        return item.html;
      }
    };

    AbstractChosen.prototype.mouse_enter = function() {
      return this.mouse_on_container = true;
    };

    AbstractChosen.prototype.mouse_leave = function() {
      return this.mouse_on_container = false;
    };

    AbstractChosen.prototype.input_focus = function(evt) {
      var _this = this;
      if (this.is_multiple) {
        if (!this.active_field) {
          return setTimeout((function() {
            return _this.container_mousedown();
          }), 50);
        }
      } else {
        if (!this.active_field) {
          return this.activate_field();
        }
      }
    };

    AbstractChosen.prototype.input_blur = function(evt) {
      var _this = this;
      if (!this.mouse_on_container) {
        this.active_field = false;
        return setTimeout((function() {
          return _this.blur_test();
        }), 100);
      }
    };

    AbstractChosen.prototype.label_click_handler = function(evt) {
      if (this.is_multiple) {
        return this.container_mousedown(evt);
      } else {
        return this.activate_field();
      }
    };

    AbstractChosen.prototype.results_option_build = function(options) {
      var content, data, data_content, shown_results, _i, _len, _ref;
      content = '';
      shown_results = 0;
      _ref = this.results_data;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        data = _ref[_i];
        data_content = '';
        if (data.group) {
          data_content = this.result_add_group(data);
        } else {
          data_content = this.result_add_option(data);
        }
        if (data_content !== '') {
          shown_results++;
          content += data_content;
        }
        if (options != null ? options.first : void 0) {
          if (data.selected && this.is_multiple) {
            this.choice_build(data);
          } else if (data.selected && !this.is_multiple) {
            this.single_set_selected_text(this.choice_label(data));
          }
        }
        if (shown_results >= this.max_shown_results) {
          break;
        }
      }
      return content;
    };

    AbstractChosen.prototype.result_add_option = function(option) {
      var classes, option_el;
      if (!option.search_match) {
        return '';
      }
      if (!this.include_option_in_results(option)) {
        return '';
      }
      classes = [];
      if (!option.disabled && !(option.selected && this.is_multiple)) {
        classes.push("active-result");
      }
      if (option.disabled && !(option.selected && this.is_multiple)) {
        classes.push("disabled-result");
      }
      if (option.selected) {
        classes.push("result-selected");
      }
      if (option.group_array_index != null) {
        classes.push("group-option");
      }
      if (option.classes !== "") {
        classes.push(option.classes);
      }
      option_el = document.createElement("li");
      option_el.className = classes.join(" ");
      option_el.style.cssText = option.style;
      option_el.setAttribute("data-option-array-index", option.array_index);
      option_el.innerHTML = option.search_text;
      if (option.title) {
        option_el.title = option.title;
      }
      return this.outerHTML(option_el);
    };

    AbstractChosen.prototype.result_add_group = function(group) {
      var classes, group_el;
      if (!(group.search_match || group.group_match)) {
        return '';
      }
      if (!(group.active_options > 0)) {
        return '';
      }
      classes = [];
      classes.push("group-result");
      if (group.classes) {
        classes.push(group.classes);
      }
      group_el = document.createElement("li");
      group_el.className = classes.join(" ");
      group_el.innerHTML = group.search_text;
      if (group.title) {
        group_el.title = group.title;
      }
      return this.outerHTML(group_el);
    };

    AbstractChosen.prototype.results_update_field = function() {
      this.set_default_text();
      if (!this.is_multiple) {
        this.results_reset_cleanup();
      }
      this.result_clear_highlight();
      this.results_build();
      if (this.results_showing) {
        return this.winnow_results();
      }
    };

    AbstractChosen.prototype.reset_single_select_options = function() {
      var result, _i, _len, _ref, _results;
      _ref = this.results_data;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        result = _ref[_i];
        if (result.selected) {
          _results.push(result.selected = false);
        } else {
          _results.push(void 0);
        }
      }
      return _results;
    };

    AbstractChosen.prototype.results_toggle = function() {
      if (this.results_showing) {
        return this.results_hide();
      } else {
        return this.results_show();
      }
    };

    AbstractChosen.prototype.results_search = function(evt) {
      if (this.results_showing) {
        return this.winnow_results();
      } else {
        return this.results_show();
      }
    };

    AbstractChosen.prototype.winnow_results = function() {
      var escapedSearchText, highlightRegex, option, regex, results, results_group, searchText, startpos, text, _i, _len, _ref;
      this.no_results_clear();
      results = 0;
      searchText = this.get_search_text();
      escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
      regex = this.get_search_regex(escapedSearchText);
      highlightRegex = this.get_highlight_regex(escapedSearchText);
      _ref = this.results_data;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        option = _ref[_i];
        option.search_match = false;
        results_group = null;
        if (this.include_option_in_results(option)) {
          if (option.group) {
            option.group_match = false;
            option.active_options = 0;
          }
          if ((option.group_array_index != null) && this.results_data[option.group_array_index]) {
            results_group = this.results_data[option.group_array_index];
            if (results_group.active_options === 0 && results_group.search_match) {
              results += 1;
            }
            results_group.active_options += 1;
          }
          option.search_text = option.group ? option.label : option.html;
          if (!(option.group && !this.group_search)) {
            option.search_match = this.search_string_match(option.search_text, regex);
            if (option.search_match && !option.group) {
              results += 1;
            }
            if (option.search_match) {
              if (searchText.length) {
                startpos = option.search_text.search(highlightRegex);
                text = option.search_text.substr(0, startpos + searchText.length) + '</em>' + option.search_text.substr(startpos + searchText.length);
                option.search_text = text.substr(0, startpos) + '<em>' + text.substr(startpos);
              }
              if (results_group != null) {
                results_group.group_match = true;
              }
            } else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) {
              option.search_match = true;
            }
          }
        }
      }
      this.result_clear_highlight();
      if (results < 1 && searchText.length) {
        this.update_results_content("");
        return this.no_results(searchText);
      } else {
        this.update_results_content(this.results_option_build());
        return this.winnow_results_set_highlight();
      }
    };

    AbstractChosen.prototype.get_search_regex = function(escaped_search_string) {
      var regex_anchor, regex_flag;
      regex_anchor = this.search_contains ? "" : "^";
      regex_flag = this.case_sensitive_search ? "" : "i";
      return new RegExp(regex_anchor + escaped_search_string, regex_flag);
    };

    AbstractChosen.prototype.get_highlight_regex = function(escaped_search_string) {
      var regex_anchor, regex_flag;
      regex_anchor = this.search_contains ? "" : "\\b";
      regex_flag = this.case_sensitive_search ? "" : "i";
      return new RegExp(regex_anchor + escaped_search_string, regex_flag);
    };

    AbstractChosen.prototype.search_string_match = function(search_string, regex) {
      var part, parts, _i, _len;
      if (regex.test(search_string)) {
        return true;
      } else if (this.enable_split_word_search && (search_string.indexOf(" ") >= 0 || search_string.indexOf("[") === 0)) {
        parts = search_string.replace(/\[|\]/g, "").split(" ");
        if (parts.length) {
          for (_i = 0, _len = parts.length; _i < _len; _i++) {
            part = parts[_i];
            if (regex.test(part)) {
              return true;
            }
          }
        }
      }
    };

    AbstractChosen.prototype.choices_count = function() {
      var option, _i, _len, _ref;
      if (this.selected_option_count != null) {
        return this.selected_option_count;
      }
      this.selected_option_count = 0;
      _ref = this.form_field.options;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        option = _ref[_i];
        if (option.selected) {
          this.selected_option_count += 1;
        }
      }
      return this.selected_option_count;
    };

    AbstractChosen.prototype.choices_click = function(evt) {
      evt.preventDefault();
      this.activate_field();
      if (!(this.results_showing || this.is_disabled)) {
        return this.results_show();
      }
    };

    AbstractChosen.prototype.keydown_checker = function(evt) {
      var stroke, _ref;
      stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
      this.search_field_scale();
      if (stroke !== 8 && this.pending_backstroke) {
        this.clear_backstroke();
      }
      switch (stroke) {
        case 8:
          this.backstroke_length = this.get_search_field_value().length;
          break;
        case 9:
          if (this.results_showing && !this.is_multiple) {
            this.result_select(evt);
          }
          this.mouse_on_container = false;
          break;
        case 13:
          if (this.results_showing) {
            evt.preventDefault();
          }
          break;
        case 27:
          if (this.results_showing) {
            evt.preventDefault();
          }
          break;
        case 32:
          if (this.disable_search) {
            evt.preventDefault();
          }
          break;
        case 38:
          evt.preventDefault();
          this.keyup_arrow();
          break;
        case 40:
          evt.preventDefault();
          this.keydown_arrow();
          break;
      }
    };

    AbstractChosen.prototype.keyup_checker = function(evt) {
      var stroke, _ref;
      stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
      this.search_field_scale();
      switch (stroke) {
        case 8:
          if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) {
            this.keydown_backstroke();
          } else if (!this.pending_backstroke) {
            this.result_clear_highlight();
            this.results_search();
          }
          break;
        case 13:
          evt.preventDefault();
          if (this.results_showing) {
            this.result_select(evt);
          }
          break;
        case 27:
          if (this.results_showing) {
            this.results_hide();
          }
          break;
        case 9:
        case 16:
        case 17:
        case 18:
        case 38:
        case 40:
        case 91:
          break;
        default:
          this.results_search();
          break;
      }
    };

    AbstractChosen.prototype.clipboard_event_checker = function(evt) {
      var _this = this;
      if (this.is_disabled) {
        return;
      }
      return setTimeout((function() {
        return _this.results_search();
      }), 50);
    };

    AbstractChosen.prototype.container_width = function() {
      if (this.options.width != null) {
        return this.options.width;
      } else {
        return "" + this.form_field.offsetWidth + "px";
      }
    };

    AbstractChosen.prototype.include_option_in_results = function(option) {
      if (this.is_multiple && (!this.display_selected_options && option.selected)) {
        return false;
      }
      if (!this.display_disabled_options && option.disabled) {
        return false;
      }
      if (option.empty) {
        return false;
      }
      return true;
    };

    AbstractChosen.prototype.search_results_touchstart = function(evt) {
      this.touch_started = true;
      return this.search_results_mouseover(evt);
    };

    AbstractChosen.prototype.search_results_touchmove = function(evt) {
      this.touch_started = false;
      return this.search_results_mouseout(evt);
    };

    AbstractChosen.prototype.search_results_touchend = function(evt) {
      if (this.touch_started) {
        return this.search_results_mouseup(evt);
      }
    };

    AbstractChosen.prototype.outerHTML = function(element) {
      var tmp;
      if (element.outerHTML) {
        return element.outerHTML;
      }
      tmp = document.createElement("div");
      tmp.appendChild(element);
      return tmp.innerHTML;
    };

    AbstractChosen.prototype.get_single_html = function() {
      return "<a class=\"chosen-single chosen-default\">\n  <span>" + this.default_text + "</span>\n  <div><b></b></div>\n</a>\n<div class=\"chosen-drop\">\n  <div class=\"chosen-search\">\n    <input class=\"chosen-search-input\" type=\"text\" autocomplete=\"off\" />\n  </div>\n  <ul class=\"chosen-results\"></ul>\n</div>";
    };

    AbstractChosen.prototype.get_multi_html = function() {
      return "<ul class=\"chosen-choices\">\n  <li class=\"search-field\">\n    <input class=\"chosen-search-input\" type=\"text\" autocomplete=\"off\" value=\"" + this.default_text + "\" />\n  </li>\n</ul>\n<div class=\"chosen-drop\">\n  <ul class=\"chosen-results\"></ul>\n</div>";
    };

    AbstractChosen.prototype.get_no_results_html = function(terms) {
      return "<li class=\"no-results\">\n  " + this.results_none_found + " <span>" + terms + "</span>\n</li>";
    };

    AbstractChosen.browser_is_supported = function() {
      if ("Microsoft Internet Explorer" === window.navigator.appName) {
        return document.documentMode >= 8;
      }
      if (/iP(od|hone)/i.test(window.navigator.userAgent) || /IEMobile/i.test(window.navigator.userAgent) || /Windows Phone/i.test(window.navigator.userAgent) || /BlackBerry/i.test(window.navigator.userAgent) || /BB10/i.test(window.navigator.userAgent) || /Android.*Mobile/i.test(window.navigator.userAgent)) {
        return false;
      }
      return true;
    };

    AbstractChosen.default_multiple_text = "Select Some Options";

    AbstractChosen.default_single_text = "Select an Option";

    AbstractChosen.default_no_result_text = "No results match";

    return AbstractChosen;

  })();

  $ = jQuery;

  $.fn.extend({
    chosen: function(options) {
      if (!AbstractChosen.browser_is_supported()) {
        return this;
      }
      return this.each(function(input_field) {
        var $this, chosen;
        $this = $(this );
        chosen = $this.data('chosen');
        if (options === 'destroy') {
          if (chosen instanceof Chosen) {
            chosen.destroy();
          }
          return;
        }
        if (!(chosen instanceof Chosen)) {
          $this.data('chosen', new Chosen(this, options));
        }
      });
    }
  });

  Chosen = (function(_super) {
    __extends(Chosen, _super);

    function Chosen() {
      _ref = Chosen.__super__.constructor.apply(this, arguments);
      return _ref;
    }

    Chosen.prototype.setup = function() {
      this.form_field_jq = $(this.form_field);
      return this.current_selectedIndex = this.form_field.selectedIndex;
    };

    Chosen.prototype.set_up_html = function() {
      var container_classes, container_props;
      container_classes = ["chosen-container"];
      container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single"));
      if (this.inherit_select_classes && this.form_field.className) {
        container_classes.push(this.form_field.className);
      }
      if (this.is_rtl) {
        container_classes.push("chosen-rtl");
      }
      container_props = {
        'class': container_classes.join(' '),
        'title': this.form_field.title
      };
      if (this.form_field.id.length) {
        container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen";
      }
      this.container = $("<div />", container_props);
      this.container.width(this.container_width());
      if (this.is_multiple) {
        this.container.html(this.get_multi_html());
      } else {
        this.container.html(this.get_single_html());
      }
      this.form_field_jq.hide().after(this.container);
      this.dropdown = this.container.find('div.chosen-drop').first();
      this.search_field = this.container.find('input').first();
      this.search_results = this.container.find('ul.chosen-results').first();
      this.search_field_scale();
      this.search_no_results = this.container.find('li.no-results').first();
      if (this.is_multiple) {
        this.search_choices = this.container.find('ul.chosen-choices').first();
        this.search_container = this.container.find('li.search-field').first();
      } else {
        this.search_container = this.container.find('div.chosen-search').first();
        this.selected_item = this.container.find('.chosen-single').first();
      }
      this.results_build();
      this.set_tab_index();
      return this.set_label_behavior();
    };

    Chosen.prototype.on_ready = function() {
      return this.form_field_jq.trigger("chosen:ready", {
        chosen: this
      });
    };

    Chosen.prototype.register_observers = function() {
      var _this = this;
      this.container.bind('touchstart.chosen', function(evt) {
        _this.container_mousedown(evt);
      });
      this.container.bind('touchend.chosen', function(evt) {
        _this.container_mouseup(evt);
      });
      this.container.bind('mousedown.chosen', function(evt) {
        _this.container_mousedown(evt);
      });
      this.container.bind('mouseup.chosen', function(evt) {
        _this.container_mouseup(evt);
      });
      this.container.bind('mouseenter.chosen', function(evt) {
        _this.mouse_enter(evt);
      });
      this.container.bind('mouseleave.chosen', function(evt) {
        _this.mouse_leave(evt);
      });
      this.search_results.bind('mouseup.chosen', function(evt) {
        _this.search_results_mouseup(evt);
      });
      this.search_results.bind('mouseover.chosen', function(evt) {
        _this.search_results_mouseover(evt);
      });
      this.search_results.bind('mouseout.chosen', function(evt) {
        _this.search_results_mouseout(evt);
      });
      this.search_results.bind('mousewheel.chosen DOMMouseScroll.chosen', function(evt) {
        _this.search_results_mousewheel(evt);
      });
      this.search_results.bind('touchstart.chosen', function(evt) {
        _this.search_results_touchstart(evt);
      });
      this.search_results.bind('touchmove.chosen', function(evt) {
        _this.search_results_touchmove(evt);
      });
      this.search_results.bind('touchend.chosen', function(evt) {
        _this.search_results_touchend(evt);
      });
      this.form_field_jq.bind("chosen:updated.chosen", function(evt) {
        _this.results_update_field(evt);
      });
      this.form_field_jq.bind("chosen:activate.chosen", function(evt) {
        _this.activate_field(evt);
      });
      this.form_field_jq.bind("chosen:open.chosen", function(evt) {
        _this.container_mousedown(evt);
      });
      this.form_field_jq.bind("chosen:close.chosen", function(evt) {
        _this.close_field(evt);
      });
      this.search_field.bind('blur.chosen', function(evt) {
        _this.input_blur(evt);
      });
      this.search_field.bind('keyup.chosen', function(evt) {
        _this.keyup_checker(evt);
      });
      this.search_field.bind('keydown.chosen', function(evt) {
        _this.keydown_checker(evt);
      });
      this.search_field.bind('focus.chosen', function(evt) {
        _this.input_focus(evt);
      });
      this.search_field.bind('cut.chosen', function(evt) {
        _this.clipboard_event_checker(evt);
      });
      this.search_field.bind('paste.chosen', function(evt) {
        _this.clipboard_event_checker(evt);
      });
      if (this.is_multiple) {
        return this.search_choices.bind('click.chosen', function(evt) {
          _this.choices_click(evt);
        });
      } else {
        return this.container.bind('click.chosen', function(evt) {
          evt.preventDefault();
        });
      }
    };

    Chosen.prototype.destroy = function() {
      $(this.container[0].ownerDocument).unbind('click.chosen', this.click_test_action);
      if (this.form_field_label.length > 0) {
        this.form_field_label.unbind('click.chosen');
      }
      if (this.search_field[0].tabIndex) {
        this.form_field_jq[0].tabIndex = this.search_field[0].tabIndex;
      }
      this.container.remove();
      this.form_field_jq.removeData('chosen');
      return this.form_field_jq.show();
    };

    Chosen.prototype.search_field_disabled = function() {
      this.is_disabled = this.form_field.disabled || this.form_field_jq.parents('fieldset').is(':disabled');
      this.container.toggleClass('chosen-disabled', this.is_disabled);
      this.search_field[0].disabled = this.is_disabled;
      if (!this.is_multiple) {
        this.selected_item.unbind('focus.chosen', this.activate_field);
      }
      if (this.is_disabled) {
        return this.close_field();
      } else if (!this.is_multiple) {
        return this.selected_item.bind('focus.chosen', this.activate_field);
      }
    };

    Chosen.prototype.container_mousedown = function(evt) {
      var _ref1;
      if (this.is_disabled) {
        return;
      }
      if (evt && ((_ref1 = evt.type) === 'mousedown' || _ref1 === 'touchstart') && !this.results_showing) {
        evt.preventDefault();
      }
      if (!((evt != null) && ($(evt.target)).hasClass("search-choice-close"))) {
        if (!this.active_field) {
          if (this.is_multiple) {
            this.search_field.val("");
          }
          $(this.container[0].ownerDocument).bind('click.chosen', this.click_test_action);
          this.results_show();
        } else if (!this.is_multiple && evt && (($(evt.target)[0] === this.selected_item[0]) || $(evt.target).parents("a.chosen-single").length)) {
          evt.preventDefault();
          this.results_toggle();
        }
        return this.activate_field();
      }
    };

    Chosen.prototype.container_mouseup = function(evt) {
      if (evt.target.nodeName === "ABBR" && !this.is_disabled) {
        return this.results_reset(evt);
      }
    };

    Chosen.prototype.search_results_mousewheel = function(evt) {
      var delta;
      if (evt.originalEvent) {
        delta = evt.originalEvent.deltaY || -evt.originalEvent.wheelDelta || evt.originalEvent.detail;
      }
      if (delta != null) {
        evt.preventDefault();
        if (evt.type === 'DOMMouseScroll') {
          delta = delta * 40;
        }
        return this.search_results.scrollTop(delta + this.search_results.scrollTop());
      }
    };

    Chosen.prototype.blur_test = function(evt) {
      if (!this.active_field && this.container.hasClass("chosen-container-active")) {
        return this.close_field();
      }
    };

    Chosen.prototype.close_field = function() {
      $(this.container[0].ownerDocument).unbind("click.chosen", this.click_test_action);
      this.active_field = false;
      this.results_hide();
      this.container.removeClass("chosen-container-active");
      this.clear_backstroke();
      this.show_search_field_default();
      this.search_field_scale();
      return this.search_field.blur();
    };

    Chosen.prototype.activate_field = function() {
      if (this.is_disabled) {
        return;
      }
      this.container.addClass("chosen-container-active");
      this.active_field = true;
      this.search_field.val(this.search_field.val());
      return this.search_field.focus();
    };

    Chosen.prototype.test_active_click = function(evt) {
      var active_container;
      active_container = $(evt.target).closest('.chosen-container');
      if (active_container.length && this.container[0] === active_container[0]) {
        return this.active_field = true;
      } else {
        return this.close_field();
      }
    };

    Chosen.prototype.results_build = function() {
      this.parsing = true;
      this.selected_option_count = null;
      this.results_data = SelectParser.select_to_array(this.form_field);
      if (this.is_multiple) {
        this.search_choices.find("li.search-choice").remove();
      } else if (!this.is_multiple) {
        this.single_set_selected_text();
        if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) {
          this.search_field[0].readOnly = true;
          this.container.addClass("chosen-container-single-nosearch");
        } else {
          this.search_field[0].readOnly = false;
          this.container.removeClass("chosen-container-single-nosearch");
        }
      }
      this.update_results_content(this.results_option_build({
        first: true
      }));
      this.search_field_disabled();
      this.show_search_field_default();
      this.search_field_scale();
      return this.parsing = false;
    };

    Chosen.prototype.result_do_highlight = function(el) {
      var high_bottom, high_top, maxHeight, visible_bottom, visible_top;
      if (el.length) {
        this.result_clear_highlight();
        this.result_highlight = el;
        this.result_highlight.addClass("highlighted");
        maxHeight = parseInt(this.search_results.css("maxHeight"), 10);
        visible_top = this.search_results.scrollTop();
        visible_bottom = maxHeight + visible_top;
        high_top = this.result_highlight.position().top + this.search_results.scrollTop();
        high_bottom = high_top + this.result_highlight.outerHeight();
        if (high_bottom >= visible_bottom) {
          return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0);
        } else if (high_top < visible_top) {
          return this.search_results.scrollTop(high_top);
        }
      }
    };

    Chosen.prototype.result_clear_highlight = function() {
      if (this.result_highlight) {
        this.result_highlight.removeClass("highlighted");
      }
      return this.result_highlight = null;
    };

    Chosen.prototype.results_show = function() {
      if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
        this.form_field_jq.trigger("chosen:maxselected", {
          chosen: this
        });
        return false;
      }
      this.container.addClass("chosen-with-drop");
      this.results_showing = true;
      this.search_field.focus();
      this.search_field.val(this.get_search_field_value());
      this.winnow_results();
      return this.form_field_jq.trigger("chosen:showing_dropdown", {
        chosen: this
      });
    };

    Chosen.prototype.update_results_content = function(content) {
      return this.search_results.html(content);
    };

    Chosen.prototype.results_hide = function() {
      if (this.results_showing) {
        this.result_clear_highlight();
        this.container.removeClass("chosen-with-drop");
        this.form_field_jq.trigger("chosen:hiding_dropdown", {
          chosen: this
        });
      }
      return this.results_showing = false;
    };

    Chosen.prototype.set_tab_index = function(el) {
      var ti;
      if (this.form_field.tabIndex) {
        ti = this.form_field.tabIndex;
        this.form_field.tabIndex = -1;
        return this.search_field[0].tabIndex = ti;
      }
    };

    Chosen.prototype.set_label_behavior = function() {
      this.form_field_label = this.form_field_jq.parents("label");
      if (!this.form_field_label.length && this.form_field.id.length) {
        this.form_field_label = $("label[for='" + this.form_field.id + "']");
      }
      if (this.form_field_label.length > 0) {
        return this.form_field_label.bind('click.chosen', this.label_click_handler);
      }
    };

    Chosen.prototype.show_search_field_default = function() {
      if (this.is_multiple && this.choices_count() < 1 && !this.active_field) {
        this.search_field.val(this.default_text);
        return this.search_field.addClass("default");
      } else {
        this.search_field.val("");
        return this.search_field.removeClass("default");
      }
    };

    Chosen.prototype.search_results_mouseup = function(evt) {
      var target;
      target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
      if (target.length) {
        this.result_highlight = target;
        this.result_select(evt);
        return this.search_field.focus();
      }
    };

    Chosen.prototype.search_results_mouseover = function(evt) {
      var target;
      target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
      if (target) {
        return this.result_do_highlight(target);
      }
    };

    Chosen.prototype.search_results_mouseout = function(evt) {
      if ($(evt.target).hasClass("active-result" || $(evt.target).parents('.active-result').first())) {
        return this.result_clear_highlight();
      }
    };

    Chosen.prototype.choice_build = function(item) {
      var choice, close_link,
        _this = this;
      choice = $('<li />', {
        "class": "search-choice"
      }).html("<span>" + (this.choice_label(item)) + "</span>");
      if (item.disabled) {
        choice.addClass('search-choice-disabled');
      } else {
        close_link = $('<a />', {
          "class": 'search-choice-close',
          'data-option-array-index': item.array_index
        });
        close_link.bind('click.chosen', function(evt) {
          return _this.choice_destroy_link_click(evt);
        });
        choice.append(close_link);
      }
      return this.search_container.before(choice);
    };

    Chosen.prototype.choice_destroy_link_click = function(evt) {
      evt.preventDefault();
      evt.stopPropagation();
      if (!this.is_disabled) {
        return this.choice_destroy($(evt.target));
      }
    };

    Chosen.prototype.choice_destroy = function(link) {
      if (this.result_deselect(link[0].getAttribute("data-option-array-index"))) {
        if (this.active_field) {
          this.search_field.focus();
        } else {
          this.show_search_field_default();
        }
        if (this.is_multiple && this.choices_count() > 0 && this.get_search_field_value().length < 1) {
          this.results_hide();
        }
        link.parents('li').first().remove();
        return this.search_field_scale();
      }
    };

    Chosen.prototype.results_reset = function() {
      this.reset_single_select_options();
      this.form_field.options[0].selected = true;
      this.single_set_selected_text();
      this.show_search_field_default();
      this.results_reset_cleanup();
      this.trigger_form_field_change();
      if (this.active_field) {
        return this.results_hide();
      }
    };

    Chosen.prototype.results_reset_cleanup = function() {
      this.current_selectedIndex = this.form_field.selectedIndex;
      return this.selected_item.find("abbr").remove();
    };

    Chosen.prototype.result_select = function(evt) {
      var high, item;
      if (this.result_highlight) {
        high = this.result_highlight;
        this.result_clear_highlight();
        if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
          this.form_field_jq.trigger("chosen:maxselected", {
            chosen: this
          });
          return false;
        }
        if (this.is_multiple) {
          high.removeClass("active-result");
        } else {
          this.reset_single_select_options();
        }
        high.addClass("result-selected");
        item = this.results_data[high[0].getAttribute("data-option-array-index")];
        item.selected = true;
        this.form_field.options[item.options_index].selected = true;
        this.selected_option_count = null;
        if (this.is_multiple) {
          this.choice_build(item);
        } else {
          this.single_set_selected_text(this.choice_label(item));
        }
        if (!(this.is_multiple && (!this.hide_results_on_select || (evt.metaKey || evt.ctrlKey)))) {
          this.results_hide();
          this.show_search_field_default();
        }
        if (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex) {
          this.trigger_form_field_change({
            selected: this.form_field.options[item.options_index].value
          });
        }
        this.current_selectedIndex = this.form_field.selectedIndex;
        evt.preventDefault();
        return this.search_field_scale();
      }
    };

    Chosen.prototype.single_set_selected_text = function(text) {
      if (text == null) {
        text = this.default_text;
      }
      if (text === this.default_text) {
        this.selected_item.addClass("chosen-default");
      } else {
        this.single_deselect_control_build();
        this.selected_item.removeClass("chosen-default");
      }
      return this.selected_item.find("span").html(text);
    };

    Chosen.prototype.result_deselect = function(pos) {
      var result_data;
      result_data = this.results_data[pos];
      if (!this.form_field.options[result_data.options_index].disabled) {
        result_data.selected = false;
        this.form_field.options[result_data.options_index].selected = false;
        this.selected_option_count = null;
        this.result_clear_highlight();
        if (this.results_showing) {
          this.winnow_results();
        }
        this.trigger_form_field_change({
          deselected: this.form_field.options[result_data.options_index].value
        });
        this.search_field_scale();
        return true;
      } else {
        return false;
      }
    };

    Chosen.prototype.single_deselect_control_build = function() {
      if (!this.allow_single_deselect) {
        return;
      }
      if (!this.selected_item.find("abbr").length) {
        this.selected_item.find("span").first().after("<abbr class=\"search-choice-close\"></abbr>");
      }
      return this.selected_item.addClass("chosen-single-with-deselect");
    };

    Chosen.prototype.get_search_field_value = function() {
      return this.search_field.val();
    };

    Chosen.prototype.get_search_text = function() {
      return this.escape_html($.trim(this.get_search_field_value()));
    };

    Chosen.prototype.escape_html = function(text) {
      return $('<div/>').text(text).html();
    };

    Chosen.prototype.winnow_results_set_highlight = function() {
      var do_high, selected_results;
      selected_results = !this.is_multiple ? this.search_results.find(".result-selected.active-result") : [];
      do_high = selected_results.length ? selected_results.first() : this.search_results.find(".active-result").first();
      if (do_high != null) {
        return this.result_do_highlight(do_high);
      }
    };

    Chosen.prototype.no_results = function(terms) {
      var no_results_html;
      no_results_html = this.get_no_results_html(terms);
      this.search_results.append(no_results_html);
      return this.form_field_jq.trigger("chosen:no_results", {
        chosen: this
      });
    };

    Chosen.prototype.no_results_clear = function() {
      return this.search_results.find(".no-results").remove();
    };

    Chosen.prototype.keydown_arrow = function() {
      var next_sib;
      if (this.results_showing && this.result_highlight) {
        next_sib = this.result_highlight.nextAll("li.active-result").first();
        if (next_sib) {
          return this.result_do_highlight(next_sib);
        }
      } else {
        return this.results_show();
      }
    };

    Chosen.prototype.keyup_arrow = function() {
      var prev_sibs;
      if (!this.results_showing && !this.is_multiple) {
        return this.results_show();
      } else if (this.result_highlight) {
        prev_sibs = this.result_highlight.prevAll("li.active-result");
        if (prev_sibs.length) {
          return this.result_do_highlight(prev_sibs.first());
        } else {
          if (this.choices_count() > 0) {
            this.results_hide();
          }
          return this.result_clear_highlight();
        }
      }
    };

    Chosen.prototype.keydown_backstroke = function() {
      var next_available_destroy;
      if (this.pending_backstroke) {
        this.choice_destroy(this.pending_backstroke.find("a").first());
        return this.clear_backstroke();
      } else {
        next_available_destroy = this.search_container.siblings("li.search-choice").last();
        if (next_available_destroy.length && !next_available_destroy.hasClass("search-choice-disabled")) {
          this.pending_backstroke = next_available_destroy;
          if (this.single_backstroke_delete) {
            return this.keydown_backstroke();
          } else {
            return this.pending_backstroke.addClass("search-choice-focus");
          }
        }
      }
    };

    Chosen.prototype.clear_backstroke = function() {
      if (this.pending_backstroke) {
        this.pending_backstroke.removeClass("search-choice-focus");
      }
      return this.pending_backstroke = null;
    };

    Chosen.prototype.search_field_scale = function() {
      var container_width, div, style, style_block, styles, width, _i, _len;
      if (!this.is_multiple) {
        return;
      }
      style_block = {
        position: 'absolute',
        left: '-1000px',
        top: '-1000px',
        display: 'none',
        whiteSpace: 'pre'
      };
      styles = ['fontSize', 'fontStyle', 'fontWeight', 'fontFamily', 'lineHeight', 'textTransform', 'letterSpacing'];
      for (_i = 0, _len = styles.length; _i < _len; _i++) {
        style = styles[_i];
        style_block[style] = this.search_field.css(style);
      }
      div = $('<div />').css(style_block);
      div.text(this.get_search_field_value());
      $('body').append(div);
      width = div.width() + 25;
      div.remove();
      container_width = this.container.outerWidth();
      width = Math.min(container_width - 10, width);
      return this.search_field.width(width);
    };

    Chosen.prototype.trigger_form_field_change = function(extra) {
      this.form_field_jq.trigger("input", extra);
      return this.form_field_jq.trigger("change", extra);
    };

    return Chosen;

  })(AbstractChosen);

}).call(this );


/*! UIkit 2.27.3 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
(function(core) {
    "use strict";

    var uikit;

    if (!window.jQuery) {
        throw new Error('UIkit 2.x requires jQuery');
    } else {
        uikit = core(window.jQuery);
    }

    if (typeof define == 'function' && define.amd) { // AMD

        define('uikit', function(){

            uikit.load = function(res, req, onload, config) {

                var resources = res.split(','), load = [], i, base = (config.config && config.config.uikit && config.config.uikit.base ? config.config.uikit.base : '').replace(/\/+$/g, '');

                if (!base) {
                    throw new Error('Please define base path to UIkit in the requirejs config.');
                }

                for (i = 0; i < resources.length; i += 1) {
                    var resource = resources[i].replace(/\./g, '/');
                    load.push(base+'/components/'+resource);
                }

                req(load, function() {
                    onload(uikit);
                });
            };

            return uikit;
        });
    }

})(function($) {

    "use strict";

    if (window.UIkit2MD) {
        return window.UIkit2MD;
    }

    var UI = {}, _UI = window.UIkit || undefined;

    UI.version = '2.27.3';

    UI.noConflict = function() {
        // restore UIkit version
        if (_UI) {
            window.UIkit = _UI;
            $.UIkit      = _UI;
            $.fn.uk      = _UI.fn;
        }

        return UI;
    };

    window.UIkit2MD = UI;

    if (!_UI) {
        window.UIkit = UI;
    }

    // cache jQuery
    UI.$ = $;

    UI.$doc  = UI.$(document);
    UI.$win  = UI.$(window);
    UI.$html = UI.$('html');

    UI.support = {};
    UI.support.transition = (function() {

        var transitionEnd = (function() {

            var element = document.body || document.documentElement,
                transEndEventNames = {
                    WebkitTransition : 'webkitTransitionEnd',
                    MozTransition    : 'transitionend',
                    OTransition      : 'oTransitionEnd otransitionend',
                    transition       : 'transitionend'
                }, name;

            for (name in transEndEventNames) {
                if (element.style[name] !== undefined) return transEndEventNames[name];
            }
        }());

        return transitionEnd && { end: transitionEnd };
    })();

    UI.support.animation = (function() {

        var animationEnd = (function() {

            var element = document.body || document.documentElement,
                animEndEventNames = {
                    WebkitAnimation : 'webkitAnimationEnd',
                    MozAnimation    : 'animationend',
                    OAnimation      : 'oAnimationEnd oanimationend',
                    animation       : 'animationend'
                }, name;

            for (name in animEndEventNames) {
                if (element.style[name] !== undefined) return animEndEventNames[name];
            }
        }());

        return animationEnd && { end: animationEnd };
    })();

    // requestAnimationFrame polyfill
    //https://github.com/darius/requestAnimationFrame
    (function() {

        Date.now = Date.now || function() { return new Date().getTime(); };

        var vendors = ['webkit', 'moz'];
        for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
            var vp = vendors[i];
            window.requestAnimationFrame = window[vp+'RequestAnimationFrame'];
            window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame']
                                       || window[vp+'CancelRequestAnimationFrame']);
        }
        if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) // iOS6 is buggy
            || !window.requestAnimationFrame || !window.cancelAnimationFrame) {
            var lastTime = 0;
            window.requestAnimationFrame = function(callback) {
                var now = Date.now();
                var nextTime = Math.max(lastTime + 16, now);
                return setTimeout(function() { callback(lastTime = nextTime); },
                                  nextTime - now);
            };
            window.cancelAnimationFrame = clearTimeout;
        }
    }());

    UI.support.touch = (
        ('ontouchstart' in document) ||
        (window.DocumentTouch && document instanceof window.DocumentTouch)  ||
        (window.navigator.msPointerEnabled && window.navigator.msMaxTouchPoints > 0) || //IE 10
        (window.navigator.pointerEnabled && window.navigator.maxTouchPoints > 0) || //IE >=11
        false
    );

    UI.support.mutationobserver = (window.MutationObserver || window.WebKitMutationObserver || null);

    UI.Utils = {};

    UI.Utils.isFullscreen = function() {
        return document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement || document.fullscreenElement || false;
    };

    UI.Utils.str2json = function(str, notevil) {
        try {
            if (notevil) {
                return JSON.parse(str
                    // wrap keys without quote with valid double quote
                    .replace(/([\$\w]+)\s*:/g, function(_, $1){return '"'+$1+'":';})
                    // replacing single quote wrapped ones to double quote
                    .replace(/'([^']+)'/g, function(_, $1){return '"'+$1+'"';})
                );
            } else {
                return (new Function('', 'var json = ' + str + '; return JSON.parse(JSON.stringify(json));'))();
            }
        } catch(e) { return false; }
    };

    UI.Utils.debounce = function(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };

    UI.Utils.throttle = function (func, limit) {
        var wait = false;
        return function () {
            if (!wait) {
                func.call();
                wait = true;
                setTimeout(function () {
                    wait = false;
                }, limit);
            }
        }
    };

    UI.Utils.removeCssRules = function(selectorRegEx) {
        var idx, idxs, stylesheet, _i, _j, _k, _len, _len1, _len2, _ref;

        if(!selectorRegEx) return;

        setTimeout(function(){
            try {
              _ref = document.styleSheets;
              for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                stylesheet = _ref[_i];
                idxs = [];
                stylesheet.cssRules = stylesheet.cssRules;
                for (idx = _j = 0, _len1 = stylesheet.cssRules.length; _j < _len1; idx = ++_j) {
                  if (stylesheet.cssRules[idx].type === CSSRule.STYLE_RULE && selectorRegEx.test(stylesheet.cssRules[idx].selectorText)) {
                    idxs.unshift(idx);
                  }
                }
                for (_k = 0, _len2 = idxs.length; _k < _len2; _k++) {
                  stylesheet.deleteRule(idxs[_k]);
                }
              }
            } catch (_error) {}
        }, 0);
    };

    UI.Utils.isInView = function(element, options) {

        var $element = $(element);

        if (!$element.is(':visible')) {
            return false;
        }

        var window_left = UI.$win.scrollLeft(), window_top = UI.$win.scrollTop(), offset = $element.offset(), left = offset.left, top = offset.top;

        options = $.extend({topoffset:0, leftoffset:0}, options);

        if (top + $element.height() >= window_top && top - options.topoffset <= window_top + UI.$win.height() &&
            left + $element.width() >= window_left && left - options.leftoffset <= window_left + UI.$win.width()) {
          return true;
        } else {
          return false;
        }
    };

    UI.Utils.checkDisplay = function(context, initanimation) {

        var elements = UI.$('[data-mdp-margin], [data-mdp-grid-match], [data-mdp-grid-margin], [data-mdp-check-display]', context || document), animated;

        if (context && !elements.length) {
            elements = $(context);
        }

        elements.trigger('display.uk.check');

        // fix firefox / IE animations
        if (initanimation) {

            if (typeof(initanimation)!='string') {
                initanimation = '[class*="mdp-animation-"]';
            }

            elements.find(initanimation).each(function(){

                var ele  = UI.$(this ),
                    cls  = ele.attr('class'),
                    anim = cls.match(/mdp-animation-(.+)/);

                ele.removeClass(anim[0]).width();

                ele.addClass(anim[0]);
            });
        }

        return elements;
    };

    UI.Utils.options = function(string) {

        if ($.type(string)!='string') return string;

        if (string.indexOf(':') != -1 && string.trim().substr(-1) != '}') {
            string = '{'+string+'}';
        }

        var start = (string ? string.indexOf("{") : -1), options = {};

        if (start != -1) {
            try {
                options = UI.Utils.str2json(string.substr(start));
            } catch (e) {}
        }

        return options;
    };

    UI.Utils.animate = function(element, cls) {

        var d = $.Deferred();

        element = UI.$(element);

        element.css('display', 'none').addClass(cls).one(UI.support.animation.end, function() {
            element.removeClass(cls);
            d.resolve();
        });

        element.css('display', '');

        return d.promise();
    };

    UI.Utils.uid = function(prefix) {
        return (prefix || 'id') + (new Date().getTime())+"RAND"+(Math.ceil(Math.random() * 100000));
    };

    UI.Utils.template = function(str, data) {

        var tokens = str.replace(/\n/g, '\\n').replace(/\{\{\{\s*(.+?)\s*\}\}\}/g, "{{!$1}}").split(/(\{\{\s*(.+?)\s*\}\})/g),
            i=0, toc, cmd, prop, val, fn, output = [], openblocks = 0;

        while(i < tokens.length) {

            toc = tokens[i];

            if(toc.match(/\{\{\s*(.+?)\s*\}\}/)) {
                i = i + 1;
                toc  = tokens[i];
                cmd  = toc[0];
                prop = toc.substring(toc.match(/^(\^|\#|\!|\~|\:)/) ? 1:0);

                switch(cmd) {
                    case '~':
                        output.push('for(var $i=0;$i<'+prop+'.length;$i++) { var $item = '+prop+'[$i];');
                        openblocks++;
                        break;
                    case ':':
                        output.push('for(var $key in '+prop+') { var $val = '+prop+'[$key];');
                        openblocks++;
                        break;
                    case '#':
                        output.push('if('+prop+') {');
                        openblocks++;
                        break;
                    case '^':
                        output.push('if(!'+prop+') {');
                        openblocks++;
                        break;
                    case '/':
                        output.push('}');
                        openblocks--;
                        break;
                    case '!':
                        output.push('__ret.push('+prop+');');
                        break;
                    default:
                        output.push('__ret.push(escape('+prop+'));');
                        break;
                }
            } else {
                output.push("__ret.push('"+toc.replace(/\'/g, "\\'")+"');");
            }
            i = i + 1;
        }

        fn  = new Function('$data', [
            'var __ret = [];',
            'try {',
            'with($data){', (!openblocks ? output.join('') : '__ret = ["Not all blocks are closed correctly."]'), '};',
            '}catch( e ) {__ret = [e.message];}',
            'return __ret.join("").replace(/\\n\\n/g, "\\n");',
            "function escape(html) { return String(html).replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');}"
        ].join("\n"));

        return data ? fn(data) : fn;
    };

    UI.Utils.focus = function(element, extra) {

        element = $(element);

        if (!element.length) {
            return element;
        }

        var autofocus = element.find('[autofocus]:first'), tabidx;

        if (autofocus.length) {
            return autofocus.focus();
        }

        autofocus = element.find(':input'+(extra && (','+extra) || '')).first();

        if (autofocus.length) {
            return autofocus.focus();
        }

        if (!element.attr('tabindex')) {
            tabidx = 1000;
            element.attr('tabindex', tabidx);
        }

        element[0].focus();

        if (tabidx) {
            element.attr('tabindex', '');
        }

        return element;
    };

    UI.Utils.events       = {};
    UI.Utils.events.click = UI.support.touch ? 'tap' : 'click';

    // deprecated

    UI.fn = function(command, options) {

        var args = arguments, cmd = command.match(/^([a-z\-]+)(?:\.([a-z]+))?/i), component = cmd[1], method = cmd[2];

        if (!UI[component]) {
            $.error('UIkit component [' + component + '] does not exist.');
            return this;
        }

        return this.each(function() {
            var $this = $(this ), data = $this.data(component);
            if (!data) $this.data(component, (data = UI[component](this, method ? undefined : options)));
            if (method) data[method].apply(data, Array.prototype.slice.call(args, 1));
        });
    };

    $.UIkit          = UI;
    $.fn.uk          = UI.fn;

    UI.langdirection = UI.$html.attr("dir") == "rtl" ? "right" : "left";

    UI.components    = {};

    UI.component = function(name, def, override) {

        if (UI.components[name] && !override) {
            return UI.components[name];
        }

        var fn = function(element, options) {

            var $this = this;

            this.UIkit   = UI;
            this.element = element ? UI.$(element) : null;
            this.options = $.extend(true, {}, this.defaults, options);
            this.plugins = {};

            if (this.element) {
                this.element.data(name, this );
            }

            this.init();

            (this.options.plugins.length ? this.options.plugins : Object.keys(fn.plugins)).forEach(function(plugin) {

                if (fn.plugins[plugin].init) {
                    fn.plugins[plugin].init($this );
                    $this.plugins[plugin] = true;
                }

            });

            this.trigger('init.uk.component', [name, this]);

            return this;
        };

        fn.plugins = {};

        $.extend(true, fn.prototype, {

            defaults : {plugins: []},

            boot: function(){},
            init: function(){},

            on: function(a1,a2,a3){
                return UI.$(this.element || this ).on(a1,a2,a3);
            },

            one: function(a1,a2,a3){
                return UI.$(this.element || this ).one(a1,a2,a3);
            },

            off: function(evt){
                return UI.$(this.element || this ).off(evt);
            },

            trigger: function(evt, params) {
                return UI.$(this.element || this ).trigger(evt, params);
            },

            find: function(selector) {
                return UI.$(this.element ? this.element: []).find(selector);
            },

            proxy: function(obj, methods) {

                var $this = this;

                methods.split(' ').forEach(function(method) {
                    if (!$this[method]) $this[method] = function() { return obj[method].apply(obj, arguments); };
                });
            },

            mixin: function(obj, methods) {

                var $this = this;

                methods.split(' ').forEach(function(method) {
                    if (!$this[method]) $this[method] = obj[method].bind($this );
                });
            },

            option: function() {

                if (arguments.length == 1) {
                    return this.options[arguments[0]] || undefined;
                } else if (arguments.length == 2) {
                    this.options[arguments[0]] = arguments[1];
                }
            }

        }, def);

        this.components[name] = fn;

        this[name] = function() {

            var element, options;

            if (arguments.length) {

                switch(arguments.length) {
                    case 1:

                        if (typeof arguments[0] === 'string' || arguments[0].nodeType || arguments[0] instanceof jQuery) {
                            element = $(arguments[0]);
                        } else {
                            options = arguments[0];
                        }

                        break;
                    case 2:

                        element = $(arguments[0]);
                        options = arguments[1];
                        break;
                }
            }

            if (element && element.data(name)) {
                return element.data(name);
            }

            return (new UI.components[name](element, options));
        };

        if (UI.domready) {
            UI.component.boot(name);
        }

        return fn;
    };

    UI.plugin = function(component, name, def) {
        this.components[component].plugins[name] = def;
    };

    UI.component.boot = function(name) {

        if (UI.components[name].prototype && UI.components[name].prototype.boot && !UI.components[name].booted) {
            UI.components[name].prototype.boot.apply(UI, []);
            UI.components[name].booted = true;
        }
    };

    UI.component.bootComponents = function() {

        for (var component in UI.components) {
            UI.component.boot(component);
        }
    };


    // DOM mutation save ready helper function

    UI.domObservers = [];
    UI.domready     = false;

    UI.ready = function(fn) {

        UI.domObservers.push(fn);

        if (UI.domready) {
            fn(document);
        }
    };

    UI.on = function(a1,a2,a3){

        if (a1 && a1.indexOf('ready.uk.dom') > -1 && UI.domready) {
            a2.apply(UI.$doc);
        }

        return UI.$doc.on(a1,a2,a3);
    };

    UI.one = function(a1,a2,a3){

        if (a1 && a1.indexOf('ready.uk.dom') > -1 && UI.domready) {
            a2.apply(UI.$doc);
            return UI.$doc;
        }

        return UI.$doc.one(a1,a2,a3);
    };

    UI.trigger = function(evt, params) {
        return UI.$doc.trigger(evt, params);
    };

    UI.domObserve = function(selector, fn) {

        if(!UI.support.mutationobserver) return;

        fn = fn || function() {};

        UI.$(selector).each(function() {

            var element  = this,
                $element = UI.$(element);

            if ($element.data('observer')) {
                return;
            }

            try {

                var observer = new UI.support.mutationobserver(UI.Utils.debounce(function(mutations) {
                    fn.apply(element, [$element]);
                    $element.trigger('changed.uk.dom');
                }, 50), {childList: true, subtree: true});

                // pass in the target node, as well as the observer options
                observer.observe(element, { childList: true, subtree: true });

                $element.data('observer', observer);

            } catch(e) {}
        });
    };

    UI.init = function(root) {

        root = root || document;

        UI.domObservers.forEach(function(fn){
            fn(root);
        });
    };

    UI.on('domready.uk.dom', function(){

        UI.init();

        if (UI.domready) UI.Utils.checkDisplay();
    });

    document.addEventListener('DOMContentLoaded', function(){

        var domReady = function() {

            UI.$body = UI.$('body');

            UI.trigger('beforeready.uk.dom');

            UI.component.bootComponents();

            // custom scroll observer
            var rafToken = requestAnimationFrame((function(){

                var memory = {dir: {x:0, y:0}, x: window.pageXOffset, y:window.pageYOffset};

                var fn = function(){
                    // reading this (window.page[X|Y]Offset) causes a full page recalc of the layout in Chrome,
                    // so we only want to do this once
                    var wpxo = window.pageXOffset;
                    var wpyo = window.pageYOffset;

                    // Did the scroll position change since the last time we were here?
                    if (memory.x != wpxo || memory.y != wpyo) {

                        // Set the direction of the scroll and store the new position
                        if (wpxo != memory.x) {memory.dir.x = wpxo > memory.x ? 1:-1; } else { memory.dir.x = 0; }
                        if (wpyo != memory.y) {memory.dir.y = wpyo > memory.y ? 1:-1; } else { memory.dir.y = 0; }

                        memory.x = wpxo;
                        memory.y = wpyo;

                        // Trigger the scroll event, this could probably be sent using memory.clone() but this is
                        // more explicit and easier to see exactly what is being sent in the event.
                        UI.$doc.trigger('scrolling.uk.document', [{
                            dir: {x: memory.dir.x, y: memory.dir.y}, x: wpxo, y: wpyo
                        }]);
                    }

                    cancelAnimationFrame(rafToken);
                    rafToken = requestAnimationFrame(fn);
                };

                if (UI.support.touch) {
                    UI.$html.on('touchmove touchend MSPointerMove MSPointerUp pointermove pointerup', fn);
                }

                if (memory.x || memory.y) fn();

                return fn;

            })());

            // run component init functions on dom
            UI.trigger('domready.uk.dom');

            if (UI.support.touch) {

                // remove css hover rules for touch devices
                // UI.Utils.removeCssRules(/\.uk-(?!navbar).*:hover/);

                // viewport unit fix for mdp-height-viewport - should be fixed in iOS 8
                if (navigator.userAgent.match(/(iPad|iPhone|iPod)/g)) {

                    UI.$win.on('load orientationchange resize', UI.Utils.debounce((function(){

                        var fn = function() {
                            $('.mdp-height-viewport').css('height', window.innerHeight);
                            return fn;
                        };

                        return fn();

                    })(), 100));
                }
            }

            UI.trigger('afterready.uk.dom');

            // mark that domready is left behind
            UI.domready = true;

            // auto init js components
            if (UI.support.mutationobserver) {

                var initFn = UI.Utils.debounce(function(){
                    requestAnimationFrame(function(){ UI.init(document.body);});
                }, 10);

                (new UI.support.mutationobserver(function(mutations) {

                    var init = false;

                    mutations.every(function(mutation){

                        if (mutation.type != 'childList') return true;

                        for (var i = 0, node; i < mutation.addedNodes.length; ++i) {

                            node = mutation.addedNodes[i];

                            if (node.outerHTML && node.outerHTML.indexOf('data-mdp-') !== -1) {
                                return (init = true) && false;
                            }
                        }
                        return true;
                    });

                    if (init) initFn();

                })).observe(document.body, {childList: true, subtree: true});
            }
        };

        if (document.readyState == 'complete' || document.readyState == 'interactive') {
            setTimeout(domReady);
        }

        return domReady;

    }());

    // add touch identifier class
    UI.$html.addClass(UI.support.touch ? 'mdp-touch' : 'mdp-notouch');

    // add mdp-hover class on tap to support overlays on touch devices
    if (UI.support.touch) {

        var hoverset = false,
            exclude,
            hovercls = 'mdp-hover',
            selector = '.mdp-overlay, .mdp-overlay-hover, .mdp-overlay-toggle, .mdp-animation-hover, .mdp-has-hover';

        UI.$html.on('mouseenter touchstart MSPointerDown pointerdown', selector, function() {

            if (hoverset) $('.'+hovercls).removeClass(hovercls);

            hoverset = $(this ).addClass(hovercls);

        }).on('mouseleave touchend MSPointerUp pointerup', function(e) {

            exclude = $(e.target).parents(selector);

            if (hoverset) {
                hoverset.not(exclude).removeClass(hovercls);
            }
        });
    }

    return UI;
});

//  Based on Zeptos touch.js
//  https://raw.github.com/madrobby/zepto/master/src/touch.js
//  Zepto.js may be freely distributed under the MIT license.

(function ($) {
  if ($.fn.swipeLeft) {
    return;
  }


  var touch = {}, touchTimeout, tapTimeout, swipeTimeout, longTapTimeout, longTapDelay = 750, gesture;
  var hasTouchEvents = 'ontouchstart' in window,
      hasPointerEvents = window.PointerEvent,
      hasTouch = hasTouchEvents
      || window.DocumentTouch && document instanceof DocumentTouch
      || navigator.msPointerEnabled && navigator.msMaxTouchPoints > 0 // IE 10
      || navigator.pointerEnabled && navigator.maxTouchPoints > 0; // IE >=11

  function swipeDirection(x1, x2, y1, y2) {
    return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down');
  }

  function longTap() {
    longTapTimeout = null;
    if (touch.last) {
      if ( touch.el !== undefined ) touch.el.trigger('longTap');
      touch = {};
    }
  }

  function cancelLongTap() {
    if (longTapTimeout) clearTimeout(longTapTimeout);
    longTapTimeout = null;
  }

  function cancelAll() {
    if (touchTimeout)   clearTimeout(touchTimeout);
    if (tapTimeout)     clearTimeout(tapTimeout);
    if (swipeTimeout)   clearTimeout(swipeTimeout);
    if (longTapTimeout) clearTimeout(longTapTimeout);
    touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null;
    touch = {};
  }

  function isPrimaryTouch(event){
    return event.pointerType == event.MSPOINTER_TYPE_TOUCH && event.isPrimary;
  }

  $(function(){
    var now, delta, deltaX = 0, deltaY = 0, firstTouch;

    if ('MSGesture' in window) {
      gesture = new MSGesture();
      gesture.target = document.body;
    }

    $(document)
      .on('MSGestureEnd gestureend', function( e ) {

        var swipeDirectionFromVelocity = e.originalEvent.velocityX > 1 ? 'Right' : e.originalEvent.velocityX < -1 ? 'Left' : e.originalEvent.velocityY > 1 ? 'Down' : e.originalEvent.velocityY < -1 ? 'Up' : null;

        if (swipeDirectionFromVelocity && touch.el !== undefined) {
          touch.el.trigger('swipe');
          touch.el.trigger('swipe'+ swipeDirectionFromVelocity);
        }
      })
      // MSPointerDown: for IE10
      // pointerdown: for IE11
      .on('touchstart MSPointerDown pointerdown', function( e ) {

        if(e.type == 'MSPointerDown' && !isPrimaryTouch(e.originalEvent)) return;

        firstTouch = (e.type == 'MSPointerDown' || e.type == 'pointerdown') ? e : e.originalEvent.touches[0];

        now      = Date.now();
        delta    = now - (touch.last || now);
        touch.el = $('tagName' in firstTouch.target ? firstTouch.target : firstTouch.target.parentNode);

        if(touchTimeout) clearTimeout(touchTimeout);

        touch.x1 = firstTouch.pageX;
        touch.y1 = firstTouch.pageY;

        if (delta > 0 && delta <= 250) touch.isDoubleTap = true;

        touch.last = now;
        longTapTimeout = setTimeout(longTap, longTapDelay);

        // adds the current touch contact for IE gesture recognition
        if (e.originalEvent && e.originalEvent.pointerId && gesture && ( e.type == 'MSPointerDown' || e.type == 'pointerdown' || e.type == 'touchstart' ) ) {
          gesture.addPointer(e.originalEvent.pointerId);
        }

      })
      // MSPointerMove: for IE10
      // pointermove: for IE11
      .on('touchmove MSPointerMove pointermove', function( e ) {

        if (e.type == 'MSPointerMove' && !isPrimaryTouch(e.originalEvent)) return;

        firstTouch = (e.type == 'MSPointerMove' || e.type == 'pointermove') ? e : e.originalEvent.touches[0];

        cancelLongTap();
        touch.x2 = firstTouch.pageX;
        touch.y2 = firstTouch.pageY;

        deltaX += Math.abs(touch.x1 - touch.x2);
        deltaY += Math.abs(touch.y1 - touch.y2);
      })
      // MSPointerUp: for IE10
      // pointerup: for IE11
      .on('touchend MSPointerUp pointerup', function( e ) {

        if (e.type == 'MSPointerUp' && !isPrimaryTouch(e.originalEvent)) return;

        cancelLongTap();

        // swipe
        if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) || (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30)){

          swipeTimeout = setTimeout(function() {
            if ( touch.el !== undefined ) {
              touch.el.trigger('swipe');
              touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)));
            }
            touch = {};
          }, 0);

        // normal tap
        } else if ('last' in touch) {

          // don't fire tap when delta position changed by more than 30 pixels,
          // for instance when moving to a point and back to origin
          if (isNaN(deltaX) || (deltaX < 30 && deltaY < 30)) {
            // delay by one tick so we can cancel the 'tap' event if 'scroll' fires
            // ('tap' fires before 'scroll')
            tapTimeout = setTimeout(function() {

              // trigger universal 'tap' with the option to cancelTouch()
              // (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
              var event = $.Event('tap');
              event.cancelTouch = cancelAll;
              if ( touch.el !== undefined ) touch.el.trigger(event);

              // trigger double tap immediately
              if (touch.isDoubleTap) {
                if ( touch.el !== undefined ) touch.el.trigger('doubleTap');
                touch = {};
              }

              // trigger single tap after 250ms of inactivity
              else {
                touchTimeout = setTimeout(function(){
                  touchTimeout = null;
                  if ( touch.el !== undefined ) touch.el.trigger('singleTap');
                  touch = {};
                }, 250);
              }
            }, 0);
          } else {
            touch = {};
          }
          deltaX = deltaY = 0;
        }
      })
      // when the browser window loses focus,
      // for example when a modal dialog is shown,
      // cancel all ongoing events
      .on('touchcancel MSPointerCancel pointercancel', function( e ) {

        // Ignore pointercancel if the event supports touch events, to prevent pointercancel in swipe gesture
        if ((e.type == 'touchcancel' && hasTouchEvents && hasTouch) || (!hasTouchEvents && e.type == 'pointercancel' && hasPointerEvents)) {
          cancelAll();
        }

    });

    // scrolling the window indicates intention of the user
    // to scroll, not tap or swipe, so cancel all ongoing events
    $(window).on('scroll', cancelAll);
  });

  ['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){
    $.fn[eventName] = function(callback){ return $(this ).on(eventName, callback); };
  });
})(jQuery);

(function(UI) {

    "use strict";

    var stacks = [];

    UI.component('stackMargin', {

        defaults: {
            cls: 'mdp-margin-small-top',
            rowfirst: false,
            observe: false
        },

        boot: function() {

            // init code
            UI.ready(function(context) {

                UI.$('[data-mdp-margin]', context).each(function() {

                    var ele = UI.$(this );

                    if (!ele.data('stackMargin')) {
                        UI.stackMargin(ele, UI.Utils.options(ele.attr('data-mdp-margin')));
                    }
                });
            });
        },

        init: function() {

            var $this = this;

            UI.$win.on('resize orientationchange', (function() {

                var fn = function() {
                    $this.process();
                };

                UI.$(function() {
                    fn();
                    UI.$win.on('load', fn);
                });

                return UI.Utils.debounce(fn, 20);
            })());

            this.on('display.uk.check', function(e) {
                if (this.element.is(':visible')) this.process();
            }.bind(this ));

            if (this.options.observe) {

                UI.domObserve(this.element, function(e) {
                    if ($this.element.is(':visible')) $this.process();
                });
            }

            stacks.push(this );
        },

        process: function() {

            var $this = this, columns = this.element.children();

            UI.Utils.stackMargin(columns, this.options);

            if (!this.options.rowfirst || !columns.length) {
                return this;
            }

            // Mark first column elements
            var group = {}, minleft = false;

            columns.removeClass(this.options.rowfirst).each(function(offset, $ele){

                $ele = UI.$(this );

                if (this.style.display != 'none') {
                    offset = $ele.offset().left;
                    ((group[offset] = group[offset] || []) && group[offset]).push(this );
                    minleft = minleft === false ? offset : Math.min(minleft, offset);
                }
            });

            UI.$(group[minleft]).addClass(this.options.rowfirst);

            return this;
        }

    });


    // responsive element e.g. iframes

    (function(){

        var elements = [], check = function(ele) {

            if (!ele.is(':visible')) return;

            var width  = ele.parent().width(),
                iwidth = ele.data('width'),
                ratio  = (width / iwidth),
                height = Math.floor(ratio * ele.data('height'));

            ele.css({height: (width < iwidth) ? height : ele.data('height')});
        };

        UI.component('responsiveElement', {

            defaults: {},

            boot: function() {

                // init code
                UI.ready(function(context) {

                    UI.$('iframe.mdp-responsive-width, [data-mdp-responsive]', context).each(function() {

                        var ele = UI.$(this ), obj;

                        if (!ele.data('responsiveElement')) {
                            obj = UI.responsiveElement(ele, {});
                        }
                    });
                });
            },

            init: function() {

                var ele = this.element;

                if (ele.attr('width') && ele.attr('height')) {

                    ele.data({
                        width : ele.attr('width'),
                        height: ele.attr('height')
                    }).on('display.uk.check', function(){
                        check(ele);
                    });

                    check(ele);

                    elements.push(ele);
                }
            }
        });

        UI.$win.on('resize load', UI.Utils.debounce(function(){

            elements.forEach(function(ele){
                check(ele);
            });

        }, 15));

    })();


    // helper

    UI.Utils.stackMargin = function(elements, options) {

        options = UI.$.extend({
            cls: 'mdp-margin-small-top'
        }, options);

        elements = UI.$(elements).removeClass(options.cls);

        var min = false;

        elements.each(function(offset, height, pos, $ele){

            $ele   = UI.$(this );

            if ($ele.css('display') != 'none') {

                offset = $ele.offset();
                height = $ele.outerHeight();
                pos    = offset.top + height;

                $ele.data({
                    ukMarginPos: pos,
                    ukMarginTop: offset.top
                });

                if (min === false || (offset.top < min.top) ) {

                    min = {
                        top  : offset.top,
                        left : offset.left,
                        pos  : pos
                    };
                }
            }

        }).each(function($ele) {

            $ele   = UI.$(this );

            if ($ele.css('display') != 'none' && $ele.data('ukMarginTop') > min.top && $ele.data('ukMarginPos') > min.pos) {
                $ele.addClass(options.cls);
            }
        });
    };

    UI.Utils.matchHeights = function(elements, options) {

        elements = UI.$(elements).css('min-height', '');
        options  = UI.$.extend({ row : true }, options);

        var matchHeights = function(group){

            if (group.length < 2) return;

            var max = 0;

            group.each(function() {
                max = Math.max(max, UI.$(this ).outerHeight());
            }).each(function() {

                var element = UI.$(this ),
                    height  = max - (element.css('box-sizing') == 'border-box' ? 0 : (element.outerHeight() - element.height()));

                element.css('min-height', height + 'px');
            });
        };

        if (options.row) {

            elements.first().width(); // force redraw

            setTimeout(function(){

                var lastoffset = false, group = [];

                elements.each(function() {

                    var ele = UI.$(this ), offset = ele.offset().top;

                    if (offset != lastoffset && group.length) {

                        matchHeights(UI.$(group));
                        group  = [];
                        offset = ele.offset().top;
                    }

                    group.push(ele);
                    lastoffset = offset;
                });

                if (group.length) {
                    matchHeights(UI.$(group));
                }

            }, 0);

        } else {
            matchHeights(elements);
        }
    };

    (function(cacheSvgs){

        UI.Utils.inlineSvg = function(selector, root) {

            var images = UI.$(selector || 'img[src$=".svg"]', root || document).each(function(){

                var img = UI.$(this ),
                    src = img.attr('src');

                if (!cacheSvgs[src]) {

                    var d = UI.$.Deferred();

                    UI.$.get(src, {nc: Math.random()}, function(data){
                        d.resolve(UI.$(data).find('svg'));
                    });

                    cacheSvgs[src] = d.promise();
                }

                cacheSvgs[src].then(function(svg) {

                    var $svg = UI.$(svg).clone();

                    if (img.attr('id')) $svg.attr('id', img.attr('id'));
                    if (img.attr('class')) $svg.attr('class', img.attr('class'));
                    if (img.attr('style')) $svg.attr('style', img.attr('style'));

                    if (img.attr('width')) {
                        $svg.attr('width', img.attr('width'));
                        if (!img.attr('height'))  $svg.removeAttr('height');
                    }

                    if (img.attr('height')){
                        $svg.attr('height', img.attr('height'));
                        if (!img.attr('width')) $svg.removeAttr('width');
                    }

                    img.replaceWith($svg);
                });
            });
        };

        // init code
        UI.ready(function(context) {
            UI.Utils.inlineSvg('[data-mdp-svg]', context);
        });

    })({});

    UI.Utils.getCssVar = function(name) {

        /* usage in css:  .var-name:before { content:"xyz" } */

        var val, doc = document.documentElement, element = doc.appendChild(document.createElement('div'));

        element.classList.add('var-'+name);

        try {
            val = JSON.parse(val = getComputedStyle(element, ':before').content.replace(/^["'](.*)["']$/, '$1'));
        } catch (e) {
            val = undefined;
        }

        doc.removeChild(element);

        return val;
    }

})(UIkit2MD);

(function(UI) {

    "use strict";

    UI.component('smoothScroll', {

        boot: function() {

            // init code
            UI.$html.on('click.smooth-scroll.uikit', '[data-mdp-smooth-scroll]', function(e) {
                var ele = UI.$(this );

                if (!ele.data('smoothScroll')) {
                    var obj = UI.smoothScroll(ele, UI.Utils.options(ele.attr('data-mdp-smooth-scroll')));
                    ele.trigger('click');
                }

                return false;
            });
        },

        init: function() {

            var $this = this;

            this.on('click', function(e) {
                e.preventDefault();
                scrollToElement(UI.$(this.hash).length ? UI.$(this.hash) : UI.$('body'), $this.options);
            });
        }
    });

    function scrollToElement(ele, options) {

        options = UI.$.extend({
            duration: 1000,
            transition: 'easeOutExpo',
            offset: 0,
            complete: function(){}
        }, options);

        // get / set parameters
        var target    = ele.offset().top - options.offset,
            docheight = UI.$doc.height(),
            winheight = window.innerHeight;

        if ((target + winheight) > docheight) {
            target = docheight - winheight;
        }

        // animate to target, fire callback when done
        UI.$('html,body').stop().animate({scrollTop: target}, options.duration, options.transition).promise().done(options.complete);
    }

    UI.Utils.scrollToElement = scrollToElement;

    if (!UI.$.easing.easeOutExpo) {
        UI.$.easing.easeOutExpo = function(x, t, b, c, d) { return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b; };
    }

})(UIkit2MD);

(function(UI) {

    "use strict";

    var $win           = UI.$win,
        $doc           = UI.$doc,
        scrollspies    = [],
        checkScrollSpy = function() {
            for(var i=0; i < scrollspies.length; i++) {
                window.requestAnimationFrame.apply(window, [scrollspies[i].check]);
            }
        };

    UI.component('scrollspy', {

        defaults: {
            target     : false,
            cls        : 'mdp-scrollspy-inview',
            initcls    : 'mdp-scrollspy-init-inview',
            topoffset  : 0,
            leftoffset : 0,
            repeat     : false,
            delay      : 0
        },

        boot: function() {

            // listen to scroll and resize
            $doc.on('scrolling.uk.document', checkScrollSpy);
            $win.on('load resize orientationchange', UI.Utils.debounce(checkScrollSpy, 50));

            // init code
            UI.ready(function(context) {

                UI.$('[data-mdp-scrollspy]', context).each(function() {

                    var element = UI.$(this );

                    if (!element.data('scrollspy')) {
                        var obj = UI.scrollspy(element, UI.Utils.options(element.attr('data-mdp-scrollspy')));
                    }
                });
            });
        },

        init: function() {

            var $this = this, inviewstate, initinview, togglecls = this.options.cls.split(/,/), fn = function(){

                var elements     = $this.options.target ? $this.element.find($this.options.target) : $this.element,
                    delayIdx     = elements.length === 1 ? 1 : 0,
                    toggleclsIdx = 0;

                elements.each(function(idx){

                    var element     = UI.$(this ),
                        inviewstate = element.data('inviewstate'),
                        inview      = UI.Utils.isInView(element, $this.options),
                        toggle      = element.attr('data-mdp-scrollspy-cls') || togglecls[toggleclsIdx].trim();

                    if (inview && !inviewstate && !element.data('scrollspy-idle')) {

                        if (!initinview) {
                            element.addClass($this.options.initcls);
                            $this.offset = element.offset();
                            initinview = true;

                            element.trigger('init.uk.scrollspy');
                        }

                        element.data('scrollspy-idle', setTimeout(function(){

                            element.addClass('mdp-scrollspy-inview').toggleClass(toggle).width();
                            element.trigger('inview.uk.scrollspy');

                            element.data('scrollspy-idle', false);
                            element.data('inviewstate', true);

                        }, $this.options.delay * delayIdx));

                        delayIdx++;
                    }

                    if (!inview && inviewstate && $this.options.repeat) {

                        if (element.data('scrollspy-idle')) {
                            clearTimeout(element.data('scrollspy-idle'));
                            element.data('scrollspy-idle', false);
                        }

                        element.removeClass('mdp-scrollspy-inview').toggleClass(toggle);
                        element.data('inviewstate', false);

                        element.trigger('outview.uk.scrollspy');
                    }

                    toggleclsIdx = togglecls[toggleclsIdx + 1] ? (toggleclsIdx + 1) : 0;

                });
            };

            fn();

            this.check = fn;

            scrollspies.push(this );
        }
    });


    var scrollspynavs = [],
        checkScrollSpyNavs = function() {
            for(var i=0; i < scrollspynavs.length; i++) {
                window.requestAnimationFrame.apply(window, [scrollspynavs[i].check]);
            }
        };

    UI.component('scrollspynav', {

        defaults: {
            cls          : 'mdp-active',
            closest      : false,
            topoffset    : 0,
            leftoffset   : 0,
            smoothscroll : false
        },

        boot: function() {

            // listen to scroll and resize
            $doc.on('scrolling.uk.document', checkScrollSpyNavs);
            $win.on('resize orientationchange', UI.Utils.debounce(checkScrollSpyNavs, 50));

            // init code
            UI.ready(function(context) {

                UI.$('[data-mdp-scrollspy-nav]', context).each(function() {

                    var element = UI.$(this );

                    if (!element.data('scrollspynav')) {
                        var obj = UI.scrollspynav(element, UI.Utils.options(element.attr('data-mdp-scrollspy-nav')));
                    }
                });
            });
        },

        init: function() {

            var ids     = [],
                links   = this.find("a[href^='#']").each(function(){ if(this.getAttribute('href').trim()!=='#') ids.push(this.getAttribute('href')); }),
                targets = UI.$(ids.join(",")),

                clsActive  = this.options.cls,
                clsClosest = this.options.closest || this.options.closest;

            var $this = this, inviews, fn = function(){

                inviews = [];

                for (var i=0 ; i < targets.length ; i++) {
                    if (UI.Utils.isInView(targets.eq(i), $this.options)) {
                        inviews.push(targets.eq(i));
                    }
                }

                if (inviews.length) {

                    var navitems,
                        scrollTop = $win.scrollTop(),
                        target = (function(){
                            for(var i=0; i< inviews.length;i++){
                                if (inviews[i].offset().top - $this.options.topoffset >= scrollTop){
                                    return inviews[i];
                                }
                            }
                        })();

                    if (!target) return;

                    if ($this.options.closest) {
                        links.blur().closest(clsClosest).removeClass(clsActive);
                        navitems = links.filter("a[href='#"+target.attr('id')+"']").closest(clsClosest).addClass(clsActive);
                    } else {
                        navitems = links.removeClass(clsActive).filter("a[href='#"+target.attr("id")+"']").addClass(clsActive);
                    }

                    $this.element.trigger('inview.uk.scrollspynav', [target, navitems]);
                }
            };

            if (this.options.smoothscroll && UI.smoothScroll) {
                links.each(function(){
                    UI.smoothScroll(this, $this.options.smoothscroll);
                });
            }

            fn();

            this.element.data('scrollspynav', this );

            this.check = fn;
            scrollspynavs.push(this );

        }
    });

})(UIkit2MD);

(function(UI){

    "use strict";

    var toggles = [];

    UI.component('toggle', {

        defaults: {
            target    : false,
            cls       : 'mdp-hidden',
            animation : false,
            duration  : 200
        },

        boot: function(){

            // init code
            UI.ready(function(context) {

                UI.$('[data-mdp-toggle]', context).each(function() {
                    var ele = UI.$(this );

                    if (!ele.data('toggle')) {
                        var obj = UI.toggle(ele, UI.Utils.options(ele.attr('data-mdp-toggle')));
                    }
                });

                setTimeout(function(){

                    toggles.forEach(function(toggle){
                        toggle.getToggles();
                    });

                }, 0);
            });
        },

        init: function() {

            var $this = this;

            this.aria = (this.options.cls.indexOf('mdp-hidden') !== -1);

            this.on('click', function(e) {

                if ($this.element.is('a[href="#"]')) {
                    e.preventDefault();
                }

                $this.toggle();
            });

            toggles.push(this );
        },

        toggle: function() {

            this.getToggles();

            if(!this.totoggle.length) return;

            if (this.options.animation && UI.support.animation) {

                var $this = this, animations = this.options.animation.split(',');

                if (animations.length == 1) {
                    animations[1] = animations[0];
                }

                animations[0] = animations[0].trim();
                animations[1] = animations[1].trim();

                this.totoggle.css('animation-duration', this.options.duration+'ms');

                this.totoggle.each(function(){

                    var ele = UI.$(this );

                    if (ele.hasClass($this.options.cls)) {

                        ele.toggleClass($this.options.cls);

                        UI.Utils.animate(ele, animations[0]).then(function(){
                            ele.css('animation-duration', '');
                            UI.Utils.checkDisplay(ele);
                        });

                    } else {

                        UI.Utils.animate(this, animations[1]+' mdp-animation-reverse').then(function(){
                            ele.toggleClass($this.options.cls).css('animation-duration', '');
                            UI.Utils.checkDisplay(ele);
                        });

                    }

                });

            } else {
                this.totoggle.toggleClass(this.options.cls);
                UI.Utils.checkDisplay(this.totoggle);
            }

            this.updateAria();

        },

        getToggles: function() {
            this.totoggle = this.options.target ? UI.$(this.options.target):[];
            this.updateAria();
        },

        updateAria: function() {
            if (this.aria && this.totoggle.length) {
                this.totoggle.not('[aria-hidden]').each(function(){
                    UI.$(this ).attr('aria-hidden', UI.$(this ).hasClass('mdp-hidden'));
                });
            }
        }
    });

})(UIkit2MD);

(function(UI) {

    "use strict";

    UI.component('alert', {

        defaults: {
            fade: true,
            duration: 200,
            trigger: '.mdp-alert-close'
        },

        boot: function() {

            // init code
            UI.$html.on('click.alert.uikit', '[data-mdp-alert]', function(e) {

                var ele = UI.$(this );

                if (!ele.data('alert')) {

                    var alert = UI.alert(ele, UI.Utils.options(ele.attr('data-mdp-alert')));

                    if (UI.$(e.target).is(alert.options.trigger)) {
                        e.preventDefault();
                        alert.close();
                    }
                }
            });
        },

        init: function() {

            var $this = this;

            this.on('click', this.options.trigger, function(e) {
                e.preventDefault();
                $this.close();
            });
        },

        close: function() {

            var element       = this.trigger('close.uk.alert'),
                removeElement = function () {
                    this.trigger('closed.uk.alert').remove();
                }.bind(this );

            if (this.options.fade) {
                element.css('overflow', 'hidden').css("max-height", element.height()).animate({
                    height         : 0,
                    opacity        : 0,
                    paddingTop    : 0,
                    paddingBottom : 0,
                    marginTop     : 0,
                    marginBottom  : 0
                }, this.options.duration, removeElement);
            } else {
                removeElement();
            }
        }

    });

})(UIkit2MD);

(function(UI) {

    "use strict";

    UI.component('buttonRadio', {

        defaults: {
            activeClass: 'mdp-active',
            target: '.mdp-button'
        },

        boot: function() {

            // init code
            UI.$html.on('click.buttonradio.uikit', '[data-mdp-button-radio]', function(e) {

                var ele = UI.$(this );

                if (!ele.data('buttonRadio')) {

                    var obj    = UI.buttonRadio(ele, UI.Utils.options(ele.attr('data-mdp-button-radio'))),
                        target = UI.$(e.target);

                    if (target.is(obj.options.target)) {
                        target.trigger('click');
                    }
                }
            });
        },

        init: function() {

            var $this = this;

            // Init ARIA
            this.find($this.options.target).attr('aria-checked', 'false').filter('.' + $this.options.activeClass).attr('aria-checked', 'true');

            this.on('click', this.options.target, function(e) {

                var ele = UI.$(this );

                if (ele.is('a[href="#"]')) e.preventDefault();

                $this.find($this.options.target).not(ele).removeClass($this.options.activeClass).blur();
                ele.addClass($this.options.activeClass);

                // Update ARIA
                $this.find($this.options.target).not(ele).attr('aria-checked', 'false');
                ele.attr('aria-checked', 'true');

                $this.trigger('change.uk.button', [ele]);
            });

        },

        getSelected: function() {
            return this.find('.' + this.options.activeClass);
        }
    });

    UI.component('buttonCheckbox', {

        defaults: {
            activeClass: 'mdp-active',
            target: '.mdp-button'
        },

        boot: function() {

            UI.$html.on('click.buttoncheckbox.uikit', '[data-mdp-button-checkbox]', function(e) {
                var ele = UI.$(this );

                if (!ele.data('buttonCheckbox')) {

                    var obj    = UI.buttonCheckbox(ele, UI.Utils.options(ele.attr('data-mdp-button-checkbox'))),
                        target = UI.$(e.target);

                    if (target.is(obj.options.target)) {
                        target.trigger('click');
                    }
                }
            });
        },

        init: function() {

            var $this = this;

            // Init ARIA
            this.find($this.options.target).attr('aria-checked', 'false').filter('.' + $this.options.activeClass).attr('aria-checked', 'true');

            this.on('click', this.options.target, function(e) {
                var ele = UI.$(this );

                if (ele.is('a[href="#"]')) e.preventDefault();

                ele.toggleClass($this.options.activeClass).blur();

                // Update ARIA
                ele.attr('aria-checked', ele.hasClass($this.options.activeClass));

                $this.trigger('change.uk.button', [ele]);
            });

        },

        getSelected: function() {
            return this.find('.' + this.options.activeClass);
        }
    });


    UI.component('button', {

        defaults: {},

        boot: function() {

            UI.$html.on('click.button.uikit', '[data-mdp-button]', function(e) {
                var ele = UI.$(this );

                if (!ele.data('button')) {

                    var obj = UI.button(ele, UI.Utils.options(ele.attr('data-mdp-button')));
                    ele.trigger('click');
                }
            });
        },

        init: function() {

            var $this = this;

            // Init ARIA
            this.element.attr('aria-pressed', this.element.hasClass("mdp-active"));

            this.on('click', function(e) {

                if ($this.element.is('a[href="#"]')) e.preventDefault();

                $this.toggle();
                $this.trigger('change.uk.button', [$this.element.blur().hasClass('mdp-active')]);
            });

        },

        toggle: function() {
            this.element.toggleClass('mdp-active');

            // Update ARIA
            this.element.attr('aria-pressed', this.element.hasClass('mdp-active'));
        }
    });

})(UIkit2MD);

(function(UI) {

    "use strict";

    var active = false, hoverIdle, flips = {
        x: {
            'bottom-left'   : 'bottom-right',
            'bottom-right'  : 'bottom-left',
            'bottom-center' : 'bottom-center',
            'top-left'      : 'top-right',
            'top-right'     : 'top-left',
            'top-center'    : 'top-center',
            'left-top'      : 'right-top',
            'left-bottom'   : 'right-bottom',
            'left-center'   : 'right-center',
            'right-top'     : 'left-top',
            'right-bottom'  : 'left-bottom',
            'right-center'  : 'left-center'
        },
        y: {
            'bottom-left'   : 'top-left',
            'bottom-right'  : 'top-right',
            'bottom-center' : 'top-center',
            'top-left'      : 'bottom-left',
            'top-right'     : 'bottom-right',
            'top-center'    : 'bottom-center',
            'left-top'      : 'left-bottom',
            'left-bottom'   : 'left-top',
            'left-center'   : 'left-center',
            'right-top'     : 'right-bottom',
            'right-bottom'  : 'right-top',
            'right-center'  : 'right-center'
        },
        xy: {
            'bottom-left'   : 'top-right',
            'bottom-right'  : 'top-left',
            'bottom-center' : 'top-center',
            'top-left'      : 'bottom-right',
            'top-right'     : 'bottom-left',
            'top-center'    : 'bottom-center',
            'left-top'      : 'right-bottom',
            'left-bottom'   : 'right-top',
            'left-center'   : 'right-center',
            'right-top'     : 'left-bottom',
            'right-bottom'  : 'left-top',
            'right-center'  : 'left-center'
        }
    };

    UI.component('dropdown', {

        defaults: {
           mode            : 'hover',
           pos             : 'bottom-left',
           offset          : 0,
           remaintime      : 800,
           justify         : false,
           boundary        : UI.$win,
           delay           : 0,
           dropdownSelector: '.mdp-dropdown,.mdp-dropdown-blank',
           hoverDelayIdle  : 250,
           preventflip     : false
        },

        remainIdle: false,

        boot: function() {

            var triggerevent = UI.support.touch ? 'click' : 'mouseenter';

            // init code
            UI.$html.on(triggerevent+'.dropdown.uikit focus pointerdown', '[data-mdp-dropdown]', function(e) {

                var ele = UI.$(this );

                if (!ele.data('dropdown')) {

                    var dropdown = UI.dropdown(ele, UI.Utils.options(ele.attr('data-mdp-dropdown')));

                    if (e.type=='click' || (e.type=='mouseenter' && dropdown.options.mode=='hover')) {
                        dropdown.element.trigger(triggerevent);
                    }

                    if (dropdown.dropdown.length) {
                        e.preventDefault();
                    }
                }
            });
        },

        init: function() {

            var $this = this;

            this.dropdown     = this.find(this.options.dropdownSelector);
            this.offsetParent = this.dropdown.parents().filter(function() {
                return UI.$.inArray(UI.$(this ).css('position'), ['relative', 'fixed', 'absolute']) !== -1;
            }).slice(0,1);

            if (!this.offsetParent.length) {
                this.offsetParent = this.element;
            }

            this.centered  = this.dropdown.hasClass('mdp-dropdown-center');
            this.justified = this.options.justify ? UI.$(this.options.justify) : false;

            this.boundary  = UI.$(this.options.boundary);

            if (!this.boundary.length) {
                this.boundary = UI.$win;
            }

            // legacy DEPRECATED!
            if (this.dropdown.hasClass('mdp-dropdown-up')) {
                this.options.pos = 'top-left';
            }
            if (this.dropdown.hasClass('mdp-dropdown-flip')) {
                this.options.pos = this.options.pos.replace('left','right');
            }
            if (this.dropdown.hasClass('mdp-dropdown-center')) {
                this.options.pos = this.options.pos.replace(/(left|right)/,'center');
            }
            //-- end legacy

            // Init ARIA
            this.element.attr('aria-haspopup', 'true');
            this.element.attr('aria-expanded', this.element.hasClass('mdp-open'));
            this.dropdown.attr('aria-hidden', 'true');

            if (this.options.mode == 'click' || UI.support.touch) {

                this.on('click.uk.dropdown', function(e) {

                    var $target = UI.$(e.target);

                    if (!$target.parents($this.options.dropdownSelector).length) {

                        if ($target.is("a[href='#']") || $target.parent().is("a[href='#']") || ($this.dropdown.length && !$this.dropdown.is(':visible')) ){
                            e.preventDefault();
                        }

                        $target.blur();
                    }

                    if (!$this.element.hasClass('mdp-open')) {

                        $this.show();

                    } else {

                        if (!$this.dropdown.find(e.target).length || $target.is('.mdp-dropdown-close') || $target.parents('.mdp-dropdown-close').length) {
                            $this.hide();
                        }
                    }
                });

            } else {

                this.on('mouseenter', function(e) {

                    $this.trigger('pointerenter.uk.dropdown', [$this]);

                    if ($this.remainIdle) {
                        clearTimeout($this.remainIdle);
                    }

                    if (hoverIdle) {
                        clearTimeout(hoverIdle);
                    }

                    if (active && active == $this ) {
                        return;
                    }

                    // pseudo manuAim
                    if (active && active != $this ) {

                        hoverIdle = setTimeout(function() {
                            hoverIdle = setTimeout($this.show.bind($this ), $this.options.delay);
                        }, $this.options.hoverDelayIdle);

                    } else {

                        hoverIdle = setTimeout($this.show.bind($this ), $this.options.delay);
                    }

                }).on('mouseleave', function() {

                    if (hoverIdle) {
                        clearTimeout(hoverIdle);
                    }

                    $this.remainIdle = setTimeout(function() {
                        if (active && active == $this ) $this.hide();
                    }, $this.options.remaintime);

                    $this.trigger('pointerleave.uk.dropdown', [$this]);

                }).on('click', function( e ) {

                    var $target = UI.$(e.target);

                    if ($this.remainIdle) {
                        clearTimeout($this.remainIdle);
                    }

                    if (active && active == $this ) {
                        if (!$this.dropdown.find(e.target).length || $target.is('.mdp-dropdown-close') || $target.parents('.mdp-dropdown-close').length) {
                            $this.hide();
                        }
                        return;
                    }

                    if ($target.is("a[href='#']") || $target.parent().is("a[href='#']")){
                        e.preventDefault();
                    }

                    $this.show();
                });
            }
        },

        show: function(){

            UI.$html.off('click.outer.dropdown');

            if (active && active != this ) {
                active.hide(true);
            }

            if (hoverIdle) {
                clearTimeout(hoverIdle);
            }

            this.trigger('beforeshow.uk.dropdown', [this]);

            this.checkDimensions();
            this.element.addClass('mdp-open');

            // Update ARIA
            this.element.attr('aria-expanded', 'true');
            this.dropdown.attr('aria-hidden', 'false');

            this.trigger('show.uk.dropdown', [this]);

            UI.Utils.checkDisplay(this.dropdown, true);
            UI.Utils.focus(this.dropdown);
            active = this;

            this.registerOuterClick();
        },

        hide: function(force) {

            this.trigger('beforehide.uk.dropdown', [this, force]);

            this.element.removeClass('mdp-open');

            if (this.remainIdle) {
                clearTimeout(this.remainIdle);
            }

            this.remainIdle = false;

            // Update ARIA
            this.element.attr('aria-expanded', 'false');
            this.dropdown.attr('aria-hidden', 'true');

            this.trigger('hide.uk.dropdown', [this, force]);

            if (active == this ) active = false;
        },

        registerOuterClick: function(){

            var $this = this;

            UI.$html.off('click.outer.dropdown');

            setTimeout(function() {

                UI.$html.on('click.outer.dropdown', function(e) {

                    if (hoverIdle) {
                        clearTimeout(hoverIdle);
                    }

                    var $target = UI.$(e.target);

                    if (active == $this && !$this.element.find(e.target).length) {
                        $this.hide(true);
                        UI.$html.off('click.outer.dropdown');
                    }
                });
            }, 10);
        },

        checkDimensions: function() {

            if (!this.dropdown.length) return;

            // reset
            this.dropdown.removeClass('mdp-dropdown-top mdp-dropdown-bottom mdp-dropdown-left mdp-dropdown-right mdp-dropdown-stack mdp-dropdown-autoflip').css({
                topLeft :'',
                left :'',
                marginLeft :'',
                marginRight :''
            });

            if (this.justified && this.justified.length) {
                this.dropdown.css('min-width', '');
            }

            var $this          = this,
                pos            = UI.$.extend({}, this.offsetParent.offset(), {width: this.offsetParent[0].offsetWidth, height: this.offsetParent[0].offsetHeight}),
                posoffset      = this.options.offset,
                dropdown       = this.dropdown,
                offset         = dropdown.show().offset() || {left: 0, top: 0},
                width          = dropdown.outerWidth(),
                height         = dropdown.outerHeight(),
                boundarywidth  = this.boundary.width(),
                boundaryoffset = this.boundary[0] !== window && this.boundary.offset() ? this.boundary.offset(): {top:0, left:0},
                dpos           = this.options.pos;

            var variants =  {
                    'bottom-left'   : {top: 0 + pos.height + posoffset, left: 0},
                    'bottom-right'  : {top: 0 + pos.height + posoffset, left: 0 + pos.width - width},
                    'bottom-center' : {top: 0 + pos.height + posoffset, left: 0 + pos.width / 2 - width / 2},
                    'top-left'      : {top: 0 - height - posoffset, left: 0},
                    'top-right'     : {top: 0 - height - posoffset, left: 0 + pos.width - width},
                    'top-center'    : {top: 0 - height - posoffset, left: 0 + pos.width / 2 - width / 2},
                    'left-top'      : {top: 0, left: 0 - width - posoffset},
                    'left-bottom'   : {top: 0 + pos.height - height, left: 0 - width - posoffset},
                    'left-center'   : {top: 0 + pos.height / 2 - height / 2, left: 0 - width - posoffset},
                    'right-top'     : {top: 0, left: 0 + pos.width + posoffset},
                    'right-bottom'  : {top: 0 + pos.height - height, left: 0 + pos.width + posoffset},
                    'right-center'  : {top: 0 + pos.height / 2 - height / 2, left: 0 + pos.width + posoffset}
                },
                css = {},
                pp;

            pp = dpos.split('-');
            css = variants[dpos] ? variants[dpos] : variants['bottom-left'];

            // justify dropdown
            if (this.justified && this.justified.length) {
                justify(dropdown.css({left:0}), this.justified, boundarywidth);
            } else {

                if (this.options.preventflip !== true) {

                    var fdpos;

                    switch(this.checkBoundary(pos.left + css.left, pos.top + css.top, width, height, boundarywidth)) {
                        case "x":
                            if(this.options.preventflip !=='x') fdpos = flips['x'][dpos] || 'right-top';
                            break;
                        case "y":
                            if(this.options.preventflip !=='y') fdpos = flips['y'][dpos] || 'top-left';
                            break;
                        case "xy":
                            if(!this.options.preventflip) fdpos = flips['xy'][dpos] || 'right-bottom';
                            break;
                    }

                    if (fdpos) {

                        pp  = fdpos.split('-');
                        css = variants[fdpos] ? variants[fdpos] : variants['bottom-left'];
                        dropdown.addClass('mdp-dropdown-autoflip');

                        // check flipped
                        if (this.checkBoundary(pos.left + css.left, pos.top + css.top, width, height, boundarywidth)) {
                            pp  = dpos.split('-');
                            css = variants[dpos] ? variants[dpos] : variants['bottom-left'];
                        }
                    }
                }
            }

            if (width > boundarywidth) {
                dropdown.addClass('mdp-dropdown-stack');
                this.trigger('stack.uk.dropdown', [this]);
            }

            dropdown.css(css).css('display', '').addClass('mdp-dropdown-'+pp[0]);
        },

        checkBoundary: function(left, top, width, height, boundarywidth) {

            var axis = "";

            if (left < 0 || ((left - UI.$win.scrollLeft())+width) > boundarywidth) {
               axis += "x";
            }

            if ((top - UI.$win.scrollTop()) < 0 || ((top - UI.$win.scrollTop())+height) > window.innerHeight) {
               axis += "y";
            }

            return axis;
        }
    });


    UI.component('dropdownOverlay', {

        defaults: {
           justify : false,
           cls     : '',
           duration: 200
        },

        boot: function() {

            // init code
            UI.ready(function(context) {

                UI.$('[data-mdp-dropdown-overlay]', context).each(function() {
                    var ele = UI.$(this );

                    if (!ele.data('dropdownOverlay')) {
                        UI.dropdownOverlay(ele, UI.Utils.options(ele.attr('data-mdp-dropdown-overlay')));
                    }
                });
            });
        },

        init: function() {

            var $this = this;

            this.justified = this.options.justify ? UI.$(this.options.justify) : false;
            this.overlay   = this.element.find('mdp-dropdown-overlay');

            if (!this.overlay.length) {
                this.overlay = UI.$('<div class="mdp-dropdown-overlay"></div>').appendTo(this.element);
            }

            this.overlay.addClass(this.options.cls);

            this.on({

                'beforeshow.uk.dropdown': function(e, dropdown) {
                    $this.dropdown = dropdown;

                    if ($this.justified && $this.justified.length) {
                        justify($this.overlay.css({display:'block', marginLeft:'', marginRight:''}), $this.justified, $this.justified.outerWidth());
                    }
                },

                'show.uk.dropdown': function(e, dropdown) {

                    var h = $this.dropdown.dropdown.outerHeight(true);

                    $this.dropdown.element.removeClass('mdp-open');

                    $this.overlay.stop().css('display', 'block').animate({height: h}, $this.options.duration, function() {

                       $this.dropdown.dropdown.css('visibility', '');
                       $this.dropdown.element.addClass('mdp-open');

                       UI.Utils.checkDisplay($this.dropdown.dropdown, true);
                    });

                    $this.pointerleave = false;
                },

                'hide.uk.dropdown': function() {
                    $this.overlay.stop().animate({height: 0}, $this.options.duration);
                },

                'pointerenter.uk.dropdown': function(e, dropdown) {
                    clearTimeout($this.remainIdle);
                },

                'pointerleave.uk.dropdown': function(e, dropdown) {
                    $this.pointerleave = true;
                }
            });


            this.overlay.on({

                'mouseenter': function() {
                    if ($this.remainIdle) {
                        clearTimeout($this.dropdown.remainIdle);
                        clearTimeout($this.remainIdle);
                    }
                },

                'mouseleave': function(){

                    if ($this.pointerleave && active) {

                        $this.remainIdle = setTimeout(function() {
                           if(active) active.hide();
                        }, active.options.remaintime);
                    }
                }
            })
        }

    });


    function justify(ele, justifyTo, boundarywidth, offset) {

        ele           = UI.$(ele);
        justifyTo     = UI.$(justifyTo);
        boundarywidth = boundarywidth || window.innerWidth;
        offset        = offset || ele.offset();

        if (justifyTo.length) {

            var jwidth = justifyTo.outerWidth();

            ele.css('min-width', jwidth);

            if (UI.langdirection == 'right') {

                var right1   = boundarywidth - (justifyTo.offset().left + jwidth),
                    right2   = boundarywidth - (ele.offset().left + ele.outerWidth());

                ele.css('margin-right', right1 - right2);

            } else {
                ele.css('margin-left', justifyTo.offset().left - offset.left);
            }
        }
    }

})(UIkit2MD);

(function(UI) {

    "use strict";

    var grids = [];

    UI.component('gridMatchHeight', {

        defaults: {
            target        : false,
            row           : true,
            ignorestacked : false,
            observe       : false
        },

        boot: function() {

            // init code
            UI.ready(function(context) {

                UI.$('[data-mdp-grid-match]', context).each(function() {
                    var grid = UI.$(this ), obj;

                    if (!grid.data('gridMatchHeight')) {
                        obj = UI.gridMatchHeight(grid, UI.Utils.options(grid.attr('data-mdp-grid-match')));
                    }
                });
            });
        },

        init: function() {

            var $this = this;

            this.columns  = this.element.children();
            this.elements = this.options.target ? this.find(this.options.target) : this.columns;

            if (!this.columns.length) return;

            UI.$win.on('load resize orientationchange', (function() {

                var fn = function() {
                    if ($this.element.is(':visible')) $this.match();
                };

                UI.$(function() { fn(); });

                return UI.Utils.debounce(fn, 50);
            })());

            if (this.options.observe) {

                UI.domObserve(this.element, function(e) {
                    if ($this.element.is(':visible')) $this.match();
                });
            }

            this.on('display.uk.check', function(e) {
                if(this.element.is(':visible')) this.match();
            }.bind(this ));

            grids.push(this );
        },

        match: function() {

            var firstvisible = this.columns.filter(':visible:first');

            if (!firstvisible.length) return;

            var stacked = Math.ceil(100 * parseFloat(firstvisible.css('width')) / parseFloat(firstvisible.parent().css('width'))) >= 100;

            if (stacked && !this.options.ignorestacked) {
                this.revert();
            } else {
                UI.Utils.matchHeights(this.elements, this.options);
            }

            return this;
        },

        revert: function() {
            this.elements.css('min-height', '');
            return this;
        }
    });

    UI.component('gridMargin', {

        defaults: {
            cls      : 'mdp-grid-margin',
            rowfirst : 'mdp-row-first'
        },

        boot: function() {

            // init code
            UI.ready(function(context) {

                UI.$('[data-mdp-grid-margin]', context).each(function() {
                    var grid = UI.$(this ), obj;

                    if (!grid.data('gridMargin')) {
                        obj = UI.gridMargin(grid, UI.Utils.options(grid.attr('data-mdp-grid-margin')));
                    }
                });
            });
        },

        init: function() {

            var stackMargin = UI.stackMargin(this.element, this.options);
        }
    });

})(UIkit2MD);

(function(UI) {

    "use strict";

    var active = false, activeCount = 0, $html = UI.$html, body;

    UI.$win.on('resize orientationchange', UI.Utils.debounce(function(){
        UI.$('.mdp-modal.mdp-open').each(function(){
            return UI.$(this ).data('modal') && UI.$(this ).data('modal').resize();
        });
    }, 150));

    UI.component('modal', {

        defaults: {
            keyboard: true,
            bgclose: true,
            minScrollHeight: 150,
            center: false,
            modal: true
        },

        scrollable: false,
        transition: false,
        hasTransitioned: true,

        init: function() {

            if (!body) body = UI.$('body');

            if (!this.element.length) return;

            var $this = this;

            this.paddingdir = 'padding-' + (UI.langdirection == 'left' ? 'right':'left');
            this.dialog     = this.find('.mdp-modal-dialog');

            this.active     = false;

            // Update ARIA
            this.element.attr('aria-hidden', this.element.hasClass('mdp-open'));

            this.on('click', '.mdp-modal-close', function(e) {
                e.preventDefault();
                $this.hide();
            }).on('click', function(e) {

                var target = UI.$(e.target);

                if (target[0] == $this.element[0] && $this.options.bgclose) {
                    $this.hide();
                }
            });

            UI.domObserve(this.element, function(e) { $this.resize(); });
        },

        toggle: function() {
            return this[this.isActive() ? 'hide' : 'show']();
        },

        show: function() {

            if (!this.element.length) return;

            var $this = this;

            if (this.isActive()) return;

            if (this.options.modal && active) {
                active.hide(true);
            }

            this.element.removeClass('mdp-open').show();
            this.resize(true);

            if (this.options.modal) {
                active = this;
            }

            this.active = true;

            activeCount++;

            if (UI.support.transition) {
                this.hasTransitioned = false;
                this.element.one(UI.support.transition.end, function(){
                    $this.hasTransitioned = true;
                    UI.Utils.focus($this.dialog, 'a[href]');
                }).addClass('mdp-open');
            } else {
                this.element.addClass('mdp-open');
                UI.Utils.focus(this.dialog, 'a[href]');
            }

            $html.addClass('mdp-modal-page').height(); // force browser engine redraw

            // Update ARIA
            this.element.attr('aria-hidden', 'false');

            this.element.trigger('show.uk.modal');

            UI.Utils.checkDisplay(this.dialog, true);

            return this;
        },

        hide: function(force) {

            if (!force && UI.support.transition && this.hasTransitioned) {

                var $this = this;

                this.one(UI.support.transition.end, function() {
                    $this._hide();
                }).removeClass('mdp-open');

            } else {

                this._hide();
            }

            return this;
        },

        resize: function(force) {

            if (!this.isActive() && !force) return;

            var bodywidth  = body.width();

            this.scrollbarwidth = window.innerWidth - bodywidth;

            body.css(this.paddingdir, this.scrollbarwidth);

            this.element.css('overflow-y', this.scrollbarwidth ? 'scroll' : 'auto');

            if (!this.updateScrollable() && this.options.center) {

                var dh  = this.dialog.outerHeight(),
                pad = parseInt(this.dialog.css('margin-top'), 10) + parseInt(this.dialog.css('margin-bottom'), 10);

                if ((dh + pad) < window.innerHeight) {
                    this.dialog.css({top: (window.innerHeight/2 - dh/2) - pad });
                } else {
                    this.dialog.css({top: ''});
                }
            }
        },

        updateScrollable: function() {

            // has scrollable?
            var scrollable = this.dialog.find('.mdp-overflow-container:visible:first');

            if (scrollable.length) {

                scrollable.css('height', 0);

                var offset = Math.abs(parseInt(this.dialog.css('margin-top'), 10)),
                dh     = this.dialog.outerHeight(),
                wh     = window.innerHeight,
                h      = wh - 2*(offset < 20 ? 20:offset) - dh;

                scrollable.css({
                    maxHeight: (h < this.options.minScrollHeight ? '':h),
                    height:''
                });

                return true;
            }

            return false;
        },

        _hide: function() {

            this.active = false;
            if (activeCount > 0) activeCount--;
            else activeCount = 0;

            this.element.hide().removeClass('mdp-open');

            // Update ARIA
            this.element.attr('aria-hidden', 'true');

            if (!activeCount) {
                $html.removeClass('mdp-modal-page');
                body.css(this.paddingdir, "");
            }

            if (active===this ) active = false;

            this.trigger('hide.uk.modal');
        },

        isActive: function() {
            return this.element.hasClass('mdp-open');
        }

    });

    UI.component('modalTrigger', {

        boot: function() {

            // init code
            UI.$html.on('click.modal.uikit', '[data-mdp-modal]', function(e) {

                var ele = UI.$(this );

                if (ele.is('a')) {
                    e.preventDefault();
                }

                if (!ele.data('modalTrigger')) {
                    var modal = UI.modalTrigger(ele, UI.Utils.options(ele.attr('data-mdp-modal')));
                    modal.show();
                }

            });

            // close modal on esc button
            UI.$html.on('keydown.modal.uikit', function (e) {

                if (active && e.keyCode === 27 && active.options.keyboard) { // ESC
                    e.preventDefault();
                    active.hide();
                }
            });
        },

        init: function() {

            var $this = this;

            this.options = UI.$.extend({
                target: $this.element.is('a') ? $this.element.attr('href') : false
            }, this.options);

            this.modal = UI.modal(this.options.target, this.options);

            this.on("click", function(e) {
                e.preventDefault();
                $this.show();
            });

            //methods
            this.proxy(this.modal, 'show hide isActive');
        }
    });

    UI.modal.dialog = function(content, options) {

        var modal = UI.modal(UI.$(UI.modal.dialog.template).appendTo('body'), options);

        modal.on('hide.uk.modal', function(){
            if (modal.persist) {
                modal.persist.appendTo(modal.persist.data('modalPersistParent'));
                modal.persist = false;
            }
            modal.element.remove();
        });

        setContent(content, modal);

        return modal;
    };

    UI.modal.dialog.template = '<div class="mdp-modal"><div class="mdp-modal-dialog" style="min-height:0;"></div></div>';

    UI.modal.alert = function(content, options) {

        options = UI.$.extend(true, {bgclose:false, keyboard:false, modal:false, labels:UI.modal.labels}, options);

        var modal = UI.modal.dialog(([
            '<div class="mdp-margin mdp-modal-content">'+String(content)+'</div>',
            '<div class="mdp-modal-footer mdp-text-right"><button class="mdp-button mdp-button-primary mdp-modal-close">'+options.labels.Ok+'</button></div>'
        ]).join(""), options);

        modal.on('show.uk.modal', function(){
            setTimeout(function(){
                modal.element.find('button:first').focus();
            }, 50);
        });

        return modal.show();
    };

    UI.modal.confirm = function(content, onconfirm, oncancel) {

        var options = arguments.length > 1 && arguments[arguments.length-1] ? arguments[arguments.length-1] : {};

        onconfirm = UI.$.isFunction(onconfirm) ? onconfirm : function(){};
        oncancel  = UI.$.isFunction(oncancel) ? oncancel : function(){};
        options   = UI.$.extend(true, {bgclose:false, keyboard:false, modal:false, labels:UI.modal.labels}, UI.$.isFunction(options) ? {}:options);

        var modal = UI.modal.dialog(([
            '<div class="mdp-margin mdp-modal-content">'+String(content)+'</div>',
            '<div class="mdp-modal-footer mdp-text-right"><button class="mdp-button js-modal-confirm-cancel">'+options.labels.Cancel+'</button> <button class="mdp-button mdp-button-primary js-modal-confirm">'+options.labels.Ok+'</button></div>'
        ]).join(""), options);

        modal.element.find(".js-modal-confirm, .js-modal-confirm-cancel").on("click", function(){
            UI.$(this ).is('.js-modal-confirm') ? onconfirm() : oncancel();
            modal.hide();
        });

        modal.on('show.uk.modal', function(){
            setTimeout(function(){
                modal.element.find('.js-modal-confirm').focus();
            }, 50);
        });

        return modal.show();
    };

    UI.modal.prompt = function(text, value, onsubmit, options) {

        onsubmit = UI.$.isFunction(onsubmit) ? onsubmit : function(value){};
        options  = UI.$.extend(true, {bgclose:false, keyboard:false, modal:false, labels:UI.modal.labels}, options);

        var modal = UI.modal.dialog(([
            text ? '<div class="mdp-modal-content mdp-form">'+String(text)+'</div>':'',
            '<div class="mdp-margin-small-top mdp-modal-content mdp-form"><p><input type="text" class="mdp-width-1-1"></p></div>',
            '<div class="mdp-modal-footer mdp-text-right"><button class="mdp-button mdp-modal-close">'+options.labels.Cancel+'</button> <button class="mdp-button mdp-button-primary js-modal-ok">'+options.labels.Ok+'</button></div>'
        ]).join(""), options),

        input = modal.element.find("input[type='text']").val(value || '').on('keyup', function( e ) {
            if (e.keyCode == 13) {
                modal.element.find('.js-modal-ok').trigger('click');
            }
        });

        modal.element.find('.js-modal-ok').on('click', function(){
            if (onsubmit(input.val())!==false){
                modal.hide();
            }
        });

        return modal.show();
    };

    UI.modal.blockUI = function(content, options) {

        var modal = UI.modal.dialog(([
            '<div class="mdp-margin mdp-modal-content">'+String(content || '<div class="mdp-text-center">...</div>')+'</div>'
        ]).join(""), UI.$.extend({bgclose:false, keyboard:false, modal:false}, options));

        modal.content = modal.element.find('.mdp-modal-content:first');

        return modal.show();
    };

    UI.modal.labels = {
        Ok: 'Ok',
        Cancel: 'Cancel'
    };

    // helper functions
    function setContent(content, modal){

        if(!modal) return;

        if (typeof content === 'object') {

            // convert DOM object to a jQuery object
            content = content instanceof jQuery ? content : UI.$(content);

            if(content.parent().length) {
                modal.persist = content;
                modal.persist.data('modalPersistParent', content.parent());
            }
        }else if (typeof content === 'string' || typeof content === 'number') {
                // just insert the data as innerHTML
                content = UI.$('<div></div>').html(content);
        }else {
                // unsupported data type!
                content = UI.$('<div></div>').html('UIkit2MD.modal Error: Unsupported data type: ' + typeof content);
        }

        content.appendTo(modal.element.find('.mdp-modal-dialog'));

        return modal;
    }

})(UIkit2MD);

(function(UI) {

    "use strict";

    UI.component('nav', {

        defaults: {
            toggle: '>li.mdp-parent > a[href="#"]',
            lists: '>li.mdp-parent > ul',
            multiple: false
        },

        boot: function() {

            // init code
            UI.ready(function(context) {

                UI.$('[data-mdp-nav]', context).each(function() {
                    var nav = UI.$(this );

                    if (!nav.data('nav')) {
                        var obj = UI.nav(nav, UI.Utils.options(nav.attr('data-mdp-nav')));
                    }
                });
            });
        },

        init: function() {

            var $this = this;

            this.on('click.uk.nav', this.options.toggle, function(e) {
                e.preventDefault();
                var ele = UI.$(this );
                $this.open(ele.parent()[0] == $this.element[0] ? ele : ele.parent("li"));
            });

            this.update();

            UI.domObserve(this.element, function(e) {
                if ($this.element.find($this.options.lists).not('[role]').length) {
                    $this.update();
                }
            });
        },

        update: function() {

            var $this = this;

            this.find(this.options.lists).each(function() {

                var $ele   = UI.$(this ).attr('role', 'menu'),
                    parent = $ele.closest('li'),
                    active = parent.hasClass("mdp-active");

                if (!parent.data('list-container')) {
                    $ele.wrap('<div style="overflow:hidden;height:0;position:relative;"></div>');
                    parent.data('list-container', $ele.parent()[active ? 'removeClass':'addClass']('mdp-hidden'));
                }

                // Init ARIA
                parent.attr('aria-expanded', parent.hasClass("mdp-open"));

                if (active) $this.open(parent, true);
            });
        },

        open: function(li, noanimation) {

            var $this = this, element = this.element, $li = UI.$(li), $container = $li.data('list-container');

            if (!this.options.multiple) {

                element.children('.mdp-open').not(li).each(function() {

                    var ele = UI.$(this );

                    if (ele.data('list-container')) {
                        ele.data('list-container').stop().animate({height: 0}, function() {
                            UI.$(this ).parent().removeClass('mdp-open').end().addClass('mdp-hidden');
                        });
                    }
                });
            }

            $li.toggleClass('mdp-open');

            // Update ARIA
            $li.attr('aria-expanded', $li.hasClass('mdp-open'));

            if ($container) {

                if ($li.hasClass('mdp-open')) {
                    $container.removeClass('mdp-hidden');
                }

                if (noanimation) {

                    $container.stop().height($li.hasClass('mdp-open') ? 'auto' : 0);

                    if (!$li.hasClass('mdp-open')) {
                        $container.addClass('mdp-hidden');
                    }

                    this.trigger('display.uk.check');

                } else {

                    $container.stop().animate({
                        height: ($li.hasClass('mdp-open') ? getHeight($container.find('ul:first')) : 0)
                    }, function() {

                        if (!$li.hasClass('mdp-open')) {
                            $container.addClass('mdp-hidden');
                        } else {
                            $container.css('height', '');
                        }

                        $this.trigger('display.uk.check');
                    });
                }
            }
        }
    });


    // helper

    function getHeight(ele) {

        var $ele = UI.$(ele), height = 'auto';

        if ($ele.is(':visible')) {
            height = $ele.outerHeight();
        } else {

            var tmp = {
                position: $ele.css('position'),
                visibility: $ele.css('visibility'),
                display: $ele.css('display')
            };

            height = $ele.css({position: 'absolute', visibility: 'hidden', display: 'block'}).outerHeight();

            $ele.css(tmp); // reset element
        }

        return height;
    }

})(UIkit2MD);

(function(UI) {

    "use strict";

    var scrollpos = {x: window.scrollX, y: window.scrollY},
        $win      = UI.$win,
        $doc      = UI.$doc,
        $html     = UI.$html,
        Offcanvas = {

        show: function(element, options) {

            element = UI.$(element);

            if (!element.length) return;

            options = UI.$.extend({mode: 'push'}, options);

            var $body     = UI.$('body'),
                bar       = element.find('.mdp-offcanvas-bar:first'),
                rtl       = (UI.langdirection == 'right'),
                flip      = bar.hasClass('mdp-offcanvas-bar-flip') ? -1:1,
                dir       = flip * (rtl ? -1 : 1),

                scrollbarwidth =  window.innerWidth - $body.width();

            scrollpos = {x: window.pageXOffset, y: window.pageYOffset};

            bar.attr('mode', options.mode);
            element.addClass('mdp-active');

            $body.css({width: window.innerWidth - scrollbarwidth, height: window.innerHeight}).addClass('mdp-offcanvas-page');

            if (options.mode == 'push' || options.mode == 'reveal') {
                $body.css((rtl ? 'margin-right' : 'margin-left'), (rtl ? -1 : 1) * (bar.outerWidth() * dir));
            }

            if (options.mode == 'reveal') {
                bar.css('clip', 'rect(0, '+bar.outerWidth()+'px, 100vh, 0)');
            }

            $html.css('margin-top', scrollpos.y * -1).width(); // .width() - force redraw


            bar.addClass('mdp-offcanvas-bar-show');

            this._initElement(element);

            bar.trigger('show.uk.offcanvas', [element, bar]);

            // Update ARIA
            element.attr('aria-hidden', 'false');
        },

        hide: function(force) {

            var $body = UI.$('body'),
                panel = UI.$('.mdp-offcanvas.mdp-active'),
                rtl   = (UI.langdirection == 'right'),
                bar   = panel.find('.mdp-offcanvas-bar:first'),
                finalize = function() {
                    $body.removeClass('mdp-offcanvas-page').css({width: '', height: '', marginLeft: '', marginRight: ''});
                    panel.removeClass('mdp-active');

                    bar.removeClass('mdp-offcanvas-bar-show');
                    $html.css('margin-top', '');
                    window.scrollTo(scrollpos.x, scrollpos.y);
                    bar.trigger('hide.uk.offcanvas', [panel, bar]);

                    // Update ARIA
                    panel.attr('aria-hidden', 'true');
                };

            if (!panel.length) return;
            if (bar.attr('mode') == 'none') force = true;

            if (UI.support.transition && !force) {

                $body.one(UI.support.transition.end, function() {
                    finalize();
                }).css((rtl ? 'margin-right' : 'margin-left'), '');

                if (bar.attr('mode') == 'reveal') {
                    bar.css('clip', '');
                }

                setTimeout(function(){
                    bar.removeClass('mdp-offcanvas-bar-show');
                }, 0);

            } else {
                finalize();
            }
        },

        _initElement: function(element) {

            if (element.data('OffcanvasInit')) return;

            element.on('click.uk.offcanvas swipeRight.uk.offcanvas swipeLeft.uk.offcanvas', function(e) {

                var target = UI.$(e.target);

                if (!e.type.match(/swipe/)) {

                    if (!target.hasClass('mdp-offcanvas-close')) {
                        if (target.hasClass('mdp-offcanvas-bar')) return;
                        if (target.parents('.mdp-offcanvas-bar:first').length) return;
                    }
                }

                e.stopImmediatePropagation();
                Offcanvas.hide();
            });

            element.on('click', 'a[href*="#"]', function( e ) {

                var link = UI.$(this ),
                    href = link.attr('href');

                if (href == '#') {
                    return;
                }

                UI.$doc.one('hide.uk.offcanvas', function() {

                    var target;

                    try {
                        target = UI.$(link[0].hash);
                    } catch ( e ) {
                        target = '';
                    }

                    if (!target.length) {
                        target = UI.$('[name="'+link[0].hash.replace('#','')+'"]');
                    }

                    if (target.length && UI.Utils.scrollToElement) {
                        UI.Utils.scrollToElement(target, UI.Utils.options(link.attr('data-mdp-smooth-scroll') || '{}'));
                    } else {
                        window.location.href = href;
                    }
                });

                Offcanvas.hide();
            });

            element.data('OffcanvasInit', true);
        }
    };

    UI.component('offcanvasTrigger', {

        boot: function() {

            // init code
            $html.on('click.offcanvas.uikit', '[data-mdp-offcanvas]', function(e) {

                e.preventDefault();

                var ele = UI.$(this );

                if (!ele.data('offcanvasTrigger')) {
                    var obj = UI.offcanvasTrigger(ele, UI.Utils.options(ele.attr('data-mdp-offcanvas')));
                    ele.trigger("click");
                }
            });

            $html.on('keydown.uk.offcanvas', function(e) {

                if (e.keyCode === 27) { // ESC
                    Offcanvas.hide();
                }
            });
        },

        init: function() {

            var $this = this;

            this.options = UI.$.extend({
                target: $this.element.is('a') ? $this.element.attr('href') : false,
                mode: 'push'
            }, this.options);

            this.on('click', function(e) {
                e.preventDefault();
                Offcanvas.show($this.options.target, $this.options);
            });
        }
    });

    UI.offcanvas = Offcanvas;

})(UIkit2MD);

(function(UI) {

    "use strict";

    var Animations;

    UI.component('switcher', {

        defaults: {
            connect   : false,
            toggle    : '>*',
            active    : 0,
            animation : false,
            duration  : 200,
            swiping   : true
        },

        animating: false,

        boot: function() {

            // init code
            UI.ready(function(context) {

                UI.$('[data-mdp-switcher]', context).each(function() {
                    var switcher = UI.$(this );

                    if (!switcher.data('switcher')) {
                        var obj = UI.switcher(switcher, UI.Utils.options(switcher.attr('data-mdp-switcher')));
                    }
                });
            });
        },

        init: function() {

            var $this = this;

            this.on('click.uk.switcher', this.options.toggle, function(e) {
                e.preventDefault();
                $this.show(this );
            });

            if (!this.options.connect) {
                return;
            }

            this.connect = UI.$(this.options.connect);

            if (!this.connect.length) {
                return;
            }

            this.connect.on('click.uk.switcher', '[data-mdp-switcher-item]', function(e) {

                e.preventDefault();

                var item = UI.$(this ).attr('data-mdp-switcher-item');

                if ($this.index == item) return;

                switch(item) {
                    case 'next':
                    case 'previous':
                        $this.show($this.index + (item=='next' ? 1:-1));
                        break;
                    default:
                        $this.show(parseInt(item, 10));
                }
            });

            if (this.options.swiping) {

                this.connect.on('swipeRight swipeLeft', function(e) {
                    e.preventDefault();
                    if (!window.getSelection().toString()) {
                        $this.show($this.index + (e.type == 'swipeLeft' ? 1 : -1));
                    }
                });
            }

            this.update();
        },

        update: function() {

            this.connect.children().removeClass('mdp-active').attr('aria-hidden', 'true');

            var toggles = this.find(this.options.toggle),
                active  = toggles.filter('.mdp-active');

            if (active.length) {
                this.show(active, false);
            } else {

                if (this.options.active===false) return;

                active = toggles.eq(this.options.active);
                this.show(active.length ? active : toggles.eq(0), false);
            }

            // Init ARIA for toggles
            toggles.not(active).attr('aria-expanded', 'false');
            active.attr('aria-expanded', 'true');
        },

        show: function(tab, animate) {

            if (this.animating) {
                return;
            }

            var toggles = this.find(this.options.toggle);

            if (isNaN(tab)) {
                tab = UI.$(tab);
            } else {
                tab = tab < 0 ? toggles.length-1 : tab;
                tab = toggles.eq(toggles[tab] ? tab : 0);
            }

            var $this     = this,
                active    = UI.$(tab),
                animation = Animations[this.options.animation] || function(current, next) {

                    if (!$this.options.animation) {
                        return Animations.none.apply($this );
                    }

                    var anim = $this.options.animation.split(',');

                    if (anim.length == 1) {
                        anim[1] = anim[0];
                    }

                    anim[0] = anim[0].trim();
                    anim[1] = anim[1].trim();

                    return coreAnimation.apply($this, [anim, current, next]);
                };

            if (animate===false || !UI.support.animation) {
                animation = Animations.none;
            }

            if (active.hasClass("mdp-disabled")) return;

            // Update ARIA for Toggles
            toggles.attr('aria-expanded', 'false');
            active.attr('aria-expanded', 'true');

            toggles.filter(".mdp-active").removeClass("mdp-active");
            active.addClass("mdp-active");

            if (this.options.connect && this.connect.length) {

                this.index = this.find(this.options.toggle).index(active);

                if (this.index == -1 ) {
                    this.index = 0;
                }

                this.connect.each(function() {

                    var container = UI.$(this ),
                        children  = UI.$(container.children()),
                        current   = UI.$(children.filter('.mdp-active')),
                        next      = UI.$(children.eq($this.index));

                        $this.animating = true;

                        animation.apply($this, [current, next]).then(function(){

                            current.removeClass("mdp-active");
                            next.addClass("mdp-active");

                            // Update ARIA for connect
                            current.attr('aria-hidden', 'true');
                            next.attr('aria-hidden', 'false');

                            UI.Utils.checkDisplay(next, true);

                            $this.animating = false;

                        });
                });
            }

            this.trigger("show.uk.switcher", [active]);
        }
    });

    Animations = {

        'none': function() {
            var d = UI.$.Deferred();
            d.resolve();
            return d.promise();
        },

        'fade': function(current, next) {
            return coreAnimation.apply(this, ['mdp-animation-fade', current, next]);
        },

        'slide-bottom': function(current, next) {
            return coreAnimation.apply(this, ['mdp-animation-slide-bottom', current, next]);
        },

        'slide-top': function(current, next) {
            return coreAnimation.apply(this, ['mdp-animation-slide-top', current, next]);
        },

        'slide-vertical': function(current, next, dir) {

            var anim = ['mdp-animation-slide-top', 'mdp-animation-slide-bottom'];

            if (current && current.index() > next.index()) {
                anim.reverse();
            }

            return coreAnimation.apply(this, [anim, current, next]);
        },

        'slide-left': function(current, next) {
            return coreAnimation.apply(this, ['mdp-animation-slide-left', current, next]);
        },

        'slide-right': function(current, next) {
            return coreAnimation.apply(this, ['mdp-animation-slide-right', current, next]);
        },

        'slide-horizontal': function(current, next, dir) {

            var anim = ['mdp-animation-slide-right', 'mdp-animation-slide-left'];

            if (current && current.index() > next.index()) {
                anim.reverse();
            }

            return coreAnimation.apply(this, [anim, current, next]);
        },

        'scale': function(current, next) {
            return coreAnimation.apply(this, ['mdp-animation-scale-up', current, next]);
        }
    };

    UI.switcher.animations = Animations;


    // helpers

    function coreAnimation(cls, current, next) {

        var d = UI.$.Deferred(), clsIn = cls, clsOut = cls, release;

        if (next[0]===current[0]) {
            d.resolve();
            return d.promise();
        }

        if (typeof(cls) == 'object') {
            clsIn  = cls[0];
            clsOut = cls[1] || cls[0];
        }

        UI.$body.css('overflow-x', 'hidden'); // fix scroll jumping in iOS

        release = function() {

            if (current) current.hide().removeClass('mdp-active '+clsOut+' mdp-animation-reverse');

            next.addClass(clsIn).one(UI.support.animation.end, function() {

                setTimeout(function () {
                    next.removeClass(''+clsIn+'').css({opacity:'', display:''});
                }, 0);

                d.resolve();

                UI.$body.css('overflow-x', '');

                if (current) current.css({opacity:'', display:''});

            }.bind(this )).show();
        };

        next.css('animation-duration', this.options.duration+'ms');

        if (current && current.length) {

            current.css('animation-duration', this.options.duration+'ms');

            current.css('display', 'none').addClass(clsOut+' mdp-animation-reverse').one(UI.support.animation.end, function() {
                release();
            }.bind(this )).css('display', '');

        } else {
            next.addClass('mdp-active');
            release();
        }

        return d.promise();
    }

})(UIkit2MD);

(function(UI) {

    "use strict";

    UI.component('tab', {

        defaults: {
            target    : '>li:not(.mdp-tab-responsive, .mdp-disabled)',
            connect   : false,
            active    : 0,
            animation : false,
            duration  : 200,
            swiping   : true
        },

        boot: function() {

            // init code
            UI.ready(function(context) {

                UI.$('[data-mdp-tab]', context).each(function() {

                    var tab = UI.$(this );

                    if (!tab.data('tab')) {
                        var obj = UI.tab(tab, UI.Utils.options(tab.attr('data-mdp-tab')));
                    }
                });
            });
        },

        init: function() {

            var $this = this;

            this.current = false;

            this.on('click.uk.tab', this.options.target, function(e) {

                e.preventDefault();

                if ($this.switcher && $this.switcher.animating) {
                    return;
                }

                var current = $this.find($this.options.target).not(this );

                current.removeClass('mdp-active').blur();

                $this.trigger('change.uk.tab', [UI.$(this ).addClass('mdp-active'), $this.current]);

                $this.current = UI.$(this );

                // Update ARIA
                if (!$this.options.connect) {
                    current.attr('aria-expanded', 'false');
                    UI.$(this ).attr('aria-expanded', 'true');
                }
            });

            if (this.options.connect) {
                this.connect = UI.$(this.options.connect);
            }

            // init responsive tab
            this.responsivetab = UI.$('<li class="mdp-tab-responsive mdp-active"><a></a></li>').append('<div class="mdp-dropdown mdp-dropdown-small"><ul class="mdp-nav mdp-nav-dropdown"></ul><div>');

            this.responsivetab.dropdown = this.responsivetab.find('.mdp-dropdown');
            this.responsivetab.lst      = this.responsivetab.dropdown.find('ul');
            this.responsivetab.caption  = this.responsivetab.find('a:first');

            if (this.element.hasClass('mdp-tab-bottom')) this.responsivetab.dropdown.addClass('mdp-dropdown-up');

            // handle click
            this.responsivetab.lst.on('click.uk.tab', 'a', function(e) {

                e.preventDefault();
                e.stopPropagation();

                var link = UI.$(this );

                $this.element.children('li:not(.mdp-tab-responsive)').eq(link.data('index')).trigger('click');
            });

            this.on('show.uk.switcher change.uk.tab', function(e, tab) {
                $this.responsivetab.caption.html(tab.text());
            });

            this.element.append(this.responsivetab);

            // init UIkit components
            if (this.options.connect) {

                this.switcher = UI.switcher(this.element, {
                    toggle    : '>li:not(.mdp-tab-responsive)',
                    connect   : this.options.connect,
                    active    : this.options.active,
                    animation : this.options.animation,
                    duration  : this.options.duration,
                    swiping   : this.options.swiping
                });
            }

            UI.dropdown(this.responsivetab, {mode: 'click', preventflip: 'y'});

            // init
            $this.trigger('change.uk.tab', [this.element.find(this.options.target).not('.mdp-tab-responsive').filter('.mdp-active')]);

            this.check();

            UI.$win.on('resize orientationchange', UI.Utils.debounce(function(){
                if ($this.element.is(':visible'))  $this.check();
            }, 100));

            this.on('display.uk.check', function(){
                if ($this.element.is(':visible'))  $this.check();
            });
        },

        check: function() {

            var children = this.element.children('li:not(.mdp-tab-responsive)').removeClass('mdp-hidden');

            if (!children.length) {
                this.responsivetab.addClass('mdp-hidden');
                return;
            }

            var top          = (children.eq(0).offset().top + Math.ceil(children.eq(0).height()/2)),
                doresponsive = false,
                item, link, clone;

            this.responsivetab.lst.empty();

            children.each(function(){

                if (UI.$(this ).offset().top > top) {
                    doresponsive = true;
                }
            });

            if (doresponsive) {

                for (var i = 0; i < children.length; i++) {

                    item  = UI.$(children.eq(i));
                    link  = item.find('a');

                    if (item.css('float') != 'none' && !item.attr('mdp-dropdown')) {

                        if (!item.hasClass('mdp-disabled')) {

                            clone = UI.$(item[0].outerHTML);
                            clone.find('a').data('index', i);

                            this.responsivetab.lst.append(clone);
                        }

                        item.addClass('mdp-hidden');
                    }
                }
            }

            this.responsivetab[this.responsivetab.lst.children('li').length ? 'removeClass':'addClass']('mdp-hidden');
        }
    });

})(UIkit2MD);

(function(UI){

    "use strict";

    UI.component('cover', {

        defaults: {
            automute : true
        },

        boot: function() {

            // auto init
            UI.ready(function(context) {

                UI.$('[data-mdp-cover]', context).each(function(){

                    var ele = UI.$(this );

                    if(!ele.data('cover')) {
                        var plugin = UI.cover(ele, UI.Utils.options(ele.attr('data-mdp-cover')));
                    }
                });
            });
        },

        init: function() {

            this.parent = this.element.parent();

            UI.$win.on('load resize orientationchange', UI.Utils.debounce(function(){
                this.check();
            }.bind(this ), 100));

            this.on('display.uk.check', function(e) {
                if (this.element.is(':visible')) this.check();
            }.bind(this ));

            this.check();

            if (this.element.is('iframe') && this.options.automute) {

                var src = this.element.attr('src');

                this.element.attr('src', '').on('load', function(){
                    this.contentWindow.postMessage('{ "event": "command", "func": "mute", "method":"setVolume", "value":0}', '*');
                }).attr('src', [src, (src.indexOf('?') > -1 ? '&':'?'), 'enablejsapi=1&api=1'].join(''));
            }
        },

        check: function() {

            this.element.css({ width  : '', height : '' });

            this.dimension = {w: this.element.width(), h: this.element.height()};

            if (this.element.attr('width') && !isNaN(this.element.attr('width'))) {
                this.dimension.w = this.element.attr('width');
            }

            if (this.element.attr('height') && !isNaN(this.element.attr('height'))) {
                this.dimension.h = this.element.attr('height');
            }

            this.ratio = this.dimension.w / this.dimension.h;

            var w = this.parent.width(), h = this.parent.height(), width, height;

            // if element height < parent height (gap underneath)
            if ((w / this.ratio) < h) {

                width  = Math.ceil(h * this.ratio);
                height = h;

            // element width < parent width (gap to right)
            } else {

                width  = w;
                height = Math.ceil(w / this.ratio);
            }

            this.element.css({ width  : width, height : height });
        }
    });

})(UIkit2MD);

/**
 * Plugin assignments,
 **/
jQuery(function($) {

    "use strict";

    /** INPUT which will save the settings */
    let assignInput = $("#mdp-assignInput");

    /**
     * Read assignments settings.
     **/
    function mdp_readSettings () {

        // Get assignments from field
        let aConf = '';
        try {

            let aConfJson = $( assignInput).val();
            aConfJson = aConfJson.replace(/\|/g, '"');
            aConf = JSON.parse(aConfJson);

            // Matching Method
            let matchingMethod = aConf.matchingMethod;
            $( "#mdp-assign-box .mdp-matching-method .mdp-button-group .mdp-button").removeClass("mdp-active");
            if ( matchingMethod === 0){ $( "#mdp-assign-box .mdp-matching-method .mdp-button-group .mdp-all").addClass("mdp-active"); }
            if ( matchingMethod === 1){ $( "#mdp-assign-box .mdp-matching-method .mdp-button-group .mdp-any").addClass("mdp-active"); }

            // WordPress Content
            let WPContent = aConf.WPContent;
            let WPContentVal = aConf.WPContentVal + '';
            $( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-button" ).removeClass( "mdp-active" );
            if ( WPContent === 0 ) { $( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-ignore" ).addClass( "mdp-active" ); }
            if ( WPContent === 1 ) { $( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-include" ).addClass( "mdp-active" ); }
            if ( WPContent === 2 ) { $( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-exclude" ).addClass( "mdp-active" ); }
            let WPContentArray = WPContentVal.split( "," );
            if ( WPContentVal !== '' ) { $( "#mdp-assign-box .mdp-wp-content select.wp-content" ).val( WPContentArray ).trigger( "chosen:updated" ); }

            // Home Page
            let homePage = aConf.homePage;
            $( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-button" ).removeClass( "mdp-active" );
            if ( homePage === 0 ) { $( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-ignore").addClass("mdp-active"); }
            if ( homePage === 1 ) { $( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-include").addClass("mdp-active"); }
            if ( homePage === 2 ) { $( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-exclude").addClass("mdp-active"); }

            // Menu Items
            let menuItems = aConf.menuItems;
            let menuItemsVal = aConf.menuItemsVal + '';
            $( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-button").removeClass("mdp-active");
            if(menuItems === 0){ $( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-ignore").addClass("mdp-active"); }
            if(menuItems === 1){ $( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-include").addClass("mdp-active"); }
            if(menuItems === 2){ $( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-exclude").addClass("mdp-active"); }
            let menuItemsArray = menuItemsVal.split(",");
            if(menuItemsVal !== '') { $( "#mdp-assign-box .mdp-menu-items select.menuitems").val(menuItemsArray).trigger("chosen:updated"); }

            // Date & Time
            let dateTime = aConf.dateTime;
            let dateTimeStart = aConf.dateTimeStart;
            let dateTimeEnd = aConf.dateTimeEnd;
            $(  '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-button' ).removeClass( 'mdp-active' );
            if( dateTime === 0 ) { $(  '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' ); }
            if( dateTime === 1 ) { $(  '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-include' ).addClass( 'mdp-active' ); }
            if( dateTime === 2 ) { $(  '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-exclude' ).addClass( 'mdp-active' ); }
            $(  '#mdp-assign-box .mdp-date-time input.mdp-period-picker-start' ).val( dateTimeStart );
            $(  '#mdp-assign-box .mdp-date-time input.mdp-period-picker-end' ).val( dateTimeEnd );

            // Languages
            let languages = aConf.languages;
            let languagesVal = aConf.languagesVal + '';
            $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-button' ).removeClass( 'mdp-active' );
            if ( languages === 0 ) { $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' ); }
            if ( languages === 1 ) { $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-include' ).addClass( 'mdp-active' ); }
            if ( languages === 2 ) { $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-exclude' ).addClass( 'mdp-active' ); }
            let languagesArray = languagesVal.split( ',' );
            if ( languagesVal !== '') { $( '#mdp-assign-box .mdp-languages select.languages' ).val( languagesArray ).trigger( 'chosen:updated' ); }

            // User Roles
            let userRoles = aConf.userRoles;
            let userRolesVal = aConf.userRolesVal + '';
            $( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-button").removeClass("mdp-active");
            if(userRoles === 0){ $( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-ignore").addClass("mdp-active"); }
            if(userRoles === 1){ $( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-include").addClass("mdp-active"); }
            if(userRoles === 2){ $( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-exclude").addClass("mdp-active"); }
            let userRolesArray = userRolesVal.split(",");
            if(userRolesVal !== '') { $( "#mdp-assign-box .mdp-user-roles select.user-roles").val(userRolesArray).trigger("chosen:updated"); }

            // URL
            let URL = aConf.URL;
            let URLVal = aConf.URLVal;
            $( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-button").removeClass("mdp-active");
            if(URL === 0){ $( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-ignore").addClass("mdp-active"); }
            if(URL === 1){ $( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-include").addClass("mdp-active"); }
            if(URL === 2){ $( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-exclude").addClass("mdp-active"); }
            $( "#mdp-assign-box .mdp-url textarea.mdp-url-field").val(URLVal);

            /** Devices. */
            let devices = aConf.devices;
            let devicesVal = aConf.devicesVal + '';
            $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-button' ).removeClass( 'mdp-active' );
            if ( devices === 0) { $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' ); }
            if ( devices === 1) { $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-include' ).addClass( 'mdp-active' ); }
            if ( devices === 2) { $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-exclude' ).addClass( 'mdp-active' ); }
            let devicesArray = devicesVal.split( ',' );
            if ( devicesVal !== '' ) { $(  '#mdp-assign-box .mdp-devices select.devices' ).val( devicesArray ).trigger( 'chosen:updated' ); }

            /** Operating Systems. */
            let os = aConf.os;
            let osVal = aConf.osVal + '';
            $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-button' ).removeClass( 'mdp-active' );
            if (  os === 0 ) { $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' ); }
            if (  os === 1 ) { $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-include' ).addClass( 'mdp-active' ); }
            if (  os === 2 ) { $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-exclude' ).addClass( 'mdp-active' ); }
            let osArray = osVal.split( ',' );
            if (  osVal !== '' ) { $( '#mdp-assign-box .mdp-os select.os' ).val( osArray ).trigger( 'chosen:updated' ); }

            /** Browsers. */
            let browsers = aConf.browsers;
            let browsersVal = aConf.browsersVal + '';
            let mobileBrowsersVal = aConf.mobileBrowsersVal + '';
            $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-button' ).removeClass( 'mdp-active' );
            if (  browsers === 0 ) { $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' ); }
            if (  browsers === 1 ) { $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-include' ).addClass( 'mdp-active' ); }
            if (  browsers === 2 ) { $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-exclude' ).addClass( 'mdp-active' ); }
            let browsersArray = browsersVal.split( ',' );
            if (  browsersVal !== '' ) { $( '#mdp-assign-box .mdp-browsers select.browsers' ).val( browsersArray ).trigger( 'chosen:updated' ); }
            let mobileBrowsersArray = mobileBrowsersVal.split( ',' );
            if (  mobileBrowsersVal !== '' ) { $( '#mdp-assign-box .mdp-browsers select.mobile-browsers' ).val( mobileBrowsersArray ).trigger( 'chosen:updated' ); }

            /** IP Addresses. */
            let IPs = aConf.IPs;
            let IPsVal = aConf.IPsVal;
            $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-button' ).removeClass( 'mdp-active' );
            if ( IPs === 0 ) { $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' ); }
            if ( IPs === 1 ) { $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-include' ).addClass( 'mdp-active' ); }
            if ( IPs === 2 ) { $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-exclude' ).addClass( 'mdp-active' ); }
            $( '#mdp-assign-box .mdp-ips textarea.mdp-ips-field' ).val( IPsVal );

            /** Custom PHP. */
            let PHP = aConf.PHP;
            let PHPVal = aConf.PHPVal;
            $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-button' ).removeClass( 'mdp-active' );
            if ( PHP === 0 ) { $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' ); }
            if ( PHP === 1 ) { $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-include' ).addClass( 'mdp-active' ); }
            if ( PHP === 2 ) { $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-exclude' ).addClass( 'mdp-active' ); }
            $(  '#mdp-assign-box .mdp-php textarea.mdp-php-field' ).val( PHPVal );

        } catch (e) {

            // Reset all controls to default state
            $( "#mdp-assign-box .mdp-button-group .mdp-button").removeClass("mdp-active");

            // Matching Method
            $( "#mdp-assign-box .mdp-matching-method .mdp-button-group .mdp-all").addClass("mdp-active");

            // WordPress Content
            $( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-ignore").addClass("mdp-active");
            $( "#mdp-assign-box .mdp-wp-content select.wp-content").val("").trigger("chosen:updated");

            // Home Page
            $( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-ignore").addClass("mdp-active");

            // Menu Items
            $( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-ignore").addClass("mdp-active");
            $( "#mdp-assign-box .mdp-menu-items select.menuitems").val("").trigger("chosen:updated");

            /** Date & Time. */
            $(  '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' );
            $(  '#mdp-assign-box .mdp-date-time input.mdp-period-picker-start' ).val('');
            $(  '#mdp-assign-box .mdp-date-time input.mdp-period-picker-end' ).val('');

            /** Languages. */
            $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' );
            $( '#mdp-assign-box .mdp-languages select.languages' ).val( '' ).trigger( 'chosen:updated' );

            // User Roles
            $( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-ignore").addClass("mdp-active");
            $( "#mdp-assign-box .mdp-user-roles select.user-roles").val("").trigger("chosen:updated");

            // URL
            $( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-ignore").addClass("mdp-active");
            $( "#mdp-assign-box .mdp-url textarea.mdp-url-field").val("");

            /** Devices. */
            $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' );
            $(  '#mdp-assign-box .mdp-devices select.devices' ).val( '' ).trigger( 'chosen:updated' );

            /** Operating Systems. */
            $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' );
            $( '#mdp-assign-box .mdp-os select.os' ).val( '' ).trigger( 'chosen:updated' );

            /** Browsers. */
            $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' );
            $( '#mdp-assign-box .mdp-browsers select.browsers' ).val( '' ).trigger( 'chosen:updated' );
            $( '#mdp-assign-box .mdp-browsers select.mobile-browsers' ).val( '' ).trigger( 'chosen:updated' );

            /** IP Addresses */
            $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' );
            $( '#mdp-assign-box .mdp-ips textarea.mdp-ips-field' ).val( '' );

            /** Custom PHP. */
            $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-ignore' ).addClass( 'mdp-active' );
            $(  '#mdp-assign-box .mdp-php textarea.mdp-php-field' ).val('');

        }

    }

    /**
     * Save settings.
     **/
    function mdp_saveSettings() {

        /** Get new values */

        // Matching Method
        var matchingMethod = 0;
        if($( "#mdp-assign-box .mdp-matching-method .mdp-button-group .mdp-all").hasClass("mdp-active")) { matchingMethod = 0; }
        if($( "#mdp-assign-box .mdp-matching-method .mdp-button-group .mdp-any").hasClass("mdp-active")) { matchingMethod = 1; }

        // WordPress Content
        var WPContent = 0;
        if($( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-ignore").hasClass("mdp-active")) { WPContent = 0; }
        if($( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-include").hasClass("mdp-active")) { WPContent = 1; }
        if($( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-exclude").hasClass("mdp-active")) { WPContent = 2; }

        var WPContentVal = '';
        if(WPContent){
            WPContentVal = $( "#mdp-assign-box .mdp-wp-content select.wp-content").val();
        }

        // Home Page
        var homePage = 0;
        if($( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-ignore").hasClass("mdp-active")) { homePage = 0; }
        if($( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-include").hasClass("mdp-active")) { homePage = 1; }
        if($( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-exclude").hasClass("mdp-active")) { homePage = 2; }

        // Menu Items
        var menuItems = 0;
        if($( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-ignore").hasClass("mdp-active")) { menuItems = 0; }
        if($( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-include").hasClass("mdp-active")) { menuItems = 1; }
        if($( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-exclude").hasClass("mdp-active")) { menuItems = 2; }

        var menuItemsVal = '';
        if(menuItems){
            menuItemsVal = $( "#mdp-assign-box .mdp-menu-items select.menuitems").val();
        }

        /** Date & Time. */
        var dateTime = 0;
        if ( $(  '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-ignore' ).hasClass( 'mdp-active' ) ) { dateTime = 0 }
        if ( $(  '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-include' ).hasClass( 'mdp-active' ) ) { dateTime = 1 }
        if ( $(  '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-exclude' ).hasClass( 'mdp-active' ) ) { dateTime = 2 }

        var dateTimeStart = '';
        var dateTimeEnd = '';
        if( dateTime ) {
            dateTimeStart = $(  '#mdp-assign-box .mdp-date-time input.mdp-period-picker-start' ).val();
            dateTimeEnd = $(  '#mdp-assign-box .mdp-date-time input.mdp-period-picker-end' ).val();
        }

        // Languages
        let languages = 0;
        if ( $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-ignore' ).hasClass( 'mdp-active' ) ) { languages = 0; }
        if ( $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-include' ).hasClass( 'mdp-active' ) ) { languages = 1; }
        if ( $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-exclude' ).hasClass( 'mdp-active' ) ) { languages = 2; }
        let languagesVal = '';
        if ( languages ) { languagesVal = $( '#mdp-assign-box .mdp-languages select.languages' ).val(); }

        // User Roles
        var userRoles = 0;
        if($( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-ignore").hasClass("mdp-active")) { userRoles = 0; }
        if($( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-include").hasClass("mdp-active")) { userRoles = 1; }
        if($( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-exclude").hasClass("mdp-active")) { userRoles = 2; }

        var userRolesVal = '';
        if(userRoles){
            userRolesVal = $( "#mdp-assign-box .mdp-user-roles select.user-roles").val();
        }

        // URL
        var URL = 0;
        if($( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-ignore").hasClass("mdp-active")) { URL = 0; }
        if($( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-include").hasClass("mdp-active")) { URL = 1; }
        if($( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-exclude").hasClass("mdp-active")) { URL = 2; }

        var URLVal = '';
        if(URL){
            URLVal = $( "#mdp-assign-box .mdp-url textarea.mdp-url-field").val();
        }

        /** Devices. */
        var devices = 0;
        if ( $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-ignore' ).hasClass( 'mdp-active' ) ) { devices = 0; }
        if ( $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-include' ).hasClass( 'mdp-active' ) ) { devices = 1; }
        if ( $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-exclude' ).hasClass( 'mdp-active' ) ) { devices = 2; }

        var devicesVal = '';
        if( devices ){
            devicesVal = $(  '#mdp-assign-box .mdp-devices select.devices' ).val();
        }

        /** Operating Systems. */
        let os = 0;
        if (  $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-ignore' ).hasClass( 'mdp-active' ) ) { os = 0; }
        if (  $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-include' ).hasClass( 'mdp-active' ) ) { os = 1; }
        if (  $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-exclude' ).hasClass( 'mdp-active' ) ) { os = 2; }
        let osVal = '';
        if ( os ) { osVal = $( '#mdp-assign-box .mdp-os select.os' ).val(); }

        /** Browsers. */
        let browsers = 0;
        if (  $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-ignore' ).hasClass( 'mdp-active' ) ) { browsers = 0; }
        if (  $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-include' ).hasClass( 'mdp-active' ) ) { browsers = 1; }
        if (  $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-exclude' ).hasClass( 'mdp-active' ) ) { browsers = 2; }

        let browsersVal = '';
        let mobileBrowsersVal = '';
        if ( browsers ) {
          browsersVal = $( '#mdp-assign-box .mdp-browsers select.browsers' ).val();
          mobileBrowsersVal = $( '#mdp-assign-box .mdp-browsers select.mobile-browsers' ).val();
        }

        /** IP Addresses */
        let IPs = 0;
        if ( $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-ignore' ).hasClass( 'mdp-active' ) ) { IPs = 0; }
        if ( $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-include' ).hasClass( 'mdp-active' ) ) { IPs = 1; }
        if ( $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-exclude' ).hasClass( 'mdp-active' ) ) { IPs = 2; }
        let IPsVal = '';
        if ( IPs ) { IPsVal = $( '#mdp-assign-box .mdp-ips textarea.mdp-ips-field' ).val(); }

        /** Custom PHP. */
        var PHP = 0;
        if( $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-ignore' ).hasClass( 'mdp-active' ) ) { PHP = 0; }
        if( $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-include' ).hasClass( 'mdp-active' ) ) { PHP = 1; }
        if( $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-exclude' ).hasClass( 'mdp-active' ) ) { PHP = 2; }

        var PHPVal = '';
        if( PHP ) {
            PHPVal = $(  '#mdp-assign-box .mdp-php textarea.mdp-php-field' ).val();
        }

        var aConf = {
            matchingMethod: matchingMethod,
            WPContent: WPContent,
            WPContentVal: WPContentVal,
            homePage: homePage,
            menuItems: menuItems,
            menuItemsVal: menuItemsVal,
            dateTime: dateTime,
            dateTimeStart: dateTimeStart,
            dateTimeEnd: dateTimeEnd,
            languages: languages,
            languagesVal: languagesVal,
            userRoles: userRoles,
            userRolesVal: userRolesVal,
            URL: URL,
            URLVal: URLVal,
            devices: devices,
            devicesVal: devicesVal,
            os: os,
            osVal: osVal,
            browsers: browsers,
            browsersVal: browsersVal,
            mobileBrowsersVal: mobileBrowsersVal,
            IPs: IPs,
            IPsVal: IPsVal,
            PHP: PHP,
            PHPVal: PHPVal
        };

        let aConfJson = JSON.stringify(aConf);
        aConfJson = aConfJson.replace(/\"/g, '|');// Input truncate quotes, so made some replacements

        assignInput.val( aConfJson );// Set setting to input
        assignInput.change();

    }

    /**
     * Initialization.
     **/
    function mdp_assignment_ini() {

        /** Periodpicker. */
        $(  '#mdp-assign-box .mdp-date-time .mdp-period-picker-start' ).periodpicker( {
            end: '#mdp-period-picker-end',
            todayButton: true,
            formatDate: 'D.MM.YYYY',
            timepicker: true,
            timepickerOptions: {
                twelveHoursFormat: false,
                hours: true,
                minutes: true,
                seconds: false,
                ampm: false
            }
        } );

        /** Make select boxes more user-friendly - Chosen. */
        $( "#mdp-assign-box select.chosen-select").chosen({
            width:'100%',
            search_contains: true,
            disable_search_threshold: 7,
            inherit_select_classes: true,
            no_results_text: "Oops, nothing found"
        });

        /** Show/Hide unused controls. */
        $(  '#mdp-assign-box .mdp-button.mdp-active' ).click();

    }

    /**
     * Matching Method click.
     **/
    $( "#mdp-assign-box .mdp-matchingMethod .mdp-button").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-matchingMethod button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        mdp_saveSettings();
    });

    /**
     * Menu Items Ignore click.
     **/
    $( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-ignore").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-menu-items button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( "#mdp-assign-box .mdp-menu-items .mdp-menuitems-selection").hide(200);
        $( this ).closest(".mdp-menu-items").removeClass("mdp-red mdp-green");
        mdp_saveSettings();
    });

    /**
     * Menu Items Include click.
     **/
    $( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-include").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-menu-items button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( "#mdp-assign-box .mdp-menu-items .mdp-menuitems-selection").show(200);
        $( this ).closest(".mdp-menu-items").removeClass("mdp-red").addClass("mdp-green");
        mdp_saveSettings();
    });

    /**
     * Menu Items Exclude click.
     **/
    $( "#mdp-assign-box .mdp-menu-items .mdp-button-group .mdp-exclude").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-menu-items button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( "#mdp-assign-box .mdp-menu-items .mdp-menuitems-selection").show(200);
        $( this ).closest(".mdp-menu-items").removeClass("mdp-green").addClass("mdp-red");
        mdp_saveSettings();
    });

    /**
     * Date & Time IGNORE click
     **/
    $(  '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-ignore' ).on( 'click', function ( e ) {
        e.preventDefault();
        $(  '#mdp-assign-box .mdp-date-time button' ).removeClass( 'mdp-active' );
        $(  this ) .addClass( 'mdp-active' );
        $(  this ).closest( '.mdp-date-time' ).removeClass( 'mdp-green mdp-red' );
        $(  '#mdp-assign-box .mdp-date-time .mdp-period-picker-box' ).hide( 200 );
        mdp_saveSettings();
    } );

    /**
     * Date & Time INCLUDE click
     **/
    $(  '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-include' ).on( 'click', function ( e ) {
        e.preventDefault();
        $(  '#mdp-assign-box .mdp-date-time button' ).removeClass( 'mdp-active' );
        $(  this ) .addClass( 'mdp-active' );
        $(  this ).closest( '.mdp-date-time' ).removeClass( 'mdp-red' ).addClass( 'mdp-green' );
        $(  '#mdp-assign-box .mdp-date-time .mdp-period-picker-box' ).show( 200 );
        mdp_saveSettings();
    } );

    /**
     * Date & Time EXCLUDE click
     **/
    $( '#mdp-assign-box .mdp-date-time .mdp-button-group .mdp-exclude' ).on( 'click', function ( e ) {
        e.preventDefault();
        $( '#mdp-assign-box .mdp-date-time button' ).removeClass( 'mdp-active' );
        $( this ).addClass( 'mdp-active' );
        $( this ).closest( '.mdp-date-time' ).removeClass( 'mdp-green' ).addClass( 'mdp-red' );
        $( '#mdp-assign-box .mdp-date-time .mdp-period-picker-box' ).show( 200 );
        mdp_saveSettings();
    } );

    /**
     * Languages Ignore click.
     **/
    $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-ignore' ).on( 'click', function ( e ) {
        e.preventDefault();
        $( '#mdp-assign-box .mdp-languages button' ).removeClass( 'mdp-active' );
        $( this ).addClass( 'mdp-active' );
        $( '#mdp-assign-box .mdp-languages .languages-box' ).hide( 200 );
        $( this ).closest( '.mdp-languages' ).removeClass( 'mdp-red mdp-green' );
        mdp_saveSettings();
    } );

    /**
     * Languages Include click.
     **/
    $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-include' ).on( 'click', function (e) {
        e.preventDefault();
        $( '#mdp-assign-box .mdp-languages button' ).removeClass( 'mdp-active' );
        $(this ).addClass( 'mdp-active' );
        $( '#mdp-assign-box .mdp-languages .languages-box' ).show(200);
        $(this ).closest( '.mdp-languages' ).removeClass( 'mdp-red' ).addClass( 'mdp-green' );
        mdp_saveSettings();
    });

    /**
     * Languages Exclude click.
     **/
    $( '#mdp-assign-box .mdp-languages .mdp-button-group .mdp-exclude' ).on( 'click', function (e) {
      e.preventDefault();
      $( '#mdp-assign-box .mdp-languages button' ).removeClass( 'mdp-active' );
      $(this ).addClass( 'mdp-active' );
      $( '#mdp-assign-box .mdp-languages .languages-box' ).show(200);
      $(this ).closest( '.mdp-languages' ).removeClass( 'mdp-green' ).addClass( 'mdp-red' );
      mdp_saveSettings();
    } );

    /**
     * User Roles Ignore click.
     **/
    $( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-ignore").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-user-roles button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( "#mdp-assign-box .mdp-user-roles .user-roles-box").hide(200);
        $( this ).closest(".mdp-user-roles").removeClass("mdp-red mdp-green");
        mdp_saveSettings();
    } );

    /**
     * User Roles Include click.
     **/
    $( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-include").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-user-roles button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( "#mdp-assign-box .mdp-user-roles .user-roles-box").show(200);
        $( this ).closest(".mdp-user-roles").removeClass("mdp-red").addClass("mdp-green");
        mdp_saveSettings();
    });

    /**
     * User Roles Exclude click.
     **/
    $( "#mdp-assign-box .mdp-user-roles .mdp-button-group .mdp-exclude").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-user-roles button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( "#mdp-assign-box .mdp-user-roles .user-roles-box").show(200);
        $( this ).closest(".mdp-user-roles").removeClass("mdp-green").addClass("mdp-red");
        mdp_saveSettings();
    });

    /**
     * Home Page IGNORE click.
     **/
    $( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-ignore").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-home-page .mdp-button-group button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( this ).closest(".mdp-home-page").removeClass("mdp-green mdp-red");
        mdp_saveSettings();
    });

    /**
     * Home Page INCLUDE click.
     **/
    $( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-include").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-home-page .mdp-button-group button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( this ).closest(".mdp-home-page").removeClass("mdp-red").addClass("mdp-green");
        mdp_saveSettings();
    });

    /**
     * Home Page EXCLUDE click.
     **/
    $( "#mdp-assign-box .mdp-home-page .mdp-button-group .mdp-exclude").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-home-page .mdp-button-group button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( this ).closest(".mdp-home-page").removeClass("mdp-green").addClass("mdp-red");
        mdp_saveSettings();
    });

    /**
     * URL IGNORE click.
     **/
    $( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-ignore").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-url button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( this ).closest(".mdp-url").removeClass("mdp-green mdp-red");
        $( "#mdp-assign-box .mdp-url .mdp-url-box").hide(200);
        mdp_saveSettings();
    });

    /**
     * URL INCLUDE click.
     **/
    $( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-include").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-url button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( this ).closest(".mdp-url").removeClass("mdp-red").addClass("mdp-green");
        $( "#mdp-assign-box .mdp-url .mdp-url-box").show(200);
        mdp_saveSettings();
    });

    /**
     * URL EXCLUDE click.
     **/
    $( "#mdp-assign-box .mdp-url .mdp-button-group .mdp-exclude").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-url button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( this ).closest(".mdp-url").removeClass("mdp-green").addClass("mdp-red");
        $( "#mdp-assign-box .mdp-url .mdp-url-box").show(200);
        mdp_saveSettings();
    });

    /**
     * WordPress Content IGNORE click.
     **/
    $( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-ignore").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-wp-content button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( this ).closest(".mdp-wp-content").removeClass("mdp-green mdp-red");
        $( "#mdp-assign-box .mdp-wp-content .mdp-wp-content-box").hide(200);
        mdp_saveSettings();
    });

    /**
     * WordPress Content INCLUDE click.
     **/
    $( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-include").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-wp-content button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( this ).closest(".mdp-wp-content").removeClass("mdp-red").addClass("mdp-green");
        $( "#mdp-assign-box .mdp-wp-content .mdp-wp-content-box").show(200);
        mdp_saveSettings();
    });

    /**
     * WordPress Content EXCLUDE click.
     **/
    $( "#mdp-assign-box .mdp-wp-content .mdp-button-group .mdp-exclude").on( 'click', function ( e ) {
        e.preventDefault();
        $( "#mdp-assign-box .mdp-wp-content button").removeClass("mdp-active");
        $( this ).addClass("mdp-active");
        $( this ).closest(".mdp-wp-content").removeClass("mdp-green").addClass("mdp-red");
        $( "#mdp-assign-box .mdp-wp-content .mdp-wp-content-box").show(200);
        mdp_saveSettings();
    });

    /**
     * Devices Ignore click.
     **/
    $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-ignore' ).on( 'click', function ( e ) {
        e.preventDefault();
        $(  '#mdp-assign-box .mdp-devices button' ).removeClass( 'mdp-active' );
        $(  this ).addClass( 'mdp-active' );
        $(  '#mdp-assign-box .mdp-devices .mdp-devices-box' ).hide( 200 );
        $(  this ).closest( '.mdp-devices' ).removeClass( 'mdp-red mdp-green' );
        mdp_saveSettings();
    });

    /**
     * Devices Include click.
     **/
    $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-include' ).on( 'click', function ( e ) {
        e.preventDefault();
        $(  '#mdp-assign-box .mdp-devices button' ).removeClass( 'mdp-active' );
        $(  this ).addClass( 'mdp-active' );
        $(  '#mdp-assign-box .mdp-devices .mdp-devices-box' ).show( 200 );
        $(  this ).closest( '.mdp-devices' ).removeClass( 'mdp-red' ).addClass( 'mdp-green' );
        mdp_saveSettings();
    });

    /**
     * Devices Exclude click.
     **/
    $(  '#mdp-assign-box .mdp-devices .mdp-button-group .mdp-exclude' ).on( 'click', function ( e ) {
        e.preventDefault();
        $(  '#mdp-assign-box .mdp-devices button' ).removeClass( 'mdp-active' );
        $(  this ).addClass( 'mdp-active' );
        $(  '#mdp-assign-box .mdp-devices .mdp-devices-box' ).show( 200 );
        $(  this ).closest( '.mdp-devices' ).removeClass( 'mdp-green' ).addClass( 'mdp-red' );
        mdp_saveSettings();
    });

    /**
     * Operating Systems Ignore click.
     **/
    $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-ignore' ).on( 'click', function ( e ) {
      e.preventDefault();
      $( '#mdp-assign-box .mdp-os button' ).removeClass( 'mdp-active' );
      $( this ).addClass( 'mdp-active' );
      $( '#mdp-assign-box .mdp-os .mdp-os-box' ).hide( 200 );
      $( this ).closest( '.mdp-os' ).removeClass( 'mdp-red mdp-green' );
      mdp_saveSettings();
    });

    /**
     * Operating Systems Include click.
     **/
    $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-include' ).on( 'click', function ( e ) {
      e.preventDefault();
      $( '#mdp-assign-box .mdp-os button' ).removeClass( 'mdp-active' );
      $( this ).addClass( 'mdp-active' );
      $( '#mdp-assign-box .mdp-os .mdp-os-box' ).show( 200 );
      $( this ).closest( '.mdp-os' ).removeClass( 'mdp-red' ).addClass( 'mdp-green' );
      mdp_saveSettings();
    });

    /**
     * Operating Systems Exclude click.
     **/
    $( '#mdp-assign-box .mdp-os .mdp-button-group .mdp-exclude' ).on( 'click', function ( e ) {
      e.preventDefault();
      $( '#mdp-assign-box .mdp-os button' ).removeClass( 'mdp-active' );
      $( this ).addClass( 'mdp-active' );
      $( '#mdp-assign-box .mdp-os .mdp-os-box' ).show( 200 );
      $( this ).closest( '.mdp-os' ).removeClass( 'mdp-green' ).addClass( 'mdp-red' );
      mdp_saveSettings();
    });

    /**
     * Browsers Ignore click.
     **/
    $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-ignore' ).on( 'click', function ( e ) {
      e.preventDefault();
      $( '#mdp-assign-box .mdp-browsers button' ).removeClass( 'mdp-active' );
      $( this ).addClass( 'mdp-active' );
      $( '#mdp-assign-box .mdp-browsers .mdp-browsers-box' ).hide( 200 );
      $( this ).closest( '.mdp-browsers' ).removeClass( 'mdp-red mdp-green' );
      mdp_saveSettings();
    });

    /**
     * Browsers Include click.
     **/
    $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-include' ).on( 'click', function ( e ) {
      e.preventDefault();
      $( '#mdp-assign-box .mdp-browsers button' ).removeClass( 'mdp-active' );
      $( this ).addClass( 'mdp-active' );
      $( '#mdp-assign-box .mdp-browsers .mdp-browsers-box' ).show( 200 );
      $( this ).closest( '.mdp-browsers' ).removeClass( 'mdp-red' ).addClass( 'mdp-green' );
      mdp_saveSettings();
    });

    /**
     * Browsers Exclude click.
     **/
    $( '#mdp-assign-box .mdp-browsers .mdp-button-group .mdp-exclude' ).on( 'click', function ( e ) {
      e.preventDefault();
      $( '#mdp-assign-box .mdp-browsers button' ).removeClass( 'mdp-active' );
      $( this ).addClass( 'mdp-active' );
      $( '#mdp-assign-box .mdp-browsers .mdp-browsers-box' ).show( 200 );
      $( this ).closest( '.mdp-browsers' ).removeClass( 'mdp-green' ).addClass( 'mdp-red' );
      mdp_saveSettings();
    });

    /**
     * IPs IGNORE click.
     **/
    $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-ignore' ).on( 'click', function (e) {
      e.preventDefault();
      $( '#mdp-assign-box .mdp-ips button' ).removeClass( 'mdp-active' );
      $(this ).addClass( 'mdp-active' );
      $(this ).closest( '.mdp-ips' ).removeClass( 'mdp-green mdp-red' );
      $( '#mdp-assign-box .mdp-ips .mdp-ips-box' ).hide(200);
      mdp_saveSettings();
    } );

    /**
     * IPs INCLUDE click.
     **/
    $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-include' ).on( 'click', function (e) {
      e.preventDefault();
      $( '#mdp-assign-box .mdp-ips button' ).removeClass( 'mdp-active' );
      $(this ).addClass( 'mdp-active' );
      $(this ).closest( '.mdp-ips' ).removeClass( 'mdp-red' ).addClass( 'mdp-green' );
      $( '#mdp-assign-box .mdp-ips .mdp-ips-box' ).show(200);
      mdp_saveSettings();
    } );

    /**
     * IPs EXCLUDE click.
     **/
    $( '#mdp-assign-box .mdp-ips .mdp-button-group .mdp-exclude' ).on( 'click', function (e) {
      e.preventDefault();
      $( '#mdp-assign-box .mdp-ips button' ).removeClass( 'mdp-active' );
      $(this ).addClass( 'mdp-active' );
      $(this ).closest( '.mdp-ips' ).removeClass( 'mdp-green' ).addClass( 'mdp-red' );
      $( '#mdp-assign-box .mdp-ips .mdp-ips-box' ).show(200);
      mdp_saveSettings();
    } );

    /** Custom PHP IGNORE click. */
    $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-ignore' ).on( 'click', function ( e ){
        e.preventDefault();
        $(  '#mdp-assign-box .mdp-php button' ).removeClass( 'mdp-active' );
        $(  this ).addClass( 'mdp-active' );
        $(  this ).closest( '.mdp-php' ).removeClass( 'mdp-green mdp-red' );
        $(  '#mdp-assign-box .mdp-php .mdp-php-box' ).hide( 200 );
        mdp_saveSettings();
    });

    /** Custom PHP INCLUDE click. */
    $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-include' ).on( 'click', function ( e ){
        e.preventDefault();
        $(  '#mdp-assign-box .mdp-php button' ).removeClass( 'mdp-active' );
        $(  this ).addClass( 'mdp-active' );
        $(  this ).closest( '.mdp-php' ).removeClass( 'mdp-red' ).addClass( 'mdp-green' );
        $(  '#mdp-assign-box .mdp-php .mdp-php-box' ).show( 200 );
        mdp_saveSettings();
    });

    /** Custom PHP EXCLUDE click. */
    $(  '#mdp-assign-box .mdp-php .mdp-button-group .mdp-exclude' ).on( 'click', function ( e ){
        e.preventDefault();
        $(  '#mdp-assign-box .mdp-php button' ).removeClass( 'mdp-active' );
        $(  this ).addClass( 'mdp-active' );
        $(  this ).closest( '.mdp-php' ).removeClass( 'mdp-green' ).addClass( 'mdp-red' );
        $(  '#mdp-assign-box .mdp-php .mdp-php-box' ).show( 200 );
        mdp_saveSettings();
    });

    /**
     * Save value in field on change.
     **/
    $( 'select.wp-content, ' +
       'select.menuitems, ' +
       '.mdp-period-picker-start, ' +
       '.mdp-period-picker-end, ' +
       'select.languages,  ' +
       'select.user-roles, ' +
       'textarea.mdp-url-field, ' +
       'select.devices, ' +
       'select.os, ' +
       'select.browsers, ' +
       'select.mobile-browsers, ' +
       'textarea.mdp-ips-field, ' +
       'textarea.mdp-php-field' ).on( 'input propertychange', function () {
        mdp_saveSettings();
    } );

    $(  document ).ready( function () {

        /** Show warning for unsaved data in form. */
        let unsaved = false;

        /** Triggers change in all input fields including text type. */
        $(  ':input' ).on( 'change', function() { unsaved = true; } );

        /** Show warning if form not saved. */
        window.addEventListener( 'beforeunload', function( event ) {
            if ( unsaved ) {
                event.returnValue = 'Are you sure you want to leave?';
            }
        } );

        /** PHP Code Editor. */
        let phpEditor;

        /** Disable unsaved form warning and save settings. */
        $(  "button[name='submit'], [type='submit']" ).on( 'click', function() {
            if ( phpEditor ) {
                phpEditor.codemirror.save(); // Save data from CodeEditor to textarea.
                mdp_saveSettings();
            }

            unsaved = false;
        } );

        mdp_readSettings();
        mdp_assignment_ini();

        /** Initialize Code Editor. */
        if ( $( '#mdp-php-field' ).length && wp.codeEditor ) {
            phpEditor = wp.codeEditor.initialize( 'mdp-php-field' );
        }

        unsaved = false;

    } );

} );
