var H5P = H5P || {};

/**
 * Constructor.
 *
 * @param {Object} params Options for this library.
 * @param {Number} id Content identifier
 * @returns {undefined}
 */
(function ($) {
  H5P.Image = function (params, id, extras) {
    H5P.EventDispatcher.call(this);
    this.extras = extras;

    if (params.file === undefined || !(params.file instanceof Object)) {
      this.placeholder = true;
    }
    else {
      this.source = H5P.getPath(params.file.path, id);
      this.width = params.file.width;
      this.height = params.file.height;
    }

    this.alt = (!params.decorative && params.alt !== undefined) ?
      this.stripHTML(this.htmlDecode(params.alt)) :
      '';

    if (params.title !== undefined) {
      this.title = this.stripHTML(this.htmlDecode(params.title));
    }
  };

  H5P.Image.prototype = Object.create(H5P.EventDispatcher.prototype);
  H5P.Image.prototype.constructor = H5P.Image;

  /**
   * Wipe out the content of the wrapper and put our HTML in it.
   *
   * @param {jQuery} $wrapper
   * @returns {undefined}
   */
  H5P.Image.prototype.attach = function ($wrapper) {
    var self = this;
    var source = this.source;

    if (self.$img === undefined) {
      if(self.placeholder) {
        self.$img = $('<div>', {
          width: '100%',
          height: '100%',
          class: 'h5p-placeholder',
          title: this.title === undefined ? '' : this.title,
          on: {
            load: function () {
              self.trigger('loaded');
            }
          }
        });
      } else {
        self.$img = $('<img>', {
          width: '100%',
          height: '100%',
          src: source,
          alt: this.alt,
          title: this.title === undefined ? '' : this.title,
          on: {
            load: function () {
              self.trigger('loaded');
            }
          }
        });
      }
    }

    $wrapper.addClass('h5p-image').html(self.$img);
  };

  /**
   * Retrieve decoded HTML encoded string.
   *
   * @param {string} input HTML encoded string.
   * @returns {string} Decoded string.
   */
  H5P.Image.prototype.htmlDecode = function (input) {
    const dparser = new DOMParser().parseFromString(input, 'text/html');
    return dparser.documentElement.textContent;
  };

  /**
   * Retrieve string without HTML tags.
   *
   * @param {string} input Input string.
   * @returns {string} Output string.
   */
  H5P.Image.prototype.stripHTML = function (html) {
    const div = document.createElement('div');
    div.innerHTML = html;
    return div.textContent || div.innerText || '';
  };

  return H5P.Image;
}(H5P.jQuery));
;var H5P = H5P || {};
/**
 * Transition contains helper function relevant for transitioning
 */
H5P.Transition = (function ($) {

  /**
   * @class
   * @namespace H5P
   */
  Transition = {};

  /**
   * @private
   */
  Transition.transitionEndEventNames = {
    'WebkitTransition': 'webkitTransitionEnd',
    'transition':       'transitionend',
    'MozTransition':    'transitionend',
    'OTransition':      'oTransitionEnd',
    'msTransition':     'MSTransitionEnd'
  };

  /**
   * @private
   */
  Transition.cache = [];

  /**
   * Get the vendor property name for an event
   *
   * @function H5P.Transition.getVendorPropertyName
   * @static
   * @private
   * @param  {string} prop Generic property name
   * @return {string}      Vendor specific property name
   */
  Transition.getVendorPropertyName = function (prop) {

    if (Transition.cache[prop] !== undefined) {
      return Transition.cache[prop];
    }

    var div = document.createElement('div');

    // Handle unprefixed versions (FF16+, for example)
    if (prop in div.style) {
      Transition.cache[prop] = prop;
    }
    else {
      var prefixes = ['Moz', 'Webkit', 'O', 'ms'];
      var prop_ = prop.charAt(0).toUpperCase() + prop.substr(1);

      if (prop in div.style) {
        Transition.cache[prop] = prop;
      }
      else {
        for (var i = 0; i < prefixes.length; ++i) {
          var vendorProp = prefixes[i] + prop_;
          if (vendorProp in div.style) {
            Transition.cache[prop] = vendorProp;
            break;
          }
        }
      }
    }

    return Transition.cache[prop];
  };

  /**
   * Get the name of the transition end event
   *
   * @static
   * @private
   * @return {string}  description
   */
  Transition.getTransitionEndEventName = function () {
    return Transition.transitionEndEventNames[Transition.getVendorPropertyName('transition')] || undefined;
  };

  /**
   * Helper function for listening on transition end events
   *
   * @function H5P.Transition.onTransitionEnd
   * @static
   * @param  {domElement} $element The element which is transitioned
   * @param  {function} callback The callback to be invoked when transition is finished
   * @param  {number} timeout  Timeout in milliseconds. Fallback if transition event is never fired
   */
  Transition.onTransitionEnd = function ($element, callback, timeout) {
    // Fallback on 1 second if transition event is not supported/triggered
    timeout = timeout || 1000;
    Transition.transitionEndEventName = Transition.transitionEndEventName || Transition.getTransitionEndEventName();
    var callbackCalled = false;

    var doCallback = function () {
      if (callbackCalled) {
        return;
      }
      $element.off(Transition.transitionEndEventName, callback);
      callbackCalled = true;
      clearTimeout(timer);
      callback();
    };

    var timer = setTimeout(function () {
      doCallback();
    }, timeout);

    $element.on(Transition.transitionEndEventName, function () {
      doCallback();
    });
  };

  /**
   * Wait for a transition - when finished, invokes next in line
   *
   * @private
   *
   * @param {Object[]}    transitions             Array of transitions
   * @param {H5P.jQuery}  transitions[].$element  Dom element transition is performed on
   * @param {number=}     transitions[].timeout   Timeout fallback if transition end never is triggered
   * @param {bool=}       transitions[].break     If true, sequence breaks after this transition
   * @param {number}      index                   The index for current transition
   */
  var runSequence = function (transitions, index) {
    if (index >= transitions.length) {
      return;
    }

    var transition = transitions[index];
    H5P.Transition.onTransitionEnd(transition.$element, function () {
      if (transition.end) {
        transition.end();
      }
      if (transition.break !== true) {
        runSequence(transitions, index+1);
      }
    }, transition.timeout || undefined);
  };

  /**
   * Run a sequence of transitions
   *
   * @function H5P.Transition.sequence
   * @static
   * @param {Object[]}    transitions             Array of transitions
   * @param {H5P.jQuery}  transitions[].$element  Dom element transition is performed on
   * @param {number=}     transitions[].timeout   Timeout fallback if transition end never is triggered
   * @param {bool=}       transitions[].break     If true, sequence breaks after this transition
   */
  Transition.sequence = function (transitions) {
    runSequence(transitions, 0);
  };

  return Transition;
})(H5P.jQuery);
;var H5P = H5P || {};

/**
 * Class responsible for creating a help text dialog
 */
H5P.JoubelHelpTextDialog = (function ($) {

  var numInstances = 0;
  /**
   * Display a pop-up containing a message.
   *
   * @param {H5P.jQuery}  $container  The container which message dialog will be appended to
   * @param {string}      message     The message
   * @param {string}      closeButtonTitle The title for the close button
   * @return {H5P.jQuery}
   */
  function JoubelHelpTextDialog(header, message, closeButtonTitle) {
    H5P.EventDispatcher.call(this);

    var self = this;

    numInstances++;
    var headerId = 'joubel-help-text-header-' + numInstances;
    var helpTextId = 'joubel-help-text-body-' + numInstances;

    var $helpTextDialogBox = $('<div>', {
      'class': 'joubel-help-text-dialog-box',
      'role': 'dialog',
      'aria-labelledby': headerId,
      'aria-describedby': helpTextId
    });

    $('<div>', {
      'class': 'joubel-help-text-dialog-background'
    }).appendTo($helpTextDialogBox);

    var $helpTextDialogContainer = $('<div>', {
      'class': 'joubel-help-text-dialog-container'
    }).appendTo($helpTextDialogBox);

    $('<div>', {
      'class': 'joubel-help-text-header',
      'id': headerId,
      'role': 'header',
      'html': header
    }).appendTo($helpTextDialogContainer);

    $('<div>', {
      'class': 'joubel-help-text-body',
      'id': helpTextId,
      'html': message,
      'role': 'document',
      'tabindex': 0
    }).appendTo($helpTextDialogContainer);

    var handleClose = function () {
      $helpTextDialogBox.remove();
      self.trigger('closed');
    };

    var $closeButton = $('<div>', {
      'class': 'joubel-help-text-remove',
      'role': 'button',
      'title': closeButtonTitle,
      'tabindex': 1,
      'click': handleClose,
      'keydown': function (event) {
        // 32 - space, 13 - enter
        if ([32, 13].indexOf(event.which) !== -1) {
          event.preventDefault();
          handleClose();
        }
      }
    }).appendTo($helpTextDialogContainer);

    /**
     * Get the DOM element
     * @return {HTMLElement}
     */
    self.getElement = function () {
      return $helpTextDialogBox;
    };

    self.focus = function () {
      $closeButton.focus();
    };
  }

  JoubelHelpTextDialog.prototype = Object.create(H5P.EventDispatcher.prototype);
  JoubelHelpTextDialog.prototype.constructor = JoubelHelpTextDialog;

  return JoubelHelpTextDialog;
}(H5P.jQuery));
;var H5P = H5P || {};

/**
 * Class responsible for creating auto-disappearing dialogs
 */
H5P.JoubelMessageDialog = (function ($) {

  /**
   * Display a pop-up containing a message.
   *
   * @param {H5P.jQuery} $container The container which message dialog will be appended to
   * @param {string} message The message
   * @return {H5P.jQuery}
   */
  function JoubelMessageDialog ($container, message) {
    var timeout;

    var removeDialog = function () {
      $warning.remove();
      clearTimeout(timeout);
      $container.off('click.messageDialog');
    };

    // Create warning popup:
    var $warning = $('<div/>', {
      'class': 'joubel-message-dialog',
      text: message
    }).appendTo($container);

    // Remove after 3 seconds or if user clicks anywhere in $container:
    timeout = setTimeout(removeDialog, 3000);
    $container.on('click.messageDialog', removeDialog);

    return $warning;
  }

  return JoubelMessageDialog;
})(H5P.jQuery);
;var H5P = H5P || {};

/**
 * Class responsible for creating a circular progress bar
 */

H5P.JoubelProgressCircle = (function ($) {

  /**
   * Constructor for the Progress Circle
   *
   * @param {Number} number The amount of progress to display
   * @param {string} progressColor Color for the progress meter
   * @param {string} backgroundColor Color behind the progress meter
   */
  function ProgressCircle(number, progressColor, fillColor, backgroundColor) {
    progressColor = progressColor || '#1a73d9';
    fillColor = fillColor || '#f0f0f0';
    backgroundColor = backgroundColor || '#ffffff';
    var progressColorRGB = this.hexToRgb(progressColor);

    //Verify number
    try {
      number = Number(number);
      if (number === '') {
        throw 'is empty';
      }
      if (isNaN(number)) {
        throw 'is not a number';
      }
    } catch (e) {
      number = 'err';
    }

    //Draw circle
    if (number > 100) {
      number = 100;
    }

    // We can not use rgba, since they will stack on top of each other.
    // Instead we create the equivalent of the rgba color
    // and applies this to the activeborder and background color.
    var progressColorString = 'rgb(' + parseInt(progressColorRGB.r, 10) +
      ',' + parseInt(progressColorRGB.g, 10) +
      ',' + parseInt(progressColorRGB.b, 10) + ')';

    // Circle wrapper
    var $wrapper = $('<div/>', {
      'class': "joubel-progress-circle-wrapper"
    });

    //Active border indicates progress
    var $activeBorder = $('<div/>', {
      'class': "joubel-progress-circle-active-border"
    }).appendTo($wrapper);

    //Background circle
    var $backgroundCircle = $('<div/>', {
      'class': "joubel-progress-circle-circle"
    }).appendTo($activeBorder);

    //Progress text/number
    $('<span/>', {
      'text': number + '%',
      'class': "joubel-progress-circle-percentage"
    }).appendTo($backgroundCircle);

    var deg = number * 3.6;
    if (deg <= 180) {
      $activeBorder.css('background-image',
        'linear-gradient(' + (90 + deg) + 'deg, transparent 50%, ' + fillColor + ' 50%),' +
        'linear-gradient(90deg, ' + fillColor + ' 50%, transparent 50%)')
        .css('border', '2px solid' + backgroundColor)
        .css('background-color', progressColorString);
    } else {
      $activeBorder.css('background-image',
        'linear-gradient(' + (deg - 90) + 'deg, transparent 50%, ' + progressColorString + ' 50%),' +
        'linear-gradient(90deg, ' + fillColor + ' 50%, transparent 50%)')
        .css('border', '2px solid' + backgroundColor)
        .css('background-color', progressColorString);
    }

    this.$activeBorder = $activeBorder;
    this.$backgroundCircle = $backgroundCircle;
    this.$wrapper = $wrapper;

    this.initResizeFunctionality();

    return $wrapper;
  }

  /**
   * Initializes resize functionality for the progress circle
   */
  ProgressCircle.prototype.initResizeFunctionality = function () {
    var self = this;

    $(window).resize(function () {
      // Queue resize
      setTimeout(function () {
        self.resize();
      });
    });

    // First resize
    setTimeout(function () {
      self.resize();
    }, 0);
  };

  /**
   * Resize function makes progress circle grow or shrink relative to parent container
   */
  ProgressCircle.prototype.resize = function () {
    var $parent = this.$wrapper.parent();

    if ($parent !== undefined && $parent) {

      // Measurements
      var fontSize = parseInt($parent.css('font-size'), 10);

      // Static sizes
      var fontSizeMultiplum = 3.75;
      var progressCircleWidthPx = parseInt((fontSize / 4.5), 10) % 2 === 0 ? parseInt((fontSize / 4.5), 10) + 4 : parseInt((fontSize / 4.5), 10) + 5;
      var progressCircleOffset = progressCircleWidthPx / 2;

      var width = fontSize * fontSizeMultiplum;
      var height = fontSize * fontSizeMultiplum;
      this.$activeBorder.css({
        'width': width,
        'height': height
      });

      this.$backgroundCircle.css({
        'width': width - progressCircleWidthPx,
        'height': height - progressCircleWidthPx,
        'top': progressCircleOffset,
        'left': progressCircleOffset
      });
    }
  };

  /**
   * Hex to RGB conversion
   * @param hex
   * @returns {{r: Number, g: Number, b: Number}}
   */
  ProgressCircle.prototype.hexToRgb = function (hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null;
  };

  return ProgressCircle;

}(H5P.jQuery));
;var H5P = H5P || {};

H5P.SimpleRoundedButton = (function ($) {

  /**
   * Creates a new tip
   */
  function SimpleRoundedButton(text) {

    var $simpleRoundedButton = $('<div>', {
      'class': 'joubel-simple-rounded-button',
      'title': text,
      'role': 'button',
      'tabindex': '0'
    }).keydown(function (e) {
      // 32 - space, 13 - enter
      if ([32, 13].indexOf(e.which) !== -1) {
        $(this).click();
        e.preventDefault();
      }
    });

    $('<span>', {
      'class': 'joubel-simple-rounded-button-text',
      'html': text
    }).appendTo($simpleRoundedButton);

    return $simpleRoundedButton;
  }

  return SimpleRoundedButton;
}(H5P.jQuery));
;var H5P = H5P || {};

/**
 * Class responsible for creating speech bubbles
 */
H5P.JoubelSpeechBubble = (function ($) {

  var $currentSpeechBubble;
  var $currentContainer;  
  var $tail;
  var $innerTail;
  var removeSpeechBubbleTimeout;
  var currentMaxWidth;

  var DEFAULT_MAX_WIDTH = 400;

  var iDevice = navigator.userAgent.match(/iPod|iPhone|iPad/g) ? true : false;

  /**
   * Creates a new speech bubble
   *
   * @param {H5P.jQuery} $container The speaking object
   * @param {string} text The text to display
   * @param {number} maxWidth The maximum width of the bubble
   * @return {H5P.JoubelSpeechBubble}
   */
  function JoubelSpeechBubble($container, text, maxWidth) {
    maxWidth = maxWidth || DEFAULT_MAX_WIDTH;
    currentMaxWidth = maxWidth;
    $currentContainer = $container;

    this.isCurrent = function ($tip) {
      return $tip.is($currentContainer);
    };

    this.remove = function () {
      remove();
    };

    var fadeOutSpeechBubble = function ($speechBubble) {
      if (!$speechBubble) {
        return;
      }

      // Stop removing bubble
      clearTimeout(removeSpeechBubbleTimeout);

      $speechBubble.removeClass('show');
      setTimeout(function () {
        if ($speechBubble) {
          $speechBubble.remove();
          $speechBubble = undefined;
        }
      }, 500);
    };

    if ($currentSpeechBubble !== undefined) {
      remove();
    }

    var $h5pContainer = getH5PContainer($container);

    // Make sure we fade out old speech bubble
    fadeOutSpeechBubble($currentSpeechBubble);

    // Create bubble
    $tail = $('<div class="joubel-speech-bubble-tail"></div>');
    $innerTail = $('<div class="joubel-speech-bubble-inner-tail"></div>');
    var $innerBubble = $(
      '<div class="joubel-speech-bubble-inner">' +
      '<div class="joubel-speech-bubble-text">' + text + '</div>' +
      '</div>'
    ).prepend($innerTail);

    $currentSpeechBubble = $(
      '<div class="joubel-speech-bubble" aria-live="assertive">'
    ).append([$tail, $innerBubble])
      .appendTo($h5pContainer);

    // Show speech bubble with transition
    setTimeout(function () {
      $currentSpeechBubble.addClass('show');
    }, 0);

    position($currentSpeechBubble, $currentContainer, maxWidth, $tail, $innerTail);

    // Handle click to close
    H5P.$body.on('mousedown.speechBubble', handleOutsideClick);

    // Handle window resizing
    H5P.$window.on('resize', '', handleResize);

    // Handle clicks when inside IV which blocks bubbling.
    $container.parents('.h5p-dialog')
      .on('mousedown.speechBubble', handleOutsideClick);

    if (iDevice) {
      H5P.$body.css('cursor', 'pointer');
    }

    return this;
  }

  // Remove speechbubble if it belongs to a dom element that is about to be hidden
  H5P.externalDispatcher.on('domHidden', function (event) {
    if ($currentSpeechBubble !== undefined && event.data.$dom.find($currentContainer).length !== 0) {
      remove();
    }
  });

  /**
   * Returns the closest h5p container for the given DOM element.
   * 
   * @param {object} $container jquery element
   * @return {object} the h5p container (jquery element)
   */
  function getH5PContainer($container) {
    var $h5pContainer = $container.closest('.h5p-frame');

    // Check closest h5p frame first, then check for container in case there is no frame.
    if (!$h5pContainer.length) {
      $h5pContainer = $container.closest('.h5p-container');
    }

    return $h5pContainer;
  }

  /**
   * Event handler that is called when the window is resized.
   */
  function handleResize() {
    position($currentSpeechBubble, $currentContainer, currentMaxWidth, $tail, $innerTail);
  }

  /**
   * Repositions the speech bubble according to the position of the container.
   * 
   * @param {object} $currentSpeechbubble the speech bubble that should be positioned   
   * @param {object} $container the container to which the speech bubble should point 
   * @param {number} maxWidth the maximum width of the speech bubble
   * @param {object} $tail the tail (the triangle that points to the referenced container)
   * @param {object} $innerTail the inner tail (the triangle that points to the referenced container)
   */
  function position($currentSpeechBubble, $container, maxWidth, $tail, $innerTail) {
    var $h5pContainer = getH5PContainer($container);

    // Calculate offset between the button and the h5p frame
    var offset = getOffsetBetween($h5pContainer, $container);

    var direction = (offset.bottom > offset.top ? 'bottom' : 'top');
    var tipWidth = offset.outerWidth * 0.9; // Var needs to be renamed to make sense
    var bubbleWidth = tipWidth > maxWidth ? maxWidth : tipWidth;

    var bubblePosition = getBubblePosition(bubbleWidth, offset);
    var tailPosition = getTailPosition(bubbleWidth, bubblePosition, offset, $container.width());
    // Need to set font-size, since element is appended to body.
    // Using same font-size as parent. In that way it will grow accordingly
    // when resizing
    var fontSize = 16;//parseFloat($parent.css('font-size'));

    // Set width and position of speech bubble
    $currentSpeechBubble.css(bubbleCSS(
      direction,
      bubbleWidth,
      bubblePosition,
      fontSize
    ));

    var preparedTailCSS = tailCSS(direction, tailPosition);
    $tail.css(preparedTailCSS);
    $innerTail.css(preparedTailCSS);
  }

  /**
   * Static function for removing the speechbubble
   */
  var remove = function () {
    H5P.$body.off('mousedown.speechBubble');
    H5P.$window.off('resize', '', handleResize);
    $currentContainer.parents('.h5p-dialog').off('mousedown.speechBubble');
    if (iDevice) {
      H5P.$body.css('cursor', '');
    }
    if ($currentSpeechBubble !== undefined) {
      // Apply transition, then remove speech bubble
      $currentSpeechBubble.removeClass('show');

      // Make sure we remove any old timeout before reassignment
      clearTimeout(removeSpeechBubbleTimeout);
      removeSpeechBubbleTimeout = setTimeout(function () {
        $currentSpeechBubble.remove();
        $currentSpeechBubble = undefined;
      }, 500);
    }
    // Don't return false here. If the user e.g. clicks a button when the bubble is visible,
    // we want the bubble to disapear AND the button to receive the event
  };

  /**
   * Remove the speech bubble and container reference
   */
  function handleOutsideClick(event) {
    if (event.target === $currentContainer[0]) {
      return; // Button clicks are not outside clicks
    }

    remove();
    // There is no current container when a container isn't clicked
    $currentContainer = undefined;
  }

  /**
   * Calculate position for speech bubble
   *
   * @param {number} bubbleWidth The width of the speech bubble
   * @param {object} offset
   * @return {object} Return position for the speech bubble
   */
  function getBubblePosition(bubbleWidth, offset) {
    var bubblePosition = {};

    var tailOffset = 9;
    var widthOffset = bubbleWidth / 2;

    // Calculate top position
    bubblePosition.top = offset.top + offset.innerHeight;

    // Calculate bottom position
    bubblePosition.bottom = offset.bottom + offset.innerHeight + tailOffset;

    // Calculate left position
    if (offset.left < widthOffset) {
      bubblePosition.left = 3;
    }
    else if ((offset.left + widthOffset) > offset.outerWidth) {
      bubblePosition.left = offset.outerWidth - bubbleWidth - 3;
    }
    else {
      bubblePosition.left = offset.left - widthOffset + (offset.innerWidth / 2);
    }

    return bubblePosition;
  }

  /**
   * Calculate position for speech bubble tail
   *
   * @param {number} bubbleWidth The width of the speech bubble
   * @param {object} bubblePosition Speech bubble position
   * @param {object} offset
   * @param {number} iconWidth The width of the tip icon
   * @return {object} Return position for the tail
   */
  function getTailPosition(bubbleWidth, bubblePosition, offset, iconWidth) {
    var tailPosition = {};
    // Magic numbers. Tuned by hand so that the tail fits visually within
    // the bounds of the speech bubble.
    var leftBoundary = 9;
    var rightBoundary = bubbleWidth - 20;

    tailPosition.left = offset.left - bubblePosition.left + (iconWidth / 2) - 6;
    if (tailPosition.left < leftBoundary) {
      tailPosition.left = leftBoundary;
    }
    if (tailPosition.left > rightBoundary) {
      tailPosition.left = rightBoundary;
    }

    tailPosition.top = -6;
    tailPosition.bottom = -6;

    return tailPosition;
  }

  /**
   * Return bubble CSS for the desired growth direction
   *
   * @param {string} direction The direction the speech bubble will grow
   * @param {number} width The width of the speech bubble
   * @param {object} position Speech bubble position
   * @param {number} fontSize The size of the bubbles font
   * @return {object} Return CSS
   */
  function bubbleCSS(direction, width, position, fontSize) {
    if (direction === 'top') {
      return {
        width: width + 'px',
        bottom: position.bottom + 'px',
        left: position.left + 'px',
        fontSize: fontSize + 'px',
        top: ''
      };
    }
    else {
      return {
        width: width + 'px',
        top: position.top + 'px',
        left: position.left + 'px',
        fontSize: fontSize + 'px',
        bottom: ''
      };
    }
  }

  /**
   * Return tail CSS for the desired growth direction
   *
   * @param {string} direction The direction the speech bubble will grow
   * @param {object} position Tail position
   * @return {object} Return CSS
   */
  function tailCSS(direction, position) {
    if (direction === 'top') {
      return {
        bottom: position.bottom + 'px',
        left: position.left + 'px',
        top: ''
      };
    }
    else {
      return {
        top: position.top + 'px',
        left: position.left + 'px',
        bottom: ''
      };
    }
  }

  /**
   * Calculates the offset between an element inside a container and the
   * container. Only works if all the edges of the inner element are inside the
   * outer element.
   * Width/height of the elements is included as a convenience.
   *
   * @param {H5P.jQuery} $outer
   * @param {H5P.jQuery} $inner
   * @return {object} Position offset
   */
  function getOffsetBetween($outer, $inner) {
    var outer = $outer[0].getBoundingClientRect();
    var inner = $inner[0].getBoundingClientRect();

    return {
      top: inner.top - outer.top,
      right: outer.right - inner.right,
      bottom: outer.bottom - inner.bottom,
      left: inner.left - outer.left,
      innerWidth: inner.width,
      innerHeight: inner.height,
      outerWidth: outer.width,
      outerHeight: outer.height
    };
  }

  return JoubelSpeechBubble;
})(H5P.jQuery);
;var H5P = H5P || {};

H5P.JoubelThrobber = (function ($) {

  /**
   * Creates a new tip
   */
  function JoubelThrobber() {

    // h5p-throbber css is described in core
    var $throbber = $('<div/>', {
      'class': 'h5p-throbber'
    });

    return $throbber;
  }

  return JoubelThrobber;
}(H5P.jQuery));
;H5P.JoubelTip = (function ($) {
  var $conv = $('<div/>');

  /**
   * Creates a new tip element.
   *
   * NOTE that this may look like a class but it doesn't behave like one.
   * It returns a jQuery object.
   *
   * @param {string} tipHtml The text to display in the popup
   * @param {Object} [behaviour] Options
   * @param {string} [behaviour.tipLabel] Set to use a custom label for the tip button (you want this for good A11Y)
   * @param {boolean} [behaviour.helpIcon] Set to 'true' to Add help-icon classname to Tip button (changes the icon)
   * @param {boolean} [behaviour.showSpeechBubble] Set to 'false' to disable functionality (you may this in the editor)
   * @param {boolean} [behaviour.tabcontrol] Set to 'true' if you plan on controlling the tabindex in the parent (tabindex="-1")
   * @return {H5P.jQuery|undefined} Tip button jQuery element or 'undefined' if invalid tip
   */
  function JoubelTip(tipHtml, behaviour) {

    // Keep track of the popup that appears when you click the Tip button
    var speechBubble;

    // Parse tip html to determine text
    var tipText = $conv.html(tipHtml).text().trim();
    if (tipText === '') {
      return; // The tip has no textual content, i.e. it's invalid.
    }

    // Set default behaviour
    behaviour = $.extend({
      tipLabel: tipText,
      helpIcon: false,
      showSpeechBubble: true,
      tabcontrol: false
    }, behaviour);

    // Create Tip button
    var $tipButton = $('<div/>', {
      class: 'joubel-tip-container' + (behaviour.showSpeechBubble ? '' : ' be-quiet'),
      'aria-label': behaviour.tipLabel,
      'aria-expanded': false,
      role: 'button',
      tabindex: (behaviour.tabcontrol ? -1 : 0),
      click: function (event) {
        // Toggle show/hide popup
        toggleSpeechBubble();
        event.preventDefault();
      },
      keydown: function (event) {
        if (event.which === 32 || event.which === 13) { // Space & enter key
          // Toggle show/hide popup
          toggleSpeechBubble();
          event.stopPropagation();
          event.preventDefault();
        }
        else { // Any other key
          // Toggle hide popup
          toggleSpeechBubble(false);
        }
      },
      // Add markup to render icon
      html: '<span class="joubel-icon-tip-normal ' + (behaviour.helpIcon ? ' help-icon': '') + '">' +
              '<span class="h5p-icon-shadow"></span>' +
              '<span class="h5p-icon-speech-bubble"></span>' +
              '<span class="h5p-icon-info"></span>' +
            '</span>'
      // IMPORTANT: All of the markup elements must have 'pointer-events: none;'
    });

    const $tipAnnouncer = $('<div>', {
      'class': 'hidden-but-read',
      'aria-live': 'polite',
      appendTo: $tipButton,
    });

    /**
     * Tip button interaction handler.
     * Toggle show or hide the speech bubble popup when interacting with the
     * Tip button.
     *
     * @private
     * @param {boolean} [force] 'true' shows and 'false' hides.
     */
    var toggleSpeechBubble = function (force) {
      if (speechBubble !== undefined && speechBubble.isCurrent($tipButton)) {
        // Hide current popup
        speechBubble.remove();
        speechBubble = undefined;

        $tipButton.attr('aria-expanded', false);
        $tipAnnouncer.html('');
      }
      else if (force !== false && behaviour.showSpeechBubble) {
        // Create and show new popup
        speechBubble = H5P.JoubelSpeechBubble($tipButton, tipHtml);
        $tipButton.attr('aria-expanded', true);
        $tipAnnouncer.html(tipHtml);
      }
    };

    return $tipButton;
  }

  return JoubelTip;
})(H5P.jQuery);
;var H5P = H5P || {};

H5P.JoubelSlider = (function ($) {

  /**
   * Creates a new Slider
   *
   * @param {object} [params] Additional parameters
   */
  function JoubelSlider(params) {
    H5P.EventDispatcher.call(this);

    this.$slider = $('<div>', $.extend({
      'class': 'h5p-joubel-ui-slider'
    }, params));

    this.$slides = [];
    this.currentIndex = 0;
    this.numSlides = 0;
  }
  JoubelSlider.prototype = Object.create(H5P.EventDispatcher.prototype);
  JoubelSlider.prototype.constructor = JoubelSlider;

  JoubelSlider.prototype.addSlide = function ($content) {
    $content.addClass('h5p-joubel-ui-slide').css({
      'left': (this.numSlides*100) + '%'
    });
    this.$slider.append($content);
    this.$slides.push($content);

    this.numSlides++;

    if(this.numSlides === 1) {
      $content.addClass('current');
    }
  };

  JoubelSlider.prototype.attach = function ($container) {
    $container.append(this.$slider);
  };

  JoubelSlider.prototype.move = function (index) {
    var self = this;

    if(index === 0) {
      self.trigger('first-slide');
    }
    if(index+1 === self.numSlides) {
      self.trigger('last-slide');
    }
    self.trigger('move');

    var $previousSlide = self.$slides[this.currentIndex];
    H5P.Transition.onTransitionEnd(this.$slider, function () {
      $previousSlide.removeClass('current');
      self.trigger('moved');
    });
    this.$slides[index].addClass('current');

    var translateX = 'translateX(' + (-index*100) + '%)';
    this.$slider.css({
      '-webkit-transform': translateX,
      '-moz-transform': translateX,
      '-ms-transform': translateX,
      'transform': translateX
    });

    this.currentIndex = index;
  };

  JoubelSlider.prototype.remove = function () {
    this.$slider.remove();
  };

  JoubelSlider.prototype.next = function () {
    if(this.currentIndex+1 >= this.numSlides) {
      return;
    }

    this.move(this.currentIndex+1);
  };

  JoubelSlider.prototype.previous = function () {
    this.move(this.currentIndex-1);
  };

  JoubelSlider.prototype.first = function () {
    this.move(0);
  };

  JoubelSlider.prototype.last = function () {
    this.move(this.numSlides-1);
  };

  return JoubelSlider;
})(H5P.jQuery);
;var H5P = H5P || {};

/**
 * @module
 */
H5P.JoubelScoreBar = (function ($) {

  /* Need to use an id for the star SVG since that is the only way to reference
     SVG filters  */
  var idCounter = 0;

  /**
   * Creates a score bar
   * @class H5P.JoubelScoreBar
   * @param {number} maxScore  Maximum score
   * @param {string} [label] Makes it easier for readspeakers to identify the scorebar
   * @param {string} [helpText] Score explanation
   * @param {string} [scoreExplanationButtonLabel] Label for score explanation button
   */
  function JoubelScoreBar(maxScore, label, helpText, scoreExplanationButtonLabel) {
    var self = this;

    self.maxScore = maxScore;
    self.score = 0;
    idCounter++;

    /**
     * @const {string}
     */
    self.STAR_MARKUP = '<svg tabindex="-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 63.77 53.87" aria-hidden="true" focusable="false">' +
        '<title>star</title>' +
        '<filter tabindex="-1" id="h5p-joubelui-score-bar-star-inner-shadow-' + idCounter + '" x0="-50%" y0="-50%" width="200%" height="200%">' +
          '<feGaussianBlur in="SourceAlpha" stdDeviation="3" result="blur"></feGaussianBlur>' +
          '<feOffset dy="2" dx="4"></feOffset>' +
          '<feComposite in2="SourceAlpha" operator="arithmetic" k2="-1" k3="1" result="shadowDiff"></feComposite>' +
          '<feFlood flood-color="#ffe95c" flood-opacity="1"></feFlood>' +
          '<feComposite in2="shadowDiff" operator="in"></feComposite>' +
          '<feComposite in2="SourceGraphic" operator="over" result="firstfilter"></feComposite>' +
          '<feGaussianBlur in="firstfilter" stdDeviation="3" result="blur2"></feGaussianBlur>' +
          '<feOffset dy="-2" dx="-4"></feOffset>' +
          '<feComposite in2="firstfilter" operator="arithmetic" k2="-1" k3="1" result="shadowDiff"></feComposite>' +
          '<feFlood flood-color="#ffe95c" flood-opacity="1"></feFlood>' +
          '<feComposite in2="shadowDiff" operator="in"></feComposite>' +
          '<feComposite in2="firstfilter" operator="over"></feComposite>' +
        '</filter>' +
        '<path tabindex="-1" class="h5p-joubelui-score-bar-star-shadow" d="M35.08,43.41V9.16H20.91v0L9.51,10.85,9,10.93C2.8,12.18,0,17,0,21.25a11.22,11.22,0,0,0,3,7.48l8.73,8.53-1.07,6.16Z"/>' +
        '<g tabindex="-1">' +
          '<path tabindex="-1" class="h5p-joubelui-score-bar-star-border" d="M61.36,22.8,49.72,34.11l2.78,16a2.6,2.6,0,0,1,.05.64c0,.85-.37,1.6-1.33,1.6A2.74,2.74,0,0,1,49.94,52L35.58,44.41,21.22,52a2.93,2.93,0,0,1-1.28.37c-.91,0-1.33-.75-1.33-1.6,0-.21.05-.43.05-.64l2.78-16L9.8,22.8A2.57,2.57,0,0,1,9,21.25c0-1,1-1.33,1.81-1.49l16.07-2.35L34.09,2.83c.27-.59.85-1.33,1.55-1.33s1.28.69,1.55,1.33l7.21,14.57,16.07,2.35c.75.11,1.81.53,1.81,1.49A3.07,3.07,0,0,1,61.36,22.8Z"/>' +
          '<path tabindex="-1" class="h5p-joubelui-score-bar-star-fill" d="M61.36,22.8,49.72,34.11l2.78,16a2.6,2.6,0,0,1,.05.64c0,.85-.37,1.6-1.33,1.6A2.74,2.74,0,0,1,49.94,52L35.58,44.41,21.22,52a2.93,2.93,0,0,1-1.28.37c-.91,0-1.33-.75-1.33-1.6,0-.21.05-.43.05-.64l2.78-16L9.8,22.8A2.57,2.57,0,0,1,9,21.25c0-1,1-1.33,1.81-1.49l16.07-2.35L34.09,2.83c.27-.59.85-1.33,1.55-1.33s1.28.69,1.55,1.33l7.21,14.57,16.07,2.35c.75.11,1.81.53,1.81,1.49A3.07,3.07,0,0,1,61.36,22.8Z"/>' +
          '<path tabindex="-1" filter="url(#h5p-joubelui-score-bar-star-inner-shadow-' + idCounter + ')" class="h5p-joubelui-score-bar-star-fill-full-score" d="M61.36,22.8,49.72,34.11l2.78,16a2.6,2.6,0,0,1,.05.64c0,.85-.37,1.6-1.33,1.6A2.74,2.74,0,0,1,49.94,52L35.58,44.41,21.22,52a2.93,2.93,0,0,1-1.28.37c-.91,0-1.33-.75-1.33-1.6,0-.21.05-.43.05-.64l2.78-16L9.8,22.8A2.57,2.57,0,0,1,9,21.25c0-1,1-1.33,1.81-1.49l16.07-2.35L34.09,2.83c.27-.59.85-1.33,1.55-1.33s1.28.69,1.55,1.33l7.21,14.57,16.07,2.35c.75.11,1.81.53,1.81,1.49A3.07,3.07,0,0,1,61.36,22.8Z"/>' +
        '</g>' +
      '</svg>';

    /**
     * @function appendTo
     * @memberOf H5P.JoubelScoreBar#
     * @param {H5P.jQuery}  $wrapper  Dom container
     */
    self.appendTo = function ($wrapper) {
      self.$scoreBar.appendTo($wrapper);
    };

    /**
     * Create the text representation of the scorebar .
     *
     * @private
     * @return {string}
     */
    var createLabel = function (score) {
      if (!label) {
        return '';
      }

      return label.replace(':num', score).replace(':total', self.maxScore);
    };

    /**
     * Creates the html for this widget
     *
     * @method createHtml
     * @private
     */
    var createHtml = function () {
      // Container div
      self.$scoreBar = $('<div>', {
        'class': 'h5p-joubelui-score-bar',
      });

      var $visuals = $('<div>', {
        'class': 'h5p-joubelui-score-bar-visuals',
        appendTo: self.$scoreBar
      });

      // The progress bar wrapper
      self.$progressWrapper = $('<div>', {
        'class': 'h5p-joubelui-score-bar-progress-wrapper',
        appendTo: $visuals
      });

      self.$progress = $('<div>', {
        'class': 'h5p-joubelui-score-bar-progress',
        'html': createLabel(self.score),
        appendTo: self.$progressWrapper
      });

      // The star
      $('<div>', {
        'class': 'h5p-joubelui-score-bar-star',
        html: self.STAR_MARKUP
      }).appendTo($visuals);

      // The score container
      var $numerics = $('<div>', {
        'class': 'h5p-joubelui-score-numeric',
        appendTo: self.$scoreBar,
        'aria-hidden': true
      });

      // The current score
      self.$scoreCounter = $('<span>', {
        'class': 'h5p-joubelui-score-number h5p-joubelui-score-number-counter',
        text: 0,
        appendTo: $numerics
      });

      // The separator
      $('<span>', {
        'class': 'h5p-joubelui-score-number-separator',
        text: '/',
        appendTo: $numerics
      });

      // Max score
      self.$maxScore = $('<span>', {
        'class': 'h5p-joubelui-score-number h5p-joubelui-score-max',
        text: self.maxScore,
        appendTo: $numerics
      });

      if (helpText) {
        H5P.JoubelUI.createTip(helpText, {
          tipLabel: scoreExplanationButtonLabel ? scoreExplanationButtonLabel : helpText,
          helpIcon: true
        }).appendTo(self.$scoreBar);
        self.$scoreBar.addClass('h5p-score-bar-has-help');
      }
    };

    /**
     * Set the current score
     * @method setScore
     * @memberOf H5P.JoubelScoreBar#
     * @param  {number} score
     */
    self.setScore = function (score) {
      // Do nothing if score hasn't changed
      if (score === self.score) {
        return;
      }
      self.score = score > self.maxScore ? self.maxScore : score;
      self.updateVisuals();
    };

    /**
     * Increment score
     * @method incrementScore
     * @memberOf H5P.JoubelScoreBar#
     * @param  {number=}        incrementBy Optional parameter, defaults to 1
     */
    self.incrementScore = function (incrementBy) {
      self.setScore(self.score + (incrementBy || 1));
    };

    /**
     * Set the max score
     * @method setMaxScore
     * @memberOf H5P.JoubelScoreBar#
     * @param  {number}    maxScore The max score
     */
    self.setMaxScore = function (maxScore) {
      self.maxScore = maxScore;
    };

    /**
     * Updates the progressbar visuals
     * @memberOf H5P.JoubelScoreBar#
     * @method updateVisuals
     */
    self.updateVisuals = function () {
      self.$progress.html(createLabel(self.score));
      self.$scoreCounter.text(self.score);
      self.$maxScore.text(self.maxScore);

      setTimeout(function () {
        // Start the progressbar animation
        self.$progress.css({
          width: ((self.score / self.maxScore) * 100) + '%'
        });

        H5P.Transition.onTransitionEnd(self.$progress, function () {
          // If fullscore fill the star and start the animation
          self.$scoreBar.toggleClass('h5p-joubelui-score-bar-full-score', self.score === self.maxScore);
          self.$scoreBar.toggleClass('h5p-joubelui-score-bar-animation-active', self.score === self.maxScore);

          // Only allow the star animation to run once
          self.$scoreBar.one("animationend", function() {
            self.$scoreBar.removeClass("h5p-joubelui-score-bar-animation-active");
          });
        }, 600);
      }, 300);
    };

    /**
     * Removes all classes
     * @method reset
     */
    self.reset = function () {
      self.$scoreBar.removeClass('h5p-joubelui-score-bar-full-score');
    };

    createHtml();
  }

  return JoubelScoreBar;
})(H5P.jQuery);
;var H5P = H5P || {};

H5P.JoubelProgressbar = (function ($) {

  /**
   * Joubel progressbar class
   * @method JoubelProgressbar
   * @constructor
   * @param  {number}          steps Number of steps
   * @param {Object} [options] Additional options
   * @param {boolean} [options.disableAria] Disable readspeaker assistance
   * @param {string} [options.progressText] A progress text for describing
   *  current progress out of total progress for readspeakers.
   *  e.g. "Slide :num of :total"
   */
  function JoubelProgressbar(steps, options) {
    H5P.EventDispatcher.call(this);
    var self = this;
    this.options = $.extend({
      progressText: 'Slide :num of :total'
    }, options);
    this.currentStep = 0;
    this.steps = steps;

    this.$progressbar = $('<div>', {
      'class': 'h5p-joubelui-progressbar'
    });
    this.$background = $('<div>', {
      'class': 'h5p-joubelui-progressbar-background'
    }).appendTo(this.$progressbar);
  }

  JoubelProgressbar.prototype = Object.create(H5P.EventDispatcher.prototype);
  JoubelProgressbar.prototype.constructor = JoubelProgressbar;

  JoubelProgressbar.prototype.updateAria = function () {
    var self = this;
    if (this.options.disableAria) {
      return;
    }

    if (!this.$currentStatus) {
      this.$currentStatus = $('<div>', {
        'class': 'h5p-joubelui-progressbar-slide-status-text',
        'aria-live': 'assertive'
      }).appendTo(this.$progressbar);
    }
    var interpolatedProgressText = self.options.progressText
      .replace(':num', self.currentStep)
      .replace(':total', self.steps);
    this.$currentStatus.html(interpolatedProgressText);
  };

  /**
   * Appends to a container
   * @method appendTo
   * @param  {H5P.jquery} $container
   */
  JoubelProgressbar.prototype.appendTo = function ($container) {
    this.$progressbar.appendTo($container);
  };

  /**
   * Update progress
   * @method setProgress
   * @param  {number}    step
   */
  JoubelProgressbar.prototype.setProgress = function (step) {
    // Check for valid value:
    if (step > this.steps || step < 0) {
      return;
    }
    this.currentStep = step;
    this.$background.css({
      width: ((this.currentStep/this.steps)*100) + '%'
    });

    this.updateAria();
  };

  /**
   * Increment progress with 1
   * @method next
   */
  JoubelProgressbar.prototype.next = function () {
    this.setProgress(this.currentStep+1);
  };

  /**
   * Reset progressbar
   * @method reset
   */
  JoubelProgressbar.prototype.reset = function () {
    this.setProgress(0);
  };

  /**
   * Check if last step is reached
   * @method isLastStep
   * @return {Boolean}
   */
  JoubelProgressbar.prototype.isLastStep = function () {
    return this.steps === this.currentStep;
  };

  return JoubelProgressbar;
})(H5P.jQuery);
;var H5P = H5P || {};

/**
 * H5P Joubel UI library.
 *
 * This is a utility library, which does not implement attach. I.e, it has to bee actively used by
 * other libraries
 * @module
 */
H5P.JoubelUI = (function ($) {

  /**
   * The internal object to return
   * @class H5P.JoubelUI
   * @static
   */
  function JoubelUI() {}

  /* Public static functions */

  /**
   * Create a tip icon
   * @method H5P.JoubelUI.createTip
   * @param  {string}  text   The textual tip
   * @param  {Object}  params Parameters
   * @return {H5P.JoubelTip}
   */
  JoubelUI.createTip = function (text, params) {
    return new H5P.JoubelTip(text, params);
  };

  /**
   * Create message dialog
   * @method H5P.JoubelUI.createMessageDialog
   * @param  {H5P.jQuery}               $container The dom container
   * @param  {string}                   message    The message
   * @return {H5P.JoubelMessageDialog}
   */
  JoubelUI.createMessageDialog = function ($container, message) {
    return new H5P.JoubelMessageDialog($container, message);
  };

  /**
   * Create help text dialog
   * @method H5P.JoubelUI.createHelpTextDialog
   * @param  {string}             header  The textual header
   * @param  {string}             message The textual message
   * @param  {string}             closeButtonTitle The title for the close button
   * @return {H5P.JoubelHelpTextDialog}
   */
  JoubelUI.createHelpTextDialog = function (header, message, closeButtonTitle) {
    return new H5P.JoubelHelpTextDialog(header, message, closeButtonTitle);
  };

  /**
   * Create progress circle
   * @method H5P.JoubelUI.createProgressCircle
   * @param  {number}             number          The progress (0 to 100)
   * @param  {string}             progressColor   The progress color in hex value
   * @param  {string}             fillColor       The fill color in hex value
   * @param  {string}             backgroundColor The background color in hex value
   * @return {H5P.JoubelProgressCircle}
   */
  JoubelUI.createProgressCircle = function (number, progressColor, fillColor, backgroundColor) {
    return new H5P.JoubelProgressCircle(number, progressColor, fillColor, backgroundColor);
  };

  /**
   * Create throbber for loading
   * @method H5P.JoubelUI.createThrobber
   * @return {H5P.JoubelThrobber}
   */
  JoubelUI.createThrobber = function () {
    return new H5P.JoubelThrobber();
  };

  /**
   * Create simple rounded button
   * @method H5P.JoubelUI.createSimpleRoundedButton
   * @param  {string}                  text The button label
   * @return {H5P.SimpleRoundedButton}
   */
  JoubelUI.createSimpleRoundedButton = function (text) {
    return new H5P.SimpleRoundedButton(text);
  };

  /**
   * Create Slider
   * @method H5P.JoubelUI.createSlider
   * @param  {Object} [params] Parameters
   * @return {H5P.JoubelSlider}
   */
  JoubelUI.createSlider = function (params) {
    return new H5P.JoubelSlider(params);
  };

  /**
   * Create Score Bar
   * @method H5P.JoubelUI.createScoreBar
   * @param  {number=}       maxScore The maximum score
   * @param {string} [label] Makes it easier for readspeakers to identify the scorebar
   * @return {H5P.JoubelScoreBar}
   */
  JoubelUI.createScoreBar = function (maxScore, label, helpText, scoreExplanationButtonLabel) {
    return new H5P.JoubelScoreBar(maxScore, label, helpText, scoreExplanationButtonLabel);
  };

  /**
   * Create Progressbar
   * @method H5P.JoubelUI.createProgressbar
   * @param  {number=}       numSteps The total numer of steps
   * @param {Object} [options] Additional options
   * @param {boolean} [options.disableAria] Disable readspeaker assistance
   * @param {string} [options.progressText] A progress text for describing
   *  current progress out of total progress for readspeakers.
   *  e.g. "Slide :num of :total"
   * @return {H5P.JoubelProgressbar}
   */
  JoubelUI.createProgressbar = function (numSteps, options) {
    return new H5P.JoubelProgressbar(numSteps, options);
  };

  /**
   * Create standard Joubel button
   *
   * @method H5P.JoubelUI.createButton
   * @param {object} params
   *  May hold any properties allowed by jQuery. If href is set, an A tag
   *  is used, if not a button tag is used.
   * @return {H5P.jQuery} The jquery element created
   */
  JoubelUI.createButton = function(params) {
    var type = 'button';
    if (params.href) {
      type = 'a';
    }
    else {
      params.type = 'button';
    }
    if (params.class) {
      params.class += ' h5p-joubelui-button';
    }
    else {
      params.class = 'h5p-joubelui-button';
    }
    return $('<' + type + '/>', params);
  };

  /**
   * Fix for iframe scoll bug in IOS. When focusing an element that doesn't have
   * focus support by default the iframe will scroll the parent frame so that
   * the focused element is out of view. This varies dependening on the elements
   * of the parent frame.
   */
  if (H5P.isFramed && !H5P.hasiOSiframeScrollFix &&
      /iPad|iPhone|iPod/.test(navigator.userAgent)) {
    H5P.hasiOSiframeScrollFix = true;

    // Keep track of original focus function
    var focus = HTMLElement.prototype.focus;

    // Override the original focus
    HTMLElement.prototype.focus = function () {
      // Only focus the element if it supports it natively
      if ( (this instanceof HTMLAnchorElement ||
            this instanceof HTMLInputElement ||
            this instanceof HTMLSelectElement ||
            this instanceof HTMLTextAreaElement ||
            this instanceof HTMLButtonElement ||
            this instanceof HTMLIFrameElement ||
            this instanceof HTMLAreaElement) && // HTMLAreaElement isn't supported by Safari yet.
          !this.getAttribute('role')) { // Focus breaks if a different role has been set
          // In theory this.isContentEditable should be able to recieve focus,
          // but it didn't work when tested.

        // Trigger the original focus with the proper context
        focus.call(this);
      }
    };
  }

  return JoubelUI;
})(H5P.jQuery);
;H5P.Question = (function ($, EventDispatcher, JoubelUI) {

  /**
   * Extending this class make it alot easier to create tasks for other
   * content types.
   *
   * @class H5P.Question
   * @extends H5P.EventDispatcher
   * @param {string} type
   */
  function Question(type) {
    var self = this;

    // Inheritance
    EventDispatcher.call(self);

    // Register default section order
    self.order = ['video', 'image', 'introduction', 'content', 'explanation', 'feedback', 'scorebar', 'buttons', 'read'];

    // Keep track of registered sections
    var sections = {};

    // Buttons
    var buttons = {};
    var buttonOrder = [];

    // Wrapper when attached
    var $wrapper;

    // Click element
    var clickElement;

    // ScoreBar
    var scoreBar;

    // Keep track of the feedback's visual status.
    var showFeedback;

    // Keep track of which buttons are scheduled for hiding.
    var buttonsToHide = [];

    // Keep track of which buttons are scheduled for showing.
    var buttonsToShow = [];

    // Keep track of the hiding and showing of buttons.
    var toggleButtonsTimer;
    var toggleButtonsTransitionTimer;
    var buttonTruncationTimer;

    // Keeps track of initialization of question
    var initialized = false;

    /**
     * @type {Object} behaviour Behaviour of Question
     * @property {Boolean} behaviour.disableFeedback Set to true to disable feedback section
     */
    var behaviour = {
      disableFeedback: false,
      disableReadSpeaker: false
    };

    // Keeps track of thumb state
    var imageThumb = true;

    // Keeps track of image transitions
    var imageTransitionTimer;

    // Keep track of whether sections is transitioning.
    var sectionsIsTransitioning = false;

    // Keep track of auto play state
    var disableAutoPlay = false;

    // Feedback transition timer
    var feedbackTransitionTimer;

    // Used when reading messages to the user
    var $read, readText;

    /**
     * Register section with given content.
     *
     * @private
     * @param {string} section ID of the section
     * @param {(string|H5P.jQuery)} [content]
     */
    var register = function (section, content) {
      sections[section] = {};
      var $e = sections[section].$element = $('<div/>', {
        'class': 'h5p-question-' + section,
      });
      if (content) {
        $e[content instanceof $ ? 'append' : 'html'](content);
      }
    };

    /**
     * Update registered section with content.
     *
     * @private
     * @param {string} section ID of the section
     * @param {(string|H5P.jQuery)} content
     */
    var update = function (section, content) {
      if (content instanceof $) {
        sections[section].$element.html('').append(content);
      }
      else {
        sections[section].$element.html(content);
      }
    };

    /**
     * Insert element with given ID into the DOM.
     *
     * @private
     * @param {array|Array|string[]} order
     * List with ordered element IDs
     * @param {string} id
     * ID of the element to be inserted
     * @param {Object} elements
     * Maps ID to the elements
     * @param {H5P.jQuery} $container
     * Parent container of the elements
     */
    var insert = function (order, id, elements, $container) {
      // Try to find an element id should be after
      for (var i = 0; i < order.length; i++) {
        if (order[i] === id) {
          // Found our pos
          while (i > 0 &&
          (elements[order[i - 1]] === undefined ||
          !elements[order[i - 1]].isVisible)) {
            i--;
          }
          if (i === 0) {
            // We are on top.
            elements[id].$element.prependTo($container);
          }
          else {
            // Add after element
            elements[id].$element.insertAfter(elements[order[i - 1]].$element);
          }
          elements[id].isVisible = true;
          break;
        }
      }
    };

    /**
     * Make feedback into a popup and position relative to click.
     *
     * @private
     * @param {string} [closeText] Text for the close button
     */
    var makeFeedbackPopup = function (closeText) {
      var $element = sections.feedback.$element;
      var $parent = sections.content.$element;
      var $click = (clickElement != null ? clickElement.$element : null);

      $element.appendTo($parent).addClass('h5p-question-popup');

      if (sections.scorebar) {
        sections.scorebar.$element.appendTo($element);
      }

      $parent.addClass('h5p-has-question-popup');

      // Draw the tail
      var $tail = $('<div/>', {
        'class': 'h5p-question-feedback-tail'
      }).hide()
        .appendTo($parent);

      // Draw the close button
      var $close = $('<div/>', {
        'class': 'h5p-question-feedback-close',
        'tabindex': 0,
        'title': closeText,
        on: {
          click: function (event) {
            $element.remove();
            $tail.remove();
            event.preventDefault();
          },
          keydown: function (event) {
            switch (event.which) {
              case 13: // Enter
              case 32: // Space
                $element.remove();
                $tail.remove();
                event.preventDefault();
            }
          }
        }
      }).hide().appendTo($element);

      if ($click != null) {
        if ($click.hasClass('correct')) {
          $element.addClass('h5p-question-feedback-correct');
          $close.show();
          sections.buttons.$element.hide();
        }
        else {
          sections.buttons.$element.appendTo(sections.feedback.$element);
        }
      }

      positionFeedbackPopup($element, $click);
    };

    /**
     * Position the feedback popup.
     *
     * @private
     * @param {H5P.jQuery} $element Feedback div
     * @param {H5P.jQuery} $click Visual click div
     */
    var positionFeedbackPopup = function ($element, $click) {
      var $container = $element.parent();
      var $tail = $element.siblings('.h5p-question-feedback-tail');
      var popupWidth = $element.outerWidth();
      var popupHeight = setElementHeight($element);
      var space = 15;
      var disableTail = false;
      var positionY = $container.height() / 2 - popupHeight / 2;
      var positionX = $container.width() / 2 - popupWidth / 2;
      var tailX = 0;
      var tailY = 0;
      var tailRotation = 0;

      if ($click != null) {
        // Edge detection for click, takes space into account
        var clickNearTop = ($click[0].offsetTop < space);
        var clickNearBottom = ($click[0].offsetTop + $click.height() > $container.height() - space);
        var clickNearLeft = ($click[0].offsetLeft < space);
        var clickNearRight = ($click[0].offsetLeft + $click.width() > $container.width() - space);

        // Click is not in a corner or close to edge, calculate position normally
        positionX = $click[0].offsetLeft - popupWidth / 2  + $click.width() / 2;
        positionY = $click[0].offsetTop - popupHeight - space;
        tailX = positionX + popupWidth / 2 - $tail.width() / 2;
        tailY = positionY + popupHeight - ($tail.height() / 2);
        tailRotation = 225;

        // If popup is outside top edge, position under click instead
        if (popupHeight + space > $click[0].offsetTop) {
          positionY = $click[0].offsetTop + $click.height() + space;
          tailY = positionY - $tail.height() / 2 ;
          tailRotation = 45;
        }

        // If popup is outside left edge, position left
        if (positionX < 0) {
          positionX = 0;
        }

        // If popup is outside right edge, position right
        if (positionX + popupWidth > $container.width()) {
          positionX = $container.width() - popupWidth;
        }

        // Special cases such as corner clicks, or close to an edge, they override X and Y positions if met
        if (clickNearTop && (clickNearLeft || clickNearRight)) {
          positionX = $click[0].offsetLeft + (clickNearLeft ? $click.width() : -popupWidth);
          positionY = $click[0].offsetTop + $click.height();
          disableTail = true;
        }
        else if (clickNearBottom && (clickNearLeft || clickNearRight)) {
          positionX = $click[0].offsetLeft + (clickNearLeft ? $click.width() : -popupWidth);
          positionY = $click[0].offsetTop - popupHeight;
          disableTail = true;
        }
        else if (!clickNearTop && !clickNearBottom) {
          if (clickNearLeft || clickNearRight) {
            positionY = $click[0].offsetTop - popupHeight / 2 + $click.width() / 2;
            positionX = $click[0].offsetLeft + (clickNearLeft ? $click.width() + space : -popupWidth + -space);
            // Make sure this does not position the popup off screen
            if (positionX < 0) {
              positionX = 0;
              disableTail = true;
            }
            else {
              tailX = positionX + (clickNearLeft ? - $tail.width() / 2 : popupWidth - $tail.width() / 2);
              tailY = positionY + popupHeight / 2 - $tail.height() / 2;
              tailRotation = (clickNearLeft ? 315 : 135);
            }
          }
        }

        // Contain popup from overflowing bottom edge
        if (positionY + popupHeight > $container.height()) {
          positionY = $container.height() - popupHeight;

          if (popupHeight > $container.height() - ($click[0].offsetTop + $click.height() + space)) {
            disableTail = true;
          }
        }
      }
      else {
        disableTail = true;
      }

      // Contain popup from ovreflowing top edge
      if (positionY < 0) {
        positionY = 0;
      }

      $element.css({top: positionY, left: positionX});
      $tail.css({top: tailY, left: tailX});

      if (!disableTail) {
        $tail.css({
          'left': tailX,
          'top': tailY,
          'transform': 'rotate(' + tailRotation + 'deg)'
        }).show();
      }
      else {
        $tail.hide();
      }
    };

    /**
     * Set element max height, used for animations.
     *
     * @param {H5P.jQuery} $element
     */
    var setElementHeight = function ($element) {
      if (!$element.is(':visible')) {
        // No animation
        $element.css('max-height', 'none');
        return;
      }

      // If this element is shown in the popup, we can't set width to 100%,
      // since it already has a width set in CSS
      var isFeedbackPopup = $element.hasClass('h5p-question-popup');

      // Get natural element height
      var $tmp = $element.clone()
        .css({
          'position': 'absolute',
          'max-height': 'none',
          'width': isFeedbackPopup ? '' : '100%'
        })
        .appendTo($element.parent());

      // Need to take margins into account when calculating available space
      var sideMargins = parseFloat($element.css('margin-left'))
        + parseFloat($element.css('margin-right'));
      var tmpElWidth = $tmp.css('width') ? $tmp.css('width') : '100%';
      $tmp.css('width', 'calc(' + tmpElWidth + ' - ' + sideMargins + 'px)');

      // Apply height to element
      var h = Math.round($tmp.get(0).getBoundingClientRect().height);
      var fontSize = parseFloat($element.css('fontSize'));
      var relativeH = h / fontSize;
      $element.css('max-height', relativeH + 'em');
      $tmp.remove();

      if (h > 0 && sections.buttons && sections.buttons.$element === $element) {
        // Make sure buttons section is visible
        showSection(sections.buttons);

        // Resize buttons after resizing button section
        setTimeout(resizeButtons, 150);
      }
      return h;
    };

    /**
     * Does the actual job of hiding the buttons scheduled for hiding.
     *
     * @private
     * @param {boolean} [relocateFocus] Find a new button to focus
     */
    var hideButtons = function (relocateFocus) {
      for (var i = 0; i < buttonsToHide.length; i++) {
        hideButton(buttonsToHide[i].id);
      }
      buttonsToHide = [];

      if (relocateFocus) {
        self.focusButton();
      }
    };

    /**
     * Does the actual hiding.
     * @private
     * @param {string} buttonId
     */
    var hideButton = function (buttonId) {
      // Using detach() vs hide() makes it harder to cheat.
      buttons[buttonId].$element.detach();
      buttons[buttonId].isVisible = false;
    };

    /**
     * Shows the buttons on the next tick. This is to avoid buttons flickering
     * If they're both added and removed on the same tick.
     *
     * @private
     */
    var toggleButtons = function () {
      // If no buttons section, return
      if (sections.buttons === undefined) {
        return;
      }

      // Clear transition timer, reevaluate if buttons will be detached
      clearTimeout(toggleButtonsTransitionTimer);

      // Show buttons
      for (var i = 0; i < buttonsToShow.length; i++) {
        insert(buttonOrder, buttonsToShow[i].id, buttons, sections.buttons.$element);
        buttons[buttonsToShow[i].id].isVisible = true;
      }
      buttonsToShow = [];

      // Hide buttons
      var numToHide = 0;
      var relocateFocus = false;
      for (var j = 0; j < buttonsToHide.length; j++) {
        var button = buttons[buttonsToHide[j].id];
        if (button.isVisible) {
          numToHide += 1;
        }
        if (button.$element.is(':focus')) {
          // Move focus to the first visible button.
          relocateFocus = true;
        }
      }

      var animationTimer = 150;
      if (sections.feedback && sections.feedback.$element.hasClass('h5p-question-popup')) {
        animationTimer = 0;
      }

      if (numToHide === sections.buttons.$element.children().length) {
        // All buttons are going to be hidden. Hide container using transition.
        hideSection(sections.buttons);
        // Detach buttons
        hideButtons(relocateFocus);
      }
      else {
        hideButtons(relocateFocus);

        // Show button section
        if (!sections.buttons.$element.is(':empty')) {
          showSection(sections.buttons);
          setElementHeight(sections.buttons.$element);

          // Trigger resize after animation
          toggleButtonsTransitionTimer = setTimeout(function () {
            self.trigger('resize');
          }, animationTimer);
        }

        // Resize buttons to fit container
        resizeButtons();
      }

      toggleButtonsTimer = undefined;
    };

    /**
     * Allows for scaling of the question image.
     */
    var scaleImage = function () {
      var $imgSection = sections.image.$element;
      clearTimeout(imageTransitionTimer);

      // Add this here to avoid initial transition of the image making
      // content overflow. Alternatively we need to trigger a resize.
      $imgSection.addClass('animatable');

      if (imageThumb) {

        // Expand image
        $(this).attr('aria-expanded', true);
        $imgSection.addClass('h5p-question-image-fill-width');
        imageThumb = false;

        imageTransitionTimer = setTimeout(function () {
          self.trigger('resize');
        }, 600);
      }
      else {

        // Scale down image
        $(this).attr('aria-expanded', false);
        $imgSection.removeClass('h5p-question-image-fill-width');
        imageThumb = true;

        imageTransitionTimer = setTimeout(function () {
          self.trigger('resize');
        }, 600);
      }
    };

    /**
     * Get scrollable ancestor of element
     *
     * @private
     * @param {H5P.jQuery} $element
     * @param {Number} [currDepth=0] Current recursive calls to ancestor, stop at maxDepth
     * @param {Number} [maxDepth=5] Maximum depth for finding ancestor.
     * @returns {H5P.jQuery} Parent element that is scrollable
     */
    var findScrollableAncestor = function ($element, currDepth, maxDepth) {
      if (!currDepth) {
        currDepth = 0;
      }
      if (!maxDepth) {
        maxDepth = 5;
      }
      // Check validation of element or if we have reached document root
      if (!$element || !($element instanceof $) || document === $element.get(0) || currDepth >= maxDepth) {
        return;
      }

      if ($element.css('overflow-y') === 'auto') {
        return $element;
      }
      else {
        return findScrollableAncestor($element.parent(), currDepth + 1, maxDepth);
      }
    };

    /**
     * Scroll to bottom of Question.
     *
     * @private
     */
    var scrollToBottom = function () {
      if (!$wrapper || ($wrapper.hasClass('h5p-standalone') && !H5P.isFullscreen)) {
        return; // No scroll
      }

      var scrollableAncestor = findScrollableAncestor($wrapper);

      // Scroll to bottom of scrollable ancestor
      if (scrollableAncestor) {
        scrollableAncestor.animate({
          scrollTop: $wrapper.css('height')
        }, "slow");
      }
    };

    /**
     * Resize buttons to fit container width
     *
     * @private
     */
    var resizeButtons = function () {
      if (!buttons || !sections.buttons) {
        return;
      }

      var go = function () {
        // Don't do anything if button elements are not visible yet
        if (!sections.buttons.$element.is(':visible')) {
          return;
        }

        // Width of all buttons
        var buttonsWidth = {
          max: 0,
          min: 0,
          current: 0
        };

        for (var i in buttons) {
          var button = buttons[i];
          if (button.isVisible) {
            setButtonWidth(buttons[i]);
            buttonsWidth.max += button.width.max;
            buttonsWidth.min += button.width.min;
            buttonsWidth.current += button.isTruncated ? button.width.min : button.width.max;
          }
        }

        var makeButtonsFit = function (availableWidth) {
          if (buttonsWidth.max < availableWidth) {
            // It is room for everyone on the right side of the score bar (without truncating)
            if (buttonsWidth.max !== buttonsWidth.current) {
              // Need to make everyone big
              restoreButtonLabels(buttonsWidth.current, availableWidth);
            }
            return true;
          }
          else if (buttonsWidth.min < availableWidth) {
            // Is it room for everyone on the right side of the score bar with truncating?
            if (buttonsWidth.current > availableWidth) {
              removeButtonLabels(buttonsWidth.current, availableWidth);
            }
            else {
              restoreButtonLabels(buttonsWidth.current, availableWidth);
            }
            return true;
          }
          return false;
        };

        toggleFullWidthScorebar(false);

        var buttonSectionWidth = Math.floor(sections.buttons.$element.width()) - 1;

        if (!makeButtonsFit(buttonSectionWidth)) {
          // If we get here we need to wrap:
          toggleFullWidthScorebar(true);
          buttonSectionWidth = Math.floor(sections.buttons.$element.width()) - 1;
          makeButtonsFit(buttonSectionWidth);
        }
      };

      // If visible, resize right away
      if (sections.buttons.$element.is(':visible')) {
        go();
      }
      else { // If not visible, try on the next tick
        // Clear button truncation timer if within a button truncation function
        if (buttonTruncationTimer) {
          clearTimeout(buttonTruncationTimer);
        }
        buttonTruncationTimer = setTimeout(function () {
          buttonTruncationTimer = undefined;
          go();
        }, 0);
      }
    };

    var toggleFullWidthScorebar = function (enabled) {
      if (sections.scorebar &&
          sections.scorebar.$element &&
          sections.scorebar.$element.hasClass('h5p-question-visible')) {
        sections.buttons.$element.addClass('has-scorebar');
        sections.buttons.$element.toggleClass('wrap', enabled);
        sections.scorebar.$element.toggleClass('full-width', enabled);
      }
      else {
        sections.buttons.$element.removeClass('has-scorebar');
      }
    };

    /**
     * Remove button labels until they use less than max width.
     *
     * @private
     * @param {Number} buttonsWidth Total width of all buttons
     * @param {Number} maxButtonsWidth Max width allowed for buttons
     */
    var removeButtonLabels = function (buttonsWidth, maxButtonsWidth) {
      // Reverse traversal
      for (var i = buttonOrder.length - 1; i >= 0; i--) {
        var buttonId = buttonOrder[i];
        var button = buttons[buttonId];
        if (!button.isTruncated && button.isVisible) {
          var $button = button.$element;
          buttonsWidth -= button.width.max - button.width.min;

          // Remove label
          button.$element.attr('aria-label', $button.text()).html('').addClass('truncated');
          button.isTruncated = true;
          if (buttonsWidth <= maxButtonsWidth) {
            // Buttons are small enough.
            return;
          }
        }
      }
    };

    /**
     * Restore button labels until it fills maximum possible width without exceeding the max width.
     *
     * @private
     * @param {Number} buttonsWidth Total width of all buttons
     * @param {Number} maxButtonsWidth Max width allowed for buttons
     */
    var restoreButtonLabels = function (buttonsWidth, maxButtonsWidth) {
      for (var i = 0; i < buttonOrder.length; i++) {
        var buttonId = buttonOrder[i];
        var button = buttons[buttonId];
        if (button.isTruncated && button.isVisible) {
          // Calculate new total width of buttons with a static pixel for consistency cross-browser
          buttonsWidth += button.width.max - button.width.min + 1;

          if (buttonsWidth > maxButtonsWidth) {
            return;
          }
          // Restore label
          button.$element.html(button.text);
          button.$element.removeClass('truncated');
          button.isTruncated = false;
        }
      }
    };

    /**
     * Helper function for finding index of keyValue in array
     *
     * @param {String} keyValue Value to be found
     * @param {String} key In key
     * @param {Array} array In array
     * @returns {number}
     */
    var existsInArray = function (keyValue, key, array) {
      var i;
      for (i = 0; i < array.length; i++) {
        if (array[i][key] === keyValue) {
          return i;
        }
      }
      return -1;
    };

    /**
     * Show a section
     * @param {Object} section
     */
    var showSection = function (section) {
      section.$element.addClass('h5p-question-visible');
      section.isVisible = true;
    };

    /**
     * Hide a section
     * @param {Object} section
     */
    var hideSection = function (section) {
      section.$element.css('max-height', '');
      section.isVisible = false;

      setTimeout(function () {
        // Only hide if section hasn't been set to visible in the meantime
        if (!section.isVisible) {
          section.$element.removeClass('h5p-question-visible');
        }
      }, 150);
    };

    /**
     * Set behaviour for question.
     *
     * @param {Object} options An object containing behaviour that will be extended by Question
     */
    self.setBehaviour = function (options) {
      $.extend(behaviour, options);
    };

    /**
     * A video to display above the task.
     *
     * @param {object} params
     */
    self.setVideo = function (params) {
      sections.video = {
        $element: $('<div/>', {
          'class': 'h5p-question-video'
        })
      };

      if (disableAutoPlay && params.params.playback) {
        params.params.playback.autoplay = false;
      }

      // Never fit to wrapper
      if (!params.params.visuals) {
        params.params.visuals = {};
      }
      params.params.visuals.fit = false;
      sections.video.instance = H5P.newRunnable(params, self.contentId, sections.video.$element, true);
      var fromVideo = false; // Hack to avoid never ending loop
      sections.video.instance.on('resize', function () {
        fromVideo = true;
        self.trigger('resize');
        fromVideo = false;
      });
      self.on('resize', function () {
        if (!fromVideo) {
          sections.video.instance.trigger('resize');
        }
      });

      return self;
    };

    /**
     * Will stop any playback going on in the task.
     */
    self.pause = function () {
      if (sections.video && sections.video.isVisible) {
        sections.video.instance.pause();
      }
    };

    /**
     * Start playback of video
     */
    self.play = function () {
      if (sections.video && sections.video.isVisible) {
        sections.video.instance.play();
      }
    };

    /**
     * Disable auto play, useful in editors.
     */
    self.disableAutoPlay = function () {
      disableAutoPlay = true;
    };

    /**
     * Add task image.
     *
     * @param {string} path Relative
     * @param {Object} [options] Options object
     * @param {string} [options.alt] Text representation
     * @param {string} [options.title] Hover text
     * @param {Boolean} [options.disableImageZooming] Set as true to disable image zooming
     */
    self.setImage = function (path, options) {
      options = options ? options : {};
      sections.image = {};
      // Image container
      sections.image.$element = $('<div/>', {
        'class': 'h5p-question-image h5p-question-image-fill-width'
      });

      // Inner wrap
      var $imgWrap = $('<div/>', {
        'class': 'h5p-question-image-wrap',
        appendTo: sections.image.$element
      });

      // Image element
      var $img = $('<img/>', {
        src: H5P.getPath(path, self.contentId),
        alt: (options.alt === undefined ? '' : options.alt),
        title: (options.title === undefined ? '' : options.title),
        on: {
          load: function () {
            self.trigger('imageLoaded', this);
            self.trigger('resize');
          }
        },
        appendTo: $imgWrap
      });

      // Disable image zooming
      if (options.disableImageZooming) {
        $img.css('maxHeight', 'none');

        // Make sure we are using the correct amount of width at all times
        var determineImgWidth = function () {

          // Remove margins if natural image width is bigger than section width
          var imageSectionWidth = sections.image.$element.get(0).getBoundingClientRect().width;

          // Do not transition, for instant measurements
          $imgWrap.css({
            '-webkit-transition': 'none',
            'transition': 'none'
          });

          // Margin as translateX on both sides of image.
          var diffX = 2 * ($imgWrap.get(0).getBoundingClientRect().left -
            sections.image.$element.get(0).getBoundingClientRect().left);

          if ($img.get(0).naturalWidth >= imageSectionWidth - diffX) {
            sections.image.$element.addClass('h5p-question-image-fill-width');
          }
          else { // Use margin for small res images
            sections.image.$element.removeClass('h5p-question-image-fill-width');
          }

          // Reset transition rules
          $imgWrap.css({
            '-webkit-transition': '',
            'transition': ''
          });
        };

        // Determine image width
        if ($img.is(':visible')) {
          determineImgWidth();
        }
        else {
          $img.on('load', determineImgWidth);
        }

        // Skip adding zoom functionality
        return;
      }

      var sizeDetermined = false;
      var determineSize = function () {
        if (sizeDetermined || !$img.is(':visible')) {
          return; // Try again next time.
        }

        $imgWrap.addClass('h5p-question-image-scalable')
          .attr('aria-expanded', false)
          .attr('role', 'button')
          .attr('tabIndex', '0')
          .on('click', function (event) {
            if (event.which === 1) {
              scaleImage.apply(this); // Left mouse button click
            }
          }).on('keypress', function (event) {
            if (event.which === 32) {
              event.preventDefault(); // Prevent default behaviour; page scroll down
              scaleImage.apply(this); // Space bar pressed
            }
          });
        sections.image.$element.removeClass('h5p-question-image-fill-width');

        sizeDetermined  = true; // Prevent any futher events
      };

      self.on('resize', determineSize);

      return self;
    };

    /**
     * Add the introduction section.
     *
     * @param {(string|H5P.jQuery)} content
     */
    self.setIntroduction = function (content) {
      register('introduction', content);

      return self;
    };

    /**
     * Add the content section.
     *
     * @param {(string|H5P.jQuery)} content
     * @param {Object} [options]
     * @param {string} [options.class]
     */
    self.setContent = function (content, options) {
      register('content', content);

      if (options && options.class) {
        sections.content.$element.addClass(options.class);
      }

      return self;
    };

    /**
     * Force readspeaker to read text. Useful when you have to use
     * setTimeout for animations.
     */
    self.read = function (content) {
      if (!$read) {
        return; // Not ready yet
      }

      if (readText) {
        // Combine texts if called multiple times
        readText += (readText.substr(-1, 1) === '.' ? ' ' : '. ') + content;
      }
      else {
        readText = content;
      }

      // Set text
      $read.html(readText);

      setTimeout(function () {
        // Stop combining when done reading
        readText = null;
        $read.html('');
      }, 100);
    };

    /**
     * Read feedback
     */
    self.readFeedback = function () {
      var invalidFeedback =
        behaviour.disableReadSpeaker ||
        !showFeedback ||
        !sections.feedback ||
        !sections.feedback.$element;

      if (invalidFeedback) {
        return;
      }

      var $feedbackText = $('.h5p-question-feedback-content-text', sections.feedback.$element);
      if ($feedbackText && $feedbackText.html() && $feedbackText.html().length) {
        self.read($feedbackText.html());
      }
    };

    /**
     * Remove feedback
     *
     * @return {H5P.Question}
     */
    self.removeFeedback = function () {

      clearTimeout(feedbackTransitionTimer);

      if (sections.feedback && showFeedback) {

        showFeedback = false;

        // Hide feedback & scorebar
        hideSection(sections.scorebar);
        hideSection(sections.feedback);

        sectionsIsTransitioning = true;

        // Detach after transition
        feedbackTransitionTimer = setTimeout(function () {
          // Avoiding Transition.onTransitionEnd since it will register multiple events, and there's no way to cancel it if the transition changes back to "show" while the animation is happening.
          if (!showFeedback) {
            sections.feedback.$element.children().detach();
            sections.scorebar.$element.children().detach();

            // Trigger resize after animation
            self.trigger('resize');
          }
          sectionsIsTransitioning = false;
          scoreBar.setScore(0);
        }, 150);

        if ($wrapper) {
          $wrapper.find('.h5p-question-feedback-tail').remove();
        }
      }

      return self;
    };

    /**
     * Set feedback message.
     *
     * @param {string} [content]
     * @param {number} score The score
     * @param {number} maxScore The maximum score for this question
     * @param {string} [scoreBarLabel] Makes it easier for readspeakers to identify the scorebar
     * @param {string} [helpText] Help text that describes the score inside a tip icon
     * @param {object} [popupSettings] Extra settings for popup feedback
     * @param {boolean} [popupSettings.showAsPopup] Should the feedback display as popup?
     * @param {string} [popupSettings.closeText] Translation for close button text
     * @param {object} [popupSettings.click] Element representing where user clicked on screen
     */
    self.setFeedback = function (content, score, maxScore, scoreBarLabel, helpText, popupSettings, scoreExplanationButtonLabel) {
      // Feedback is disabled
      if (behaviour.disableFeedback) {
        return self;
      }

      // Need to toggle buttons right away to avoid flickering/blinking
      // Note: This means content types should invoke hide/showButton before setFeedback
      toggleButtons();

      clickElement = (popupSettings != null && popupSettings.click != null ? popupSettings.click : null);
      clearTimeout(feedbackTransitionTimer);

      var $feedback = $('<div>', {
        'class': 'h5p-question-feedback-container'
      });

      var $feedbackContent = $('<div>', {
        'class': 'h5p-question-feedback-content'
      }).appendTo($feedback);

      // Feedback text
      $('<div>', {
        'class': 'h5p-question-feedback-content-text',
        'html': content
      }).appendTo($feedbackContent);

      var $scorebar = $('<div>', {
        'class': 'h5p-question-scorebar-container'
      });
      if (scoreBar === undefined) {
        scoreBar = JoubelUI.createScoreBar(maxScore, scoreBarLabel, helpText, scoreExplanationButtonLabel);
      }
      scoreBar.appendTo($scorebar);

      $feedbackContent.toggleClass('has-content', content !== undefined && content.length > 0);

      // Feedback for readspeakers
      if (!behaviour.disableReadSpeaker && scoreBarLabel) {
        self.read(scoreBarLabel.replace(':num', score).replace(':total', maxScore) + '. ' + (content ? content : ''));
      }

      showFeedback = true;
      if (sections.feedback) {
        // Update section
        update('feedback', $feedback);
        update('scorebar', $scorebar);
      }
      else {
        // Create section
        register('feedback', $feedback);
        register('scorebar', $scorebar);
        if (initialized && $wrapper) {
          insert(self.order, 'feedback', sections, $wrapper);
          insert(self.order, 'scorebar', sections, $wrapper);
        }
      }

      showSection(sections.feedback);
      showSection(sections.scorebar);

      resizeButtons();

      if (popupSettings != null && popupSettings.showAsPopup == true) {
        makeFeedbackPopup(popupSettings.closeText);
        scoreBar.setScore(score);
      }
      else {
        // Show feedback section
        feedbackTransitionTimer = setTimeout(function () {
          setElementHeight(sections.feedback.$element);
          setElementHeight(sections.scorebar.$element);
          sectionsIsTransitioning = true;

          // Scroll to bottom after showing feedback
          scrollToBottom();

          // Trigger resize after animation
          feedbackTransitionTimer = setTimeout(function () {
            sectionsIsTransitioning = false;
            self.trigger('resize');
            scoreBar.setScore(score);
          }, 150);
        }, 0);
      }

      return self;
    };

    /**
     * Set feedback content (no animation).
     *
     * @param {string} content
     * @param {boolean} [extendContent] True will extend content, instead of replacing it
     */
    self.updateFeedbackContent = function (content, extendContent) {
      if (sections.feedback && sections.feedback.$element) {

        if (extendContent) {
          content = $('.h5p-question-feedback-content', sections.feedback.$element).html() + ' ' + content;
        }

        // Update feedback content html
        $('.h5p-question-feedback-content', sections.feedback.$element).html(content).addClass('has-content');

        // Make sure the height is correct
        setElementHeight(sections.feedback.$element);

        // Need to trigger resize when feedback has finished transitioning
        setTimeout(self.trigger.bind(self, 'resize'), 150);
      }

      return self;
    };

    /**
     * Set the content of the explanation / feedback panel
     *
     * @param {Object} data
     * @param {string} data.correct
     * @param {string} data.wrong
     * @param {string} data.text
     * @param {string} title Title for explanation panel
     *
     * @return {H5P.Question}
     */
    self.setExplanation = function (data, title) {
      if (data) {
        var explainer = new H5P.Question.Explainer(title, data);

        if (sections.explanation) {
          // Update section
          update('explanation', explainer.getElement());
        }
        else {
          register('explanation', explainer.getElement());

          if (initialized && $wrapper) {
            insert(self.order, 'explanation', sections, $wrapper);
          }
        }
      }
      else if (sections.explanation) {
        // Hide explanation section
        sections.explanation.$element.children().detach();
      }

      return self;
    };

    /**
     * Checks to see if button is registered.
     *
     * @param {string} id
     * @returns {boolean}
     */
    self.hasButton = function (id) {
      return (buttons[id] !== undefined);
    };

    /**
     * @typedef {Object} ConfirmationDialog
     * @property {boolean} [enable] Must be true to show confirmation dialog
     * @property {Object} [instance] Instance that uses confirmation dialog
     * @property {jQuery} [$parentElement] Append to this element.
     * @property {Object} [l10n] Translatable fields
     * @property {string} [l10n.header] Header text
     * @property {string} [l10n.body] Body text
     * @property {string} [l10n.cancelLabel]
     * @property {string} [l10n.confirmLabel]
     */

    /**
     * Register buttons for the task.
     *
     * @param {string} id
     * @param {string} text label
     * @param {function} clicked
     * @param {boolean} [visible=true]
     * @param {Object} [options] Options for button
     * @param {Object} [extras] Extra options
     * @param {ConfirmationDialog} [extras.confirmationDialog] Confirmation dialog
     * @param {Object} [extras.contentData] Content data
     * @params {string} [extras.textIfSubmitting] Text to display if submitting
     */
    self.addButton = function (id, text, clicked, visible, options, extras) {
      if (buttons[id]) {
        return self; // Already registered
      }

      if (sections.buttons === undefined)  {
        // We have buttons, register wrapper
        register('buttons');
        if (initialized) {
          insert(self.order, 'buttons', sections, $wrapper);
        }
      }

      extras = extras || {};
      extras.confirmationDialog = extras.confirmationDialog || {};
      options = options || {};

      var confirmationDialog =
        self.addConfirmationDialogToButton(extras.confirmationDialog, clicked);

      /**
       * Handle button clicks through both mouse and keyboard
       * @private
       */
      var handleButtonClick = function () {
        if (extras.confirmationDialog.enable && confirmationDialog) {
          // Show popups section if used
          if (!extras.confirmationDialog.$parentElement) {
            sections.popups.$element.removeClass('hidden');
          }
          confirmationDialog.show($e.position().top);
        }
        else {
          clicked();
        }
      };

      const isSubmitting = extras.contentData && extras.contentData.standalone
        && (extras.contentData.isScoringEnabled || extras.contentData.isReportingEnabled);

      if (isSubmitting && extras.textIfSubmitting) {
        text = extras.textIfSubmitting;
      }

      buttons[id] = {
        isTruncated: false,
        text: text,
        isVisible: false
      };
      // The button might be <button> or <a>
      // (dependent on options.href set or not)
      var isAnchorTag = (options.href !== undefined);
      var $e = buttons[id].$element = JoubelUI.createButton($.extend({
        'class': 'h5p-question-' + id,
        html: text,
        title: text,
        on: {
          click: function (event) {
            handleButtonClick();
            if (isAnchorTag) {
              event.preventDefault();
            }
          }
        }
      }, options));
      buttonOrder.push(id);

      // The button might be <button> or <a>. If <a>, the space key is not
      // triggering the click event, must therefore handle this here:
      if (isAnchorTag) {
        $e.on('keypress', function (event) {
          if (event.which === 32) { // Space
            handleButtonClick();
            event.preventDefault();
          }
        });
      }

      if (visible === undefined || visible) {
        // Button should be visible
        $e.appendTo(sections.buttons.$element);
        buttons[id].isVisible = true;
        showSection(sections.buttons);
      }

      return self;
    };

    var setButtonWidth = function (button) {
      var $button = button.$element;
      var $tmp = $button.clone()
        .css({
          'position': 'absolute',
          'white-space': 'nowrap',
          'max-width': 'none'
        }).removeClass('truncated')
        .html(button.text)
        .appendTo($button.parent());

      // Calculate max width (button including text)
      button.width = {
        max: Math.ceil($tmp.outerWidth() + parseFloat($tmp.css('margin-left')) + parseFloat($tmp.css('margin-right')))
      };

      // Calculate min width (truncated, icon only)
      $tmp.html('').addClass('truncated');
      button.width.min = Math.ceil($tmp.outerWidth() + parseFloat($tmp.css('margin-left')) + parseFloat($tmp.css('margin-right')));
      $tmp.remove();
    };

    /**
     * Add confirmation dialog to button
     * @param {ConfirmationDialog} options
     *  A confirmation dialog that will be shown before click handler of button
     *  is triggered
     * @param {function} clicked
     *  Click handler of button
     * @return {H5P.ConfirmationDialog|undefined}
     *  Confirmation dialog if enabled
     */
    self.addConfirmationDialogToButton = function (options, clicked) {
      options = options || {};

      if (!options.enable) {
        return;
      }

      // Confirmation dialog
      var confirmationDialog = new H5P.ConfirmationDialog({
        instance: options.instance,
        headerText: options.l10n.header,
        dialogText: options.l10n.body,
        cancelText: options.l10n.cancelLabel,
        confirmText: options.l10n.confirmLabel
      });

      // Determine parent element
      if (options.$parentElement) {
        confirmationDialog.appendTo(options.$parentElement.get(0));
      }
      else {

        // Create popup section and append to that
        if (sections.popups === undefined) {
          register('popups');
          if (initialized) {
            insert(self.order, 'popups', sections, $wrapper);
          }
          sections.popups.$element.addClass('hidden');
          self.order.push('popups');
        }
        confirmationDialog.appendTo(sections.popups.$element.get(0));
      }

      // Add event listeners
      confirmationDialog.on('confirmed', function () {
        if (!options.$parentElement) {
          sections.popups.$element.addClass('hidden');
        }
        clicked();

        // Trigger to content type
        self.trigger('confirmed');
      });

      confirmationDialog.on('canceled', function () {
        if (!options.$parentElement) {
          sections.popups.$element.addClass('hidden');
        }
        // Trigger to content type
        self.trigger('canceled');
      });

      return confirmationDialog;
    };

    /**
     * Show registered button with given identifier.
     *
     * @param {string} id
     * @param {Number} [priority]
     */
    self.showButton = function (id, priority) {
      var aboutToBeHidden = existsInArray(id, 'id', buttonsToHide) !== -1;
      if (buttons[id] === undefined || (buttons[id].isVisible === true && !aboutToBeHidden)) {
        return self;
      }

      priority = priority || 0;

      // Skip if already being shown
      var indexToShow = existsInArray(id, 'id', buttonsToShow);
      if (indexToShow !== -1) {

        // Update priority
        if (buttonsToShow[indexToShow].priority < priority) {
          buttonsToShow[indexToShow].priority = priority;
        }

        return self;
      }

      // Check if button is going to be hidden on next tick
      var exists = existsInArray(id, 'id', buttonsToHide);
      if (exists !== -1) {

        // Skip hiding if higher priority
        if (buttonsToHide[exists].priority <= priority) {
          buttonsToHide.splice(exists, 1);
          buttonsToShow.push({id: id, priority: priority});
        }

      } // If button is not shown
      else if (!buttons[id].$element.is(':visible')) {

        // Show button on next tick
        buttonsToShow.push({id: id, priority: priority});
      }

      if (!toggleButtonsTimer) {
        toggleButtonsTimer = setTimeout(toggleButtons, 0);
      }

      return self;
    };

    /**
     * Hide registered button with given identifier.
     *
     * @param {string} id
     * @param {number} [priority]
     */
    self.hideButton = function (id, priority) {
      var aboutToBeShown = existsInArray(id, 'id', buttonsToShow) !== -1;
      if (buttons[id] === undefined || (buttons[id].isVisible === false && !aboutToBeShown)) {
        return self;
      }

      priority = priority || 0;

      // Skip if already being hidden
      var indexToHide = existsInArray(id, 'id', buttonsToHide);
      if (indexToHide !== -1) {

        // Update priority
        if (buttonsToHide[indexToHide].priority < priority) {
          buttonsToHide[indexToHide].priority = priority;
        }

        return self;
      }

      // Check if buttons is going to be shown on next tick
      var exists = existsInArray(id, 'id', buttonsToShow);
      if (exists !== -1) {

        // Skip showing if higher priority
        if (buttonsToShow[exists].priority <= priority) {
          buttonsToShow.splice(exists, 1);
          buttonsToHide.push({id: id, priority: priority});
        }
      }
      else if (!buttons[id].$element.is(':visible')) {

        // Make sure it is detached in case the container is hidden.
        hideButton(id);
      }
      else {

        // Hide button on next tick.
        buttonsToHide.push({id: id, priority: priority});
      }

      if (!toggleButtonsTimer) {
        toggleButtonsTimer = setTimeout(toggleButtons, 0);
      }

      return self;
    };

    /**
     * Set focus to the given button. If no button is given the first visible
     * button gets focused. This is useful if you lose focus.
     *
     * @param {string} [id]
     */
    self.focusButton = function (id) {
      if (id === undefined) {
        // Find first button that is visible.
        for (var i = 0; i < buttonOrder.length; i++) {
          var button = buttons[buttonOrder[i]];
          if (button && button.isVisible) {
            // Give that button focus
            button.$element.focus();
            break;
          }
        }
      }
      else if (buttons[id] && buttons[id].$element.is(':visible')) {
        // Set focus to requested button
        buttons[id].$element.focus();
      }

      return self;
    };

    /**
     * Toggle readspeaker functionality
     * @param {boolean} [disable] True to disable, false to enable.
     */
    self.toggleReadSpeaker = function (disable) {
      behaviour.disableReadSpeaker = disable || !behaviour.disableReadSpeaker;
    };

    /**
     * Set new element for section.
     *
     * @param {String} id
     * @param {H5P.jQuery} $element
     */
    self.insertSectionAtElement = function (id, $element) {
      if (sections[id] === undefined) {
        register(id);
      }
      sections[id].parent = $element;

      // Insert section if question is not initialized
      if (!initialized) {
        insert([id], id, sections, $element);
      }

      return self;
    };

    /**
     * Attach content to given container.
     *
     * @param {H5P.jQuery} $container
     */
    self.attach = function ($container) {
      if (self.isRoot()) {
        self.setActivityStarted();
      }

      // The first time we attach we also create our DOM elements.
      if ($wrapper === undefined) {
        if (self.registerDomElements !== undefined &&
           (self.registerDomElements instanceof Function ||
           typeof self.registerDomElements === 'function')) {

          // Give the question type a chance to register before attaching
          self.registerDomElements();
        }

        // Create section for reading messages
        $read = $('<div/>', {
          'aria-live': 'polite',
          'class': 'h5p-hidden-read'
        });
        register('read', $read);
        self.trigger('registerDomElements');
      }

      // Prepare container
      $wrapper = $container;
      $container.html('')
        .addClass('h5p-question h5p-' + type);

      // Add sections in given order
      var $sections = [];
      for (var i = 0; i < self.order.length; i++) {
        var section = self.order[i];
        if (sections[section]) {
          if (sections[section].parent) {
            // Section has a different parent
            sections[section].$element.appendTo(sections[section].parent);
          }
          else {
            $sections.push(sections[section].$element);
          }
          sections[section].isVisible = true;
        }
      }

      // Only append once to DOM for optimal performance
      $container.append($sections);

      // Let others react to dom changes
      self.trigger('domChanged', {
        '$target': $container,
        'library': self.libraryInfo.machineName,
        'contentId': self.contentId,
        'key': 'newLibrary'
      }, {'bubbles': true, 'external': true});

      // ??
      initialized = true;

      return self;
    };

    /**
     * Detach all sections from their parents
     */
    self.detachSections = function () {
      // Deinit Question
      initialized = false;

      // Detach sections
      for (var section in sections) {
        sections[section].$element.detach();
      }

      return self;
    };

    // Listen for resize
    self.on('resize', function () {
      // Allow elements to attach and set their height before resizing
      if (!sectionsIsTransitioning && sections.feedback && showFeedback) {
        // Resize feedback to fit
        setElementHeight(sections.feedback.$element);
      }

      // Re-position feedback popup if in use
      var $element = sections.feedback;
      var $click = clickElement;

      if ($element != null && $element.$element != null && $click != null && $click.$element != null) {
        setTimeout(function () {
          positionFeedbackPopup($element.$element, $click.$element);
        }, 10);
      }

      resizeButtons();
    });
  }

  // Inheritance
  Question.prototype = Object.create(EventDispatcher.prototype);
  Question.prototype.constructor = Question;

  /**
   * Determine the overall feedback to display for the question.
   * Returns empty string if no matching range is found.
   *
   * @param {Object[]} feedbacks
   * @param {number} scoreRatio
   * @return {string}
   */
  Question.determineOverallFeedback = function (feedbacks, scoreRatio) {
    scoreRatio = Math.floor(scoreRatio * 100);

    for (var i = 0; i < feedbacks.length; i++) {
      var feedback = feedbacks[i];
      var hasFeedback = (feedback.feedback !== undefined && feedback.feedback.trim().length !== 0);

      if (feedback.from <= scoreRatio && feedback.to >= scoreRatio && hasFeedback) {
        return feedback.feedback;
      }
    }

    return '';
  };

  return Question;
})(H5P.jQuery, H5P.EventDispatcher, H5P.JoubelUI);
;H5P.Question.Explainer = (function ($) {
  /**
   * Constructor
   *
   * @class
   * @param {string} title
   * @param {array} explanations
   */
  function Explainer(title, explanations) {
    var self = this;

    /**
     * Create the DOM structure
     */
    var createHTML = function () {
      self.$explanation = $('<div>', {
        'class': 'h5p-question-explanation-container'
      });

      // Add title:
      $('<div>', {
        'class': 'h5p-question-explanation-title',
        role: 'heading',
        html: title,
        appendTo: self.$explanation
      });

      var $explanationList = $('<ul>', {
        'class': 'h5p-question-explanation-list',
        appendTo: self.$explanation
      });

      for (var i = 0; i < explanations.length; i++) {
        var feedback = explanations[i];
        var $explanationItem = $('<li>', {
          'class': 'h5p-question-explanation-item',
          appendTo: $explanationList
        });

        var $content = $('<div>', {
          'class': 'h5p-question-explanation-status'
        });

        if (feedback.correct) {
          $('<span>', {
            'class': 'h5p-question-explanation-correct',
            html: feedback.correct,
            appendTo: $content
          });
        }
        if (feedback.wrong) {
          $('<span>', {
            'class': 'h5p-question-explanation-wrong',
            html: feedback.wrong,
            appendTo: $content
          });
        }
        $content.appendTo($explanationItem);

        if (feedback.text) {
          $('<div>', {
            'class': 'h5p-question-explanation-text',
            html: feedback.text,
            appendTo: $explanationItem
          });
        }
      }
    };

    createHTML();

    /**
     * Return the container HTMLElement
     *
     * @return {HTMLElement}
     */
    self.getElement = function () {
      return self.$explanation;
    };
  }

  return Explainer;

})(H5P.jQuery);
;(function (Question) {

  /**
   * Makes it easy to add animated score points for your question type.
   *
   * @class H5P.Question.ScorePoints
   */
  Question.ScorePoints = function () {
    var self = this;

    var elements = [];
    var showElementsTimer;

    /**
     * Create the element that displays the score point element for questions.
     *
     * @param {boolean} isCorrect
     * @return {HTMLElement}
     */
    self.getElement = function (isCorrect) {
      var element = document.createElement('div');
      element.classList.add(isCorrect ? 'h5p-question-plus-one' : 'h5p-question-minus-one');
      element.classList.add('h5p-question-hidden-one');
      elements.push(element);

      // Schedule display animation of all added elements
      if (showElementsTimer) {
        clearTimeout(showElementsTimer);
      }
      showElementsTimer = setTimeout(showElements, 0);

      return element;
    };

    /**
     * @private
     */
    var showElements = function () {
      // Determine delay between triggering animations
      var delay = 0;
      var increment = 150;
      var maxTime = 1000;

      if (elements.length && elements.length > Math.ceil(maxTime / increment)) {
        // Animations will run for more than ~1 second, reduce it.
        increment = maxTime / elements.length;
      }

      for (var i = 0; i < elements.length; i++) {
        // Use timer to trigger show
        setTimeout(showElement(elements[i]), delay);

        // Increse delay for next element
        delay += increment;
      }
    };

    /**
     * Trigger transition animation for the given element
     *
     * @private
     * @param {HTMLElement} element
     * @return {function}
     */
    var showElement = function (element) {
      return function () {
        element.classList.remove('h5p-question-hidden-one');
      };
    };
  };

})(H5P.Question);
;/* Ractive.js v0.8.14-9cf380262b870f4fd676e2fd42accf8be9a22c5b - License MIT */
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):function(){var n=t.Ractive,i=e();i.noConflict=function(){return t.Ractive=n,i},t.Ractive=i}()}(this,function(){"use strict";function t(){return ms.createDocumentFragment()}function e(t){var e;if(t&&"boolean"!=typeof t)return ds&&ms&&t?t.nodeType?t:"string"==typeof t&&(e=ms.getElementById(t),!e&&ms.querySelector&&(e=ms.querySelector(t)),e&&e.nodeType)?e:t[0]&&t[0].nodeType?t[0]:null:null}function n(t){return t&&"unknown"!=typeof t.parentNode&&t.parentNode&&t.parentNode.removeChild(t),t}function i(t){return null!=t&&t.toString?""+t:""}function r(t){return i(t).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function o(t){return t.replace(Ms,function(t){return"-"+t.toLowerCase()})}function s(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];var i;return e.forEach(function(e){for(i in e)Rs.call(e,i)&&(t[i]=e[i])}),t}function a(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];return e.forEach(function(e){for(var n in e)!Rs.call(e,n)||n in t||(t[n]=e[n])}),t}function h(t){return"[object Array]"===Ls.call(t)}function u(t,e){return null===t&&null===e||"object"!=typeof t&&"object"!=typeof e&&t===e}function l(t){return!isNaN(parseFloat(t))&&isFinite(t)}function c(t){return t&&"[object Object]"===Ls.call(t)}function p(){}function f(t,e){return t.replace(/%s/g,function(){return e.shift()})}function d(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];throw t=f(t,e),new Error(t)}function m(){ls.DEBUG&&Bs.apply(null,arguments)}function g(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];t=f(t,e),Ks(t,e)}function v(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];t=f(t,e),Ds[t]||(Ds[t]=!0,Ks(t,e))}function y(){ls.DEBUG&&g.apply(null,arguments)}function b(){ls.DEBUG&&v.apply(null,arguments)}function w(t,e,n){var i=k(t,e,n);return i?i[t][n]:null}function k(t,e,n){for(;e;){if(n in e[t])return e;if(e.isolated)return null;e=e.parent}}function x(t,e,n,i){if(t===e)return null;if(i){var r=w("interpolators",n,i);if(r)return r(t,e)||null;d($s(i,"interpolator"))}return qs.number(t,e)||qs.array(t,e)||qs.object(t,e)||null}function E(t){return function(){return t}}function _(t,e){-1===t.indexOf(e)&&t.push(e)}function A(t,e){for(var n=0,i=t.length;n<i;n++)if(t[n]==e)return!0;return!1}function O(t,e){var n;if(!h(t)||!h(e))return!1;if(t.length!==e.length)return!1;for(n=t.length;n--;)if(t[n]!==e[n])return!1;return!0}function S(t){return"string"==typeof t?[t]:void 0===t?[]:t}function C(t){return t[t.length-1]}function j(t,e){if(t){var n=t.indexOf(e);-1!==n&&t.splice(n,1)}}function T(t){for(var e=[],n=t.length;n--;)e[n]=t[n];return e}function F(t){setTimeout(t,0)}function N(t,e){return function(){for(var n;n=t.shift();)n(e)}}function P(t,e,n,i){var r;if(e===t)throw new TypeError("A promise's fulfillment handler cannot return the same promise");if(e instanceof Qs)e.then(n,i);else if(!e||"object"!=typeof e&&"function"!=typeof e)n(e);else{try{r=e.then}catch(t){return void i(t)}if("function"==typeof r){var o,s,a;s=function(e){o||(o=!0,P(t,e,n,i))},a=function(t){o||(o=!0,i(t))};try{r.call(e,s,a)}catch(t){if(!o)return i(t),void(o=!0)}}else n(e)}}function V(t){t.detach()}function M(t){t.detachNodes()}function B(t){!t.ready||t.outros.length||t.outroChildren||(t.outrosComplete||(t.outrosComplete=!0,t.parent&&!t.parent.outrosComplete?t.parent.decrementOutros(t):t.detachNodes()),t.intros.length||t.totalChildren||("function"==typeof t.callback&&t.callback(),t.parent&&!t.notifiedTotal&&(t.notifiedTotal=!0,t.parent.decrementTotal())))}function K(t){var e,n,i=t.detachQueue,r=I(t),o=i.length,s=0;t:for(;o--;){for(e=i[o].node,s=r.length;s--;)if((n=r[s].element.node)===e||n.contains(e)||e.contains(n))continue t;i[o].detach(),i.splice(o,1)}}function I(t,e){if(e){for(var n=t.children.length;n--;)e=I(t.children[n],e);return e=e.concat(t.outros)}e=[];for(var i=t;i.parent;)i=i.parent;return I(i,e)}function R(t){t.dispatch()}function L(){var t=ea.immediateObservers;ea.immediateObservers=[],t.forEach(R);var e,n=ea.fragments.length;t=ea.fragments,ea.fragments=[];var i=ea.ractives;for(ea.ractives=[];n--;){e=t[n];var r=e.ractive;Object.keys(r.viewmodel.changes).length&&na.fire(r,r.viewmodel.changes),r.viewmodel.changes={},j(i,r),e.update()}for(n=i.length;n--;){var o=i[n];na.fire(o,o.viewmodel.changes),o.viewmodel.changes={}}ea.transitionManager.ready(),t=ea.deferredObservers,ea.deferredObservers=[],t.forEach(R);var s=ea.tasks;for(ea.tasks=[],n=0;n<s.length;n+=1)s[n]();if(ea.fragments.length||ea.immediateObservers.length||ea.deferredObservers.length||ea.ractives.length||ea.tasks.length)return L()}function D(t){return"string"==typeof t?t.replace(sa,"\\$&"):t}function W(t){return t?t.replace(ra,".$1"):""}function U(t){var e,n=[];for(t=W(t);e=oa.exec(t);){var i=e.index+e[1].length;n.push(t.substr(0,i)),t=t.substr(i+1)}return n.push(t),n}function z(t){return"string"==typeof t?t.replace(aa,"$1$2"):t}function $(t,e){if(!/this/.test(t.toString()))return t;var n=ha.call(t,e);for(var i in t)n[i]=t[i];return n}function q(t,e){for(var n=ia.start(t,!0),i=e.length;i--;){var r=e[i],o=r[0],s=r[1];"function"==typeof s&&(s=$(s,t)),o.set(s)}return ia.end(),n}function Z(t,e,n){return void 0===n&&(n=t.viewmodel),ua.test(e)?n.findMatches(U(e)):[n.joinAll(U(e))]}function H(t,e,n){var i=[];if(c(e)){for(var r in e)!function(n){e.hasOwnProperty(n)&&i.push.apply(i,Z(t,n).map(function(t){return[t,e[n]]}))}(r)}else i.push.apply(i,Z(t,e).map(function(t){return[t,n]}));return i}function Q(t,e,n){if("string"!=typeof e||!l(n))throw new Error("Bad arguments");return q(t,H(t,e,n).map(function(t){var e=t[0],n=t[1],i=e.get();if(!l(n)||!l(i))throw new Error(la);return[e,i+n]}))}function G(t,e){return Q(this,t,void 0===e?1:+e)}function Y(t,e){t=t||{};var n;return t.easing&&(n="function"==typeof t.easing?t.easing:e.easing[t.easing]),{easing:n||pa,duration:"duration"in t?t.duration:400,complete:t.complete||p,step:t.step||p}}function J(t,e,n,i){i=Y(i,t);var r=e.get();if(u(r,n))return i.complete(i.to),ca;var o=x(r,n,t,i.interpolator);return o?e.animate(r,n,i,o):(ia.start(),e.set(n),ia.end(),ca)}function X(t,e,n){if("object"==typeof t){var i=Object.keys(t);throw new Error("ractive.animate(...) no longer supports objects. Instead of ractive.animate({\n  "+i.map(function(e){return"'"+e+"': "+t[e]}).join("\n  ")+"\n}, {...}), do\n\n"+i.map(function(e){return"ractive.animate('"+e+"', "+t[e]+", {...});"}).join("\n")+"\n")}return J(this,this.viewmodel.joinAll(U(t)),e,n)}function tt(){return this.isDetached?this.el:(this.el&&j(this.el.__ractive_instances__,this),this.el=this.fragment.detach(),this.isDetached=!0,fa.fire(this),this.el)}function et(t){if(!this.el)throw new Error("Cannot call ractive.find('"+t+"') unless instance is rendered to the DOM");return this.fragment.find(t)}function nt(t,e){if(t.compareDocumentPosition){return 2&t.compareDocumentPosition(e)?1:-1}return it(t,e)}function it(t,e){for(var n,i=ot(t.component||t._ractive.proxy),r=ot(e.component||e._ractive.proxy),o=C(i),s=C(r);o&&o===s;)i.pop(),r.pop(),n=o,o=C(i),s=C(r);o=o.component||o,s=s.component||s;var a=o.parentFragment,h=s.parentFragment;if(a===h){return a.items.indexOf(o)-h.items.indexOf(s)||i.length-r.length}var u=n.iterations;if(u){return u.indexOf(a)-u.indexOf(h)||i.length-r.length}throw new Error("An unexpected condition was met while comparing the position of two components. Please file an issue at https://github.com/ractivejs/ractive/issues - thanks!")}function rt(t){var e=t.parentFragment;return e?e.owner:t.component&&(e=t.component.parentFragment)?e.owner:void 0}function ot(t){for(var e=[t],n=rt(t);n;)e.push(n),n=rt(n);return e}function st(t,e){if(!this.el)throw new Error("Cannot call ractive.findAll('"+t+"', ...) unless instance is rendered to the DOM");e=e||{};var n=this._liveQueries,i=n[t];return i?e&&e.live?i:i.slice():(i=new da(this,t,!!e.live,!1),i.live&&(n.push(t),n["_"+t]=i),this.fragment.findAll(t,i),i.init(),i.result)}function at(t,e){e=e||{};var n=this._liveComponentQueries,i=n[t];return i?e&&e.live?i:i.slice():(i=new da(this,t,!!e.live,!0),i.live&&(n.push(t),n["_"+t]=i),this.fragment.findAllComponents(t,i),i.init(),i.result)}function ht(t){return this.fragment.findComponent(t)}function ut(t){return this.container?this.container.component&&this.container.component.name===t?this.container:this.container.findContainer(t):null}function lt(t){return this.parent?this.parent.component&&this.parent.component.name===t?this.parent:this.parent.findParent(t):null}function ct(t,e){t.event&&t._eventQueue.push(t.event),t.event=e}function pt(t){t._eventQueue.length?t.event=t._eventQueue.pop():t.event=null}function ft(t){var e,n,i,r,o,s;for(e=U(t),(n=ga[e.length])||(n=dt(e.length)),o=[],i=function(t,n){return t?"*":e[n]},r=n.length;r--;)s=n[r].map(i).join("."),o.hasOwnProperty(s)||(o.push(s),o[s]=!0);return o}function dt(t){var e,n,i,r,o,s,a,h,u="";if(!ga[t]){for(i=[];u.length<t;)u+=1;for(e=parseInt(u,2),r=function(t){return"1"===t},o=0;o<=e;o+=1){for(n=o.toString(2);n.length<t;)n="0"+n;for(h=[],a=n.length,s=0;s<a;s++)h.push(r(n[s]));i[o]=h}ga[t]=i}return ga[t]}function mt(t,e,n){if(void 0===n&&(n={}),e){n.event?n.event.name=e:n.event={name:e,_noArg:!0};return vt(t,gt(e),n.event,n.args,!0)}}function gt(t){return va.hasOwnProperty(t)?va[t]:va[t]=ft(t)}function vt(t,e,n,i,r){void 0===r&&(r=!1);var o,s,a=!0;for(ct(t,n),s=e.length;s>=0;s--)(o=t._subs[e[s]])&&(a=yt(t,o,n,i)&&a);if(pt(t),t.parent&&a){if(r&&t.component){e=gt(t.component.name+"."+e[e.length-1]),n&&!n.component&&(n.component=t)}a=vt(t.parent,e,n,i)}return a}function yt(t,e,n,i){var r=null,o=!1;n&&!n._noArg&&(i=[n].concat(i)),e=e.slice();for(var s=0,a=e.length;s<a;s+=1)e[s].off||!1!==e[s].callback.apply(t,i)||(o=!0);return n&&!n._noArg&&o&&(r=n.original)&&(r.preventDefault&&r.preventDefault(),r.stopPropagation&&r.stopPropagation()),!o}function bt(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];return mt(this,t,{args:e})}function wt(t){throw new Error("An index or key reference ("+t+") cannot have child properties")}function kt(t,e){for(var n,i,r,o=t.findContext().root,s=U(e),a=s[0];t;){if(t.isIteration){if(a===t.parent.keyRef)return s.length>1&&wt(a),t.context.getKeyModel(t.key);if(a===t.parent.indexRef)return s.length>1&&wt(a),t.context.getKeyModel(t.index)}if(((r=t.owner.aliases)||(r=t.aliases))&&r.hasOwnProperty(a)){var h=r[a];if(1===s.length)return h;if("function"==typeof h.joinAll)return h.joinAll(s.slice(1))}if(t.context&&(t.isRoot&&!t.ractive.component||(n=!0),t.context.has(a)))return i?o.createLink(a,t.context.joinKey(s.shift()),a).joinAll(s):t.context.joinAll(s);t.componentParent&&!t.ractive.isolated?(t=t.componentParent,i=!0):t=t.parent}if(!n)return o.joinAll(s)}function xt(){ya.push(ma=[])}function Et(){var t=ya.pop();return ma=ya[ya.length-1],t}function _t(t){ma&&ma.push(t)}function At(t){t.bind()}function Ot(t){t.cancel()}function St(t){t.handleChange()}function Ct(t){t.mark()}function jt(t){t.marked()}function Tt(t){t.markedAll()}function Ft(t){t.notifiedUpstream()}function Nt(t){t.render()}function Pt(t){t.teardown()}function Vt(t){t.unbind()}function Mt(t){t.unrender()}function Bt(t){t.unrender(!0)}function Kt(t){t.update()}function It(t){return t.toString()}function Rt(t){return t.toString(!0)}function Lt(t){t.updateFromBindings(!0)}function Dt(t){for(var e=t.length;e--;)if(t[e].bound){var n=t[e].owner;if(n){var i="checked"===n.name?n.node.checked:n.node.value;return{value:i}}}}function Wt(t){if(t){var e=xa[t];xa[t]=[];for(var n=e.length;n--;)e[n]();var i=Ea[t];for(Ea[t]=[],n=i.length;n--;)i[n].model.register(i[n].item)}else Wt("early"),Wt("mark")}function Ut(t,e,n){var i=t.r||t;if(!i||"string"!=typeof i)return e;if("."===i||"@"===i[0]||(e||n).isKey||(e||n).isKeypath)return e;for(var r=i.split("/"),o=U(r[r.length-1]),s=e||n,a=o.length,h=!0,u=!1;s&&a--;)s.shuffling&&(u=!0),o[a]!=s.key&&(h=!1),s=s.parent;return!e&&h&&u?n:e&&!h&&u?n:e}function zt(){ia.start();var t,e,n=Ca();for(t=0;t<ja.length;t+=1)e=ja[t],e.tick(n)||ja.splice(t--,1);ia.end(),ja.length?Sa(zt):Ta=!1}function $t(t,e){var n,i={};if(!e)return t;e+=".";for(n in t)t.hasOwnProperty(n)&&(i[e+n]=t[n]);return i}function qt(t){var e;return Na[t]||(e=t?t+".":"",Na[t]=function(n,i){var r;return"string"==typeof n?(r={},r[e+n]=i,r):"object"==typeof n?e?$t(n,t):n:void 0}),Na[t]}function Zt(t){for(var e=[],n=0;n<t.length;n++)e[n]=(t.childByKey[n]||{}).value;return e}function Ht(t,e){var n=t.findContext();if("."===e||"this"===e)return n;if(0===e.indexOf("@keypath")){var i=Ba.exec(e);if(i&&i[1]){var r=Ht(t,i[1]);if(r)return r.getKeypathModel()}return n.getKeypathModel()}if(0===e.indexOf("@rootpath")){for(;n.isRoot&&n.ractive.component;)n=n.ractive.component.parentFragment.findContext();var o=Ba.exec(e);if(o&&o[1]){var s=Ht(t,o[1]);if(s)return s.getKeypathModel(t.ractive.root)}return n.getKeypathModel(t.ractive.root)}if("@index"===e||"@key"===e){var a=t.findRepeatingFragment();if(!a.isIteration)return;return a.context.getKeyModel(a["i"===e[1]?"index":"key"])}if("@this"===e)return t.ractive.viewmodel.getRactiveModel();if("@global"===e)return Ma;if("~"===e[0])return t.ractive.viewmodel.joinAll(U(e.slice(2)));if("."===e[0]){for(var h=e.split("/");"."===h[0]||".."===h[0];){".."===h.shift()&&(n=n.parent)}return e=h.join("/"),"."===e[0]&&(e=e.slice(1)),n.joinAll(U(e))}return kt(t,e)}function Qt(t,e){if("string"!=typeof t)return this.viewmodel.get(!0,t);var n,i=U(t),r=i[0];return this.viewmodel.has(r)||this.component&&!this.isolated&&(n=Ht(this.component.parentFragment,r))&&this.viewmodel.map(r,n),n=this.viewmodel.joinAll(i),n.get(!0,e)}function Gt(t){for(var e={},n={};t;){if(t.parent&&(t.parent.indexRef||t.parent.keyRef)){var i=t.parent.indexRef;!i||i in n||(n[i]=t.index),i=t.parent.keyRef,!i||i in e||(e[i]=t.key)}t=t.componentParent&&!t.ractive.isolated?t.componentParent:t.parent}return{key:e,index:n}}function Yt(t,e,n){var i,r,o,s,a,h=[];if(!(i=Jt(t,e,n)))return null;for(s=i.length-2-i[1],r=Math.min(t,i[0]),o=r+i[1],h.startIndex=r,a=0;a<r;a+=1)h.push(a);for(;a<o;a+=1)h.push(-1);for(;a<t;a+=1)h.push(a+s);return h.touchedFrom=0!==s?i[0]:t,h}function Jt(t,e,n){switch(e){case"splice":for(void 0!==n[0]&&n[0]<0&&(n[0]=t+Math.max(n[0],-t)),void 0===n[0]&&(n[0]=0);n.length<2;)n.push(t-n[0]);return"number"!=typeof n[1]&&(n[1]=t-n[0]),n[1]=Math.min(n[1],t-n[0]),n;case"sort":case"reverse":return null;case"pop":return t?[t-1,1]:[0,0];case"push":return[t,0].concat(n);case"shift":return[0,t?1:0];case"unshift":return[0,0].concat(n)}}function Xt(t){function e(t){for(var e=[],i=arguments.length-1;i-- >0;)e[i]=arguments[i+1];return n(this.viewmodel.joinAll(U(t)),e)}function n(e,n){var i=e.get();if(!h(i)){if(void 0===i){i=[];var r=Ka[t].apply(i,n),o=ia.start(this,!0).then(function(){return r});return e.set(i),ia.end(),o}throw new Error("shuffle array method "+t+" called on non-array at "+e.getKeypath())}var s=Yt(i.length,t,n),a=Ka[t].apply(i,n),u=ia.start(this,!0).then(function(){return a});return u.result=a,s?e.shuffle(s):e.set(a),ia.end(),u}return{path:e,model:n}}function te(t){if(!t)return null;if(!0===t)return JSON.stringify;if("function"==typeof t)return t;if("string"==typeof t)return Ia[t]||(Ia[t]=function(e){return e[t]});throw new Error("If supplied, options.compare must be a string, function, or `true`")}function ee(t,e,n,i){var r=ia.start(t,!0);if(!h(e.get())||!h(n))throw new Error("You cannot merge an array with a non-array");var o=te(i&&i.compare);return e.merge(n,o),ia.end(),r}function ne(t,e,n){return ee(this,this.viewmodel.joinAll(U(t)),e,n)}function ie(t,e){e.parent&&e.parent.wrapper&&e.parent.adapt();var n=ia.start(t,!0);if(e.mark(),e.registerChange(e.getKeypath(),e.get()),!e.isRoot)for(var i=e.parent,r=e.key;i&&!i.isRoot;)i.clearUnresolveds&&i.clearUnresolveds(r),r=i.key,i=i.parent;return e.notifyUpstream(),ia.end(),Ra.fire(t,e),n}function re(t){return t&&(t=U(t)),ie(this,t?this.viewmodel.joinAll(t):this.viewmodel)}function oe(t,e,n){var i=[];if(c(e))for(var r in e)e.hasOwnProperty(r)&&i.push([he(t,r).model,e[r]]);else i.push([he(t,e).model,n]);return i}function se(t){if(!t)return this._element.parentFragment.findContext().get(!0);var e=Ht(this._element.parentFragment,t);return e?e.get(!0):void 0}function ae(t,e){var n=he(this,t),i=n.model,r=n.instance;return i?i.getKeypath(e||r):t}function he(t,e){var n=t._element.parentFragment;return"string"!=typeof e?{model:n.findContext(),instance:e}:{model:Ht(n,e),instance:n.ractive}}function ue(t,e){if(void 0===e&&(e=1),!l(e))throw new Error("Bad arguments");return q(this.ractive,oe(this,t,e).map(function(t){var e=t[0],n=t[1],i=e.get();if(!l(n)||!l(i))throw new Error("Cannot add non-numeric value");return[e,i+n]}))}function le(t,e,n){var i=he(this,t).model;return J(this.ractive,i,e,n)}function ce(t,e){var n=he(this,t).model,i=he(this,e).model,r=ia.start(this.ractive,!0);return i.link(n,t),ia.end(),r}function pe(t,e,n){return ee(this.ractive,he(this,t).model,e,n)}function fe(t){return Da(he(this,t).model,[])}function de(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];return La(he(this,t).model,e)}function me(t){return qa(he(this,t).model,[])}function ge(t,e){return q(this.ractive,oe(this,t,e))}function ve(t){return Wa(he(this,t).model,[])}function ye(t,e,n){for(var i=[],r=arguments.length-3;r-- >0;)i[r]=arguments[r+3];return i.unshift(e,n),$a(he(this,t).model,i)}function be(t){return za(he(this,t).model,[])}function we(t,e){if(void 0===e&&(e=1),!l(e))throw new Error("Bad arguments");return q(this.ractive,oe(this,t,e).map(function(t){var e=t[0],n=t[1],i=e.get();if(!l(n)||!l(i))throw new Error("Cannot add non-numeric value");return[e,i-n]}))}function ke(t){var e=he(this,t),n=e.model;return q(this.ractive,[[n,!n.get()]])}function xe(t){var e=he(this,t).model,n=ia.start(this.ractive,!0);return e.owner&&e.owner._link&&e.owner.unlink(),ia.end(),n}function Ee(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];return Ua(he(this,t).model,e)}function _e(t){return ie(this.ractive,he(this,t).model)}function Ae(t,e){var n=he(this,t),i=n.model,r=ia.start(this.ractive,!0);return i.updateFromBindings(e),ia.end(),r}function Oe(){return!!je(this).model}function Se(t){var e=je(this),n=e.model,i=e.instance;if(n)return n.getKeypath(t||i)}function Ce(){var t=je(this),e=t.model;if(e)return e.get(!0)}function je(t){var e=t._element;return{model:e.binding&&e.binding.model,instance:e.parentFragment.ractive}}function Te(t){var e=je(this),n=e.model;return q(this.ractive,[[n,t]])}function Fe(){return b("Object property keypath is deprecated, please use resolve() instead."),this.resolve()}function Ne(){return b("Object property rootpath is deprecated, please use resolve( ractive.root ) instead."),this.resolve(this.ractive.root)}function Pe(){return b("Object property context is deprecated, please use get() instead."),this.get()}function Ve(){return b('Object property index is deprecated, you can use get( "indexName" ) instead.'),Gt(this._element.parentFragment).index}function Me(){return b('Object property key is deprecated, you can use get( "keyName" ) instead.'),Gt(this._element.parentFragment).key}function Be(t,e){return Vs(t,{_element:{value:e},ractive:{value:e.parentFragment.ractive},resolve:{value:ae},get:{value:se},add:{value:ue},animate:{value:le},link:{value:ce},merge:{value:pe},pop:{value:fe},push:{value:de},reverse:{value:me},set:{value:ge},shift:{value:ve},sort:{value:be},splice:{value:ye},subtract:{value:we},toggle:{value:ke},unlink:{value:xe},unshift:{value:Ee},update:{value:_e},updateModel:{value:Ae},isBound:{value:Oe},getBindingPath:{value:Se},getBinding:{value:Ce},setBinding:{value:Te},keypath:{get:Fe},rootpath:{get:Ne},context:{get:Pe},index:{get:Ve},key:{get:Me}}),t}function Ke(t){if("string"==typeof t&&Za&&(t=Za.call(document,t)),t&&t._ractive){return Be({},t._ractive.proxy)}}function Ie(t){return"string"==typeof t&&(t=this.find(t)),Ke(t)}function Re(t,n){if(!this.fragment.rendered)throw new Error("The API has changed - you must call `ractive.render(target[, anchor])` to render your Ractive instance. Once rendered you can use `ractive.insert()`.");if(t=e(t),n=e(n)||null,!t)throw new Error("You must specify a valid target to insert into");t.insertBefore(this.detach(),n),this.el=t,(t.__ractive_instances__||(t.__ractive_instances__=[])).push(this),this.isDetached=!1,Le(this)}function Le(t){Ha.fire(t),t.findAllComponents("*").forEach(function(t){Le(t.instance)})}function De(t,e){if(e===t||0===(t+".").indexOf(e+".")||0===(e+".").indexOf(t+"."))throw new Error("A keypath cannot be linked to itself.");var n,i=ia.start(),r=U(t);return!this.viewmodel.has(r[0])&&this.component&&(n=Ht(this.component.parentFragment,r[0]),n=n.joinAll(r.slice(1))),this.viewmodel.joinAll(U(e)).link(n||this.viewmodel.joinAll(r),t),ia.end(),i}function We(t,e,n){var i=this;if(this.torndown)return{cancel:function(){}};var r,o=[];if(c(t))r=t,n=e||{},Object.keys(r).forEach(function(t){var e=r[t],s=t.split(" ");s.length>1&&(s=s.filter(function(t){return t})),s.forEach(function(t){o.push(Ue(i,t,e,n))})});else{var s;"function"==typeof t?(n=e,e=t,s=[""]):s=t.split(" "),s.length>1&&(s=s.filter(function(t){return t})),s.forEach(function(t){o.push(Ue(i,t,e,n||{}))})}return this._observers.push.apply(this._observers,o),{cancel:function(){o.forEach(function(t){j(i._observers,t),t.cancel()})}}}function Ue(t,e,n,i){var r=t.viewmodel,o=U(e),s=o.indexOf("*");if(i.keypath=e,!~s){var a,h=o[0];return""===h||r.has(h)?a=r.joinAll(o):t.component&&!t.isolated&&(a=Ht(t.component.parentFragment,h))&&(r.map(h,a),a=r.joinAll(o)),new Ga(t,a,n,i)}var u=0===s?r:r.joinAll(o.slice(0,s));return new Ya(t,u,o.splice(s),n,i)}function ze(t,e,n){if("string"!=typeof t)throw new Error("ractive.observeList() must be passed a string as its first argument");var i=this.viewmodel.joinAll(U(t)),r=new Ja(this,i,e,n||{});return this._observers.push(r),{cancel:function(){r.cancel()}}}function $e(){return-1}function qe(t,e,n){return c(t)||"function"==typeof t?(n=s(e||{},Xa),this.observe(t,n)):(n=s(n||{},Xa),this.observe(t,e,n))}function Ze(t){return t.trim()}function He(t){return""!==t}function Qe(t,e){var n=this;if(t){t.split(" ").map(Ze).filter(He).forEach(function(t){var i=n._subs[t];if(i)if(e)for(var r=i.length;r--;)i[r].callback===e&&(i[r].off=!0,i.splice(r,1));else n._subs[t]=[]})}else for(t in this._subs)delete this._subs[t];return this}function Ge(t,e){var n=this;if("object"==typeof t){var i,r=[];for(i in t)t.hasOwnProperty(i)&&r.push(this.on(i,t[i]));return{cancel:function(){r.forEach(function(t){return t.cancel()})}}}var o=t.split(" ").map(Ze).filter(He);return o.forEach(function(t){(n._subs[t]||(n._subs[t]=[])).push({callback:e})}),{cancel:function(){return o.forEach(function(t){return n.off(t,e)})}}}function Ye(t,e){var n=this.on(t,function(){e.apply(this,arguments),n.cancel()});return n}function Je(t){ih.push(t),rh=!0}function Xe(){ms&&rh&&(sh?oh.styleSheet.cssText=tn(null):oh.innerHTML=tn(null),rh=!1)}function tn(t){return(t?ih.filter(function(e){return~t.indexOf(e.id)}):ih).reduce(function(t,e){return t+"\n\n/* {"+e.id+"} */\n"+e.styles},nh)}function en(t,n,i,r){var o=t.transitionsEnabled;t.noIntro&&(t.transitionsEnabled=!1);var s=ia.start(t,!0);if(ia.scheduleTask(function(){return uh.fire(t)},!0),t.fragment.rendered)throw new Error("You cannot call ractive.render() on an already rendered instance! Call ractive.unrender() first");if(i=e(i)||t.anchor,t.el=n,t.anchor=i,t.cssId&&Xe(),n)if((n.__ractive_instances__||(n.__ractive_instances__=[])).push(t),i){var a=ms.createDocumentFragment();t.fragment.render(a),n.insertBefore(a,i)}else t.fragment.render(n,r);return ia.end(),t.transitionsEnabled=o,s.then(function(){return lh.fire(t)})}function nn(t,n){if(this.torndown)return y("ractive.render() was called on a Ractive instance that was already torn down"),Promise.resolve();if(t=e(t)||this.el,!this.append&&t){var i=t.__ractive_instances__;i&&i.forEach(Pt),this.enhance||(t.innerHTML="")}var r=this.enhance?T(t.childNodes):null,o=en(this,t,n,r);if(r)for(;r.length;)t.removeChild(r.pop());return o}function rn(t,e){for(var n=t.slice(),i=e.length;i--;)~n.indexOf(e[i])||n.push(e[i]);return n}function on(t,e,n){void 0===n&&(n=[]);var i=[],r=function(t){return t.replace(dh,function(t,e){return i[e]})};return t=t.replace(fh,function(t){return"\0"+(i.push(t)-1)}).replace(ph,""),n.forEach(function(e){t=t.replace(e,function(t){return"\0"+(i.push(t)-1)})}),e(t,r)}function sn(t){return t.trim()}function an(t){return t.str}function hn(t,e){for(var n,i=[];n=vh.exec(t);)i.push({str:n[0],base:n[1],modifiers:n[2]});for(var r=i.map(an),o=[],s=i.length;s--;){var a=r.slice(),h=i[s];a[s]=h.base+e+h.modifiers||"";var u=r.slice();u[s]=e+" "+u[s],o.push(a.join(" "),u.join(" "))}return o.join(", ")}function un(t,e){var n='[data-ractive-css~="{'+e+'}"]';return bh.test(t)?t.replace(bh,n):on(t,function(t,e){return t=t.replace(mh,function(t,e){if(yh.test(e))return t;var i=e.split(",").map(sn),r=i.map(function(t){return hn(t,n)}).join(", ")+" ";return t.replace(e,r)}),e(t)},[gh])}function ln(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function cn(){return ln()+ln()+"-"+ln()+"-"+ln()+"-"+ln()+"-"+ln()+ln()+ln()}function pn(t){t&&t.constructor!==Object&&("function"==typeof t||("object"!=typeof t?d("data option must be an object or a function, `"+t+"` is not valid"):y("If supplied, options.data should be a plain JavaScript object - using a non-POJO as the root object may work, but is discouraged")))}function fn(t,e){pn(e);var n="function"==typeof t,i="function"==typeof e;return e||n||(e={}),n||i?function(){return mn(i?dn(e,this):e,n?dn(t,this):t)}:mn(e,t)}function dn(t,e){var n=t.call(e);if(n)return"object"!=typeof n&&d("Data function must return an object"),n.constructor!==Object&&b("Data function returned something other than a plain JavaScript object. This might work, but is strongly discouraged"),n}function mn(t,e){if(t&&e){for(var n in e)n in t||(t[n]=e[n]);return t}return t||e}function gn(t,e){void 0===e&&(e=0);for(var n=new Array(e);e--;)n[e]="_"+e;return new Function([],"return function ("+n.join(",")+"){return("+t+");};")()}function vn(t,e){var n,i="return ("+t.replace(Eh,function(t,e){return n=!0,'__ractive.get("'+e+'")'})+");";n&&(i="var __ractive = this; "+i);var r=new Function(i);return n?r.bind(e):r}function yn(t,e){return _h[t]?_h[t]:_h[t]=Li(t,e)}function bn(t){if(t){var e=t.e;e&&Object.keys(e).forEach(function(t){_h[t]||(_h[t]=e[t])})}}function wn(t){var e,n,i;return t.matchString("=")?(e=t.pos,t.allowWhitespace(),(n=t.matchPattern(wu))?t.matchPattern(ku)?(i=t.matchPattern(wu))?(t.allowWhitespace(),t.matchString("=")?[n,i]:(t.pos=e,null)):(t.pos=e,null):null:(t.pos=e,null)):null}function kn(t){var e;return(e=t.matchPattern(xu))?{t:Jh,v:e}:null}function xn(t){return t.replace(Eu,"\\$&")}function En(t,e){return t.search(_u[e.join()]||(_u[e.join()]=new RegExp(e.map(xn).join("|"))))}function _n(t){return t.replace(ju,function(t,e){var n;return n="#"!==e[0]?Su[e]:"x"===e[1]?parseInt(e.substring(2),16):parseInt(e.substring(1),10),n?Fu(On(n)):t})}function An(t){return t.replace(Vu,"&amp;").replace(Nu,"&lt;").replace(Pu,"&gt;")}function On(t){return t?10===t?32:t<128?t:t<=159?Cu[t-128]:t<55296?t:t<=57343?Mu:t<=65535?t:Tu?t>=65536&&t<=131071?t:t>=131072&&t<=196607?t:Mu:Mu:Mu}function Sn(t){var e;return(e=t.matchPattern(Iu))?{t:Zh,v:e}:null}function Cn(t){var e=t.remaining();return"true"===e.substr(0,4)?(t.pos+=4,{t:Yh,v:"true"}):"false"===e.substr(0,5)?(t.pos+=5,{t:Yh,v:"false"}):null}function jn(t){return function(e){for(var n,i='"',r=!1;!r;)n=e.matchPattern(Oh)||e.matchPattern(Sh)||e.matchString(t),n?i+='"'===n?'\\"':"\\'"===n?"'":n:(n=e.matchPattern(Ch),n?i+="\\u"+("000"+n.charCodeAt(1).toString(16)).slice(-4):r=!0);return i+='"',JSON.parse(i)}}function Tn(t){var e,n;return e=t.pos,t.matchString('"')?(n=Wu(t),t.matchString('"')?{t:Hh,v:n}:(t.pos=e,null)):t.matchString("'")?(n=Du(t),t.matchString("'")?{t:Hh,v:n}:(t.pos=e,null)):null}function Fn(t){var e;return(e=Tn(t))?zu.test(e.v)?e.v:'"'+e.v.replace(/"/g,'\\"')+'"':(e=Sn(t))?e.v:(e=t.matchPattern(Uu))?e:null}function Nn(t){var e,n,i;e=t.pos,t.allowWhitespace();var r="'"!==t.nextChar()&&'"'!==t.nextChar();return null===(n=Fn(t))?(t.pos=e,null):(t.allowWhitespace(),!r||","!==t.nextChar()&&"}"!==t.nextChar()?t.matchString(":")?(t.allowWhitespace(),i=zn(t),null===i?(t.pos=e,null):{t:tu,k:n,v:i}):(t.pos=e,null):(Uu.test(n)||t.error("Expected a valid reference, but found '"+n+"' instead."),{t:tu,k:n,v:{t:eu,n:n}}))}function Pn(t){var e,n,i,r;return e=t.pos,null===(i=Nn(t))?null:(n=[i],t.matchString(",")?(r=Pn(t),r?n.concat(r):(t.pos=e,null)):n)}function Vn(t){var e,n;return e=t.pos,t.allowWhitespace(),t.matchString("{")?(n=Pn(t),t.allowWhitespace(),t.matchString("}")?{t:Gh,m:n}:(t.pos=e,null)):(t.pos=e,null)}function Mn(t){t.allowWhitespace();var e=zn(t);if(null===e)return null;var n=[e];if(t.allowWhitespace(),t.matchString(",")){var i=Mn(t);null===i&&t.error(Bu),n.push.apply(n,i)}return n}function Bn(t){var e,n;return e=t.pos,t.allowWhitespace(),t.matchString("[")?(n=Mn(t),t.matchString("]")?{t:Qh,m:n}:(t.pos=e,null)):(t.pos=e,null)}function Kn(t){return Sn(t)||Cn(t)||Tn(t)||Vn(t)||Bn(t)||kn(t)}function In(t){var e,n,i,r,o,s,a,h;if(e=t.pos,("@keypath"===(i=t.matchPattern(Gu))||"@rootpath"===i)&&t.matchPattern(Yu)){var u=In(t);u||t.error("Expected a valid reference for a keypath expression"),t.allowWhitespace(),t.matchString(")")||t.error("Unclosed keypath expression"),i+="("+u.n+")"}if(h=!i&&t.spreadArgs&&t.matchPattern(Ju),i||(n=t.matchPattern($u)||"",i=!n&&t.relaxedNames&&t.matchPattern(Qu)||t.matchPattern(Hu),i||"."!==n?!i&&n&&(i=n,n=""):(n="",i=".")),!i)return null;if(!n&&!t.relaxedNames&&Lu.test(i))return t.pos=e,null;if(!n&&Ru.test(i))return r=Ru.exec(i)[0],t.pos=e+r.length,{t:Xh,v:(h?"...":"")+r};if(s=(h?3:0)+(n||"").length+i.length,o=(n||"")+W(i),t.matchString("("))if(-1!==(a=o.lastIndexOf("."))&&"]"!==i[i.length-1]){var l=o.length;o=o.substr(0,a),t.pos=e+(s-(l-a))}else t.pos-=1;return{t:eu,n:(h?"...":"")+o.replace(/^this\./,"./").replace(/^this$/,".")}}function Rn(t){if(!t.matchString("("))return null;t.allowWhitespace();var e=zn(t);return e||t.error(Bu),t.allowWhitespace(),t.matchString(")")||t.error(Ku),{t:ou,x:e}}function Ln(t){return Kn(t)||In(t)||Rn(t)}function Dn(t){if(t.strictRefinement||t.allowWhitespace(),t.matchString(".")){t.allowWhitespace();var e=t.matchPattern(Uu);if(e)return{t:nu,n:e};t.error("Expected a property name")}if(t.matchString("[")){t.allowWhitespace();var n=zn(t);return n||t.error(Bu),t.allowWhitespace(),t.matchString("]")||t.error("Expected ']'"),{t:nu,x:n}}return null}function Wn(t){var e=Ln(t);if(!e)return null;for(;e;){var n=Dn(t);if(n)e={t:iu,x:e,r:n};else{if(!t.matchString("("))break;t.allowWhitespace();var i=t.spreadArgs;t.spreadArgs=!0;var r=Mn(t);t.spreadArgs=i,t.allowWhitespace(),t.matchString(")")||t.error(Ku),e={t:hu,x:e},r&&(e.o=r)}}return e}function Un(t){var e,n,i,r;return(n=il(t))?(e=t.pos,t.allowWhitespace(),t.matchString("?")?(t.allowWhitespace(),i=zn(t),i||t.error(Bu),t.allowWhitespace(),t.matchString(":")||t.error('Expected ":"'),t.allowWhitespace(),r=zn(t),r||t.error(Bu),{t:su,o:[n,i,r]}):(t.pos=e,n)):null}function zn(t){return Un(t)}function $n(t){function e(t){switch(t.t){case Yh:case Xh:case Zh:case Jh:return t.v;case Hh:return JSON.stringify(String(t.v));case Qh:return"["+(t.m?t.m.map(e).join(","):"")+"]";case Gh:return"{"+(t.m?t.m.map(e).join(","):"")+"}";case tu:return t.k+":"+e(t.v);case ru:return("typeof"===t.s?"typeof ":t.s)+e(t.o);case au:return e(t.o[0])+("in"===t.s.substr(0,2)?" "+t.s+" ":t.s)+e(t.o[1]);case hu:if(t.spread){var i=r++;return"(spread$"+i+" = "+e(t.x)+").apply(spread$"+i+", [].concat("+(t.o?t.o.map(function(t){return t.n&&0===t.n.indexOf("...")?e(t):"["+e(t)+"]"}).join(","):"")+") )"}return e(t.x)+"("+(t.o?t.o.map(e).join(","):"")+")";case ou:
return"("+e(t.x)+")";case iu:return e(t.x)+e(t.r);case nu:return t.n?"."+t.n:"["+e(t.x)+"]";case su:return e(t.o[0])+"?"+e(t.o[1])+":"+e(t.o[2]);case eu:return"_"+n.indexOf(t.n);default:throw new Error("Expected legal JavaScript")}}var n,i,r=0;return qn(t,n=[]),i=e(t),n=n.map(function(t){return 0===t.indexOf("...")?t.substr(3):t}),{r:n,s:function(t){for(var e=[],n=r-1;n>=0;n--)e.push("spread$"+n);return e.length?"(function(){var "+e.join(",")+";return("+t+");})()":t}(i)}}function qn(t,e){var n,i;if(t.t===eu&&-1===e.indexOf(t.n)&&e.unshift(t.n),i=t.o||t.m)if(c(i))qn(i,e);else for(n=i.length;n--;)i[n].n&&0===i[n].n.indexOf("...")&&(t.spread=!0),qn(i[n],e);t.x&&qn(t.x,e),t.r&&qn(t.r,e),t.v&&qn(t.v,e)}function Zn(t){t.allowWhitespace();var e=Fn(t);if(!e)return null;var n={key:e};if(t.allowWhitespace(),!t.matchString(":"))return null;t.allowWhitespace();var i=t.read();return i?(n.value=i.v,n):null}function Hn(t,e){return new ll(t,{values:e}).result}function Qn(t,e,n){var i,r,o,s,a,h,u;if("string"==typeof t){var l=e.pos-t.length;if(n===vu||n===yu){return{a:$n(new nl("["+t+"]").result[0])}}if(n===gu&&(r=cl.exec(t))&&(y(e.getContextMessage(l,"Unqualified method events are deprecated. Prefix methods with '@this.' to call methods on the current Ractive instance.")[2]),t="@this."+r[1]+t.substr(r[1].length)),n===gu&&~t.indexOf("(")){var c=new nl("["+t+"]");if(c.result&&c.result[0])return c.remaining().length&&(e.pos=l+t.length-c.remaining().length,e.error("Invalid input after event expression '"+c.remaining()+"'")),{x:$n(c.result[0])};(t.indexOf(":")>t.indexOf("(")||!~t.indexOf(":"))&&(e.pos=l,e.error("Invalid input in event expression '"+t+"'"))}if(-1===t.indexOf(":"))return t.trim();t=[t]}if(i={},a=[],h=[],t){for(;t.length;)if("string"==typeof(o=t.shift())){if(pl.test(o))continue;if(-1!==(s=o.indexOf(":"))){s&&a.push(o.substr(0,s)),o.length>s+1&&(h[0]=o.substring(s+1));break}a.push(o)}else a.push(o);h=h.concat(t)}return a.length?h.length||"string"!=typeof a?(i={n:1===a.length&&"string"==typeof a[0]?a[0]:a},1===h.length&&"string"==typeof h[0]?(u=Hn("["+h[0]+"]"),i.a=u?u.value:[h[0].trim()]):i.d=h):i=a:i="",h.length&&n&&y(e.getContextMessage(e.pos,"Proxy events with arguments are deprecated. You can fire events with arguments using \"@this.fire('eventName', arg1, arg2, ...)\".")[2]),i}function Gn(t){var e,n,i,r,o,s;if(t.allowWhitespace(),!(n=t.matchPattern(dl)))return null;for(o=n.length,r=0;r<t.tags.length;r++)~(s=n.indexOf(t.tags[r].open))&&s<o&&(o=s);return o<n.length?(t.pos-=n.length-o,n=n.substr(0,o),n?{n:n}:null):(e={n:n},i=Yn(t),null!=i&&(e.f=i),e)}function Yn(t){var e,n,i,r;return e=t.pos,/[=\/>\s]/.test(t.nextChar())||t.error("Expected `=`, `/`, `>` or whitespace"),t.allowWhitespace(),t.matchString("=")?(t.allowWhitespace(),n=t.pos,i=t.sectionDepth,r=ti(t,"'")||ti(t,'"')||Xn(t),null===r&&t.error("Expected valid attribute value"),t.sectionDepth!==i&&(t.pos=n,t.error("An attribute value must contain as many opening section tags as closing section tags")),r.length?1===r.length&&"string"==typeof r[0]?_n(r[0]):r:""):(t.pos=e,null)}function Jn(t){var e,n,i,r,o;return e=t.pos,(n=t.matchPattern(kl))?(i=n,r=t.tags.map(function(t){return t.open}),-1!==(o=En(i,r))&&(n=n.substr(0,o),t.pos=e+n.length),n):null}function Xn(t){var e,n;for(t.inAttribute=!0,e=[],n=ii(t)||Jn(t);n;)e.push(n),n=ii(t)||Jn(t);return e.length?(t.inAttribute=!1,e):null}function ti(t,e){var n,i,r;if(n=t.pos,!t.matchString(e))return null;for(t.inAttribute=e,i=[],r=ii(t)||ei(t,e);null!==r;)i.push(r),r=ii(t)||ei(t,e);return t.matchString(e)?(t.inAttribute=!1,i):(t.pos=n,null)}function ei(t,e){var n=t.remaining(),i=t.tags.map(function(t){return t.open});i.push(e);var r=En(n,i);return-1===r&&t.error("Quoted attribute value must have a closing quote"),r?(t.pos+=r,n.substr(0,r)):null}function ni(t){var e,n,i;if(!(n=Gn(t)))return null;if(i=wl[n.n])n.t=i.t,i.v&&(n.v=i.v),delete n.n,i.t!==yu&&i.t!==vu||(n.f=Qn(n.f,t)),i.t===yu?b(("t0"===i.v?"intro-outro":"t1"===i.v?"intro":"outro")+" is deprecated. To specify tranisitions, use the transition name suffixed with '-in', '-out', or '-in-out' as an attribute. Arguments can be specified in the attribute value as a simple list of expressions without mustaches."):i.t===vu&&b("decorator is deprecated. To specify decorators, use the decorator name prefixed with 'as-' as an attribute. Arguments can be specified in the attribute value as a simple list of expressions without mustaches.");else if(e=yl.exec(n.n))delete n.n,n.t=vu,n.f=Qn(n.f,t,vu),"object"==typeof n.f?n.f.n=e[1]:n.f=e[1];else if(e=bl.exec(n.n))delete n.n,n.t=yu,n.f=Qn(n.f,t,yu),"object"==typeof n.f?n.f.n=e[1]:n.f=e[1],n.v="in-out"===e[2]?"t0":"in"===e[2]?"t1":"t2";else if(e=gl.exec(n.n))n.n=e[1],n.t=gu,n.f=Qn(n.f,t,gu),vl.test(n.f.n||n.f)&&(t.pos-=(n.f.n||n.f).length,t.error("Cannot use reserved event names (change, reset, teardown, update, construct, config, init, render, unrender, detach, insert)"));else{if(t.sanitizeEventAttributes&&ml.test(n.n))return{exclude:!0};n.f=n.f||(""===n.f?"":0),n.t=Lh}return n}function ii(t){var e,n;if(!1===t.interpolate[t.inside])return null;for(n=0;n<t.tags.length;n+=1)if(e=ri(t,t.tags[n]))return e;return t.inTag&&!t.inAttribute&&(e=ni(t))?(t.allowWhitespace(),e):void 0}function ri(t,e){var n,i,r,o;if(n=t.pos,t.matchString("\\"+e.open)){if(0===n||"\\"!==t.str[n-1])return e.open}else if(!t.matchString(e.open))return null;if(i=wn(t))return t.matchString(e.close)?(e.open=i[0],e.close=i[1],t.sortMustacheTags(),xl):null;if(t.allowWhitespace(),t.matchString("/")){t.pos-=1;var s=t.pos;if(kn(t))t.pos=s;else{if(t.pos=s-e.close.length,t.inAttribute)return t.pos=n,null;t.error("Attempted to close a section that wasn't open")}}for(o=0;o<e.readers.length;o+=1)if(r=e.readers[o],i=r(t,e))return e.isStatic&&(i.s=!0),t.includeLinePositions&&(i.p=t.getLinePos(n)),i;return t.pos=n,null}function oi(t,e){var n;if(t){for(;t.t===ou&&t.x;)t=t.x;return t.t===eu?e.r=t.n:(n=si(t))?e.rx=n:e.x=$n(t),e}}function si(t){for(var e,n=[];t.t===iu&&t.r.t===nu;)e=t.r,e.x?e.x.t===eu?n.unshift(e.x):n.unshift($n(e.x)):n.unshift(e.n),t=t.x;return t.t!==eu?null:{r:t.n,m:n}}function ai(t,e){var n,i=zn(t);return i?(t.matchString(e.close)||t.error("Expected closing delimiter '"+e.close+"'"),n={t:Nh},oi(i,n),n):null}function hi(t,e){var n,i;return t.matchString("&")?(t.allowWhitespace(),(n=zn(t))?(t.matchString(e.close)||t.error("Expected closing delimiter '"+e.close+"'"),i={t:Nh},oi(n,i),i):null):null}function ui(t){var e,n=[],i=t.pos;if(t.allowWhitespace(),e=li(t)){for(e.x=oi(e.x,{}),n.push(e),t.allowWhitespace();t.matchString(",");)e=li(t),e||t.error("Expected another alias."),e.x=oi(e.x,{}),n.push(e),t.allowWhitespace();return n}return t.pos=i,null}function li(t){var e,n,i=t.pos;return t.allowWhitespace(),(e=zn(t,[]))?(t.allowWhitespace(),t.matchPattern(_l)?(t.allowWhitespace(),n=t.matchPattern(El),n||t.error("Expected a legal alias name."),{n:n,x:e}):(t.pos=i,null)):(t.pos=i,null)}function ci(t,e){if(!t.matchString(">"))return null;t.allowWhitespace(),t.relaxedNames=t.strictRefinement=!0;var n=zn(t);if(t.relaxedNames=t.strictRefinement=!1,!n)return null;var i={t:Kh};oi(n,i),t.allowWhitespace();var r=ui(t);if(r)i={t:qh,z:r,f:[i]};else{var o=zn(t);o&&(i={t:Ph,n:pu,f:[i]},oi(o,i))}return t.allowWhitespace(),t.matchString(e.close)||t.error("Expected closing delimiter '"+e.close+"'"),i}function pi(t,e){var n;return t.matchString("!")?(n=t.remaining().indexOf(e.close),-1!==n?(t.pos+=n+e.close.length,{t:Ih}):void 0):null}function fi(t,e){var n,i,r;if(n=t.pos,!(i=zn(t))){var o=t.matchPattern(/^(\w+)/);return o?{t:eu,n:o}:null}for(r=0;r<e.length;r+=1)if(t.remaining().substr(0,e[r].length)===e[r])return i;return t.pos=n,In(t)}function di(t,e){var n,i,r,o;n=t.pos;try{i=fi(t,[e.close])}catch(t){o=t}if(!i){if("!"===t.str.charAt(n))return t.pos=n,null;if(o)throw o}if(!t.matchString(e.close)&&(t.error("Expected closing delimiter '"+e.close+"' after reference"),!i)){if("!"===t.nextChar())return null;t.error("Expected expression or legal reference")}return r={t:Fh},oi(i,r),r}function mi(t,e){if(!t.matchPattern(Al))return null;var n=t.matchPattern(/^[a-zA-Z_$][a-zA-Z_$0-9\-]*/);t.allowWhitespace(),t.matchString(e.close)||t.error("expected legal partial name");var i={t:Uh};return n&&(i.n=n),i}function gi(t,e){var n,i,r,o;return n=t.pos,t.matchString(e.open)?(t.allowWhitespace(),t.matchString("/")?(t.allowWhitespace(),i=t.remaining(),-1!==(r=i.indexOf(e.close))?(o={t:Mh,r:i.substr(0,r).split(" ")[0]},t.pos+=r,t.matchString(e.close)||t.error("Expected closing delimiter '"+e.close+"'"),o):(t.pos=n,null)):(t.pos=n,null)):null}function vi(t,e){var n=t.pos;return t.matchString(e.open)?t.matchPattern(Ol)?(t.matchString(e.close)||t.error("Expected closing delimiter '"+e.close+"'"),{t:du}):(t.pos=n,null):null}function yi(t,e){var n=t.pos;if(!t.matchString(e.open))return null;if(!t.matchPattern(Sl))return t.pos=n,null;var i=zn(t);return t.matchString(e.close)||t.error("Expected closing delimiter '"+e.close+"'"),{t:mu,x:i}}function bi(t,e){var n,i,r,o,s,a,h,u,l,c,p,f=!1;if(n=t.pos,t.matchString("^"))r={t:Ph,f:[],n:lu};else{if(!t.matchString("#"))return null;r={t:Ph,f:[]},t.matchString("partial")&&(t.pos=n-t.standardDelimiters[0].length,t.error("Partial definitions can only be at the top level of the template, or immediately inside components")),(h=t.matchPattern(Fl))&&(p=h,r.n=Cl[h])}if(t.allowWhitespace(),"with"===h){var d=ui(t);d&&(f=!0,r.z=d,r.t=qh)}else if("each"===h){var m=li(t);m&&(r.z=[{n:m.n,x:{r:"."}}],i=m.x)}if(!f&&(i||(i=zn(t)),i||t.error("Expected expression"),c=t.matchPattern(jl))){var g;(g=t.matchPattern(Tl))?r.i=c+","+g:r.i=c}t.allowWhitespace(),t.matchString(e.close)||t.error("Expected closing delimiter '"+e.close+"'"),t.sectionDepth+=1,s=r.f;var v;do{if(v=t.pos,o=gi(t,e))p&&o.r!==p&&(t.pos=v,t.error("Expected "+e.open+"/"+p+e.close)),t.sectionDepth-=1,l=!0;else if(!f&&(o=yi(t,e))){r.n===lu&&t.error("{{else}} not allowed in {{#unless}}"),a&&t.error("illegal {{elseif...}} after {{else}}"),u||(u=[]);var y={t:Ph,n:uu,f:s=[]};oi(o.x,y),u.push(y)}else if(!f&&(o=vi(t,e)))r.n===lu&&t.error("{{else}} not allowed in {{#unless}}"),a&&t.error("there can only be one {{else}} block, at the end of a section"),a=!0,u||(u=[]),u.push({t:Ph,n:lu,f:s=[]});else{if(!(o=t.read(tc)))break;s.push(o)}}while(!l);return u&&(r.l=u),f||oi(i,r),r.f.length||delete r.f,r}function wi(t){var e,n,i,r,o;return e=t.pos,t.textOnlyMode||!t.matchString(Nl)?null:(i=t.remaining(),r=i.indexOf(Pl),-1===r&&t.error("Illegal HTML - expected closing comment sequence ('--\x3e')"),n=i.substr(0,r),t.pos+=r+3,o={t:Ih,c:n},t.includeLinePositions&&(o.p=t.getLinePos(e)),o)}function ki(t){var e,n,i,r,o;for(e=1;e<t.length;e+=1)n=t[e],i=t[e-1],r=t[e-2],xi(n)&&Ei(i)&&xi(r)&&Ml.test(r)&&Vl.test(n)&&(t[e-2]=r.replace(Ml,"\n"),t[e]=n.replace(Vl,"")),_i(n)&&xi(i)&&Ml.test(i)&&xi(n.f[0])&&Vl.test(n.f[0])&&(t[e-1]=i.replace(Ml,"\n"),n.f[0]=n.f[0].replace(Vl,"")),xi(n)&&_i(i)&&(o=C(i.f),xi(o)&&Ml.test(o)&&Vl.test(n)&&(i.f[i.f.length-1]=o.replace(Ml,"\n"),t[e]=n.replace(Vl,"")));return t}function xi(t){return"string"==typeof t}function Ei(t){return t.t===Ih||t.t===Rh}function _i(t){return(t.t===Ph||t.t===Vh)&&t.f}function Ai(t,e,n){var i;e&&"string"==typeof(i=t[0])&&(i=i.replace(e,""),i?t[0]=i:t.shift()),n&&"string"==typeof(i=C(t))&&(i=i.replace(n,""),i?t[t.length-1]=i:t.pop())}function Oi(t,e,n,i,r){if("string"!=typeof t){var o,s,a,u,l,c,p,f;for(ki(t),o=t.length;o--;)s=t[o],s.exclude?t.splice(o,1):e&&s.t===Ih&&t.splice(o,1);for(Ai(t,i?Il:null,r?Rl:null),o=t.length;o--;){if(s=t[o],s.f){var d=s.t===Bh&&Kl.test(s.e);l=n||d,!n&&d&&Ai(s.f,Ll,Dl),l||(a=t[o-1],u=t[o+1],(!a||"string"==typeof a&&Rl.test(a))&&(c=!0),(!u||"string"==typeof u&&Il.test(u))&&(p=!0)),Oi(s.f,e,l,c,p),h(s.f.n)&&Oi(s.f.n,e,n,c,r),h(s.f.d)&&Oi(s.f.d,e,n,c,r)}if(s.l&&(Oi(s.l,e,n,c,p),s.l.forEach(function(t){return t.l=1}),s.l.unshift(o+1,0),t.splice.apply(t,s.l),delete s.l),s.a)for(f in s.a)s.a.hasOwnProperty(f)&&"string"!=typeof s.a[f]&&Oi(s.a[f],e,n,c,p);s.m&&(Oi(s.m,e,n,c,p),s.m.length<1&&delete s.m)}for(o=t.length;o--;)"string"==typeof t[o]&&("string"==typeof t[o+1]&&(t[o]=t[o]+t[o+1],t.splice(o+1,1)),n||(t[o]=t[o].replace(Bl," ")),""===t[o]&&t.splice(o,1))}}function Si(t){var e,n;return e=t.pos,t.matchString("</")?(n=t.matchPattern(Wl))?t.inside&&n!==t.inside?(t.pos=e,null):{t:Dh,e:n}:(t.pos-=2,void t.error("Illegal closing tag")):null}function Ci(t){var e,n,i,r,o,s,a,h,u,l,c,p;if(e=t.pos,t.inside||t.inAttribute||t.textOnlyMode)return null;if(!t.matchString("<"))return null;if("/"===t.nextChar())return null;if(n={},t.includeLinePositions&&(n.p=t.getLinePos(e)),t.matchString("!"))return n.t=$h,t.matchPattern(/^doctype/i)||t.error("Expected DOCTYPE declaration"),n.a=t.matchPattern(/^(.+?)>/),n;if(n.t=Bh,n.e=t.matchPattern(Ul),!n.e)return null;for(zl.test(t.nextChar())||t.error("Illegal tag name"),t.allowWhitespace(),t.inTag=!0;i=ii(t);)!1!==i&&(n.m||(n.m=[]),n.m.push(i)),t.allowWhitespace();if(t.inTag=!1,t.allowWhitespace(),t.matchString("/")&&(r=!0),!t.matchString(">"))return null;var f=n.e.toLowerCase(),d=t.preserveWhitespace;if(!r&&!Ou.test(n.e)){t.elementStack.push(f),"script"!==f&&"style"!==f&&"textarea"!==f||(t.inside=f),o=[],s=Ns(null);do{if(l=t.pos,c=t.remaining(),c||t.error("Missing end "+(t.elementStack.length>1?"tags":"tag")+" ("+t.elementStack.reverse().map(function(t){return"</"+t+">"}).join("")+")"),ji(f,c))if(p=Si(t)){u=!0;var m=p.e.toLowerCase();if(m!==f&&(t.pos=l,!~t.elementStack.indexOf(m))){var g="Unexpected closing tag";Ou.test(m)&&(g+=" (<"+m+"> is a void element - it cannot contain children)"),t.error(g)}}else(h=gi(t,{open:t.standardDelimiters[0],close:t.standardDelimiters[1]}))?(u=!0,t.pos=l):(h=t.read(ec))?(s[h.n]&&(t.pos=l,t.error("Duplicate partial definition")),Oi(h.f,t.stripComments,d,!d,!d),s[h.n]=h.f,a=!0):(h=t.read(tc))?o.push(h):u=!0;else u=!0}while(!u);o.length&&(n.f=o),a&&(n.p=s),t.elementStack.pop()}return t.inside=null,t.sanitizeElements&&-1!==t.sanitizeElements.indexOf(f)?$l:n}function ji(t,e){var n,i;return n=/^<([a-zA-Z][a-zA-Z0-9]*)/.exec(e),i=fl[t],!n||!i||!~i.indexOf(n[1].toLowerCase())}function Ti(t){var e,n,i,r;return n=t.remaining(),t.textOnlyMode?(i=t.tags.map(function(t){return t.open}),i=i.concat(t.tags.map(function(t){return"\\"+t.open})),e=En(n,i)):(r=t.inside?"</"+t.inside:"<",t.inside&&!t.interpolate[t.inside]?e=n.indexOf(r):(i=t.tags.map(function(t){return t.open}),i=i.concat(t.tags.map(function(t){return"\\"+t.open})),!0===t.inAttribute?i.push('"',"'","=","<",">","`"):t.inAttribute?i.push(t.inAttribute):i.push(r),e=En(n,i))),e?(-1===e&&(e=n.length),t.pos+=e,t.inside&&"textarea"!==t.inside||t.textOnlyMode?n.substr(0,e):_n(n.substr(0,e))):null}function Fi(t){var e=t.pos,n=t.standardDelimiters[0],i=t.standardDelimiters[1];if(!t.matchPattern(Zl)||!t.matchString(n))return t.pos=e,null;var r=t.matchPattern(Hl);if(b("Inline partial comments are deprecated.\nUse this...\n  {{#partial "+r+"}} ... {{/partial}}\n\n...instead of this:\n  \x3c!-- {{>"+r+"}} --\x3e ... \x3c!-- {{/"+r+"}} --\x3e'"),!t.matchString(i)||!t.matchPattern(Ql))return t.pos=e,null;var o,s=[],a=new RegExp("^\x3c!--\\s*"+xn(n)+"\\s*\\/\\s*"+r+"\\s*"+xn(i)+"\\s*--\x3e");do{if(t.matchPattern(a))o=!0;else{var h=t.read(tc);h||t.error("expected closing comment ('\x3c!-- "+n+"/"+r+i+" --\x3e')"),s.push(h)}}while(!o);return{t:zh,f:s,n:r}}function Ni(t){var e,n,i,r,o;e=t.pos;var s=t.standardDelimiters;if(!t.matchString(s[0]))return null;if(!t.matchPattern(Gl))return t.pos=e,null;n=t.matchPattern(/^[a-zA-Z_$][a-zA-Z_$0-9\-\/]*/),n||t.error("expected legal partial name"),t.allowWhitespace(),t.matchString(s[1])||t.error("Expected closing delimiter '"+s[1]+"'"),i=[];do{(r=gi(t,{open:t.standardDelimiters[0],close:t.standardDelimiters[1]}))?("partial"===!r.r&&t.error("Expected "+s[0]+"/partial"+s[1]),o=!0):(r=t.read(tc),r||t.error("Expected "+s[0]+"/partial"+s[1]),i.push(r))}while(!o);return{t:zh,n:n,f:i}}function Pi(t){for(var e=[],n=Ns(null),i=!1,r=t.preserveWhitespace;t.pos<t.str.length;){var o,s,a=t.pos;(s=t.read(ec))?(n[s.n]&&(t.pos=a,t.error("Duplicated partial definition")),Oi(s.f,t.stripComments,r,!r,!r),n[s.n]=s.f,i=!0):(o=t.read(tc))?e.push(o):t.error("Unexpected template content")}var h={v:xh,t:e};return i&&(h.p=n),h}function Vi(t,e){Object.keys(t).forEach(function(n){if(Mi(n,t))return Bi(t,e);var i=t[n];Ki(i)&&Vi(i,e)})}function Mi(t,e){return"s"===t&&h(e.r)}function Bi(t,e){var n=t.s,i=t.r;e[n]||(e[n]=gn(n,i.length))}function Ki(t){return h(t)||c(t)}function Ii(t,e){return new ql(t,e||{}).result}function Ri(t,e,n){t||d("Missing Ractive.parse - cannot parse "+e+". "+n)}function Li(t,e){return Ri(gn,"new expression function",ic),gn(t,e)}function Di(t,e){return Ri(vn,'compution string "${str}"',rc),vn(t,e)}function Wi(t){var e=t._config.template;if(e&&e.fn){var n=Ui(t,e.fn);return n!==e.result?(e.result=n,n):void 0}}function Ui(t,e){return e.call(t,{fromId:oc.fromId,isParsed:oc.isParsed,parse:function(e,n){return void 0===n&&(n=oc.getParseOptions(t)),oc.parse(e,n)}})}function zi(t,e){return"string"==typeof t?t=$i(t,e):(qi(t),bn(t)),t}function $i(t,e){return"#"===t[0]&&(t=oc.fromId(t)),oc.parseFor(t,e)}function qi(t){if(void 0==t)throw new Error("The template cannot be "+t+".");if("number"!=typeof t.v)throw new Error("The template parser was passed a non-string template, but the template doesn't have a version.  Make sure you're passing in the template you think you are.");if(t.v!==xh)throw new Error("Mismatched template version (expected "+xh+", got "+t.v+") Please ensure you are using the latest version of Ractive.js in your build process as well as in your app")}function Zi(t,e,n){if(e)for(var i in e)!n&&t.hasOwnProperty(i)||(t[i]=e[i])}function Hi(t,e,n){function i(){var t=Qi(i._parent,e),r="_super"in this,o=this._super;this._super=t;var s=n.apply(this,arguments);return r?this._super=o:delete this._super,s}return/_super/.test(n)?(i._parent=t,i._method=n,i):n}function Qi(t,e){if(e in t){var n=t[e];return"function"==typeof n?n:function(){return n}}return p}function Gi(t,e,n){return"options."+t+" has been deprecated in favour of options."+e+"."+(n?" You cannot specify both options, please use options."+e+".":"")}function Yi(t,e,n){if(e in t){if(n in t)throw new Error(Gi(e,n,!0));y(Gi(e,n)),t[n]=t[e]}}function Ji(t){Yi(t,"beforeInit","onconstruct"),Yi(t,"init","onrender"),Yi(t,"complete","oncomplete"),Yi(t,"eventDefinitions","events"),h(t.adaptors)&&Yi(t,"adaptors","adapt")}function Xi(t,e,n,i){Ji(i);for(var r in i)if(pc.hasOwnProperty(r)){var o=i[r];"el"!==r&&"function"==typeof o?y(r+" is a Ractive option that does not expect a function and will be ignored","init"===t?n:null):n[r]=o}if(i.append&&i.enhance)throw new Error("Cannot use append and enhance at the same time");uc.forEach(function(r){r[t](e,n,i)}),ch[t](e,n,i),sc[t](e,n,i),wh[t](e,n,i),tr(e.prototype,n,i)}function tr(t,e,n){for(var i in n)if(!fc[i]&&n.hasOwnProperty(i)){var r=n[i];"function"==typeof r&&(r=Hi(t,i,r)),e[i]=r}}function er(t){var e={};return t.forEach(function(t){return e[t]=!0}),e}function nr(t){if("object"!=typeof(t=t||{}))throw new Error("The reset method takes either no arguments, or an object containing new data");t=kh.init(this.constructor,this,{data:t});var e=ia.start(this,!0),n=this.viewmodel.wrapper;n&&n.reset?!1===n.reset(t)&&this.viewmodel.set(t):this.viewmodel.set(t);for(var i,r=mc.reset(this),o=r.length;o--;)if(gc.indexOf(r[o])>-1){i=!0;break}return i&&(wc.fire(this),this.fragment.resetTemplate(this.template),bc.fire(this),vc.fire(this)),ia.end(),yc.fire(this,t),e}function ir(t,e,n,i){t.forEach(function(t){if(t.type===Kh&&(t.refName===e||t.name===e))return t.inAttribute=n,void i.push(t);if(t.fragment)ir(t.fragment.iterations||t.fragment.items,e,n,i);else if(h(t.items))ir(t.items,e,n,i);else if(t.type===Wh&&t.instance){if(t.instance.partials[e])return;ir(t.instance.fragment.items,e,n,i)}t.type===Bh&&h(t.attributes)&&ir(t.attributes,e,!0,i)})}function rr(t){t.forceResetTemplate()}function or(t,e){var n=[];ir(this.fragment.items,t,!1,n);var i=ia.start(this,!0);return this.partials[t]=e,n.forEach(rr),ia.end(),i}function sr(t,e,n){var i=t.fragment.resolve(e,function(e){j(t.resolvers,i),t.models[n]=e,t.bubble()});t.resolvers.push(i)}function ar(t,e){return e.r?Ht(t,e.r):e.x?new Ec(t,e.x):e.rx?new Ac(t,e.rx):void 0}function hr(t){if(t.template.z){t.aliases={};for(var e=t.template.z,n=0;n<e.length;n++)t.aliases[e[n].n]=ar(t.parentFragment,e[n].x)}for(var i in t.aliases)t.aliases[i].reference()}function ur(t,e,n){for(void 0===e&&(e=!0);t&&(t.type!==Bh||n&&t.name!==n)&&(!e||t.type!==Wh);)t=t.owner?t.owner:t.component?t.containerFragment||t.component.parentFragment:t.parent?t.parent:t.parentFragment?t.parentFragment:void 0;return t}function lr(t){var e=[];return"string"!=typeof t?{}:t.replace(jc,function(t){return"\0"+(e.push(t)-1)}).replace(Cc,"").split(";").filter(function(t){return!!t.trim()}).map(function(t){return t.replace(Tc,function(t,n){return e[n]})}).reduce(function(t,e){var n=e.indexOf(":");return t[e.substr(0,n).trim()]=e.substr(n+1).trim(),t},{})}function cr(t){for(var e=t.split(Sc),n=e.length;n--;)e[n]||e.splice(n,1);return e}function pr(t){var e=t.element,n=t.name;if("id"===n)return fr;if("value"===n){if(t.interpolator&&(t.interpolator.bound=!0),"select"===e.name&&"value"===n)return e.getAttribute("multiple")?dr:mr;if("textarea"===e.name)return br;if(null!=e.getAttribute("contenteditable"))return gr;if("input"===e.name){var i=e.getAttribute("type");if("file"===i)return p;if("radio"===i&&e.binding&&"name"===e.binding.attribute.name)return vr;if(~Fc.indexOf(i))return br}return yr}var r=e.node;if(t.isTwoway&&"name"===n){if("radio"===r.type)return wr;if("checkbox"===r.type)return kr}if("style"===n)return xr;if(0===n.indexOf("style-"))return Er;if("class"===n&&(!r.namespaceURI||r.namespaceURI===js))return _r;if(0===n.indexOf("class-"))return Ar;if(t.isBoolean){var o=e.getAttribute("type");return!t.interpolator||"checked"!==n||"checkbox"!==o&&"radio"!==o||(t.interpolator.bound=!0),Or}return t.namespace&&t.namespace!==t.node.namespaceURI?Cr:Sr}function fr(t){var e=this,n=e.node,i=this.getValue();if(this.ractive.nodes[n.id]===n&&delete this.ractive.nodes[n.id],t)return n.removeAttribute("id");this.ractive.nodes[i]=n,n.id=i}function dr(t){var e=this.getValue();h(e)||(e=[e]);var n=this.node.options,i=n.length;if(t)for(;i--;)n[i].selected=!1;else for(;i--;){var r=n[i],o=r._ractive?r._ractive.value:r.value;r.selected=A(e,o)}}function mr(t){var e=this.getValue();if(!this.locked){this.node._ractive.value=e;var n=this.node.options,i=n.length,r=!1;if(t)for(;i--;)n[i].selected=!1;else for(;i--;){var o=n[i],s=o._ractive?o._ractive.value:o.value;if(o.disabled&&o.selected&&(r=!0),s==e)return void(o.selected=!0)}r||(this.node.selectedIndex=-1)}}function gr(t){var e=this.getValue();this.locked||(this.node.innerHTML=t?"":void 0===e?"":e)}function vr(t){var e=this.node,n=e.checked,i=this.getValue();if(t)return e.checked=!1;e.value=this.node._ractive.value=i,e.checked=i===this.element.getAttribute("name"),n&&!e.checked&&this.element.binding&&this.element.binding.rendered&&this.element.binding.group.model.set(this.element.binding.group.getValue())}function yr(t){if(!this.locked){if(t)return this.node.removeAttribute("value"),void(this.node.value=this.node._ractive.value=null);var e=this.getValue();this.node.value=this.node._ractive.value=e,this.node.setAttribute("value",i(e))}}function br(t){if(!this.locked){if(t)return this.node._ractive.value="",void this.node.removeAttribute("value");var e=this.getValue();this.node._ractive.value=e,this.node.value=i(e),this.node.setAttribute("value",i(e))}}function wr(t){this.node.checked=!t&&this.getValue()==this.node._ractive.value}function kr(t){var e=this,n=e.element,i=e.node,r=n.binding,o=this.getValue(),s=n.getAttribute("value");if(h(o)){for(var a=o.length;a--;)if(s==o[a])return void(r.isChecked=i.checked=!0);r.isChecked=i.checked=!1}else r.isChecked=i.checked=o==s}function xr(t){for(var e=t?{}:lr(this.getValue()||""),n=this.node.style,i=Object.keys(e),r=this.previous||[],o=0;o<i.length;){if(i[o]in n){var s=e[i[o]].replace("!important","");n.setProperty(i[o],s,s.length!==e[i[o]].length?"important":"")}o++}for(o=r.length;o--;)!~i.indexOf(r[o])&&r[o]in n&&n.setProperty(r[o],"","");this.previous=i}function Er(t){this.style||(this.style=o(this.name.substr(6)));var e=t?"":i(this.getValue()),n=e.replace("!important","");this.node.style.setProperty(this.style,n,n.length!==e.length?"important":"")}function _r(t){var e=t?[]:cr(i(this.getValue())),n=this.node.className;n=void 0!==n.baseVal?n.baseVal:n;var r=cr(n),o=this.previous||r.slice(0),s=e.concat(r.filter(function(t){return!~o.indexOf(t)})).join(" ");s!==n&&("string"!=typeof this.node.className?this.node.className.baseVal=s:this.node.className=s),this.previous=e}function Ar(t){var e=this.name.substr(6),n=this.node.className;n=void 0!==n.baseVal?n.baseVal:n;var i=cr(n),r=!t&&this.getValue();this.inlineClass||(this.inlineClass=e),r&&!~i.indexOf(e)?i.push(e):!r&&~i.indexOf(e)&&i.splice(i.indexOf(e),1),"string"!=typeof this.node.className?this.node.className.baseVal=i.join(" "):this.node.className=i.join(" ")}function Or(t){if(!this.locked){if(t)return this.useProperty&&(this.node[this.propertyName]=!1),void this.node.removeAttribute(this.propertyName);this.useProperty?this.node[this.propertyName]=this.getValue():this.getValue()?this.node.setAttribute(this.propertyName,""):this.node.removeAttribute(this.propertyName)}}function Sr(t){t?this.node.removeAttribute(this.name):this.node.setAttribute(this.name,i(this.getString()))}function Cr(t){t?this.node.removeAttributeNS(this.namespace,this.name.slice(this.name.indexOf(":")+1)):this.node.setAttributeNS(this.namespace,this.name.slice(this.name.indexOf(":")+1),i(this.getString()))}function jr(t,e){for(var n="xmlns:"+e;t;){if(t.hasAttribute&&t.hasAttribute(n))return t.getAttribute(n);t=t.parentNode}return Fs[e]}function Tr(){return Pc}function Fr(t,e,n){t.value=0===e||("true"===e||"false"!==e&&"0"!==e&&e);var i=t.element[t.flag];return t.element[t.flag]=t.value,n&&!t.element.attributes.binding&&i!==t.value&&t.element.recreateTwowayBinding(),t.value}function Nr(){return Kc}function Pr(t){Kc=!0,t(),Kc=!1}function Vr(t,e){var n=e?"svg":"div";return t?(Bc.innerHTML="<"+n+" "+t+"></"+n+">")&&T(Bc.childNodes[0].attributes):[]}function Mr(t,e){for(var n=t.length;n--;)if(t[n].name===e.name)return!1;return!0}function Br(t,e,n,i){var r=t.__model;i&&r.shuffle(i)}function Kr(t,e,n,i){if(t.set&&t.set.__magic)return t.set.__magic.dependants.push({ractive:e,keypath:n}),t;var r,o=[{ractive:e,keypath:n}],s={get:function(){return"value"in t?t.value:t.get.call(this)},set:function(e){r||("value"in t?t.value=e:t.set.call(this,e),i.locked||(r=!0,o.forEach(function(t){var n=t.ractive,i=t.keypath;n.set(i,e)}),r=!1))},enumerable:!0};return s.set.__magic={dependants:o,originalDescriptor:t},s}function Ir(t,e,n){if(!t.set||!t.set.__magic)return!0;for(var i=t.set.__magic,r=i.length;r--;){var o=i[r];if(o.ractive===e&&o.keypath===n)return i.splice(r,1),!1}}function Rr(t){var e=t.replace(/^\t+/gm,function(t){return t.split("\t").join("  ")}).split("\n"),n=e.length<2?0:e.slice(1).reduce(function(t,e){return Math.min(t,/^\s*/.exec(e)[0].length)},1/0);return e.map(function(t,e){return"    "+(e?t.substring(n):t)}).join("\n")}function Lr(t){if(!t)return"";for(var e=t.split("\n"),n=Jc.name+".getValue",i=[],r=e.length,o=1;o<r;o+=1){var s=e[o];if(~s.indexOf(n))return i.join("\n");i.push(s)}}function Dr(t,e,n){var i,r,o,s,a;return"function"==typeof n&&(i=$(n,t),o=n.toString(),s=!0),"string"==typeof n&&(i=Di(n,t),o=n),"object"==typeof n&&("string"==typeof n.get?(i=Di(n.get,t),o=n.get):"function"==typeof n.get?(i=$(n.get,t),o=n.get.toString(),s=!0):d("`%s` computation must have a `get()` method",e),"function"==typeof n.set&&(r=$(n.set,t),a=n.set.toString())),{getter:i,setter:r,getterString:o,setterString:a,getterUseStack:s}}function Wr(t,e){ls.DEBUG&&Is(),$r(t),Ps(t,"data",{get:qr}),np.fire(t,e),ip.forEach(function(n){t[n]=s(Ns(t.constructor[n]||null),e[n])});var n=new ep({adapt:zr(t,t.adapt,e),data:kh.init(t.constructor,t,e),ractive:t});t.viewmodel=n;var i=s(Ns(t.constructor.prototype.computed),e.computed);for(var r in i){var o=Dr(t,r,i[r]);n.compute(r,o)}}function Ur(t){for(var e=[],n=e.concat.apply(e,t),i=n.length;i--;)~e.indexOf(n[i])||e.unshift(n[i]);return e}function zr(t,e,n){function i(e){return"string"==typeof e&&((e=w("adaptors",t,e))||d($s(e,"adaptor"))),e}e=e.map(i);var r=S(n.adapt).map(i),o=[],s=[e,r];t.parent&&!t.isolated&&s.push(t.parent.viewmodel.adaptors),s.push(o);var a="magic"in n?n.magic:t.magic,h="modifyArrays"in n?n.modifyArrays:t.modifyArrays;if(a){if(!cs)throw new Error("Getters and setters (magic mode) are not supported in this browser");h&&o.push(Yc),o.push(Hc)}return h&&o.push($c),Ur(s)}function $r(t){t._guid="r-"+rp++,t._subs=Ns(null),t._config={},t.nodes={},t.event=null,t._eventQueue=[],t._liveQueries=[],t._liveComponentQueries=[],t._observers=[],t.component||(t.root=t,t.parent=t.container=null)}function qr(){throw new Error("Using `ractive.data` is no longer supported - you must use the `ractive.get()` API instead")}function Zr(t,e){return t[e._guid]||(t[e._guid]=[])}function Hr(t,e){var n=Zr(t.queue,e);for(t.hook.fire(e);n.length;)Hr(t,n.shift());delete t.queue[e._guid]}function Qr(t,n,i){Object.keys(t.viewmodel.computations).forEach(function(e){var n=t.viewmodel.computations[e];t.viewmodel.value.hasOwnProperty(e)&&n.set(t.viewmodel.value[e])}),mc.init(t.constructor,t,n),sp.fire(t),ap.begin(t);var r;if(t.template){var o;(i.cssIds||t.cssId)&&(o=i.cssIds?i.cssIds.slice():[],t.cssId&&o.push(t.cssId)),t.fragment=r=new Cf({owner:t,template:t.template,cssIds:o}).bind(t.viewmodel)}if(ap.end(t),r){var s=e(t.el);if(s){var a=t.render(s,t.append);ls.DEBUG_PROMISES&&a.catch(function(e){throw b("Promise debugging is enabled, to help solve errors that happen asynchronously. Some browsers will log unhandled promise rejections, in which case you can safely disable promise debugging:\n  Ractive.DEBUG_PROMISES = false;"),y("An error happened during rendering",{ractive:t}),m(e),e})}}}function Gr(t){var e=t.ractive;do{for(var n=e._liveComponentQueries,i=n.length;i--;){var r=n[i],o=n["_"+r];o.test(t)&&(o.add(t.instance),t.liveQueries.push(o))}}while(e=e.parent)}function Yr(t){for(var e=t.ractive;e;){var n=e._liveComponentQueries["_"+t.name];n&&n.remove(t),e=e.parent}}function Jr(t){t.makeDirty()}function Xr(t){var e=t.node,n=t.ractive;do{for(var i=n._liveQueries,r=i.length;r--;){var o=i[r],s=i["_"+o];s.test(e)&&(s.add(e),t.liveQueries.push(s))}}while(n=n.parent)}function to(t,e){b("The "+t+" being used for two-way binding is ambiguous, and may cause unexpected results. Consider initialising your data to eliminate the ambiguity",{ractive:e})}function eo(){this._ractive.binding.handleChange()}function no(t,e,n){var i=t+"-bindingGroup";return e[i]||(e[i]=new kp(i,e,n))}function io(){var t=this.bindings.filter(function(t){return t.node&&t.node.checked}).map(function(t){return t.element.getAttribute("value")}),e=[];return t.forEach(function(t){A(e,t)||e.push(t)}),e}function ro(){eo.call(this);var t=this._ractive.binding.model.get();this.value=void 0==t?"":t}function oo(t){var e;return function(){var n=this;e&&clearTimeout(e),e=setTimeout(function(){n._ractive.binding.rendered&&eo.call(n),e=null},t)}}function so(t){return t.selectedOptions?T(t.selectedOptions):t.options?T(t.options).filter(function(t){return t.selected}):[]}function ao(t){return jp[t]||(jp[t]=[])}function ho(){var t=this.bindings.filter(function(t){return t.node.checked});if(t.length>0)return t[0].element.getAttribute("value")}function uo(t){return t&&t.template.f&&1===t.template.f.length&&t.template.f[0].t===Fh&&!t.template.f[0].s}function lo(t){var e=t.attributeByName;if(t.getAttribute("contenteditable")||uo(e.contenteditable))return uo(e.value)?_p:null;if("input"===t.name){var n=t.getAttribute("type")
;if("radio"===n||"checkbox"===n){var i=uo(e.name),r=uo(e.checked);if(i&&r){if("radio"!==n)return wp;y("A radio input can have two-way binding on its name attribute, or its checked attribute - not both",{ractive:t.root})}if(i)return"radio"===n?Fp:Ep;if(r)return"radio"===n?Tp:wp}return"file"===n&&uo(e.value)?Op:uo(e.value)?"number"===n||"range"===n?Cp:Ap:null}return"select"===t.name&&uo(e.value)?t.getAttribute("multiple")?Sp:Np:"textarea"===t.name&&uo(e.value)?Ap:void 0}function co(t){t.makeDirty()}function po(t){var e=t.attributeByName,n=e.type,i=e.value,r=e.name;if(n&&"radio"===n.value&&i&&r.interpolator)return i.getValue()===r.interpolator.model.get()||void 0}function fo(t){var e=t.toString();return e?" "+e:""}function mo(t){for(var e=t.liveQueries.length;e--;){t.liveQueries[e].remove(t.node)}}function go(t){var e=t.getAttribute("xmlns");if(e)return e;if("svg"===t.name)return Ts;var n=t.parent;return n?"foreignobject"===n.name?js:n.node.namespaceURI:t.ractive.el.namespaceURI}function vo(){var t=this._ractive.proxy;ia.start(),t.formBindings.forEach(yo),ia.end()}function yo(t){t.model.set(t.resetValue)}function bo(t){var e=t.template.f,n=t.element.instance.viewmodel,i=n.value;1===e.length&&e[0].t===Fh?(t.model=ar(t.parentFragment,e[0]),t.model||(b("The "+t.name+"='{{"+e[0].r+"}}' mapping is ambiguous, and may cause unexpected results. Consider initialising your data to eliminate the ambiguity",{ractive:t.element.instance}),t.parentFragment.ractive.get(t.name),t.model=t.parentFragment.findContext().joinKey(t.name)),t.link=n.createLink(t.name,t.model,e[0].r),void 0===t.model.get()&&!t.model.isReadonly&&t.name in i&&t.model.set(i[t.name])):(t.boundFragment=new Cf({owner:t,template:e}).bind(),t.model=n.joinKey(t.name),t.model.set(t.boundFragment.valueOf()),t.boundFragment.bubble=function(){Cf.prototype.bubble.call(t.boundFragment),ia.scheduleTask(function(){t.boundFragment.update(),t.model.set(t.boundFragment.valueOf())})})}function wo(t,e,n){var i=ko(t,e,n||{});if(i)return i;if(i=oc.fromId(e,{noThrow:!0})){var r=oc.parseFor(i,t);return r.p&&a(t.partials,r.p),t.partials[e]=r.t}}function ko(t,e,n){var i=_o(e,n.owner);if(i)return i;var r=k("partials",t,e);if(r){i=r.partials[e];var o;if("function"==typeof i&&(o=i.bind(r),o.isOwner=r.partials.hasOwnProperty(e),i=o.call(t,oc)),!i&&""!==i)return void y(zs,e,"partial","partial",{ractive:t});if(!oc.isParsed(i)){var s=oc.parseFor(i,r);s.p&&y("Partials ({{>%s}}) cannot contain nested inline partials",e,{ractive:t});(o?r:xo(r,e)).partials[e]=i=s.t}return o&&(i._fn=o),i.v?i.t:i}}function xo(t,e){return t.partials.hasOwnProperty(e)?t:Eo(t.constructor,e)}function Eo(t,e){if(t)return t.partials.hasOwnProperty(e)?t:Eo(t._Parent,e)}function _o(t,e){if(e){if(e.template&&e.template.p&&e.template.p[t])return e.template.p[t];if(e.parentFragment&&e.parentFragment.owner)return _o(t,e.parentFragment.owner)}}function Ao(t,e,n){var i;try{i=oc.parse(e,oc.getParseOptions(n))}catch(e){y("Could not parse partial from expression '"+t+"'\n"+e.message)}return i||{t:[]}}function Oo(t){return!t||h(t)&&0===t.length||c(t)&&0===Object.keys(t).length}function So(t,e){return e||h(t)?cu:c(t)||"function"==typeof t?fu:void 0===t?null:uu}function Co(t,e){for(var n=t.length;n--;)if(t[n]==e)return!0}function jo(t){return t.replace(/-([a-zA-Z])/g,function(t,e){return e.toUpperCase()})}function To(){Gp=!ms[Jp]}function Fo(){Gp=!1}function No(){Gp=!0}function Po(t){return t.replace(rf,"")}function Vo(t){return t?(of.test(t)&&(t="-"+t),t.replace(/[A-Z]/g,function(t){return"-"+t.toLowerCase()})):""}function Mo(t,e){e?t.setAttribute("style",e):(t.getAttribute("style"),t.removeAttribute("style"))}function Bo(t,e,n){var i=[];if(null==t||""===t)return i;var r,o,s;kf&&(o=xf[e.tagName])?(r=Ko("DIV"),r.innerHTML=o[0]+t+o[1],r=r.querySelector(".x"),"SELECT"===r.tagName&&(s=r.options[r.selectedIndex])):e.namespaceURI===Ts?(r=Ko("DIV"),r.innerHTML='<svg class="x">'+t+"</svg>",r=r.querySelector(".x")):"TEXTAREA"===e.tagName?(r=ys("div"),void 0!==r.textContent?r.textContent=t:r.innerHTML=t):(r=Ko(e.tagName),r.innerHTML=t,"SELECT"===r.tagName&&(s=r.options[r.selectedIndex]));for(var a;a=r.firstChild;)i.push(a),n.appendChild(a);var h;if("SELECT"===e.tagName)for(h=i.length;h--;)i[h]!==s&&(i[h].selected=!1);return i}function Ko(t){return Ef[t]||(Ef[t]=ys(t))}function Io(t,e){var n,i=k("components",t,e);if(i&&(n=i.components[e],!n._Parent)){var r=n.bind(i);if(r.isOwner=i.components.hasOwnProperty(e),!(n=r()))return void y(zs,e,"component","component",{ractive:t});"string"==typeof n&&(n=Io(t,n)),n._fn=r,i.components[e]=n}return n}function Ro(t){if("string"==typeof t.template)return new Zp(t);if(t.template.t===Bh){var e=Io(t.parentFragment.ractive,t.template.e);if(e)return new mp(t,e);var n=t.template.e.toLowerCase();return new(Sf[n]||Vp)(t)}var i;if(t.template.t===Lh){var r=t.owner;(!r||r.type!==Wh&&r.type!==Bh)&&(r=ur(t.parentFragment)),t.element=r,i=r.type===Wh?Rp:Vc}else i=Of[t.template.t];if(!i)throw new Error("Unrecognised item type "+t.template.t);return new i(t)}function Lo(t,e,n,i){return void 0===i&&(i=0),t.map(function(t){if(t.type===Th)return t.template;if(t.fragment)return t.fragment.iterations?t.fragment.iterations.map(function(t){return Lo(t.items,e,n,i)}).join(""):Lo(t.fragment.items,e,n,i);var r=n+"-"+i++,o=t.model||t.newModel;return e[r]=o?o.wrapper?o.wrapperValue:o.get():void 0,"${"+r+"}"}).join("")}function Do(t){t.unrender(!0)}function Wo(e){sc.init(null,this,{template:e});var n=this.transitionsEnabled;this.transitionsEnabled=!1;var i=this.component;i&&(i.shouldDestroy=!0),this.unrender(),i&&(i.shouldDestroy=!1),this.fragment.unbind().unrender(!0),this.fragment=new Cf({template:this.template,root:this,owner:this});var r=t();this.fragment.bind(this.viewmodel).render(r),i?this.fragment.findParentNode().insertBefore(r,i.findNextNode()):this.el.insertBefore(r,this.anchor),this.transitionsEnabled=n}function Uo(t,e){var n=this;return q(n,H(n,t,e))}function zo(t,e){return Q(this,t,void 0===e?-1:-e)}function $o(){if(this.torndown)return y("ractive.teardown() was called on a Ractive instance that was already torn down"),Xs.resolve();this.torndown=!0,this.fragment.unbind(),this.viewmodel.teardown(),this._observers.forEach(Ot),this.fragment.rendered&&this.el.__ractive_instances__&&j(this.el.__ractive_instances__,this),this.shouldDestroy=!0;var t=this.fragment.rendered?this.unrender():Xs.resolve();return Pf.fire(this),t}function qo(t){if("string"!=typeof t)throw new TypeError(Us);return q(this,Z(this,t).map(function(t){return[t,!t.get()]}))}function Zo(){var t=[this.cssId].concat(this.findAllComponents().map(function(t){return t.cssId}));return tn(Object.keys(t.reduce(function(t,e){return t[e]=!0,t},{})))}function Ho(){return this.fragment.toString(!0)}function Qo(){return this.fragment.toString(!1)}function Go(t,e,n){e instanceof HTMLElement||c(e)&&(n=e),e=e||this.event.node,e&&e._ractive||d("No node was supplied for transition "+t),n=n||{};var i=e._ractive.proxy,r=new wf({owner:i,parentFragment:i.parentFragment,name:t,params:n});r.bind();var o=ia.start(this,!0);return ia.registerTransition(r),ia.end(),o.then(function(){return r.unbind()}),o}function Yo(t){var e=ia.start();return this.viewmodel.joinAll(U(t),{lastLink:!1}).unlink(),ia.end(),e}function Jo(){if(!this.fragment.rendered)return y("ractive.unrender() was called on a Ractive instance that was not rendered"),Xs.resolve();var t=ia.start(this,!0),e=!this.component||this.component.shouldDestroy||this.shouldDestroy;return this.fragment.unrender(e),j(this.el.__ractive_instances__,this),Vf.fire(this),ia.end(),t}function Xo(t,e){var n=ia.start(this,!0);return t?this.viewmodel.joinAll(U(t)).updateFromBindings(!1!==e):this.viewmodel.updateFromBindings(!0),ia.end(),n}function ts(t,e,n){return n||es(t,e)?function(){var n,i="_super"in this,r=this._super;return this._super=e,n=t.apply(this,arguments),i&&(this._super=r),n}:t}function es(t,e){return"function"==typeof e&&/_super/.test(t)}function ns(t){for(var e={};t;)is(t,e),os(t,e),t=t._Parent!==ls&&t._Parent;return e}function is(t,e){uc.forEach(function(n){rs(n.useDefaults?t.prototype:t,e,n.name)})}function rs(t,e,n){var i,r=Object.keys(t[n]);r.length&&((i=e[n])||(i=e[n]={}),r.filter(function(t){return!(t in i)}).forEach(function(e){return i[e]=t[n][e]}))}function os(t,e){Object.keys(t.prototype).forEach(function(n){if("computed"!==n){var i=t.prototype[n];if(n in e){if("function"==typeof e[n]&&"function"==typeof i&&e[n]._method){var r,o=i._method;o&&(i=i._method),r=ts(e[n]._method,i),o&&(r._method=r),e[n]=r}}else e[n]=i._method?i._method:i}})}function ss(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.length?t.reduce(as,this):as(this)}function as(t,e){void 0===e&&(e={});var n,i;return e.prototype instanceof ls&&(e=ns(e)),n=function(t){if(!(this instanceof n))return new n(t);Wr(this,t||{}),Qr(this,t||{},{})},i=Ns(t.prototype),i.constructor=n,Vs(n,{defaults:{value:i},extend:{value:ss,writable:!0,configurable:!0},_Parent:{value:t}}),mc.extend(t,i,e),kh.extend(t,i,e),e.computed&&(i.computed=s(Ns(t.prototype.computed),e.computed)),n.prototype=i,n}function hs(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];return t.map(D).join(".")}function us(t){return U(t).map(z)}function ls(t){if(!(this instanceof ls))return new ls(t);Wr(this,t||{}),Qr(this,t||{},{})}var cs,ps={el:void 0,append:!1,template:null,delimiters:["{{","}}"],tripleDelimiters:["{{{","}}}"],staticDelimiters:["[[","]]"],staticTripleDelimiters:["[[[","]]]"],csp:!0,interpolate:!1,preserveWhitespace:!1,sanitize:!1,stripComments:!0,contextLines:0,data:{},computed:{},magic:!1,modifyArrays:!1,adapt:[],isolated:!1,twoway:!0,lazy:!1,noIntro:!1,transitionsEnabled:!0,complete:void 0,css:null,noCssTransform:!1},fs={linear:function(t){return t},easeIn:function(t){return Math.pow(t,3)},easeOut:function(t){return Math.pow(t-1,3)+1},easeInOut:function(t){return(t/=.5)<1?.5*Math.pow(t,3):.5*(Math.pow(t-2,3)+2)}},ds="undefined"!=typeof window?window:null,ms=ds?document:null,gs=!!ms,vs=("undefined"!=typeof navigator&&/jsDom/.test(navigator.appName),"undefined"!=typeof console&&"function"==typeof console.warn&&"function"==typeof console.warn.apply);try{Object.defineProperty({},"test",{value:0}),cs=!0}catch(t){cs=!1}var ys,bs,ws,ks,xs,Es,_s,As,Os,Ss=!!ms&&ms.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1"),Cs=["o","ms","moz","webkit"],js="http://www.w3.org/1999/xhtml",Ts="http://www.w3.org/2000/svg",Fs={html:js,mathml:"http://www.w3.org/1998/Math/MathML",svg:Ts,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns"};if(ys=Ss?function(t,e,n){return e&&e!==js?n?ms.createElementNS(e,t,n):ms.createElementNS(e,t):n?ms.createElement(t,n):ms.createElement(t)}:function(t,e,n){if(e&&e!==js)throw"This browser does not support namespaces other than http://www.w3.org/1999/xhtml. The most likely cause of this error is that you're trying to render SVG in an older browser. See http://docs.ractivejs.org/latest/svg-and-older-browsers for more information";return n?ms.createElement(t,n):ms.createElement(t)},gs){for(ws=ys("div"),ks=["matches","matchesSelector"],Os=function(t){return function(e,n){return e[t](n)}},_s=ks.length;_s--&&!bs;)if(xs=ks[_s],ws[xs])bs=Os(xs);else for(As=Cs.length;As--;)if(Es=Cs[_s]+xs.substr(0,1).toUpperCase()+xs.substring(1),ws[Es]){bs=Os(Es);break}bs||(bs=function(t,e){var n,i,r;for(i=t.parentNode,i||(ws.innerHTML="",i=ws,t=t.cloneNode(),ws.appendChild(t)),n=i.querySelectorAll(e),r=n.length;r--;)if(n[r]===t)return!0;return!1})}else bs=null;var Ns,Ps,Vs,Ms=/[A-Z]/g;try{Object.defineProperty({},"test",{get:function(){},set:function(){}}),ms&&Object.defineProperty(ys("div"),"test",{value:0}),Ps=Object.defineProperty}catch(t){Ps=function(t,e,n){n.get?t[e]=n.get():t[e]=n.value}}try{try{Object.defineProperties({},{test:{value:0}})}catch(t){throw t}ms&&Object.defineProperties(ys("div"),{test:{value:0}}),Vs=Object.defineProperties}catch(t){Vs=function(t,e){var n;for(n in e)e.hasOwnProperty(n)&&Ps(t,n,e[n])}}try{Object.create(null),Ns=Object.create}catch(t){Ns=function(){var t=function(){};return function(e,n){var i;return null===e?{}:(t.prototype=e,i=new t,n&&Object.defineProperties(i,n),i)}}()}var Bs,Ks,Is,Rs=Object.prototype.hasOwnProperty,Ls=Object.prototype.toString,Ds={};if(vs){var Ws=["%cRactive.js %c0.8.14 %cin debug mode, %cmore...","color: rgb(114, 157, 52); font-weight: normal;","color: rgb(85, 85, 85); font-weight: normal;","color: rgb(85, 85, 85); font-weight: normal;","color: rgb(82, 140, 224); font-weight: normal; text-decoration: underline;"];Is=function(){if(!1===ls.WELCOME_MESSAGE)return void(Is=p);var t="WELCOME_MESSAGE"in ls?ls.WELCOME_MESSAGE:"You're running Ractive 0.8.14 in debug mode - messages will be printed to the console to help you fix problems and optimise your application.\n\nTo disable debug mode, add this line at the start of your app:\n  Ractive.DEBUG = false;\n\nTo disable debug mode when your app is minified, add this snippet:\n  Ractive.DEBUG = /unminified/.test(function(){/*unminified*/});\n\nGet help and support:\n  http://docs.ractivejs.org\n  http://stackoverflow.com/questions/tagged/ractivejs\n  http://groups.google.com/forum/#!forum/ractive-js\n  http://twitter.com/ractivejs\n\nFound a bug? Raise an issue:\n  https://github.com/ractivejs/ractive/issues\n\n",e=!!console.groupCollapsed;e&&console.groupCollapsed.apply(console,Ws),console.log(t),e&&console.groupEnd(Ws),Is=p},Ks=function(t,e){if(Is(),"object"==typeof e[e.length-1]){var n=e.pop(),i=n?n.ractive:null;if(i){var r;i.component&&(r=i.component.name)&&(t="<"+r+"> "+t);var o;(o=n.node||i.fragment&&i.fragment.rendered&&i.find("*"))&&e.push(o)}}console.warn.apply(console,["%cRactive.js: %c"+t,"color: rgb(114, 157, 52);","color: rgb(85, 85, 85);"].concat(e))},Bs=function(){console.log.apply(console,arguments)}}else Ks=Bs=Is=p;var Us="Bad arguments",zs='A function was specified for "%s" %s, but no %s was returned',$s=function(t,e){return'Missing "'+t+'" '+e+" plugin. You may need to download a plugin via http://docs.ractivejs.org/latest/plugins#"+e+"s"},qs={number:function(t,e){var n;return l(t)&&l(e)?(t=+t,e=+e,n=e-t,n?function(e){return t+e*n}:function(){return t}):null},array:function(t,e){var n,i,r,o;if(!h(t)||!h(e))return null;for(n=[],i=[],o=r=Math.min(t.length,e.length);o--;)i[o]=x(t[o],e[o]);for(o=r;o<t.length;o+=1)n[o]=t[o];for(o=r;o<e.length;o+=1)n[o]=e[o];return function(t){for(var e=r;e--;)n[e]=i[e](t);return n}},object:function(t,e){var n,i,r,o,s;if(!c(t)||!c(e))return null;n=[],o={},r={};for(s in t)Rs.call(t,s)&&(Rs.call(e,s)?(n.push(s),r[s]=x(t[s],e[s])||E(e[s])):o[s]=t[s]);for(s in e)Rs.call(e,s)&&!Rs.call(t,s)&&(o[s]=e[s]);return i=n.length,function(t){for(var e,s=i;s--;)e=n[s],o[e]=r[e](t);return o}}},Zs={construct:{deprecated:"beforeInit",replacement:"onconstruct"},render:{deprecated:"init",message:'The "init" method has been deprecated and will likely be removed in a future release. You can either use the "oninit" method which will fire only once prior to, and regardless of, any eventual ractive instance being rendered, or if you need to access the rendered DOM, use "onrender" instead. See http://docs.ractivejs.org/latest/migrating for more information.'},complete:{deprecated:"complete",replacement:"oncomplete"}},Hs=function(t){this.event=t,this.method="on"+t,this.deprecate=Zs[t]};Hs.prototype.call=function(t,e,n){if(e[t])return n?e[t](n):e[t](),!0},Hs.prototype.fire=function(t,e){this.call(this.method,t,e),!t[this.method]&&this.deprecate&&this.call(this.deprecate.deprecated,t,e)&&(this.deprecate.message?y(this.deprecate.message):y('The method "%s" has been deprecated in favor of "%s" and will likely be removed in a future release. See http://docs.ractivejs.org/latest/migrating for more information.',this.deprecate.deprecated,this.deprecate.replacement)),e?t.fire(this.event,e):t.fire(this.event)};var Qs,Gs={},Ys={},Js={};"function"==typeof Promise?Qs=Promise:(Qs=function(t){var e,n,i,r,o,s,a=[],h=[],u=Gs;i=function(t){return function(i){u===Gs&&(e=i,u=t,n=N(u===Ys?a:h,e),F(n))}},r=i(Ys),o=i(Js);try{t(r,o)}catch(t){o(t)}return s={then:function(t,e){var i=new Qs(function(r,o){var s=function(t,e,n){"function"==typeof t?e.push(function(e){var n;try{n=t(e),P(i,n,r,o)}catch(t){o(t)}}):e.push(n)};s(t,a,r),s(e,h,o),u!==Gs&&F(n)});return i}},s.catch=function(t){return this.then(null,t)},s},Qs.all=function(t){return new Qs(function(e,n){var i,r,o,s=[];if(!t.length)return void e(s);for(o=function(t,r){t&&"function"==typeof t.then?t.then(function(t){s[r]=t,--i||e(s)},n):(s[r]=t,--i||e(s))},i=r=t.length;r--;)o(t[r],r)})},Qs.resolve=function(t){return new Qs(function(e){e(t)})},Qs.reject=function(t){return new Qs(function(e,n){n(t)})});var Xs=Qs,ta=function(t,e){this.callback=t,this.parent=e,this.intros=[],this.outros=[],this.children=[],this.totalChildren=this.outroChildren=0,this.detachQueue=[],this.outrosComplete=!1,e&&e.addChild(this)};ta.prototype.add=function(t){(t.isIntro?this.intros:this.outros).push(t)},ta.prototype.addChild=function(t){this.children.push(t),this.totalChildren+=1,this.outroChildren+=1},ta.prototype.decrementOutros=function(){this.outroChildren-=1,B(this)},ta.prototype.decrementTotal=function(){this.totalChildren-=1,B(this)},ta.prototype.detachNodes=function(){this.detachQueue.forEach(V),this.children.forEach(M),this.detachQueue=[]},ta.prototype.ready=function(){K(this)},ta.prototype.remove=function(t){j(t.isIntro?this.intros:this.outros,t),B(this)},ta.prototype.start=function(){this.children.forEach(function(t){return t.start()}),this.intros.concat(this.outros).forEach(function(t){return t.start()}),this.ready=!0,B(this)};var ea,na=new Hs("change"),ia={start:function(t,e){var n,i;return e&&(n=new Xs(function(t){return i=t})),ea={previousBatch:ea,transitionManager:new ta(i,ea&&ea.transitionManager),fragments:[],tasks:[],immediateObservers:[],deferredObservers:[],ractives:[],instance:t},n},end:function(){L(),ea.previousBatch||ea.transitionManager.start(),ea=ea.previousBatch},addFragment:function(t){_(ea.fragments,t)},addFragmentToRoot:function(t){if(ea){for(var e=ea;e.previousBatch;)e=e.previousBatch;_(e.fragments,t)}},addInstance:function(t){ea&&_(ea.ractives,t)},addObserver:function(t,e){_(e?ea.deferredObservers:ea.immediateObservers,t)},registerTransition:function(t){t._manager=ea.transitionManager,ea.transitionManager.add(t)},detachWhenReady:function(t){ea.transitionManager.detachQueue.push(t)},scheduleTask:function(t,e){var n;if(ea){for(n=ea;e&&n.previousBatch;)n=n.previousBatch;n.tasks.push(t)}else t()}},ra=/\[\s*(\*|[0-9]|[1-9][0-9]+)\s*\]/g,oa=/([^\\](?:\\\\)*)\./,sa=/\\|\./g,aa=/((?:\\)+)\1|\\(\.)/g,ha=Function.prototype.bind,ua=/\*/,la="Cannot add to a non-numeric value",ca=Xs.resolve();Ps(ca,"stop",{value:p});var pa=fs.linear,fa=new Hs("detach"),da=function(t,e,n,i){this.ractive=t,this.selector=e,this.live=n,this.isComponentQuery=i,this.result=[],this.dirty=!0};da.prototype.add=function(t){this.result.push(t),this.makeDirty()},da.prototype.cancel=function(){var t=this._root[this.isComponentQuery?"liveComponentQueries":"liveQueries"],e=this.selector,n=t.indexOf(e);-1!==n&&(t.splice(n,1),t[e]=null)},da.prototype.init=function(){this.dirty=!1},da.prototype.makeDirty=function(){var t=this;this.dirty||(this.dirty=!0,ia.scheduleTask(function(){return t.update()}))},da.prototype.remove=function(t){var e=this.result.indexOf(this.isComponentQuery?t.instance:t);-1!==e&&this.result.splice(e,1)},da.prototype.update=function(){this.result.sort(this.isComponentQuery?it:nt),this.dirty=!1},da.prototype.test=function(t){return this.isComponentQuery?!this.selector||t.name===this.selector:t?bs(t,this.selector):null};var ma,ga={},va={},ya=[],ba=function(t,e){this.value=t,this.isReadonly=this.isKey=!0,this.deps=[],this.links=[],this.parent=e};ba.prototype.get=function(t){return t&&_t(this),z(this.value)},ba.prototype.getKeypath=function(){return z(this.value)},ba.prototype.rebinding=function(t,e){for(var n=this,i=this.deps.length;i--;)n.deps[i].rebinding(t,e,!1);for(i=this.links.length;i--;)n.links[i].rebinding(t,e,!1)},ba.prototype.register=function(t){this.deps.push(t)},ba.prototype.registerLink=function(t){_(this.links,t)},ba.prototype.unregister=function(t){j(this.deps,t)},ba.prototype.unregisterLink=function(t){j(this.links,t)},ba.prototype.reference=p,ba.prototype.unreference=p;var wa=function(t,e){this.parent=t,this.ractive=e,this.value=e?t.getKeypath(e):t.getKeypath(),this.deps=[],this.children={},this.isReadonly=this.isKeypath=!0};wa.prototype.get=function(t){return t&&_t(this),this.value},wa.prototype.getChild=function(t){if(!(t._guid in this.children)){var e=new wa(this.parent,t);this.children[t._guid]=e,e.owner=this}return this.children[t._guid]},wa.prototype.getKeypath=function(){return this.value},wa.prototype.handleChange=function(){for(var t=this,e=Object.keys(this.children),n=e.length;n--;)t.children[e[n]].handleChange();this.deps.forEach(St)},wa.prototype.rebindChildren=function(t){for(var e=this,n=Object.keys(this.children),i=n.length;i--;){var r=e.children[n[i]];r.value=t.getKeypath(r.ractive),r.handleChange()}},wa.prototype.rebinding=function(t,e){for(var n=this,i=t?t.getKeypathModel(this.ractive):void 0,r=Object.keys(this.children),o=r.length;o--;)n.children[r[o]].rebinding(t,e,!1);for(o=this.deps.length;o--;)n.deps[o].rebinding(i,n,!1)},wa.prototype.register=function(t){this.deps.push(t)},wa.prototype.removeChild=function(t){t.ractive&&delete this.children[t.ractive._guid]},wa.prototype.teardown=function(){var t=this;this.owner&&this.owner.removeChild(this);for(var e=Object.keys(this.children),n=e.length;n--;)t.children[e[n]].teardown()},wa.prototype.unregister=function(t){j(this.deps,t),this.deps.length||this.teardown()},wa.prototype.reference=p,wa.prototype.unreference=p;var ka=Object.prototype.hasOwnProperty,xa={early:[],mark:[]},Ea={early:[],mark:[]},_a=function(t){this.deps=[],this.children=[],this.childByKey={},this.links=[],this.keyModels={},this.unresolved=[],this.unresolvedByKey={},this.bindings=[],this.patternObservers=[],t&&(this.parent=t,this.root=t.root)};_a.prototype.addUnresolved=function(t,e){this.unresolvedByKey[t]||(this.unresolved.push(t),this.unresolvedByKey[t]=[]),this.unresolvedByKey[t].push(e)},_a.prototype.addShuffleTask=function(t,e){void 0===e&&(e="early"),xa[e].push(t)},_a.prototype.addShuffleRegister=function(t,e){void 0===e&&(e="early"),Ea[e].push({model:this,item:t})},_a.prototype.clearUnresolveds=function(t){for(var e=this,n=this.unresolved.length;n--;){var i=e.unresolved[n];if(!t||i===t){for(var r=e.unresolvedByKey[i],o=e.has(i),s=r.length;s--;)o&&r[s].attemptResolution(),r[s].resolved&&r.splice(s,1);r.length||(e.unresolved.splice(n,1),e.unresolvedByKey[i]=null)}}},_a.prototype.findMatches=function(t){var e,n,i=t.length,r=[this];for(n=0;n<i;n+=1)!function(){var i=t[n];"*"===i?(e=[],r.forEach(function(t){e.push.apply(e,t.getValueChildren(t.get()))})):e=r.map(function(t){return t.joinKey(i)}),r=e}();return e},_a.prototype.getKeyModel=function(t,e){return void 0===t||e?(t in this.keyModels||(this.keyModels[t]=new ba(D(t),this)),this.keyModels[t]):this.parent.getKeyModel(t,!0)},_a.prototype.getKeypath=function(t){return t!==this.ractive&&this._link?this._link.target.getKeypath(t):(this.keypath||(this.keypath=this.parent.isRoot?this.key:this.parent.getKeypath(t)+"."+D(this.key)),this.keypath)},_a.prototype.getValueChildren=function(t){var e,n=this;if(h(t))e=[],"length"in this&&this.length!==t.length&&e.push(this.joinKey("length")),t.forEach(function(t,i){e.push(n.joinKey(i))});else if(c(t)||"function"==typeof t)e=Object.keys(t).map(function(t){return n.joinKey(t)});else if(null!=t)return[];return e},_a.prototype.getVirtual=function(t){var e=this,n=this.get(t,{virtual:!1});if(c(n)){for(var i=h(n)?[]:{},r=Object.keys(n),o=r.length;o--;){var s=e.childByKey[r[o]];s?s._link?i[r[o]]=s._link.getVirtual():i[r[o]]=s.getVirtual():i[r[o]]=n[r[o]]}for(o=this.children.length;o--;){var a=e.children[o];a.key in i||!a._link||(i[a.key]=a._link.getVirtual())}return i}return n},_a.prototype.has=function(t){if(this._link)return this._link.has(t);var e=this.get();if(!e)return!1;if(t=z(t),ka.call(e,t))return!0;for(var n=e.constructor;n!==Function&&n!==Array&&n!==Object;){if(ka.call(n.prototype,t))return!0;n=n.constructor}return!1},_a.prototype.joinAll=function(t,e){for(var n=this,i=0;i<t.length;i+=1){if(e&&!1===e.lastLink&&i+1===t.length&&n.childByKey[t[i]]&&n.childByKey[t[i]]._link)return n.childByKey[t[i]];n=n.joinKey(t[i],e)}return n},_a.prototype.notifyUpstream=function(){for(var t=this.parent,e=[this.key];t;)t.patternObservers.length&&t.patternObservers.forEach(function(t){return t.notify(e.slice())}),e.unshift(t.key),t.links.forEach(Ft),t.deps.forEach(St),t=t.parent},_a.prototype.rebinding=function(t,e,n){for(var i=this,r=this.deps.length;r--;)i.deps[r].rebinding&&i.deps[r].rebinding(t,e,n);for(r=this.links.length;r--;){var o=i.links[r];o.owner._link&&o.relinking(t,!0,n)}for(r=this.children.length;r--;){var s=i.children[r];s.rebinding(t?t.joinKey(s.key):void 0,s,n)}for(r=this.unresolved.length;r--;)for(var a=i.unresolvedByKey[i.unresolved[r]],h=a.length;h--;)a[h].rebinding(t,e);for(this.keypathModel&&this.keypathModel.rebinding(t,e,!1),r=this.bindings.length;r--;)i.bindings[r].rebinding(t,e,n)},_a.prototype.reference=function(){"refs"in this?this.refs++:this.refs=1},_a.prototype.register=function(t){this.deps.push(t)},_a.prototype.registerChange=function(t,e){this.isRoot?(this.changes[t]=e,ia.addInstance(this.root.ractive)):this.root.registerChange(t,e)},_a.prototype.registerLink=function(t){_(this.links,t)},_a.prototype.registerPatternObserver=function(t){this.patternObservers.push(t),this.register(t)},_a.prototype.registerTwowayBinding=function(t){this.bindings.push(t)},_a.prototype.removeUnresolved=function(t,e){var n=this.unresolvedByKey[t];n&&j(n,e)},_a.prototype.shuffled=function(){for(var t=this,e=this.children.length;e--;)t.children[e].shuffled();this.wrapper&&(this.wrapper.teardown(),this.wrapper=null,this.rewrap=!0)},_a.prototype.unreference=function(){"refs"in this&&this.refs--},_a.prototype.unregister=function(t){j(this.deps,t)},_a.prototype.unregisterLink=function(t){j(this.links,t)},_a.prototype.unregisterPatternObserver=function(t){j(this.patternObservers,t),this.unregister(t)},_a.prototype.unregisterTwowayBinding=function(t){j(this.bindings,t)},_a.prototype.updateFromBindings=function(t){for(var e=this,n=this.bindings.length;n--;){var i=e.bindings[n].getValue();i!==e.value&&e.set(i)}if(!this.bindings.length){var r=Dt(this.deps);r&&r.value!==this.value&&this.set(r.value)}t&&(this.children.forEach(Lt),this.links.forEach(Lt),this._link&&this._link.updateFromBindings(t))},ba.prototype.addShuffleTask=_a.prototype.addShuffleTask,ba.prototype.addShuffleRegister=_a.prototype.addShuffleRegister,wa.prototype.addShuffleTask=_a.prototype.addShuffleTask,wa.prototype.addShuffleRegister=_a.prototype.addShuffleRegister;var Aa=function(t){function e(e,n,i,r){t.call(this,e),this.owner=n,this.target=i,this.key=void 0===r?n.key:r,n.isLink&&(this.sourcePath=n.sourcePath+"."+this.key),i.registerLink(this),this.isReadonly=e.isReadonly,this.isLink=!0}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.animate=function(t,e,n,i){return this.target.animate(t,e,n,i)},e.prototype.applyValue=function(t){this.target.applyValue(t)},e.prototype.get=function(t,e){return t&&(_t(this),e=e||{},e.unwrap=!0),this.target.get(!1,e)},e.prototype.getKeypath=function(e){return e&&e!==this.root.ractive?this.target.getKeypath(e):t.prototype.getKeypath.call(this,e)},e.prototype.getKeypathModel=function(t){return this.keypathModel||(this.keypathModel=new wa(this)),t&&t!==this.root.ractive?this.keypathModel.getChild(t):this.keypathModel},e.prototype.handleChange=function(){this.deps.forEach(St),this.links.forEach(St),this.notifyUpstream()},e.prototype.joinKey=function(t){if(void 0===t||""===t)return this;if(!this.childByKey.hasOwnProperty(t)){var n=new e(this,this,this.target.joinKey(t),t);this.children.push(n),this.childByKey[t]=n}return this.childByKey[t]},e.prototype.mark=function(){this.target.mark()},e.prototype.marked=function(){this.links.forEach(jt),this.deps.forEach(St),this.clearUnresolveds()},e.prototype.markedAll=function(){this.children.forEach(Tt),this.marked()},e.prototype.notifiedUpstream=function(){this.links.forEach(Ft),this.deps.forEach(St)},e.prototype.relinked=function(){this.target.registerLink(this),this.children.forEach(function(t){return t.relinked()})},e.prototype.relinking=function(t,e,n){var i=this;e&&this.sourcePath&&(t=Ut(this.sourcePath,t,this.target)),t&&this.target!==t&&(this.target.unregisterLink(this),this.keypathModel&&this.keypathModel.rebindChildren(t),this.target=t,this.children.forEach(function(e){e.relinking(t.joinKey(e.key),!1,n)}),e&&this.addShuffleTask(function(){i.relinked(),n||i.notifyUpstream()}))},e.prototype.set=function(t){this.target.set(t)},e.prototype.shuffle=function(t){var e=this;if(!this.shuffling)if(this.target.shuffling){this.shuffling=!0;for(var n=t.length;n--;){var i=t[n];n!==i&&(n in e.childByKey&&e.childByKey[n].rebinding(~i?e.joinKey(i):void 0,e.childByKey[n],!0),!~i&&e.keyModels[n]?e.keyModels[n].rebinding(void 0,e.keyModels[n],!1):~i&&e.keyModels[n]&&(e.keyModels[i]||e.childByKey[i].getKeyModel(i),e.keyModels[n].rebinding(e.keyModels[i],e.keyModels[n],!1)))}var r=this.source().length!==this.source().value.length;for(this.links.forEach(function(e){return e.shuffle(t)}),n=this.deps.length;n--;)e.deps[n].shuffle&&e.deps[n].shuffle(t);this.marked(),r&&this.notifyUpstream(),this.shuffling=!1}else this.target.shuffle(t)},e.prototype.source=function(){return this.target.source?this.target.source():this.target},e.prototype.teardown=function(){this._link&&this._link.teardown(),this.target.unregisterLink(this),this.children.forEach(Pt)},e}(_a);_a.prototype.link=function(t,e){var n=this._link||new Aa(this.parent,this,t,this.key);n.sourcePath=e,this._link&&this._link.relinking(t,!0,!1),this.rebinding(n,this,!1),Wt();var i=!this._link;return this._link=n,i&&this.parent.clearUnresolveds(),n.markedAll(),n},_a.prototype.unlink=function(){if(this._link){var t=this._link;this._link=void 0,t.rebinding(this,this._link),Wt(),t.teardown()}};var Oa;ds?(!function(t,e,n){var i,r;if(!n.requestAnimationFrame){for(i=0;i<t.length&&!n.requestAnimationFrame;++i)n.requestAnimationFrame=n[t[i]+"RequestAnimationFrame"];n.requestAnimationFrame||(r=n.setTimeout,n.requestAnimationFrame=function(t){var n,i,o;return n=Date.now(),i=Math.max(0,16-(n-e)),o=r(function(){t(n+i)},i),e=n+i,o})}}(Cs,0,ds),Oa=ds.requestAnimationFrame):Oa=null;var Sa=Oa,Ca=ds&&ds.performance&&"function"==typeof ds.performance.now?function(){return ds.performance.now()}:function(){return Date.now()},ja=[],Ta=!1,Fa=function(t){this.duration=t.duration,this.step=t.step,this.complete=t.complete,this.easing=t.easing,this.start=Ca(),this.end=this.start+this.duration,this.running=!0,ja.push(this),Ta||Sa(zt)};Fa.prototype.tick=function(t){if(!this.running)return!1;if(t>this.end)return this.step&&this.step(1),this.complete&&this.complete(1),!1;var e=t-this.start,n=this.easing(e/this.duration);return this.step&&this.step(n),!0},Fa.prototype.stop=function(){this.abort&&this.abort(),this.running=!1};var Na={},Pa=function(t){function e(e,n){t.call(this,e),this.ticker=null,e&&(this.key=z(n),this.isReadonly=e.isReadonly,e.value&&(this.value=e.value[this.key],h(this.value)&&(this.length=this.value.length),this.adapt()))}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.adapt=function(){var t=this,e=this.root.adaptors,n=e.length;if(this.rewrap=!1,0!==n){var i=this.wrapper?"newWrapperValue"in this?this.newWrapperValue:this.wrapperValue:this.value,r=this.root.ractive,o=this.getKeypath();if(this.wrapper){
if(!(this.wrapperValue!==i&&(!this.wrapper.reset||!1===this.wrapper.reset(i))))return delete this.newWrapperValue,this.wrapperValue=i,void(this.value=this.wrapper.get());if(this.wrapper.teardown(),this.wrapper=null,void 0!==this.value){var s=this.parent.value||this.parent.createBranch(this.key);s[this.key]!==i&&(s[this.key]=i)}}var a;for(a=0;a<n;a+=1){var h=e[a];if(h.filter(i,o,r)){t.wrapper=h.wrap(r,i,o,qt(o)),t.wrapperValue=i,t.wrapper.__model=t,t.value=t.wrapper.get();break}}}},e.prototype.animate=function(t,e,n,i){var r=this;this.ticker&&this.ticker.stop();var o,s=new Xs(function(t){return o=t});return this.ticker=new Fa({duration:n.duration,easing:n.easing,step:function(t){var e=i(t);r.applyValue(e),n.step&&n.step(t,e)},complete:function(){r.applyValue(e),n.complete&&n.complete(e),r.ticker=null,o()}}),s.stop=this.ticker.stop,s},e.prototype.applyValue=function(t){if(!u(t,this.value)){if(this.registerChange(this.getKeypath(),t),this.parent.wrapper&&this.parent.wrapper.set)this.parent.wrapper.set(this.key,t),this.parent.value=this.parent.wrapper.get(),this.value=this.parent.value[this.key],this.wrapper&&(this.newWrapperValue=this.value),this.adapt();else if(this.wrapper)this.newWrapperValue=t,this.adapt();else{var e=this.parent.value||this.parent.createBranch(this.key);e[this.key]=t,this.value=t,this.adapt()}this.parent.clearUnresolveds(),this.clearUnresolveds(),h(t)?(this.length=t.length,this.isArray=!0):this.isArray=!1,this.links.forEach(St),this.children.forEach(Ct),this.deps.forEach(St),this.notifyUpstream(),this.parent.isArray&&("length"===this.key?this.parent.length=t:this.parent.joinKey("length").mark())}},e.prototype.createBranch=function(t){var e=l(t)?[]:{};return this.set(e),e},e.prototype.get=function(t,e){return this._link?this._link.get(t,e):(t&&_t(this),e&&e.virtual?this.getVirtual(!1):(t||e&&e.unwrap)&&this.wrapper?this.wrapperValue:this.value)},e.prototype.getKeypathModel=function(t){return this.keypathModel||(this.keypathModel=new wa(this)),this.keypathModel},e.prototype.joinKey=function(t,n){if(this._link)return!n||!1!=!n.lastLink||void 0!==t&&""!==t?this._link.joinKey(t):this;if(void 0===t||""===t)return this;if(!this.childByKey.hasOwnProperty(t)){var i=new e(this,t);this.children.push(i),this.childByKey[t]=i}return this.childByKey[t]._link?this.childByKey[t]._link:this.childByKey[t]},e.prototype.mark=function(){if(this._link)return this._link.mark();var t=this.retrieve();if(!u(t,this.value)){var e=this.value;this.value=t,(e!==t||this.rewrap)&&(this.wrapper&&(this.newWrapperValue=t),this.adapt()),h(t)?(this.length=t.length,this.isArray=!0):this.isArray=!1,this.children.forEach(Ct),this.links.forEach(jt),this.deps.forEach(St),this.clearUnresolveds()}},e.prototype.merge=function(t,e){var n=this.value,i=t;n===i&&(n=Zt(this)),e&&(n=n.map(e),i=i.map(e));var r=n.length,o={},s=0,a=n.map(function(t){var e,n=s;do{if(-1===(e=i.indexOf(t,n)))return-1;n=e+1}while(!0===o[e]&&n<r);return e===s&&(s+=1),o[e]=!0,e});this.parent.value[this.key]=t,this.shuffle(a)},e.prototype.retrieve=function(){return this.parent.value?this.parent.value[this.key]:void 0},e.prototype.set=function(t){this.ticker&&this.ticker.stop(),this.applyValue(t)},e.prototype.shuffle=function(t){var e=this;this.shuffling=!0;for(var n=t.length;n--;){var i=t[n];n!==i&&(n in e.childByKey&&e.childByKey[n].rebinding(~i?e.joinKey(i):void 0,e.childByKey[n],!0),!~i&&e.keyModels[n]?e.keyModels[n].rebinding(void 0,e.keyModels[n],!1):~i&&e.keyModels[n]&&(e.keyModels[i]||e.childByKey[i].getKeyModel(i),e.keyModels[n].rebinding(e.keyModels[i],e.keyModels[n],!1)))}var r=this.length!==this.value.length;for(this.links.forEach(function(e){return e.shuffle(t)}),Wt("early"),n=this.deps.length;n--;)e.deps[n].shuffle&&e.deps[n].shuffle(t);this.mark(),Wt("mark"),r&&this.notifyUpstream(),this.shuffling=!1},e.prototype.teardown=function(){this._link&&this._link.teardown(),this.children.forEach(Pt),this.wrapper&&this.wrapper.teardown(),this.keypathModel&&this.keypathModel.teardown()},e}(_a),Va=function(t){function e(){t.call(this,null,"@global"),this.value="undefined"!=typeof global?global:window,this.isRoot=!0,this.root=this,this.adaptors=[]}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getKeypath=function(){return"@global"},e.prototype.registerChange=function(){},e}(Pa),Ma=new Va,Ba=/^@[^\(]+\(([^\)]+)\)/,Ka=Array.prototype,Ia={},Ra=new Hs("update"),La=Xt("push").model,Da=Xt("pop").model,Wa=Xt("shift").model,Ua=Xt("unshift").model,za=Xt("sort").model,$a=Xt("splice").model,qa=Xt("reverse").model,Za=ms&&ms.querySelector,Ha=new Hs("insert"),Qa=function(t,e,n){var i=this;for(this.fragment=t,this.reference=W(e),this.callback=n,this.keys=U(e),this.resolved=!1,this.contexts=[];t;)t.context&&(t.context.addUnresolved(i.keys[0],i),i.contexts.push(t.context)),t=t.componentParent||t.parent};Qa.prototype.attemptResolution=function(){if(!this.resolved){var t=kt(this.fragment,this.reference);t&&(this.resolved=!0,this.callback(t))}},Qa.prototype.forceResolution=function(){if(!this.resolved){var t=this.fragment.findContext().joinAll(this.keys);this.callback(t),this.resolved=!0}},Qa.prototype.rebinding=function(t,e){var n=this;e&&e.removeUnresolved(this.keys[0],this),this.next=t,t&&ia.scheduleTask(function(){t===n.next&&(t.addUnresolved(n.keys[0],n),n.next=null)})},Qa.prototype.unbind=function(){var t=this;this.fragment&&j(this.fragment.unresolved,this),this.resolved||this.contexts.forEach(function(e){return e.removeUnresolved(t.keys[0],t)})};var Ga=function(t,e,n,i){var r=this;this.context=i.context||t,this.callback=n,this.ractive=t,e?this.resolved(e):(this.keypath=i.keypath,this.resolver=new Qa(t.fragment,i.keypath,function(t){r.resolved(t)})),!1!==i.init?(this.dirty=!0,this.dispatch()):this.oldValue=this.newValue,this.defer=i.defer,this.once=i.once,this.strict=i.strict,this.dirty=!1};Ga.prototype.cancel=function(){this.cancelled=!0,this.model?this.model.unregister(this):this.resolver.unbind()},Ga.prototype.dispatch=function(){this.cancelled||(this.callback.call(this.context,this.newValue,this.oldValue,this.keypath),this.oldValue=this.model?this.model.get():this.newValue,this.dirty=!1)},Ga.prototype.handleChange=function(){var t=this;if(!this.dirty){var e=this.model.get();if(u(e,this.oldValue))return;if(this.newValue=e,this.strict&&this.newValue===this.oldValue)return;ia.addObserver(this,this.defer),this.dirty=!0,this.once&&ia.scheduleTask(function(){return t.cancel()})}},Ga.prototype.rebinding=function(t,e){var n=this;if((t=Ut(this.keypath,t,e))===this.model)return!1;this.model&&this.model.unregister(this),t&&t.addShuffleTask(function(){return n.resolved(t)})},Ga.prototype.resolved=function(t){this.model=t,this.keypath=t.getKeypath(this.ractive),this.oldValue=void 0,this.newValue=t.get(),t.register(this)};var Ya=function(t,e,n,i,r){var o=this;this.context=r.context||t,this.ractive=t,this.baseModel=e,this.keys=n,this.callback=i;var s=n.join("\\.").replace(/\*/g,"(.+)"),a=e.getKeypath(t);this.pattern=new RegExp("^"+(a?a+"\\.":"")+s+"$"),this.oldValues={},this.newValues={},this.defer=r.defer,this.once=r.once,this.strict=r.strict,this.dirty=!1,this.changed=[],this.partial=!1,e.findMatches(this.keys).forEach(function(t){o.newValues[t.getKeypath(o.ractive)]=t.get()}),!1!==r.init?this.dispatch():this.oldValues=this.newValues,e.registerPatternObserver(this)};Ya.prototype.cancel=function(){this.baseModel.unregisterPatternObserver(this)},Ya.prototype.dispatch=function(){var t=this,e=this.newValues;if(this.newValues={},Object.keys(e).forEach(function(n){if(!t.newKeys||t.newKeys[n]){var i=e[n],r=t.oldValues[n];if(!(t.strict&&i===r||u(i,r))){var o=[i,r,n];if(n){var s=t.pattern.exec(n);s&&(o=o.concat(s.slice(1)))}t.callback.apply(t.context,o)}}}),this.partial)for(var n in e)this.oldValues[n]=e[n];else this.oldValues=e;this.newKeys=null,this.dirty=!1},Ya.prototype.notify=function(t){this.changed.push(t)},Ya.prototype.shuffle=function(t){var e=this;if(h(this.baseModel.value)){var n=this.baseModel.getKeypath(this.ractive),i=this.baseModel.value.length,r=this.keys.length>1?"."+this.keys.slice(1).join("."):"";this.newKeys={};for(var o=0;o<t.length;o++)-1!==t[o]&&t[o]!==o&&(e.newKeys[n+"."+o+r]=!0);for(var s=t.touchedFrom;s<i;s++)e.newKeys[n+"."+s+r]=!0}},Ya.prototype.handleChange=function(){var t=this;if(!this.dirty||this.changed.length){if(this.dirty||(this.newValues={}),this.changed.length){var e=0,n=this.baseModel.isRoot?this.changed.map(function(t){return t.map(D).join(".")}):this.changed.map(function(e){return t.baseModel.getKeypath(t.ractive)+"."+e.map(D).join(".")});if(this.baseModel.findMatches(this.keys).forEach(function(i){var r=i.getKeypath(t.ractive),o=function(t){return 0===t.indexOf(r)&&(t.length===r.length||"."===t[r.length])||0===r.indexOf(t)&&(t.length===r.length||"."===r[t.length])};n.filter(o).length&&(e++,t.newValues[r]=i.get())}),!e)return;this.partial=!0}else this.baseModel.findMatches(this.keys).forEach(function(e){var n=e.getKeypath(t.ractive);t.newValues[n]=e.get()}),this.partial=!1;ia.addObserver(this,this.defer),this.dirty=!0,this.changed.length=0,this.once&&this.cancel()}};var Ja=function(t,e,n,i){this.context=t,this.model=e,this.keypath=e.getKeypath(),this.callback=n,this.pending=null,e.register(this),!1!==i.init?(this.sliced=[],this.shuffle([]),this.handleChange()):this.sliced=this.slice()};Ja.prototype.handleChange=function(){this.pending?(this.callback(this.pending),this.pending=null):(this.shuffle(this.sliced.map($e)),this.handleChange())},Ja.prototype.shuffle=function(t){var e,n=this,i=this.slice(),r=[],o=[],s={};t.forEach(function(t,i){s[t]=!0,t!==i&&void 0===e&&(e=i),-1===t&&o.push(n.sliced[i])}),void 0===e&&(e=t.length);for(var a=i.length,h=0;h<a;h+=1)s[h]||r.push(i[h]);this.pending={inserted:r,deleted:o,start:e},this.sliced=i},Ja.prototype.slice=function(){var t=this.model.get();return h(t)?t.slice():[]};var Xa={init:!1,once:!0},th=Xt("pop").path,eh=Xt("push").path,nh="/* Ractive.js component styles */",ih=[],rh=!1,oh=null,sh=null;!ms||oh&&oh.parentNode||(oh=ms.createElement("style"),oh.type="text/css",ms.getElementsByTagName("head")[0].appendChild(oh),sh=!!oh.styleSheet);var ah,hh,uh=new Hs("render"),lh=new Hs("complete"),ch={extend:function(t,e,n){e.adapt=rn(e.adapt,S(n.adapt))},init:function(){}},ph=/\/\*(?:[\s\S]*?)\*\//g,fh=/url\(\s*(['"])(?:\\[\s\S]|(?!\1).)*\1\s*\)|url\((?:\\[\s\S]|[^)])*\)|(['"])(?:\\[\s\S]|(?!\2).)*\2/gi,dh=/\0(\d+)/g,mh=/(?:^|\}|\{)\s*([^\{\}\0]+)\s*(?=\{)/g,gh=/@keyframes\s+[^\{\}]+\s*\{(?:[^{}]+|\{[^{}]+})*}/gi,vh=/((?:(?:\[[^\]]+\])|(?:[^\s\+\>~:]))+)((?:::?[^\s\+\>\~\(:]+(?:\([^\)]+\))?)*\s*[\s\+\>\~]?)\s*/g,yh=/^(?:@|\d+%)/,bh=/\[data-ractive-css~="\{[a-z0-9-]+\}"]/g,wh={name:"css",extend:function(t,e,n){if(n.css){var i=cn(),r=n.noCssTransform?n.css:un(n.css,i);e.cssId=i,Je({id:i,styles:r})}},init:function(t,e,n){n.css&&y("\nThe css option is currently not supported on a per-instance basis and will be discarded. Instead, we recommend instantiating from a component definition with a css option.\n\nconst Component = Ractive.extend({\n\t...\n\tcss: '/* your css */',\n\t...\n});\n\nconst componentInstance = new Component({ ... })\n\t\t")}},kh={name:"data",extend:function(t,e,n){var i,r;if(n.data&&c(n.data))for(i in n.data)(r=n.data[i])&&"object"==typeof r&&(c(r)||h(r))&&y("Passing a `data` option with object and array properties to Ractive.extend() is discouraged, as mutating them is likely to cause bugs. Consider using a data function instead:\n\n  // this...\n  data: function () {\n    return {\n      myObject: {}\n    };\n  })\n\n  // instead of this:\n  data: {\n    myObject: {}\n  }");e.data=fn(e.data,n.data)},init:function(t,e,n){var i=fn(t.prototype.data,n.data);if("function"==typeof i&&(i=i.call(e)),i&&i.constructor===Object)for(var r in i)"function"==typeof i[r]&&(i[r]=$(i[r],e));return i||{}},reset:function(t){var e=this.init(t.constructor,t,t.viewmodel);return t.viewmodel.root.set(e),!0}},xh=4,Eh=/\$\{([^\}]+)\}/g,_h=Ns(null),Ah=/^\s+/;hh=function(t){this.name="ParseError",this.message=t;try{throw new Error(t)}catch(t){this.stack=t.stack}},hh.prototype=Error.prototype,ah=function(t,e){var n,i,r=this,o=0;for(this.str=t,this.options=e||{},this.pos=0,this.lines=this.str.split("\n"),this.lineEnds=this.lines.map(function(t){var e=o+t.length+1;return o=e,e},0),this.init&&this.init(t,e),n=[];r.pos<r.str.length&&(i=r.read());)n.push(i);this.leftover=this.remaining(),this.result=this.postProcess?this.postProcess(n,e):n},ah.prototype={read:function(t){var e,n,i,r,o=this;for(t||(t=this.converters),e=this.pos,i=t.length,n=0;n<i;n+=1)if(o.pos=e,r=t[n](o))return r;return null},getContextMessage:function(t,e){var n=this.getLinePos(t),i=n[0],r=n[1];if(-1===this.options.contextLines)return[i,r,e+" at line "+i+" character "+r];var o=this.lines[i-1],s="",a="";if(this.options.contextLines){var h=i-1-this.options.contextLines<0?0:i-1-this.options.contextLines;s=this.lines.slice(h,i-1-h).join("\n").replace(/\t/g,"  "),a=this.lines.slice(i,i+this.options.contextLines).join("\n").replace(/\t/g,"  "),s&&(s+="\n"),a&&(a="\n"+a)}var u=0,l=s+o.replace(/\t/g,function(t,e){return e<r&&(u+=1),"  "})+"\n"+new Array(r+u).join(" ")+"^----"+a;return[i,r,e+" at line "+i+" character "+r+":\n"+l]},getLinePos:function(t){for(var e,n=this,i=0,r=0;t>=n.lineEnds[i];)r=n.lineEnds[i],i+=1;return e=t-r,[i+1,e+1,t]},error:function(t){var e=this.getContextMessage(this.pos,t),n=e[0],i=e[1],r=e[2],o=new hh(r);throw o.line=n,o.character=i,o.shortMessage=t,o},matchString:function(t){if(this.str.substr(this.pos,t.length)===t)return this.pos+=t.length,t},matchPattern:function(t){var e;if(e=t.exec(this.remaining()))return this.pos+=e[0].length,e[1]||e[0]},allowWhitespace:function(){this.matchPattern(Ah)},remaining:function(){return this.str.substring(this.pos)},nextChar:function(){return this.str.charAt(this.pos)}},ah.extend=function(t){var e,n,i=this;e=function(t,e){ah.call(this,t,e)},e.prototype=Ns(i.prototype);for(n in t)Rs.call(t,n)&&(e.prototype[n]=t[n]);return e.extend=ah.extend,e};var Oh,Sh,Ch,jh=ah,Th=1,Fh=2,Nh=3,Ph=4,Vh=5,Mh=6,Bh=7,Kh=8,Ih=9,Rh=10,Lh=13,Dh=14,Wh=15,Uh=16,zh=17,$h=18,qh=19,Zh=20,Hh=21,Qh=22,Gh=23,Yh=24,Jh=25,Xh=26,tu=27,eu=30,nu=31,iu=32,ru=33,ou=34,su=35,au=36,hu=40,uu=50,lu=51,cu=52,pu=53,fu=54,du=60,mu=61,gu=70,vu=71,yu=72,bu=73,wu=/^[^\s=]+/,ku=/^\s+/,xu=/^(\/(?:[^\n\r\u2028\u2029\/\\[]|\\.|\[(?:[^\n\r\u2028\u2029\]\\]|\\.)*])+\/(?:([gimuy])(?![a-z]*\2))*(?![a-zA-Z_$0-9]))/,Eu=/[-\/\\^$*+?.()|[\]{}]/g,_u={},Au=/^(allowFullscreen|async|autofocus|autoplay|checked|compact|controls|declare|default|defaultChecked|defaultMuted|defaultSelected|defer|disabled|enabled|formNoValidate|hidden|indeterminate|inert|isMap|itemScope|loop|multiple|muted|noHref|noResize|noShade|noValidate|noWrap|open|pauseOnExit|readOnly|required|reversed|scoped|seamless|selected|sortable|translate|trueSpeed|typeMustMatch|visible)$/i,Ou=/^(?:area|base|br|col|command|doctype|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i,Su={quot:34,amp:38,apos:39,lt:60,gt:62,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,copy:169,ordf:170,laquo:171,not:172,shy:173,reg:174,macr:175,deg:176,plusmn:177,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,sup1:185,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,Agrave:192,Aacute:193,Acirc:194,Atilde:195,Auml:196,Aring:197,AElig:198,Ccedil:199,Egrave:200,Eacute:201,Ecirc:202,Euml:203,Igrave:204,Iacute:205,Icirc:206,Iuml:207,ETH:208,Ntilde:209,Ograve:210,Oacute:211,Ocirc:212,Otilde:213,Ouml:214,times:215,Oslash:216,Ugrave:217,Uacute:218,Ucirc:219,Uuml:220,Yacute:221,THORN:222,szlig:223,agrave:224,aacute:225,acirc:226,atilde:227,auml:228,aring:229,aelig:230,ccedil:231,egrave:232,eacute:233,ecirc:234,euml:235,igrave:236,iacute:237,icirc:238,iuml:239,eth:240,ntilde:241,ograve:242,oacute:243,ocirc:244,otilde:245,ouml:246,divide:247,oslash:248,ugrave:249,uacute:250,ucirc:251,uuml:252,yacute:253,thorn:254,yuml:255,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Cu=[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376],ju=new RegExp("&(#?(?:x[\\w\\d]+|\\d+|"+Object.keys(Su).join("|")+"));?","g"),Tu="function"==typeof String.fromCodePoint,Fu=Tu?String.fromCodePoint:String.fromCharCode,Nu=/</g,Pu=/>/g,Vu=/&/g,Mu=65533,Bu="Expected a JavaScript expression",Ku="Expected closing paren",Iu=/^(?:[+-]?)0*(?:(?:(?:[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/;Oh=/^(?=.)[^"'\\]+?(?:(?!.)|(?=["'\\]))/,Sh=/^\\(?:['"\\bfnrt]|0(?![0-9])|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|(?=.)[^ux0-9])/,Ch=/^\\(?:\r\n|[\u000A\u000D\u2028\u2029])/;var Ru,Lu,Du=jn('"'),Wu=jn("'"),Uu=/^[a-zA-Z_$][a-zA-Z_$0-9]*/,zu=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/,$u=/^(?:~\/|(?:\.\.\/)+|\.\/(?:\.\.\/)*|\.)/;Ru=/^(?:Array|console|Date|RegExp|decodeURIComponent|decodeURI|encodeURIComponent|encodeURI|isFinite|isNaN|parseFloat|parseInt|JSON|Math|NaN|undefined|null|Object|Number|String|Boolean)\b/,Lu=/^(?:break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|throw|try|typeof|var|void|while|with)$/;var qu,Zu,Hu=/^(?:[a-zA-Z$_0-9]|\\\.)+(?:(?:\.(?:[a-zA-Z$_0-9]|\\\.)+)|(?:\[[0-9]+\]))*/,Qu=/^[a-zA-Z_$][-\/a-zA-Z_$0-9]*/,Gu=/^@(?:keypath|rootpath|index|key|this|global)/,Yu=/^\s*\(/,Ju=/^\s*\.{3}/;Zu=function(t,e){return function(n){var i;return(i=e(n))?i:n.matchString(t)?(n.allowWhitespace(),i=zn(n),i||n.error(Bu),{s:t,o:i,t:ru}):null}},function(){var t,e,n,i,r;for(i="! ~ + - typeof".split(" "),r=Wn,t=0,e=i.length;t<e;t+=1)n=Zu(i[t],r),r=n;qu=r}();var Xu,tl,el=qu;tl=function(t,e){return function(n){var i,r,o;if(!(r=e(n)))return null;for(;;){if(i=n.pos,n.allowWhitespace(),!n.matchString(t))return n.pos=i,r;if("in"===t&&/[a-zA-Z_$0-9]/.test(n.remaining().charAt(0)))return n.pos=i,r;if(n.allowWhitespace(),!(o=e(n)))return n.pos=i,r;r={t:au,s:t,o:[r,o]}}}},function(){var t,e,n,i,r;for(i="* / % + - << >> >>> < <= > >= in instanceof == != === !== & ^ | && ||".split(" "),r=el,t=0,e=i.length;t<e;t+=1)n=tl(i[t],r),r=n;Xu=r}();var nl,il=Xu,rl={true:!0,false:!1,null:null,undefined:void 0},ol=new RegExp("^(?:"+Object.keys(rl).join("|")+")"),sl=/^(?:[+-]?)(?:(?:(?:0|[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/,al=/\$\{([^\}]+)\}/g,hl=/^\$\{([^\}]+)\}/,ul=/^\s*$/,ll=jh.extend({init:function(t,e){this.values=e.values,this.allowWhitespace()},postProcess:function(t){return 1===t.length&&ul.test(this.leftover)?{value:t[0].v}:null},converters:[function(t){if(!t.values)return null;var e=t.matchPattern(hl);return e&&t.values.hasOwnProperty(e)?{v:t.values[e]}:void 0},function(t){var e=t.matchPattern(ol);if(e)return{v:rl[e]}},function(t){var e=t.matchPattern(sl);if(e)return{v:+e}},function(t){var e=Tn(t),n=t.values;return e&&n?{v:e.v.replace(al,function(t,e){return e in n?n[e]:e})}:e},function(t){if(!t.matchString("{"))return null;var e={};if(t.allowWhitespace(),t.matchString("}"))return{v:e};for(var n;n=Zn(t);){if(e[n.key]=n.value,t.allowWhitespace(),t.matchString("}"))return{v:e};if(!t.matchString(","))return null}return null},function(t){if(!t.matchString("["))return null;var e=[];if(t.allowWhitespace(),t.matchString("]"))return{v:e};for(var n;n=t.read();){if(e.push(n.v),t.allowWhitespace(),t.matchString("]"))return{v:e};if(!t.matchString(","))return null;t.allowWhitespace()}return null}]}),cl=/^([a-zA-Z_$][a-zA-Z_$0-9]*)\(.*\)\s*$/,pl=/^\s*$/;nl=jh.extend({converters:[zn],spreadArgs:!0});var fl,dl=/^[^\s"'>\/=]+/,ml=/^on/,gl=/^on-([a-zA-Z\\*\\.$_][a-zA-Z\\*\\.$_0-9\-]+)$/,vl=/^(?:change|reset|teardown|update|construct|config|init|render|unrender|detach|insert)$/,yl=/^as-([a-z-A-Z][-a-zA-Z_0-9]*)$/,bl=/^([a-zA-Z](?:(?!-in-out)[-a-zA-Z_0-9])*)-(in|out|in-out)$/,wl={"intro-outro":{t:yu,v:"t0"},intro:{t:yu,v:"t1"},outro:{t:yu,v:"t2"},lazy:{t:bu,v:"l"},twoway:{t:bu,v:"t"},decorator:{t:vu}},kl=/^[^\s"'=<>\/`]+/,xl={t:Rh,exclude:!0},El=/^(?:[a-zA-Z$_0-9]|\\\.)+(?:(?:(?:[a-zA-Z$_0-9]|\\\.)+)|(?:\[[0-9]+\]))*/,_l=/^as/i,Al=/^yield\s*/,Ol=/^\s*else\s*/,Sl=/^\s*elseif\s+/,Cl={each:cu,if:uu,with:fu,unless:lu},jl=/^\s*:\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/,Tl=/^\s*,\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/,Fl=new RegExp("^("+Object.keys(Cl).join("|")+")\\b"),Nl="\x3c!--",Pl="--\x3e",Vl=/^[ \t\f\r\n]*\r?\n/,Ml=/\r?\n[ \t\f\r\n]*$/,Bl=/[ \t\f\r\n]+/g,Kl=/^(?:pre|script|style|textarea)$/i,Il=/^[ \t\f\r\n]+/,Rl=/[ \t\f\r\n]+$/,Ll=/^(?:\r\n|\r|\n)/,Dl=/(?:\r\n|\r|\n)$/,Wl=/^([a-zA-Z]{1,}:?[a-zA-Z0-9\-]*)\s*\>/,Ul=/^[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/,zl=/^[\s\n\/>]/,$l={exclude:!0};fl={li:["li"],dt:["dt","dd"],dd:["dt","dd"],p:"address article aside blockquote div dl fieldset footer form h1 h2 h3 h4 h5 h6 header hgroup hr main menu nav ol p pre section table ul".split(" "),rt:["rt","rp"],rp:["rt","rp"],optgroup:["optgroup"],option:["option","optgroup"],thead:["tbody","tfoot"],tbody:["tbody","tfoot"],tfoot:["tbody"],tr:["tr","tbody"],td:["td","th","tr"],th:["td","th","tr"]};var ql,Zl=/^<!--\s*/,Hl=/s*>\s*([a-zA-Z_$][-a-zA-Z_$0-9]*)\s*/,Ql=/\s*-->/,Gl=/^\s*#\s*partial\s+/,Yl=[ci,hi,bi,mi,di,pi],Jl=[ai],Xl=[hi,bi,di];Ii.computedStrings=function(t){if(!t)return[];Object.keys(t).forEach(function(e){var n=t[e];"string"==typeof n&&(t[e]=vn(n))})};var tc=[ii,wi,Ci,Ti],ec=[Fi,Ni];ql=jh.extend({init:function(t,e){var n=e.tripleDelimiters||["{{{","}}}"],i=e.staticDelimiters||["[[","]]"],r=e.staticTripleDelimiters||["[[[","]]]"];this.standardDelimiters=e.delimiters||["{{","}}"],this.tags=[{isStatic:!1,isTriple:!1,open:this.standardDelimiters[0],close:this.standardDelimiters[1],readers:Yl},{isStatic:!1,isTriple:!0,open:n[0],close:n[1],readers:Jl},{isStatic:!0,isTriple:!1,open:i[0],close:i[1],readers:Xl},{isStatic:!0,isTriple:!0,open:r[0],close:r[1],readers:Jl}],this.contextLines=e.contextLines||0,this.sortMustacheTags(),this.sectionDepth=0,this.elementStack=[],this.interpolate={script:!e.interpolate||!1!==e.interpolate.script,style:!e.interpolate||!1!==e.interpolate.style,textarea:!0},!0===e.sanitize&&(e.sanitize={elements:"applet base basefont body frame frameset head html isindex link meta noframes noscript object param script style title".split(" "),eventAttributes:!0}),this.stripComments=!1!==e.stripComments,this.preserveWhitespace=e.preserveWhitespace,this.sanitizeElements=e.sanitize&&e.sanitize.elements,this.sanitizeEventAttributes=e.sanitize&&e.sanitize.eventAttributes,this.includeLinePositions=e.includeLinePositions,this.textOnlyMode=e.textOnlyMode,this.csp=e.csp},postProcess:function(t){if(!t.length)return{t:[],v:xh};if(this.sectionDepth>0&&this.error("A section was left open"),Oi(t[0].t,this.stripComments,this.preserveWhitespace,!this.preserveWhitespace,!this.preserveWhitespace),!1!==this.csp){var e={};Vi(t[0].t,e),Object.keys(e).length&&(t[0].e=e)}return t[0]},converters:[Pi],sortMustacheTags:function(){this.tags.sort(function(t,e){return e.open.length-t.open.length})}});var nc=["delimiters","tripleDelimiters","staticDelimiters","staticTripleDelimiters","csp","interpolate","preserveWhitespace","sanitize","stripComments","contextLines"],ic="Either preparse or use a ractive runtime source that includes the parser. ",rc="Either use:\n\n\tRactive.parse.computedStrings( component.computed )\n\nat build time to pre-convert the strings to functions, or use functions instead of strings in computed properties.",oc={fromId:function(t,e){if(!ms){if(e&&e.noThrow)return;throw new Error("Cannot retrieve template #"+t+" as Ractive is not running in a browser.")}t&&(t=t.replace(/^#/,""));var n;if(!(n=ms.getElementById(t))){if(e&&e.noThrow)return;throw new Error("Could not find template element with id #"+t)}if("SCRIPT"!==n.tagName.toUpperCase()){if(e&&e.noThrow)return;throw new Error("Template element with id #"+t+", must be a <script> element")}return"textContent"in n?n.textContent:n.innerHTML},isParsed:function(t){return!("string"==typeof t)},getParseOptions:function(t){return t.defaults&&(t=t.defaults),nc.reduce(function(e,n){return e[n]=t[n],e},{})},parse:function(t,e){Ri(Ii,"template",ic);var n=Ii(t,e);return bn(n),n},parseFor:function(t,e){return this.parse(t,this.getParseOptions(e))}},sc={name:"template",extend:function(t,e,n){if("template"in n){var i=n.template;e.template="function"==typeof i?i:zi(i,e)}},init:function(t,e,n){var i="template"in n?n.template:t.prototype.template;if("function"==typeof(i=i||{v:xh,t:[]})){var r=i;i=Ui(e,r),e._config.template={fn:r,result:i}}i=zi(i,e),e.template=i.t,i.p&&Zi(e.partials,i.p)},reset:function(t){var e=Wi(t);if(e){var n=zi(e,t);return t.template=n.t,Zi(t.partials,n.p,!0),!0}}},ac=["adaptors","components","computed","decorators","easing","events","interpolators","partials","transitions"],hc=function(t,e){this.name=t,this.useDefaults=e};hc.prototype.extend=function(t,e,n){this.configure(this.useDefaults?t.defaults:t,this.useDefaults?e:e.constructor,n)},hc.prototype.init=function(){},hc.prototype.configure=function(t,e,n){var i=this.name,r=n[i],o=Ns(t[i]);for(var s in r)o[s]=r[s];e[i]=o},hc.prototype.reset=function(t){var e=t[this.name],n=!1;return Object.keys(e).forEach(function(t){var i=e[t];i._fn&&(i._fn.isOwner?e[t]=i._fn:delete e[t],n=!0)}),n};var uc=ac.map(function(t){return new hc(t,"computed"===t)}),lc={adapt:ch,css:wh,data:kh,template:sc},cc=Object.keys(ps),pc=er(cc.filter(function(t){return!lc[t]})),fc=er(cc.concat(uc.map(function(t){return t.name}))),dc=[].concat(cc.filter(function(t){return!uc[t]&&!lc[t]}),uc,lc.template,lc.css),mc={extend:function(t,e,n){return Xi("extend",t,e,n)},init:function(t,e,n){return Xi("init",t,e,n)},reset:function(t){return dc.filter(function(e){return e.reset&&e.reset(t)}).map(function(t){return t.name})},order:dc},gc=["template","partials","components","decorators","events"],vc=new Hs("complete"),yc=new Hs("reset"),bc=new Hs("render"),wc=new Hs("unrender"),kc=function(t){this.parentFragment=t.parentFragment,this.ractive=t.parentFragment.ractive,this.template=t.template,this.index=t.index,this.type=t.template.t,this.dirty=!1};kc.prototype.bubble=function(){this.dirty||(this.dirty=!0,this.parentFragment.bubble())},kc.prototype.destroyed=function(){this.fragment&&this.fragment.destroyed()},kc.prototype.find=function(){return null},kc.prototype.findAll=function(){},kc.prototype.findComponent=function(){return null},kc.prototype.findAllComponents=function(){},kc.prototype.findNextNode=function(){return this.parentFragment.findNextNode(this)},kc.prototype.shuffled=function(){this.fragment&&this.fragment.shuffled()},kc.prototype.valueOf=function(){return this.toString()};var xc=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){t&&_t(this);var e=this.parent.get();return e?e[this.key]:void 0},e.prototype.handleChange=function(){this.dirty=!0,this.links.forEach(jt),this.deps.forEach(St),this.children.forEach(St),this.clearUnresolveds()},e.prototype.joinKey=function(t){if(void 0===t||""===t)return this;if(!this.childByKey.hasOwnProperty(t)){var n=new e(this,t);this.children.push(n),this.childByKey[t]=n}return this.childByKey[t]},e}(Pa),Ec=function(t){function e(e,n){var i=this;t.call(this,e.ractive.viewmodel,null),this.fragment=e,this.template=n,this.isReadonly=!0,this.dirty=!0,this.fn=yn(n.s,n.r.length),this.resolvers=[],this.models=this.template.r.map(function(t,e){var n=Ht(i.fragment,t);return n||sr(i,t,e),n}),this.dependencies=[],this.shuffle=void 0,this.bubble()}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bubble=function(t){void 0===t&&(t=!0),this.registered&&delete this.root.expressions[this.keypath],this.keypath=void 0,t&&(this.dirty=!0,this.handleChange())},e.prototype.get=function(t){return t&&_t(this),this.dirty&&(this.dirty=!1,this.value=this.getValue(),this.wrapper&&(this.newWrapperValue=this.value),this.adapt()),t&&this.wrapper?this.wrapperValue:this.value},e.prototype.getKeypath=function(){var t=this;return this.template?(this.keypath||(this.keypath="@"+this.template.s.replace(/_(\d+)/g,function(e,n){if(n>=t.models.length)return e;var i=t.models[n];return i?i.getKeypath():"@undefined"}),this.root.expressions[this.keypath]=this,this.registered=!0),this.keypath):"@undefined"},e.prototype.getValue=function(){var t=this;xt();var e;try{var n=this.models.map(function(t){return t?t.get(!0):void 0});e=this.fn.apply(this.fragment.ractive,n)}catch(t){y("Failed to compute "+this.getKeypath()+": "+(t.message||t))}var i=Et();return this.dependencies.filter(function(t){return!~i.indexOf(t)}).forEach(function(e){e.unregister(t),j(t.dependencies,e)}),i.filter(function(e){return!~t.dependencies.indexOf(e)}).forEach(function(e){e.register(t),t.dependencies.push(e)}),e},e.prototype.handleChange=function(){this.dirty=!0,this.links.forEach(jt),this.deps.forEach(St),this.children.forEach(St),this.clearUnresolveds()},e.prototype.joinKey=function(t){if(void 0===t||""===t)return this;if(!this.childByKey.hasOwnProperty(t)){var e=new xc(this,t);this.children.push(e),this.childByKey[t]=e}return this.childByKey[t]},e.prototype.mark=function(){this.handleChange()},e.prototype.rebinding=function(t,e,n){var i=this.models.indexOf(e);~i&&(t=Ut(this.template.r[i],t,e))!==e&&(e.unregister(this),this.models.splice(i,1,t),t&&t.addShuffleRegister(this,"mark")),this.bubble(!n)},e.prototype.retrieve=function(){return this.get()},e.prototype.teardown=function(){var e=this;this.unbind(),this.fragment=void 0,this.dependencies&&this.dependencies.forEach(function(t){return t.unregister(e)}),t.prototype.teardown.call(this)},e.prototype.unreference=function(){t.prototype.unreference.call(this),this.deps.length||this.refs||this.teardown()},e.prototype.unregister=function(e){t.prototype.unregister.call(this,e),this.deps.length||this.refs||this.teardown()},e.prototype.unbind=function(){this.resolvers.forEach(Vt)},e}(Pa),_c=function(t){function e(e,n){t.call(this,e,n)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.applyValue=function(t){if(!u(t,this.value))for(var e=this.parent,n=[this.key];e;){if(e.base){var i=e.model.joinAll(n);i.applyValue(t);break}n.unshift(e.key),e=e.parent}},e.prototype.joinKey=function(t){if(void 0===t||""===t)return this;if(!this.childByKey.hasOwnProperty(t)){var n=new e(this,t);this.children.push(n),this.childByKey[t]=n}return this.childByKey[t]},e.prototype.retrieve=function(){var t=this.parent.get();return t&&t[this.key]},e}(Pa),Ac=function(t){
function e(e,n){var i=this;t.call(this,null,null),this.dirty=!0,this.root=e.ractive.viewmodel,this.template=n,this.resolvers=[],this.base=ar(e,n);var r;this.base||(r=e.resolve(n.r,function(t){i.base=t,i.bubble(),j(i.resolvers,r)}),this.resolvers.push(r));var o=this.intermediary={handleChange:function(){return i.handleChange()},rebinding:function(t,e){if(e===i.base)(t=Ut(n,t,e))!==i.base&&(i.base.unregister(o),i.base=t);else{var r=i.members.indexOf(e);~r&&(t=Ut(n.m[r].n,t,e))!==i.members[r]&&i.members.splice(r,1,t)}t!==e&&e.unregister(o),t&&t.addShuffleTask(function(){return t.register(o)}),i.bubble()}};this.members=n.m.map(function(t,n){if("string"==typeof t)return{get:function(){return t}};var r,s;return t.t===eu?(r=Ht(e,t.n),r?r.register(o):(s=e.resolve(t.n,function(t){i.members[n]=t,t.register(o),i.handleChange(),j(i.resolvers,s)}),i.resolvers.push(s)),r):(r=new Ec(e,t),r.register(o),r)}),this.isUnresolved=!0,this.bubble()}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bubble=function(){this.base&&(this.dirty||this.handleChange())},e.prototype.forceResolution=function(){this.resolvers.forEach(function(t){return t.forceResolution()}),this.dirty=!0,this.bubble()},e.prototype.get=function(t){var e=this;if(this.dirty){this.bubble();for(var n=this.members.length,i=!0;i&&n--;)e.members[n]||(i=!1);if(this.base&&i){var r=this.members.map(function(t){return D(String(t.get()))}),o=this.base.joinAll(r);o!==this.model&&(this.model&&(this.model.unregister(this),this.model.unregisterTwowayBinding(this)),this.model=o,this.parent=o.parent,this.model.register(this),this.model.registerTwowayBinding(this),this.keypathModel&&this.keypathModel.handleChange())}return this.value=this.model?this.model.get(t):void 0,this.dirty=!1,this.mark(),this.value}return this.model?this.model.get(t):void 0},e.prototype.getValue=function(){var t=this;this.value=this.model?this.model.get():void 0;for(var e=this.bindings.length;e--;){var n=t.bindings[e].getValue();if(n!==t.value)return n}var i=Dt(this.deps);return i?i.value:this.value},e.prototype.getKeypath=function(){return this.model?this.model.getKeypath():"@undefined"},e.prototype.handleChange=function(){this.dirty=!0,this.mark()},e.prototype.joinKey=function(t){if(void 0===t||""===t)return this;if(!this.childByKey.hasOwnProperty(t)){var e=new _c(this,t);this.children.push(e),this.childByKey[t]=e}return this.childByKey[t]},e.prototype.mark=function(){this.dirty&&this.deps.forEach(St),this.links.forEach(jt),this.children.forEach(Ct),this.clearUnresolveds()},e.prototype.retrieve=function(){return this.value},e.prototype.rebinding=function(){},e.prototype.set=function(t){if(!this.model)throw new Error("Unresolved reference expression. This should not happen!");this.model.set(t)},e.prototype.teardown=function(){var t=this;this.resolvers.forEach(Vt),this.model&&(this.model.unregister(this),this.model.unregisterTwowayBinding(this)),this.members&&this.members.forEach(function(e){return e&&e.unregister&&e.unregister(t)})},e.prototype.unreference=function(){t.prototype.unreference.call(this),this.deps.length||this.refs||this.teardown()},e.prototype.unregister=function(e){t.prototype.unregister.call(this,e),this.deps.length||this.refs||this.teardown()},e}(Pa),Oc=function(e){function n(t){e.call(this,t),this.fragment=null}return n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.bind=function(){hr(this),this.fragment=new Cf({owner:this,template:this.template.f}).bind()},n.prototype.detach=function(){return this.fragment?this.fragment.detach():t()},n.prototype.find=function(t){if(this.fragment)return this.fragment.find(t)},n.prototype.findAll=function(t,e){this.fragment&&this.fragment.findAll(t,e)},n.prototype.findComponent=function(t){if(this.fragment)return this.fragment.findComponent(t)},n.prototype.findAllComponents=function(t,e){this.fragment&&this.fragment.findAllComponents(t,e)},n.prototype.firstNode=function(t){return this.fragment&&this.fragment.firstNode(t)},n.prototype.rebinding=function(){var t=this;this.locked||(this.locked=!0,ia.scheduleTask(function(){t.locked=!1,hr(t)}))},n.prototype.render=function(t){this.rendered=!0,this.fragment&&this.fragment.render(t)},n.prototype.toString=function(t){return this.fragment?this.fragment.toString(t):""},n.prototype.unbind=function(){this.aliases={};for(var t in this.fragment.aliases)this.aliases[t].unreference();this.fragment&&this.fragment.unbind()},n.prototype.unrender=function(t){this.rendered&&this.fragment&&this.fragment.unrender(t),this.rendered=!1},n.prototype.update=function(){this.dirty&&(this.dirty=!1,this.fragment.update())},n}(kc),Sc=/\s+/,Cc=/\/\*(?:[\s\S]*?)\*\//g,jc=/url\(\s*(['"])(?:\\[\s\S]|(?!\1).)*\1\s*\)|url\((?:\\[\s\S]|[^)])*\)|(['"])(?:\\[\s\S]|(?!\1).)*\2/gi,Tc=/\0(\d+)/g,Fc=[void 0,"text","search","url","email","hidden","password","search","reset","submit"],Nc={"accept-charset":"acceptCharset",accesskey:"accessKey",bgcolor:"bgColor",class:"className",codebase:"codeBase",colspan:"colSpan",contenteditable:"contentEditable",datetime:"dateTime",dirname:"dirName",for:"htmlFor","http-equiv":"httpEquiv",ismap:"isMap",maxlength:"maxLength",novalidate:"noValidate",pubdate:"pubDate",readonly:"readOnly",rowspan:"rowSpan",tabindex:"tabIndex",usemap:"useMap"},Pc=!1,Vc=function(t){function e(e){t.call(this,e),this.name=e.template.n,this.namespace=null,this.owner=e.owner||e.parentFragment.owner||e.element||ur(e.parentFragment),this.element=e.element||(this.owner.attributeByName?this.owner:ur(e.parentFragment)),this.parentFragment=e.parentFragment,this.ractive=this.parentFragment.ractive,this.rendered=!1,this.updateDelegate=null,this.fragment=null,this.element.attributeByName[this.name]=this,h(e.template.f)?this.fragment=new Cf({owner:this,template:e.template.f}):(this.value=e.template.f,0===this.value&&(this.value="")),this.interpolator=this.fragment&&1===this.fragment.items.length&&this.fragment.items[0].type===Fh&&this.fragment.items[0],this.interpolator&&(this.interpolator.owner=this)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){this.fragment&&this.fragment.bind()},e.prototype.bubble=function(){this.dirty||(this.parentFragment.bubble(),this.element.bubble(),this.dirty=!0)},e.prototype.destroyed=function(){this.updateDelegate(!0)},e.prototype.getString=function(){Pc=!0;var t=this.fragment?this.fragment.toString():null!=this.value?""+this.value:"";return Pc=!1,t},e.prototype.getValue=function(){Pc=!0;var t=this.fragment?this.fragment.valueOf():!!Au.test(this.name)||this.value;return Pc=!1,t},e.prototype.render=function(){var t=this.element.node;if(this.node=t,t.namespaceURI&&t.namespaceURI!==Fs.html||(this.propertyName=Nc[this.name]||this.name,void 0!==t[this.propertyName]&&(this.useProperty=!0),(Au.test(this.name)||this.isTwoway)&&(this.isBoolean=!0),"value"===this.propertyName&&(t._ractive.value=this.value)),t.namespaceURI){var e=this.name.indexOf(":");this.namespace=-1!==e?jr(t,this.name.slice(0,e)):t.namespaceURI}this.rendered=!0,this.updateDelegate=pr(this),this.updateDelegate()},e.prototype.toString=function(){Pc=!0;var t=this.getValue();if("value"!==this.name||void 0===this.element.getAttribute("contenteditable")&&"select"!==this.element.name&&"textarea"!==this.element.name){if("name"===this.name&&"input"===this.element.name&&this.interpolator&&"radio"===this.element.getAttribute("type"))return'name="{{'+this.interpolator.model.getKeypath()+'}}"';if(this.owner!==this.element||"style"!==this.name&&"class"!==this.name&&!this.style&&!this.inlineClass){if(!(this.rendered||this.owner!==this.element||this.name.indexOf("style-")&&this.name.indexOf("class-")))return void(this.name.indexOf("style-")?this.inlineClass=this.name.substr(6):this.style=o(this.name.substr(6)));if(Au.test(this.name))return t?this.name:"";if(null==t)return"";var e=r(this.getString());return Pc=!1,e?this.name+'="'+e+'"':this.name}}},e.prototype.unbind=function(){this.fragment&&this.fragment.unbind()},e.prototype.unrender=function(){this.updateDelegate(!0),this.rendered=!1},e.prototype.update=function(){this.dirty&&(this.dirty=!1,this.fragment&&this.fragment.update(),this.rendered&&this.updateDelegate(),this.isTwoway&&!this.locked&&this.interpolator.twowayBinding.lastVal(!0,this.interpolator.model.get()))},e}(kc),Mc=function(t){function e(e){t.call(this,e),this.owner=e.owner||e.parentFragment.owner||ur(e.parentFragment),this.element=this.owner.attributeByName?this.owner:ur(e.parentFragment),this.flag="l"===e.template.v?"lazy":"twoway",this.element.type===Bh&&(h(e.template.f)&&(this.fragment=new Cf({owner:this,template:e.template.f})),this.interpolator=this.fragment&&1===this.fragment.items.length&&this.fragment.items[0].type===Fh&&this.fragment.items[0])}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){this.fragment&&this.fragment.bind(),Fr(this,this.getValue(),!0)},e.prototype.bubble=function(){this.dirty||(this.element.bubble(),this.dirty=!0)},e.prototype.getValue=function(){return this.fragment?this.fragment.valueOf():"value"in this?this.value:!("f"in this.template)||this.template.f},e.prototype.render=function(){Fr(this,this.getValue(),!0)},e.prototype.toString=function(){return""},e.prototype.unbind=function(){this.fragment&&this.fragment.unbind(),delete this.element[this.flag]},e.prototype.unrender=function(){this.element.rendered&&this.element.recreateTwowayBinding()},e.prototype.update=function(){this.dirty&&(this.fragment&&this.fragment.update(),Fr(this,this.getValue(),!0))},e}(kc),Bc=ms?ys("div"):null,Kc=!1,Ic=function(t){function e(e){t.call(this,e),this.attributes=[],this.owner=e.owner,this.fragment=new Cf({ractive:this.ractive,owner:this,template:this.template}),this.fragment.findNextNode=p,this.dirty=!1}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){this.fragment.bind()},e.prototype.bubble=function(){this.dirty||(this.dirty=!0,this.owner.bubble())},e.prototype.render=function(){this.node=this.owner.node,this.node&&(this.isSvg=this.node.namespaceURI===Ts),Kc=!0,this.rendered||this.fragment.render(),Kc=!1,this.rendered=!0,this.dirty=!0,this.update()},e.prototype.toString=function(){return this.fragment.toString()},e.prototype.unbind=function(){this.fragment.unbind()},e.prototype.unrender=function(){this.rendered=!1,this.fragment.unrender()},e.prototype.update=function(){var t,e,n=this;this.dirty&&(this.dirty=!1,Kc=!0,this.fragment.update(),Kc=!1,this.rendered&&this.node&&(t=this.fragment.toString(),e=Vr(t,this.isSvg),this.attributes.filter(function(t){return Mr(e,t)}).forEach(function(t){n.node.removeAttribute(t.name)}),e.forEach(function(t){n.node.setAttribute(t.name,t.value)}),this.attributes=e))},e}(kc),Rc=["pop","push","reverse","shift","sort","splice","unshift"],Lc=[];Rc.forEach(function(t){Ps(Lc,t,{value:function(){for(var e=this,n=[],i=arguments.length;i--;)n[i]=arguments[i];var r=Yt(this.length,t,n);this._ractive.wrappers.forEach(function(t){t.magic&&(t.magic.locked=!0)});var o=Array.prototype[t].apply(this,arguments);ia.start(),this._ractive.setting=!0;for(var s=this._ractive.wrappers.length;s--;)Br(e._ractive.wrappers[s],e,t,r);return ia.end(),this._ractive.setting=!1,this._ractive.wrappers.forEach(function(t){t.magic&&(t.magic.locked=!1)}),o},configurable:!0})});var Dc,Wc;!{}.__proto__?(Dc=function(t){for(var e=Rc.length;e--;){var n=Rc[e];Ps(t,n,{value:Lc[n],configurable:!0})}},Wc=function(t){for(var e=Rc.length;e--;)delete t[Rc[e]]}):(Dc=function(t){return t.__proto__=Lc},Wc=function(t){return t.__proto__=Array.prototype}),Dc.unpatch=Wc;var Uc=Dc,zc="Something went wrong in a rather interesting way",$c={filter:function(t){return h(t)&&(!t._ractive||!t._ractive.setting)},wrap:function(t,e,n){return new qc(t,e,n)}},qc=function(t,e){this.root=t,this.value=e,this.__model=null,e._ractive||(Ps(e,"_ractive",{value:{wrappers:[],instances:[],setting:!1},configurable:!0}),Uc(e)),e._ractive.instances[t._guid]||(e._ractive.instances[t._guid]=0,e._ractive.instances.push(t)),e._ractive.instances[t._guid]+=1,e._ractive.wrappers.push(this)};qc.prototype.get=function(){return this.value},qc.prototype.reset=function(t){return this.value===t},qc.prototype.teardown=function(){var t,e,n,i,r;if(t=this.value,e=t._ractive,n=e.wrappers,i=e.instances,e.setting)return!1;if(-1===(r=n.indexOf(this)))throw new Error(zc);if(n.splice(r,1),n.length){if(i[this.root._guid]-=1,!i[this.root._guid]){if(-1===(r=i.indexOf(this.root)))throw new Error(zc);i.splice(r,1)}}else delete t._ractive,Uc.unpatch(this.value)};var Zc;try{Object.defineProperty({},"test",{get:function(){},set:function(){}}),Zc={filter:function(t){return t&&"object"==typeof t},wrap:function(t,e,n){return new Qc(t,e,n)}}}catch(t){Zc=!1}var Hc=Zc,Qc=function(t,e,n){var i=this;this.ractive=t,this.value=e,this.keypath=n,this.originalDescriptors={},Object.keys(e).forEach(function(e){var r=Object.getOwnPropertyDescriptor(i.value,e);i.originalDescriptors[e]=r;var o=n?n+"."+D(e):D(e),s=Kr(r,t,o,i);Object.defineProperty(i.value,e,s)})};Qc.prototype.get=function(){return this.value},Qc.prototype.reset=function(t){return this.value===t},Qc.prototype.set=function(t,e){this.value[t]=e},Qc.prototype.teardown=function(){var t=this;Object.keys(this.value).forEach(function(e){var n=Object.getOwnPropertyDescriptor(t.value,e);n.set&&n.set.__magic&&(Ir(n),1===n.set.__magic.dependants.length&&Object.defineProperty(t.value,e,n.set.__magic.originalDescriptor))})};var Gc=function(t,e,n){this.value=e,this.magic=!0,this.magicWrapper=Hc.wrap(t,e,n),this.arrayWrapper=$c.wrap(t,e,n),this.arrayWrapper.magic=this.magicWrapper,Object.defineProperty(this,"__model",{get:function(){return this.arrayWrapper.__model},set:function(t){this.arrayWrapper.__model=t}})};Gc.prototype.get=function(){return this.value},Gc.prototype.teardown=function(){this.arrayWrapper.teardown(),this.magicWrapper.teardown()},Gc.prototype.reset=function(t){return this.arrayWrapper.reset(t)&&this.magicWrapper.reset(t)};var Yc={filter:function(t,e,n){return Hc.filter(t,e,n)&&$c.filter(t)},wrap:function(t,e,n){return new Gc(t,e,n)}},Jc=function(t){function e(e,n,i){t.call(this,null,null),this.root=this.parent=e,this.signature=n,this.key=i,this.isExpression=i&&"@"===i[0],this.isReadonly=!this.signature.setter,this.context=e.computationContext,this.dependencies=[],this.children=[],this.childByKey={},this.deps=[],this.dirty=!0,this.shuffle=void 0}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return t&&_t(this),this.dirty&&(this.dirty=!1,this.value=this.getValue(),this.wrapper&&(this.newWrapperValue=this.value),this.adapt()),t&&this.wrapper?this.wrapperValue:this.value},e.prototype.getValue=function(){xt();var t;try{t=this.signature.getter.call(this.context)}catch(t){if(y("Failed to compute "+this.getKeypath()+": "+(t.message||t)),vs){console.groupCollapsed&&console.groupCollapsed("%cshow details","color: rgb(82, 140, 224); font-weight: normal; text-decoration: underline;");var e=Rr(this.signature.getterString),n=this.signature.getterUseStack?"\n\n"+Lr(t.stack):"";console.error(t.name+": "+t.message+"\n\n"+e+n),console.groupCollapsed&&console.groupEnd()}}var i=Et();return this.setDependencies(i),"value"in this&&t!==this.value&&this.registerChange(this.getKeypath(),t),t},e.prototype.handleChange=function(){this.dirty=!0,this.links.forEach(jt),this.deps.forEach(St),this.children.forEach(St),this.clearUnresolveds()},e.prototype.joinKey=function(t){if(void 0===t||""===t)return this;if(!this.childByKey.hasOwnProperty(t)){var e=new xc(this,t);this.children.push(e),this.childByKey[t]=e}return this.childByKey[t]},e.prototype.mark=function(){this.handleChange()},e.prototype.rebinding=function(t,e){t!==e&&this.handleChange()},e.prototype.set=function(t){if(!this.signature.setter)throw new Error("Cannot set read-only computed value '"+this.key+"'");this.signature.setter(t),this.mark()},e.prototype.setDependencies=function(t){for(var e=this,n=this.dependencies.length;n--;){var i=e.dependencies[n];~t.indexOf(i)||i.unregister(e)}for(n=t.length;n--;){var r=t[n];~e.dependencies.indexOf(r)||r.register(e)}this.dependencies=t},e.prototype.teardown=function(){for(var e=this,n=this.dependencies.length;n--;)e.dependencies[n]&&e.dependencies[n].unregister(e);this.root.computations[this.key]===this&&delete this.root.computations[this.key],t.prototype.teardown.call(this)},e.prototype.unregister=function(e){t.prototype.unregister.call(this,e),this.isExpression&&0===this.deps.length&&this.teardown()},e}(Pa),Xc=function(t){function e(e){t.call(this,null,""),this.value=e,this.isRoot=!0,this.root=this,this.adaptors=[],this.ractive=e,this.changes={}}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getKeypath=function(){return"@this"},e}(Pa),tp=Object.prototype.hasOwnProperty,ep=function(t){function e(e){t.call(this,null,null),this.changes={},this.isRoot=!0,this.root=this,this.ractive=e.ractive,this.value=e.data,this.adaptors=e.adapt,this.adapt(),this.computationContext=e.ractive,this.computations={},this.expressions={}}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.applyChanges=function(){return this._changeHash={},this.flush(),this._changeHash},e.prototype.compute=function(t,e){var n=new Jc(this,e,t);return this.computations[D(t)]=n,n},e.prototype.createLink=function(t,e,n){for(var i=this,r=U(t),o=this;r.length;){var s=r.shift();o=i.childByKey[s]||i.joinKey(s)}return o.link(e,n)},e.prototype.get=function(t,e){var n=this;if(t&&_t(this),e&&!1===e.virtual)return this.value;for(var i=this.getVirtual(),r=Object.keys(this.computations),o=r.length;o--;){var s=n.computations[r[o]];s.isExpression||(i[r[o]]=s.get())}return i},e.prototype.getKeypath=function(){return""},e.prototype.getRactiveModel=function(){return this.ractiveModel||(this.ractiveModel=new Xc(this.ractive))},e.prototype.getValueChildren=function(){var e=t.prototype.getValueChildren.call(this,this.value);this.children.forEach(function(t){if(t._link){var n=e.indexOf(t);~n?e.splice(n,1,t._link):e.push(t._link)}});for(var n in this.computations)e.push(this.computations[n]);return e},e.prototype.handleChange=function(){this.deps.forEach(St)},e.prototype.has=function(t){var e=this.value,n=z(t);if(tp.call(e,n))return!0;if(t in this.computations||this.childByKey[n]&&this.childByKey[n]._link)return!0;if(t in this.expressions)return!0;for(var i=e.constructor;i!==Function&&i!==Array&&i!==Object;){if(tp.call(i.prototype,n))return!0;i=i.constructor}return!1},e.prototype.joinKey=function(e,n){return"@global"===e?Ma:"@this"===e?this.getRactiveModel():this.expressions.hasOwnProperty(e)?(y("Accessing expression keypaths ("+e.substr(1)+") from the instance is deprecated. You can used a getNodeInfo or event object to access keypaths with expression context."),this.expressions[e]):this.computations.hasOwnProperty(e)?this.computations[e]:t.prototype.joinKey.call(this,e,n)},e.prototype.map=function(t,e){this.joinKey(t).link(e)},e.prototype.rebinding=function(){},e.prototype.set=function(t){var e=this.wrapper;if(e){(!e.reset||!1===e.reset(t))&&(e.teardown(),this.wrapper=null,this.value=t,this.adapt())}else this.value=t,this.adapt();this.deps.forEach(St),this.children.forEach(Ct),this.clearUnresolveds()},e.prototype.retrieve=function(){return this.wrapper?this.wrapper.get():this.value},e.prototype.teardown=function(){t.prototype.teardown.call(this);for(var e in this.computations)this.computations[e].teardown()},e.prototype.update=function(){},e}(Pa),np=new Hs("construct"),ip=["adaptors","components","decorators","easing","events","interpolators","partials","transitions"],rp=0,op=function(t){this.hook=new Hs(t),this.inProcess={},this.queue={}};op.prototype.begin=function(t){this.inProcess[t._guid]=!0},op.prototype.end=function(t){var e=t.parent;e&&this.inProcess[e._guid]?Zr(this.queue,e).push(t):Hr(this,t),delete this.inProcess[t._guid]};var sp=new Hs("config"),ap=new op("init"),hp=function(t,e){-1!==t.indexOf("*")&&d('Only component proxy-events may contain "*" wildcards, <'+e.name+" on-"+t+'="..."/> is not valid'),this.name=t,this.owner=e,this.node=null,this.handler=null};hp.prototype.listen=function(t){var e=this.node=this.owner.node,n=this.name;"on"+n in e||v($s(n,"events")),e.addEventListener(n,this.handler=function(n){t.fire({node:e,original:n})},!1)},hp.prototype.unlisten=function(){this.handler&&this.node.removeEventListener(this.name,this.handler,!1)};var up=function(t,e){this.eventPlugin=t,this.owner=e,this.handler=null};up.prototype.listen=function(t){var e=this.owner.node;this.handler=this.eventPlugin(e,function(n){void 0===n&&(n={}),n.node=n.node||e,t.fire(n)})},up.prototype.unlisten=function(){this.handler.teardown()};var lp=function(t,e){this.ractive=t,this.name=e,this.handler=null};lp.prototype.listen=function(t){var e=this.ractive;this.handler=e.on(this.name,function(){var n;arguments.length&&arguments[0]&&arguments[0].node&&(n=Array.prototype.shift.call(arguments),n.component=e);var i=Array.prototype.slice.call(arguments);return t.fire(n,i),!1})},lp.prototype.unlisten=function(){this.handler.cancel()};var cp=/^(event|arguments)(\..+)?$/,pp=/^\$(\d+)(\..+)?$/,fp=function(t){var e=this;this.owner=t.owner||t.parentFragment.owner||ur(t.parentFragment),this.element=this.owner.attributeByName?this.owner:ur(t.parentFragment),this.template=t.template,this.parentFragment=t.parentFragment,this.ractive=t.parentFragment.ractive,this.events=[],this.element.type===Wh?this.template.n.split("-").forEach(function(t){e.events.push(new lp(e.element.instance,t))}):this.template.n.split("-").forEach(function(t){var n=w("events",e.ractive,t);e.events.push(n?new up(n,e.element):new hp(t,e.element))}),this.context=null,this.resolvers=null,this.models=null,this.action=null,this.args=null};fp.prototype.bind=function(){var t=this;this.context=this.parentFragment.findContext();var e=this.template.f;e.x?(this.fn=yn(e.x.s,e.x.r.length),this.resolvers=[],this.models=e.x.r.map(function(e,n){var i=cp.exec(e);if(i)return{special:i[1],keys:i[2]?U(i[2].substr(1)):[]};var r=pp.exec(e);if(r)return{special:"arguments",keys:[r[1]-1].concat(r[2]?U(r[2].substr(1)):[])};var o,s=Ht(t.parentFragment,e);return s?s.register(t):(o=t.parentFragment.resolve(e,function(e){t.models[n]=e,j(t.resolvers,o),e.register(t)}),t.resolvers.push(o)),s})):(this.action="string"==typeof e?e:"string"==typeof e.n?e.n:new Cf({owner:this,template:e.n}),this.args=e.a?"string"==typeof e.a?[e.a]:e.a:e.d?new Cf({owner:this,template:e.d}):[]),this.action&&"string"!=typeof this.action&&this.action.bind(),this.args&&e.d&&this.args.bind()},fp.prototype.bubble=function(){this.dirty||(this.dirty=!0,this.owner.bubble())},fp.prototype.destroyed=function(){this.events.forEach(function(t){return t.unlisten()})},fp.prototype.fire=function(t,e){if(void 0===e&&(e=[]),t&&!t.hasOwnProperty("_element")&&Be(t,this.owner),this.fn){var n=[];t&&e.unshift(t),this.models&&this.models.forEach(function(i){if(!i)return n.push(void 0);if(i.special){for(var r="event"===i.special?t:e,o=i.keys.slice();o.length;)r=r[o.shift()];return n.push(r)}if(i.wrapper)return n.push(i.wrapperValue);n.push(i.get())});var i=this.ractive,r=i.event;i.event=t;if(!1===this.fn.apply(i,n).pop()){var o=t?t.original:void 0;o?(o.preventDefault&&o.preventDefault(),o.stopPropagation&&o.stopPropagation()):b("handler '"+this.template.n+"' returned false, but there is no event available to cancel")}i.event=r}else{var s=this.action.toString(),a=this.template.f.d?this.args.getArgsList():this.args;e.length&&(a=a.concat(e)),t&&(t.name=s),mt(this.ractive,s,{event:t,args:a})}},fp.prototype.handleChange=function(){},fp.prototype.rebinding=function(t,e){var n=this;if(this.models){var i=this.models.indexOf(e);~i&&(this.models.splice(i,1,t),e.unregister(this),t&&t.addShuffleTask(function(){return t.register(n)}))}},fp.prototype.render=function(){var t=this;ia.scheduleTask(function(){return t.events.forEach(function(e){return e.listen(t)},!0)})},fp.prototype.toString=function(){return""},fp.prototype.unbind=function(){var t=this;this.template.f.x?(this.resolvers&&this.resolvers.forEach(Vt),this.resolvers=[],this.models&&this.models.forEach(function(e){e&&e.unregister&&e.unregister(t)}),this.models=null):(this.action&&this.action.unbind&&this.action.unbind(),this.args&&this.args.unbind&&this.args.unbind())},fp.prototype.unrender=function(){this.events.forEach(function(t){return t.unlisten()})},fp.prototype.update=function(){!this.method&&this.dirty&&(this.dirty=!1,this.action&&this.action.update&&this.action.update(),this.args&&this.args.update&&this.args.update())};var dp=new Hs("teardown"),mp=function(t){function e(e,n){var i=this;t.call(this,e),this.type=Wh;var r=Ns(n.prototype);this.instance=r,this.name=e.template.e,this.parentFragment=e.parentFragment,this.liveQueries=[],r.el&&y("The <"+this.name+"> component has a default 'el' property; it has been disregarded");var o=e.template.p||{};"content"in o||(o.content=e.template.f||[]),this._partials=o,this.yielders={};for(var s,a=e.parentFragment;a;){if(a.owner.type===Uh){s=a.owner.container;break}a=a.parent}r.parent=this.parentFragment.ractive,r.container=s||null,r.root=r.parent.root,r.component=this,Wr(this.instance,{partials:o}),r._inlinePartials=o,this.attributeByName={},this.attributes=[];var h=[];(this.template.m||[]).forEach(function(t){switch(t.t){case Lh:case gu:case yu:i.attributes.push(Ro({owner:i,parentFragment:i.parentFragment,template:t}));break;case bu:case vu:break;default:h.push(t)}}),this.attributes.push(new Ic({owner:this,parentFragment:this.parentFragment,template:h})),this.eventHandlers=[],this.template.v&&this.setupEvents()}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){this.attributes.forEach(At),Qr(this.instance,{partials:this._partials},{cssIds:this.parentFragment.cssIds}),this.eventHandlers.forEach(At),this.bound=!0},e.prototype.bubble=function(){this.dirty||(this.dirty=!0,this.parentFragment.bubble())},e.prototype.checkYielders=function(){var t=this;Object.keys(this.yielders).forEach(function(e){if(t.yielders[e].length>1)throw ia.end(),new Error("A component template can only have one {{yield"+(e?" "+e:"")+"}} declaration at a time")})},e.prototype.destroyed=function(){this.instance.fragment&&this.instance.fragment.destroyed()},e.prototype.detach=function(){return this.instance.fragment.detach()},e.prototype.find=function(t){return this.instance.fragment.find(t)},e.prototype.findAll=function(t,e){this.instance.fragment.findAll(t,e)},e.prototype.findComponent=function(t){return t&&this.name!==t?this.instance.fragment?this.instance.fragment.findComponent(t):void 0:this.instance},e.prototype.findAllComponents=function(t,e){e.test(this)&&(e.add(this.instance),e.live&&this.liveQueries.push(e)),this.instance.fragment.findAllComponents(t,e)},e.prototype.firstNode=function(t){return this.instance.fragment.firstNode(t)},e.prototype.render=function(t,e){en(this.instance,t,null,e),this.checkYielders(),this.attributes.forEach(Nt),this.eventHandlers.forEach(Nt),Gr(this),this.rendered=!0},e.prototype.setupEvents=function(){var t=this,e=this.eventHandlers;Object.keys(this.template.v).forEach(function(n){var i=n.split("-"),r=t.template.v[n];i.forEach(function(n){var i=new lp(t.instance,n);e.push(new fp(t,i,r))})})},e.prototype.shuffled=function(){this.liveQueries.forEach(Jr),t.prototype.shuffled.call(this)},e.prototype.toString=function(){return this.instance.toHTML()},e.prototype.unbind=function(){this.bound=!1,this.attributes.forEach(Vt);var t=this.instance;t.viewmodel.teardown(),t.fragment.unbind(),t._observers.forEach(Ot),Yr(this),t.el&&t.el.__ractive_instances__&&j(t.el.__ractive_instances__,t),dp.fire(t)},e.prototype.unrender=function(t){var e=this;this.rendered=!1,this.shouldDestroy=t,this.instance.unrender(),this.attributes.forEach(Mt),this.eventHandlers.forEach(Mt),this.liveQueries.forEach(function(t){return t.remove(e.instance)})},e.prototype.update=function(){this.dirty=!1,this.instance.fragment.update(),this.checkYielders(),this.attributes.forEach(Kt),this.eventHandlers.forEach(Kt)},e}(kc),gp={update:p,teardown:p},vp=function(t){this.owner=t.owner||t.parentFragment.owner||ur(t.parentFragment),this.element=this.owner.attributeByName?this.owner:ur(t.parentFragment),this.parentFragment=this.owner.parentFragment,this.ractive=this.owner.ractive;var e=this.template=t.template;this.dynamicName="object"==typeof e.f.n,this.dynamicArgs=!!e.f.d,this.dynamicName?this.nameFragment=new Cf({owner:this,template:e.f.n}):this.name=e.f.n||e.f,this.dynamicArgs?this.argsFragment=new Cf({owner:this,template:e.f.d}):e.f.a&&e.f.a.s?this.args=[]:this.args=e.f.a||[],this.node=null,this.intermediary=null,this.element.decorators.push(this)};vp.prototype.bind=function(){var t=this;this.dynamicName&&(this.nameFragment.bind(),this.name=this.nameFragment.toString()),this.dynamicArgs&&this.argsFragment.bind(),this.template.f.a&&this.template.f.a.s&&(this.resolvers=[],this.models=this.template.f.a.r.map(function(e,n){var i,r=Ht(t.parentFragment,e);return r?r.register(t):(i=t.parentFragment.resolve(e,function(e){t.models[n]=e,j(t.resolvers,i),e.register(t)}),t.resolvers.push(i)),r}),this.argsFn=yn(this.template.f.a.s,this.template.f.a.r.length))},vp.prototype.bubble=function(){this.dirty||(this.dirty=!0,this.owner.bubble())},vp.prototype.destroyed=function(){this.intermediary&&this.intermediary.teardown(),this.shouldDestroy=!0},vp.prototype.handleChange=function(){this.bubble()},vp.prototype.rebinding=function(t,e,n){var i=this.models.indexOf(e);~i&&(t=Ut(this.template.f.a.r[i],t,e))!==e&&(e.unregister(this),this.models.splice(i,1,t),t&&t.addShuffleRegister(this,"mark"),n||this.bubble())},vp.prototype.render=function(){var t=this;ia.scheduleTask(function(){var e=w("decorators",t.ractive,t.name);if(!e)return v($s(t.name,"decorator")),void(t.intermediary=gp);t.node=t.element.node;var n;if(t.argsFn?(n=t.models.map(function(t){if(t)return t.get()}),n=t.argsFn.apply(t.ractive,n)):n=t.dynamicArgs?t.argsFragment.getArgsList():t.args,t.intermediary=e.apply(t.ractive,[t.node].concat(n)),!t.intermediary||!t.intermediary.teardown)throw new Error("The '"+t.name+"' decorator must return an object with a teardown method");t.shouldDestroy&&t.destroyed()},!0),this.rendered=!0},vp.prototype.toString=function(){return""},vp.prototype.unbind=function(){var t=this;this.dynamicName&&this.nameFragment.unbind(),this.dynamicArgs&&this.argsFragment.unbind(),this.resolvers&&this.resolvers.forEach(Vt),this.models&&this.models.forEach(function(e){e&&e.unregister(t)})},vp.prototype.unrender=function(t){t&&!this.element.rendered||!this.intermediary||this.intermediary.teardown(),this.rendered=!1},vp.prototype.update=function(){if(this.dirty){this.dirty=!1;var t=!1;if(this.dynamicName&&this.nameFragment.dirty){var e=this.nameFragment.toString();t=e!==this.name,this.name=e}if(this.intermediary)if(t||!this.intermediary.update)this.unrender(),this.render();else if(this.dynamicArgs){if(this.argsFragment.dirty){var n=this.argsFragment.getArgsList();this.intermediary.update.apply(this.ractive,n)}}else if(this.argsFn){var i=this.models.map(function(t){if(t)return t.get()});this.intermediary.update.apply(this.ractive,this.argsFn.apply(this.ractive,i))}else this.intermediary.update.apply(this.ractive,this.args);this.dynamicName&&this.nameFragment.dirty&&this.nameFragment.update(),this.dynamicArgs&&this.argsFragment.dirty&&this.argsFragment.update()}};var yp=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){},e.prototype.render=function(){},e.prototype.teardown=function(){},e.prototype.toString=function(){return"<!DOCTYPE"+this.template.a+">"},e.prototype.unbind=function(){},e.prototype.unrender=function(){},e.prototype.update=function(){},e
}(kc),bp=function(t,e){void 0===e&&(e="value"),this.element=t,this.ractive=t.ractive,this.attribute=t.attributeByName[e];var n=this.attribute.interpolator;n.twowayBinding=this;var i=n.model;if(i){if(i.isUnresolved)i.forceResolution(),to("expression",this.ractive);else if(i.isReadonly){var r=i.getKeypath().replace(/^@/,"");return b("Cannot use two-way binding on <"+t.name+"> element: "+r+" is read-only. To suppress this warning use <"+t.name+" twoway='false'...>",{ractive:this.ractive}),!1}}else n.resolver.forceResolution(),i=n.model,to("'"+n.template.r+"' reference",this.ractive);this.attribute.isTwoway=!0,this.model=i;var o=i.get();this.wasUndefined=void 0===o,void 0===o&&this.getInitialValue&&(o=this.getInitialValue(),i.set(o)),this.lastVal(!0,o);var s=ur(this.element,!1,"form");s&&(this.resetValue=o,s.formBindings.push(this))};bp.prototype.bind=function(){this.model.registerTwowayBinding(this)},bp.prototype.handleChange=function(){var t=this,e=this.getValue();this.lastVal()!==e&&(ia.start(this.root),this.attribute.locked=!0,this.model.set(e),this.lastVal(!0,e),this.model.get()!==e?this.attribute.locked=!1:ia.scheduleTask(function(){return t.attribute.locked=!1}),ia.end())},bp.prototype.lastVal=function(t,e){if(!t)return this.lastValue;this.lastValue=e},bp.prototype.rebinding=function(t,e){var n=this;this.model&&this.model===e&&e.unregisterTwowayBinding(this),t&&(this.model=t,ia.scheduleTask(function(){return t.registerTwowayBinding(n)}))},bp.prototype.render=function(){this.node=this.element.node,this.node._ractive.binding=this,this.rendered=!0},bp.prototype.setFromNode=function(t){this.model.set(t.value)},bp.prototype.unbind=function(){this.model.unregisterTwowayBinding(this)},bp.prototype.unrender=function(){};var wp=function(t){function e(e){t.call(this,e,"checked")}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.render=function(){t.prototype.render.call(this),this.node.addEventListener("change",eo,!1),this.node.attachEvent&&this.node.addEventListener("click",eo,!1)},e.prototype.unrender=function(){this.node.removeEventListener("change",eo,!1),this.node.removeEventListener("click",eo,!1)},e.prototype.getInitialValue=function(){return!!this.element.getAttribute("checked")},e.prototype.getValue=function(){return this.node.checked},e.prototype.setFromNode=function(t){this.model.set(t.checked)},e}(bp),kp=function(t,e,n){var i=this;this.model=e,this.hash=t,this.getValue=function(){return i.value=n.call(i),i.value},this.bindings=[]};kp.prototype.add=function(t){this.bindings.push(t)},kp.prototype.bind=function(){this.value=this.model.get(),this.model.registerTwowayBinding(this),this.bound=!0},kp.prototype.remove=function(t){j(this.bindings,t),this.bindings.length||this.unbind()},kp.prototype.unbind=function(){this.model.unregisterTwowayBinding(this),this.bound=!1,delete this.model[this.hash]},kp.prototype.rebinding=bp.prototype.rebinding;var xp=[].push,Ep=function(t){function e(e){if(t.call(this,e,"name"),this.checkboxName=!0,this.group=no("checkboxes",this.model,io),this.group.add(this),this.noInitialValue&&(this.group.noInitialValue=!0),this.group.noInitialValue&&this.element.getAttribute("checked")){var n=this.model.get(),i=this.element.getAttribute("value");A(n,i)||xp.call(n,i)}}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){this.group.bound||this.group.bind()},e.prototype.changed=function(){var t=!!this.isChecked;return this.isChecked=this.node.checked,this.isChecked===t},e.prototype.getInitialValue=function(){return this.noInitialValue=!0,[]},e.prototype.getValue=function(){return this.group.value},e.prototype.handleChange=function(){this.isChecked=this.element.node.checked,this.group.value=this.model.get();var e=this.element.getAttribute("value");this.isChecked&&!A(this.group.value,e)?this.group.value.push(e):!this.isChecked&&A(this.group.value,e)&&j(this.group.value,e),this.lastValue=null,t.prototype.handleChange.call(this)},e.prototype.render=function(){t.prototype.render.call(this);var e=this.node,n=this.model.get(),i=this.element.getAttribute("value");h(n)?this.isChecked=A(n,i):this.isChecked=n==i,e.name="{{"+this.model.getKeypath()+"}}",e.checked=this.isChecked,e.addEventListener("change",eo,!1),e.attachEvent&&e.addEventListener("click",eo,!1)},e.prototype.setFromNode=function(t){if(this.group.bindings.forEach(function(t){return t.wasUndefined=!0}),t.checked){var e=this.group.getValue();e.push(this.element.getAttribute("value")),this.group.model.set(e)}},e.prototype.unbind=function(){this.group.remove(this)},e.prototype.unrender=function(){var t=this.element.node;t.removeEventListener("change",eo,!1),t.removeEventListener("click",eo,!1)},e}(bp),_p=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getInitialValue=function(){return this.element.fragment?this.element.fragment.toString():""},e.prototype.getValue=function(){return this.element.node.innerHTML},e.prototype.render=function(){t.prototype.render.call(this);var e=this.node;e.addEventListener("change",eo,!1),e.addEventListener("blur",eo,!1),this.ractive.lazy||(e.addEventListener("input",eo,!1),e.attachEvent&&e.addEventListener("keyup",eo,!1))},e.prototype.setFromNode=function(t){this.model.set(t.innerHTML)},e.prototype.unrender=function(){var t=this.node;t.removeEventListener("blur",eo,!1),t.removeEventListener("change",eo,!1),t.removeEventListener("input",eo,!1),t.removeEventListener("keyup",eo,!1)},e}(bp),Ap=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getInitialValue=function(){return""},e.prototype.getValue=function(){return this.node.value},e.prototype.render=function(){t.prototype.render.call(this);var e=this.ractive.lazy,n=!1;"lazy"in this.element&&(e=this.element.lazy),l(e)&&(n=+e,e=!1),this.handler=n?oo(n):eo;var i=this.node;i.addEventListener("change",eo,!1),e||(i.addEventListener("input",this.handler,!1),i.attachEvent&&i.addEventListener("keyup",this.handler,!1)),i.addEventListener("blur",ro,!1)},e.prototype.unrender=function(){var t=this.element.node;this.rendered=!1,t.removeEventListener("change",eo,!1),t.removeEventListener("input",this.handler,!1),t.removeEventListener("keyup",this.handler,!1),t.removeEventListener("blur",ro,!1)},e}(bp),Op=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getInitialValue=function(){},e.prototype.getValue=function(){return this.node.files},e.prototype.render=function(){this.element.lazy=!1,t.prototype.render.call(this)},e.prototype.setFromNode=function(t){this.model.set(t.files)},e}(Ap),Sp=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.forceUpdate=function(){var t=this,e=this.getValue();void 0!==e&&(this.attribute.locked=!0,ia.scheduleTask(function(){return t.attribute.locked=!1}),this.model.set(e))},e.prototype.getInitialValue=function(){return this.element.options.filter(function(t){return t.getAttribute("selected")}).map(function(t){return t.getAttribute("value")})},e.prototype.getValue=function(){for(var t=this.element.node.options,e=t.length,n=[],i=0;i<e;i+=1){var r=t[i];if(r.selected){var o=r._ractive?r._ractive.value:r.value;n.push(o)}}return n},e.prototype.handleChange=function(){var e=this.attribute,n=e.getValue(),i=this.getValue();return void 0!==n&&O(i,n)||t.prototype.handleChange.call(this),this},e.prototype.render=function(){t.prototype.render.call(this),this.node.addEventListener("change",eo,!1),void 0===this.model.get()&&this.handleChange()},e.prototype.setFromNode=function(t){for(var e=so(t),n=e.length,i=new Array(n);n--;){var r=e[n];i[n]=r._ractive?r._ractive.value:r.value}this.model.set(i)},e.prototype.setValue=function(){throw new Error("TODO not implemented yet")},e.prototype.unrender=function(){this.node.removeEventListener("change",eo,!1)},e.prototype.updateModel=function(){void 0!==this.attribute.value&&this.attribute.value.length||this.keypath.set(this.initialValue)},e}(bp),Cp=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getInitialValue=function(){},e.prototype.getValue=function(){var t=parseFloat(this.node.value);return isNaN(t)?void 0:t},e.prototype.setFromNode=function(t){var e=parseFloat(t.value);isNaN(e)||this.model.set(e)},e}(Ap),jp={},Tp=function(t){function e(e){t.call(this,e,"checked"),this.siblings=ao(this.ractive._guid+this.element.getAttribute("name")),this.siblings.push(this)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getValue=function(){return this.node.checked},e.prototype.handleChange=function(){ia.start(this.root),this.siblings.forEach(function(t){t.model.set(t.getValue())}),ia.end()},e.prototype.render=function(){t.prototype.render.call(this),this.node.addEventListener("change",eo,!1),this.node.attachEvent&&this.node.addEventListener("click",eo,!1)},e.prototype.setFromNode=function(t){this.model.set(t.checked)},e.prototype.unbind=function(){j(this.siblings,this)},e.prototype.unrender=function(){this.node.removeEventListener("change",eo,!1),this.node.removeEventListener("click",eo,!1)},e}(bp),Fp=function(t){function e(e){t.call(this,e,"name"),this.group=no("radioname",this.model,ho),this.group.add(this),e.checked&&(this.group.value=this.getValue())}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){var t=this;this.group.bound||this.group.bind(),this.nameAttributeBinding={handleChange:function(){return t.node.name="{{"+t.model.getKeypath()+"}}"},rebinding:p},this.model.getKeypathModel().register(this.nameAttributeBinding)},e.prototype.getInitialValue=function(){if(this.element.getAttribute("checked"))return this.element.getAttribute("value")},e.prototype.getValue=function(){return this.element.getAttribute("value")},e.prototype.handleChange=function(){this.node.checked&&(this.group.value=this.getValue(),t.prototype.handleChange.call(this))},e.prototype.lastVal=function(t,e){if(this.group)return t?void(this.group.lastValue=e):this.group.lastValue},e.prototype.render=function(){t.prototype.render.call(this);var e=this.node;e.name="{{"+this.model.getKeypath()+"}}",e.checked=this.model.get()==this.element.getAttribute("value"),e.addEventListener("change",eo,!1),e.attachEvent&&e.addEventListener("click",eo,!1)},e.prototype.setFromNode=function(t){t.checked&&this.group.model.set(this.element.getAttribute("value"))},e.prototype.unbind=function(){this.group.remove(this),this.model.getKeypathModel().unregister(this.nameAttributeBinding)},e.prototype.unrender=function(){var t=this.node;t.removeEventListener("change",eo,!1),t.removeEventListener("click",eo,!1)},e}(bp),Np=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.forceUpdate=function(){var t=this,e=this.getValue();void 0!==e&&(this.attribute.locked=!0,ia.scheduleTask(function(){return t.attribute.locked=!1}),this.model.set(e))},e.prototype.getInitialValue=function(){if(void 0===this.element.getAttribute("value")){var t=this.element.options,e=t.length;if(e){for(var n,i,r=e;r--;){var o=t[r];if(o.getAttribute("selected")){o.getAttribute("disabled")||(n=o.getAttribute("value")),i=!0;break}}if(!i)for(;++r<e;)if(!t[r].getAttribute("disabled")){n=t[r].getAttribute("value");break}return void 0!==n&&(this.element.attributeByName.value.value=n),n}}},e.prototype.getValue=function(){var t,e=this.node.options,n=e.length;for(t=0;t<n;t+=1){var i=e[t];if(e[t].selected&&!e[t].disabled)return i._ractive?i._ractive.value:i.value}},e.prototype.render=function(){t.prototype.render.call(this),this.node.addEventListener("change",eo,!1)},e.prototype.setFromNode=function(t){var e=so(t)[0];this.model.set(e._ractive?e._ractive.value:e.value)},e.prototype.setValue=function(t){this.model.set(t)},e.prototype.unrender=function(){this.node.removeEventListener("change",eo,!1)},e}(bp),Pp=/;\s*$/,Vp=function(t){function e(e){var n=this;if(t.call(this,e),this.liveQueries=[],this.name=e.template.e.toLowerCase(),this.isVoid=Ou.test(this.name),this.parent=ur(this.parentFragment,!1),this.parent&&"option"===this.parent.name)throw new Error("An <option> element cannot contain other elements (encountered <"+this.name+">)");this.decorators=[],this.attributeByName={},this.attributes=[];var i=[];(this.template.m||[]).forEach(function(t){switch(t.t){case Lh:case bu:case vu:case gu:case yu:n.attributes.push(Ro({owner:n,parentFragment:n.parentFragment,template:t}));break;default:i.push(t)}}),i.length&&this.attributes.push(new Ic({owner:this,parentFragment:this.parentFragment,template:i}));for(var r=this.attributes.length;r--;){var o=n.attributes[r];"type"===o.name?n.attributes.unshift(n.attributes.splice(r,1)[0]):"max"===o.name?n.attributes.unshift(n.attributes.splice(r,1)[0]):"min"===o.name?n.attributes.unshift(n.attributes.splice(r,1)[0]):"class"===o.name?n.attributes.unshift(n.attributes.splice(r,1)[0]):"value"===o.name&&n.attributes.push(n.attributes.splice(r,1)[0])}e.template.f&&!e.deferContent&&(this.fragment=new Cf({template:e.template.f,owner:this,cssIds:null})),this.binding=null}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){this.attributes.binding=!0,this.attributes.forEach(At),this.attributes.binding=!1,this.fragment&&this.fragment.bind(),this.binding||this.recreateTwowayBinding()},e.prototype.createTwowayBinding=function(){if(!("twoway"in this?this.twoway:this.ractive.twoway))return null;var t=lo(this);if(!t)return null;var e=new t(this);return e&&e.model?e:null},e.prototype.destroyed=function(){this.attributes.forEach(function(t){return t.destroyed()}),this.fragment&&this.fragment.destroyed()},e.prototype.detach=function(){return this.rendered||this.destroyed(),n(this.node)},e.prototype.find=function(t){return this.node&&bs(this.node,t)?this.node:this.fragment?this.fragment.find(t):void 0},e.prototype.findAll=function(t,e){e.test(this.node)&&(e.add(this.node),e.live&&this.liveQueries.push(e)),this.fragment&&this.fragment.findAll(t,e)},e.prototype.findComponent=function(t){if(this.fragment)return this.fragment.findComponent(t)},e.prototype.findAllComponents=function(t,e){this.fragment&&this.fragment.findAllComponents(t,e)},e.prototype.findNextNode=function(){return null},e.prototype.firstNode=function(){return this.node},e.prototype.getAttribute=function(t){var e=this.attributeByName[t];return e?e.getValue():void 0},e.prototype.recreateTwowayBinding=function(){this.binding&&(this.binding.unbind(),this.binding.unrender()),(this.binding=this.createTwowayBinding())&&(this.binding.bind(),this.rendered&&this.binding.render())},e.prototype.render=function(t,e){var i=this;this.namespace=go(this);var r,o=!1;if(e)for(var s;s=e.shift();){if(s.nodeName.toUpperCase()===i.template.e.toUpperCase()&&s.namespaceURI===i.namespace){i.node=r=s,o=!0;break}n(s)}if(r||(r=ys(this.template.e,this.namespace,this.getAttribute("is")),this.node=r),Ps(r,"_ractive",{value:{proxy:this}}),this.parentFragment.cssIds&&r.setAttribute("data-ractive-css",this.parentFragment.cssIds.map(function(t){return"{"+t+"}"}).join(" ")),o&&this.foundNode&&this.foundNode(r),this.fragment){var a=o?T(r.childNodes):void 0;this.fragment.render(r,a),a&&a.forEach(n)}if(o){this.binding&&this.binding.wasUndefined&&this.binding.setFromNode(r);for(var h=r.attributes.length;h--;){var u=r.attributes[h].name;u in i.attributeByName||r.removeAttribute(u)}}this.attributes.forEach(Nt),this.binding&&this.binding.render(),Xr(this),this._introTransition&&this.ractive.transitionsEnabled&&(this._introTransition.isIntro=!0,ia.registerTransition(this._introTransition)),o||t.appendChild(r),this.rendered=!0},e.prototype.shuffled=function(){this.liveQueries.forEach(co),t.prototype.shuffled.call(this)},e.prototype.toString=function(){var t=this.template.e,e=this.attributes.map(fo).join("");"option"===this.name&&this.isSelected()&&(e+=" selected"),"input"===this.name&&po(this)&&(e+=" checked");var n,i;this.attributes.forEach(function(t){"class"===t.name?i=(i||"")+(i?" ":"")+r(t.getString()):"style"===t.name?(n=(n||"")+(n?" ":"")+r(t.getString()))&&!Pp.test(n)&&(n+=";"):t.style?n=(n||"")+(n?" ":"")+t.style+": "+r(t.getString())+";":t.inlineClass&&t.getValue()&&(i=(i||"")+(i?" ":"")+t.inlineClass)}),void 0!==n&&(e=" style"+(n?'="'+n+'"':"")+e),void 0!==i&&(e=" class"+(i?'="'+i+'"':"")+e);var o="<"+t+e+">";return this.isVoid?o:("textarea"===this.name&&void 0!==this.getAttribute("value")?o+=An(this.getAttribute("value")):void 0!==this.getAttribute("contenteditable")&&(o+=this.getAttribute("value")||""),this.fragment&&(o+=this.fragment.toString(!/^(?:script|style)$/i.test(this.template.e))),o+="</"+t+">")},e.prototype.unbind=function(){this.attributes.unbinding=!0,this.attributes.forEach(Vt),this.attributes.unbinding=!1,this.binding&&this.binding.unbind(),this.fragment&&this.fragment.unbind()},e.prototype.unrender=function(t){if(this.rendered){this.rendered=!1;var e=this._introTransition;e&&e.complete&&e.complete(),"option"===this.name?this.detach():t&&ia.detachWhenReady(this),this.fragment&&this.fragment.unrender(),this.binding&&this.binding.unrender(),this._outroTransition&&this.ractive.transitionsEnabled&&(this._outroTransition.isIntro=!1,ia.registerTransition(this._outroTransition)),mo(this)}},e.prototype.update=function(){this.dirty&&(this.dirty=!1,this.attributes.forEach(Kt),this.fragment&&this.fragment.update())},e}(kc),Mp=function(t){function e(e){t.call(this,e),this.formBindings=[]}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.render=function(e,n){t.prototype.render.call(this,e,n),this.node.addEventListener("reset",vo,!1)},e.prototype.unrender=function(e){this.node.removeEventListener("reset",vo,!1),t.prototype.unrender.call(this,e)},e}(Vp),Bp=function(t){function e(e){t.call(this,e),this.parentFragment=e.parentFragment,this.template=e.template,this.index=e.index,e.owner&&(this.parent=e.owner),this.isStatic=!!e.template.s,this.model=null,this.dirty=!1}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){var t=this,e=ar(this.parentFragment,this.template),n=e?e.get():void 0;if(this.isStatic)return void(this.model={get:function(){return n}});e?(e.register(this),this.model=e):this.template.r&&(this.resolver=this.parentFragment.resolve(this.template.r,function(e){t.model=e,e.register(t),t.handleChange(),t.resolver=null}))},e.prototype.handleChange=function(){this.bubble()},e.prototype.rebinding=function(t,e,n){return t=Ut(this.template,t,e),!this.static&&(t!==this.model&&(this.model&&this.model.unregister(this),t&&t.addShuffleRegister(this,"mark"),this.model=t,n||this.handleChange(),!0))},e.prototype.unbind=function(){this.isStatic||(this.model&&this.model.unregister(this),this.model=void 0,this.resolver&&this.resolver.unbind())},e}(kc),Kp=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bubble=function(){this.owner&&this.owner.bubble(),t.prototype.bubble.call(this)},e.prototype.detach=function(){return n(this.node)},e.prototype.firstNode=function(){return this.node},e.prototype.getString=function(){return this.model?i(this.model.get()):""},e.prototype.render=function(t,e){if(!Nr()){var n=this.getString();if(this.rendered=!0,e){var i=e[0];i&&3===i.nodeType?(e.shift(),i.nodeValue!==n&&(i.nodeValue=n)):(i=this.node=ms.createTextNode(n),e[0]?t.insertBefore(i,e[0]):t.appendChild(i)),this.node=i}else this.node=ms.createTextNode(n),t.appendChild(this.node)}},e.prototype.toString=function(t){var e=this.getString();return t?An(e):e},e.prototype.unrender=function(t){t&&this.detach(),this.rendered=!1},e.prototype.update=function(){this.dirty&&(this.dirty=!1,this.rendered&&(this.node.data=this.getString()))},e.prototype.valueOf=function(){return this.model?this.model.get():void 0},e}(Bp),Ip=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.render=function(e,n){t.prototype.render.call(this,e,n),this.node.defaultValue=this.node.value},e}(Vp),Rp=function(t){function e(e){t.call(this,e),this.name=e.template.n,this.owner=e.owner||e.parentFragment.owner||e.element||ur(e.parentFragment),this.element=e.element||(this.owner.attributeByName?this.owner:ur(e.parentFragment)),this.parentFragment=this.element.parentFragment,this.ractive=this.parentFragment.ractive,this.fragment=null,this.element.attributeByName[this.name]=this,this.value=e.template.f}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){this.fragment&&this.fragment.bind();var t=this.template.f,e=this.element.instance.viewmodel;if(0===t)e.joinKey(this.name).set(!0);else if("string"==typeof t){var n=Hn(t);e.joinKey(this.name).set(n?n.value:t)}else h(t)&&bo(this)},e.prototype.render=function(){},e.prototype.unbind=function(){this.fragment&&this.fragment.unbind(),this.model&&this.model.unregister(this),this.boundFragment&&this.boundFragment.unbind(),this.element.bound&&this.link.target===this.model&&this.link.owner.unlink()},e.prototype.unrender=function(){},e.prototype.update=function(){this.dirty&&(this.dirty=!1,this.fragment&&this.fragment.update(),this.boundFragment&&this.boundFragment.update(),this.rendered&&this.updateDelegate())},e}(kc),Lp=function(t){function e(e){var n=e.template;n.a||(n.a={}),void 0!==n.a.value||"disabled"in n.a||(n.a.value=n.f||""),t.call(this,e),this.select=ur(this.parent||this.parentFragment,!1,"select")}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){if(!this.select)return void t.prototype.bind.call(this);var e=this.attributeByName.selected;if(e&&void 0!==this.select.getAttribute("value")){var n=this.attributes.indexOf(e);this.attributes.splice(n,1),delete this.attributeByName.selected}t.prototype.bind.call(this),this.select.options.push(this)},e.prototype.bubble=function(){var e=this.getAttribute("value");this.node&&this.node.value!==e&&(this.node._ractive.value=e),t.prototype.bubble.call(this)},e.prototype.getAttribute=function(t){var e=this.attributeByName[t];return e?e.getValue():"value"===t&&this.fragment?this.fragment.valueOf():void 0},e.prototype.isSelected=function(){var t=this.getAttribute("value");if(void 0===t||!this.select)return!1;var e=this.select.getAttribute("value");if(e==t)return!0;if(this.select.getAttribute("multiple")&&h(e))for(var n=e.length;n--;)if(e[n]==t)return!0},e.prototype.render=function(e,n){t.prototype.render.call(this,e,n),this.attributeByName.value||(this.node._ractive.value=this.getAttribute("value"))},e.prototype.unbind=function(){t.prototype.unbind.call(this),this.select&&j(this.select.options,this)},e}(Vp),Dp=function(t){function e(){t.apply(this,arguments)}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){this.refName=this.template.r;var e,n=this.refName?wo(this.ractive,this.refName,this.parentFragment)||null:null;n&&(this.named=!0,this.setTemplate(this.template.r,n)),n||(t.prototype.bind.call(this),this.model&&(e=this.model.get())&&"object"==typeof e&&("string"==typeof e.template||h(e.t))?(e.template?(this.source=e.template,e=Ao(this.template.r,e.template,this.ractive)):this.source=e.t,this.setTemplate(this.template.r,e.t)):this.model&&"string"==typeof this.model.get()||!this.refName?this.setTemplate(this.model.get()):this.setTemplate(this.refName,n)),this.fragment=new Cf({owner:this,template:this.partialTemplate}).bind()},e.prototype.detach=function(){return this.fragment.detach()},e.prototype.find=function(t){return this.fragment.find(t)},e.prototype.findAll=function(t,e){this.fragment.findAll(t,e)},e.prototype.findComponent=function(t){return this.fragment.findComponent(t)},e.prototype.findAllComponents=function(t,e){this.fragment.findAllComponents(t,e)},e.prototype.firstNode=function(t){return this.fragment.firstNode(t)},e.prototype.forceResetTemplate=function(){var t=this;this.partialTemplate=void 0,this.refName&&(this.partialTemplate=wo(this.ractive,this.refName,this.parentFragment)),this.partialTemplate||(this.partialTemplate=wo(this.ractive,this.name,this.parentFragment)),this.partialTemplate||(b("Could not find template for partial '"+this.name+"'"),this.partialTemplate=[]),this.inAttribute?Pr(function(){return t.fragment.resetTemplate(t.partialTemplate)}):this.fragment.resetTemplate(this.partialTemplate),this.bubble()},e.prototype.render=function(t,e){this.fragment.render(t,e)},e.prototype.setTemplate=function(t,e){this.name=t,e||null===e||(e=wo(this.ractive,t,this.parentFragment)),e||b("Could not find template for partial '"+t+"'"),this.partialTemplate=e||[]},e.prototype.toString=function(t){return this.fragment.toString(t)},e.prototype.unbind=function(){t.prototype.unbind.call(this),this.fragment.unbind()},e.prototype.unrender=function(t){this.fragment.unrender(t)},e.prototype.update=function(){var t;this.dirty&&(this.dirty=!1,this.named||(this.model&&(t=this.model.get()),t&&"string"==typeof t&&t!==this.name?(this.setTemplate(t),this.fragment.resetTemplate(this.partialTemplate)):t&&"object"==typeof t&&("string"==typeof t.template||h(t.t))&&t.t!==this.source&&t.template!==this.source&&(t.template?(this.source=t.template,t=Ao(this.name,t.template,this.ractive)):this.source=t.t,this.setTemplate(this.name,t.t),this.fragment.resetTemplate(this.partialTemplate))),this.fragment.update())},e}(Bp),Wp=function(t){this.parent=t.owner.parentFragment,this.parentFragment=this,this.owner=t.owner,this.ractive=this.parent.ractive,this.cssIds="cssIds"in t?t.cssIds:this.parent?this.parent.cssIds:null,this.context=null,this.rendered=!1,this.iterations=[],this.template=t.template,this.indexRef=t.indexRef,this.keyRef=t.keyRef,this.pendingNewIndices=null,this.previousIterations=null,this.isArray=!1};Wp.prototype.bind=function(t){var e=this;this.context=t;var n=t.get();if(this.isArray=h(n)){this.iterations=[];for(var i=n.length,r=0;r<i;r+=1)e.iterations[r]=e.createIteration(r,r)}else if(c(n)){if(this.isArray=!1,this.indexRef){var o=this.indexRef.split(",");this.keyRef=o[0],this.indexRef=o[1]}this.iterations=Object.keys(n).map(function(t,n){return e.createIteration(t,n)})}return this},Wp.prototype.bubble=function(){this.owner.bubble()},Wp.prototype.createIteration=function(t,e){var n=new Cf({owner:this,template:this.template});n.key=t,n.index=e,n.isIteration=!0;var i=this.context.joinKey(t);return this.owner.template.z&&(n.aliases={},n.aliases[this.owner.template.z[0].n]=i),n.bind(i)},Wp.prototype.destroyed=function(){this.iterations.forEach(function(t){return t.destroyed()})},Wp.prototype.detach=function(){var e=t();return this.iterations.forEach(function(t){return e.appendChild(t.detach())}),e},Wp.prototype.find=function(t){var e,n=this,i=this.iterations.length;for(e=0;e<i;e+=1){var r=n.iterations[e].find(t);if(r)return r}},Wp.prototype.findAll=function(t,e){var n,i=this,r=this.iterations.length;for(n=0;n<r;n+=1)i.iterations[n].findAll(t,e)},Wp.prototype.findComponent=function(t){var e,n=this,i=this.iterations.length;for(e=0;e<i;e+=1){var r=n.iterations[e].findComponent(t);if(r)return r}},Wp.prototype.findAllComponents=function(t,e){var n,i=this,r=this.iterations.length;for(n=0;n<r;n+=1)i.iterations[n].findAllComponents(t,e)},Wp.prototype.findNextNode=function(t){var e=this;if(t.index<this.iterations.length-1)for(var n=t.index+1;n<e.iterations.length;n++){var i=e.iterations[n].firstNode(!0);if(i)return i}return this.owner.findNextNode()},Wp.prototype.firstNode=function(t){return this.iterations[0]?this.iterations[0].firstNode(t):null},Wp.prototype.rebinding=function(t){var e=this;this.context=t,this.iterations.forEach(function(n){var i=t?t.joinKey(n.key||n.index):void 0;n.context=i,e.owner.template.z&&(n.aliases={},n.aliases[e.owner.template.z[0].n]=i)})},Wp.prototype.render=function(t,e){this.iterations&&this.iterations.forEach(function(n){return n.render(t,e)}),this.rendered=!0},Wp.prototype.shuffle=function(t){var e=this;this.pendingNewIndices||(this.previousIterations=this.iterations.slice()),this.pendingNewIndices||(this.pendingNewIndices=[]),this.pendingNewIndices.push(t);var n=[];t.forEach(function(t,i){if(-1!==t){var r=e.iterations[i];n[t]=r,t!==i&&r&&(r.dirty=!0)}}),this.iterations=n,this.bubble()},Wp.prototype.shuffled=function(){this.iterations.forEach(function(t){return t.shuffled()})},Wp.prototype.toString=function(t){return this.iterations?this.iterations.map(t?Rt:It).join(""):""},Wp.prototype.unbind=function(){return this.iterations.forEach(Vt),this},Wp.prototype.unrender=function(t){this.iterations.forEach(t?Bt:Mt),this.pendingNewIndices&&this.previousIterations&&this.previousIterations.forEach(function(e){e.rendered&&(t?Bt(e):Mt(e))}),this.rendered=!1},Wp.prototype.update=function(){var e=this;if(this.pendingNewIndices)return void this.updatePostShuffle();if(!this.updating){this.updating=!0;var n,i,r,o=this.context.get(),s=this.isArray,a=!0;if(this.isArray=h(o))s&&(a=!1,this.iterations.length>o.length&&(n=this.iterations.splice(o.length)));else if(c(o)&&!s)for(a=!1,n=[],i={},r=this.iterations.length;r--;){var u=e.iterations[r];u.key in o?i[u.key]=!0:(e.iterations.splice(r,1),n.push(u))}a&&(n=this.iterations,this.iterations=[]),n&&n.forEach(function(t){t.unbind(),t.unrender(!0)}),this.iterations.forEach(Kt);var l,p,f=h(o)?o.length:c(o)?Object.keys(o).length:0;if(f>this.iterations.length){if(l=this.rendered?t():null,r=this.iterations.length,h(o))for(;r<o.length;)p=e.createIteration(r,r),e.iterations.push(p),e.rendered&&p.render(l),r+=1;else if(c(o)){if(this.indexRef&&!this.keyRef){var d=this.indexRef.split(",");this.keyRef=d[0],this.indexRef=d[1]}Object.keys(o).forEach(function(t){i&&t in i||(p=e.createIteration(t,r),e.iterations.push(p),e.rendered&&p.render(l),r+=1)})}if(this.rendered){var m=this.parent.findParentNode(),g=this.parent.findNextNode(this.owner);m.insertBefore(l,g)}}this.updating=!1}},Wp.prototype.updatePostShuffle=function(){var e=this,n=this.pendingNewIndices[0];this.pendingNewIndices.slice(1).forEach(function(t){n.forEach(function(e,i){n[i]=t[e]})});var i,r=this.context.get().length,o=this.previousIterations.length,s={};n.forEach(function(t,n){var i=e.previousIterations[n];if(e.previousIterations[n]=null,-1===t)s[n]=i;else if(i.index!==t){var r=e.context.joinKey(t);i.index=i.key=t,i.context=r,e.owner.template.z&&(i.aliases={},i.aliases[e.owner.template.z[0].n]=r)}}),this.previousIterations.forEach(function(t,e){t&&(s[e]=t)});var a=this.rendered?t():null,h=this.rendered?this.parent.findParentNode():null,u="startIndex"in n;for(i=u?n.startIndex:0;i<r;i++){var l=e.iterations[i];l&&u?e.rendered&&(s[i]&&a.appendChild(s[i].detach()),a.childNodes.length&&h.insertBefore(a,l.firstNode())):(l||(e.iterations[i]=e.createIteration(i,i)),e.rendered&&(s[i]&&a.appendChild(s[i].detach()),l?a.appendChild(l.detach()):e.iterations[i].render(a)))}if(this.rendered){for(i=r;i<o;i++)s[i]&&a.appendChild(s[i].detach());a.childNodes.length&&h.insertBefore(a,this.owner.findNextNode())}Object.keys(s).forEach(function(t){return s[t].unbind().unrender(!0)}),this.iterations.forEach(Kt),this.pendingNewIndices=null,this.shuffled()};var Up,zp=function(e){function n(t){e.call(this,t),this.sectionType=t.template.n||null,this.templateSectionType=this.sectionType,this.subordinate=1===t.template.l,this.fragment=null}return n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.bind=function(){e.prototype.bind.call(this),this.subordinate&&(this.sibling=this.parentFragment.items[this.parentFragment.items.indexOf(this)-1],this.sibling.nextSibling=this),this.model?(this.dirty=!0,
this.update()):!this.sectionType||this.sectionType!==lu||this.sibling&&this.sibling.isTruthy()||(this.fragment=new Cf({owner:this,template:this.template.f}).bind())},n.prototype.detach=function(){return this.fragment?this.fragment.detach():t()},n.prototype.find=function(t){if(this.fragment)return this.fragment.find(t)},n.prototype.findAll=function(t,e){this.fragment&&this.fragment.findAll(t,e)},n.prototype.findComponent=function(t){if(this.fragment)return this.fragment.findComponent(t)},n.prototype.findAllComponents=function(t,e){this.fragment&&this.fragment.findAllComponents(t,e)},n.prototype.firstNode=function(t){return this.fragment&&this.fragment.firstNode(t)},n.prototype.isTruthy=function(){if(this.subordinate&&this.sibling.isTruthy())return!0;var t=this.model?this.model.isRoot?this.model.value:this.model.get():void 0;return!(!t||this.templateSectionType!==fu&&Oo(t))},n.prototype.rebinding=function(t,n,i){e.prototype.rebinding.call(this,t,n,i)&&this.fragment&&this.sectionType!==uu&&this.sectionType!==lu&&this.fragment.rebinding(t,n)},n.prototype.render=function(t,e){this.rendered=!0,this.fragment&&this.fragment.render(t,e)},n.prototype.shuffle=function(t){this.fragment&&this.sectionType===cu&&this.fragment.shuffle(t)},n.prototype.toString=function(t){return this.fragment?this.fragment.toString(t):""},n.prototype.unbind=function(){e.prototype.unbind.call(this),this.fragment&&this.fragment.unbind()},n.prototype.unrender=function(t){this.rendered&&this.fragment&&this.fragment.unrender(t),this.rendered=!1},n.prototype.update=function(){if(this.dirty&&(this.fragment&&this.sectionType!==uu&&this.sectionType!==lu&&(this.fragment.context=this.model),this.model||this.sectionType===lu)){this.dirty=!1;var e=this.model?this.model.isRoot?this.model.value:this.model.get():void 0,n=!this.subordinate||!this.sibling.isTruthy(),i=this.sectionType;null!==this.sectionType&&null!==this.templateSectionType||(this.sectionType=So(e,this.template.i)),i&&i!==this.sectionType&&this.fragment&&(this.rendered&&this.fragment.unbind().unrender(!0),this.fragment=null);var r;if(this.sectionType===cu||this.sectionType===pu||n&&(this.sectionType===lu?!this.isTruthy():this.isTruthy()))if(this.fragment)this.fragment.update();else if(this.sectionType===cu)r=new Wp({owner:this,template:this.template.f,indexRef:this.template.i}).bind(this.model);else{var o=this.sectionType!==uu&&this.sectionType!==lu?this.model:null;r=new Cf({owner:this,template:this.template.f}).bind(o)}else this.fragment&&(this.fragment.unbind(),this.rendered&&this.fragment.unrender(!0)),this.fragment=null;if(r){if(this.rendered){var s=this.parentFragment.findParentNode(),a=this.parentFragment.findNextNode(this);if(a){var h=t();r.render(h),a.parentNode.insertBefore(h,a)}else r.render(s)}this.fragment=r}this.nextSibling&&(this.nextSibling.dirty=!0,this.nextSibling.update())}},n}(Bp),$p=function(t){function e(e){t.call(this,e),this.options=[]}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.foundNode=function(t){if(this.binding){var e=so(t);e.length>0&&(this.selectedOptions=e)}},e.prototype.render=function(e,n){t.prototype.render.call(this,e,n),this.sync();for(var i=this.node,r=i.options.length;r--;)i.options[r].defaultSelected=i.options[r].selected;this.rendered=!0},e.prototype.sync=function(){var t=this,e=this.node;if(e){var n=T(e.options);if(this.selectedOptions)return n.forEach(function(e){t.selectedOptions.indexOf(e)>=0?e.selected=!0:e.selected=!1}),this.binding.setFromNode(e),void delete this.selectedOptions;var i=this.getAttribute("value"),r=this.getAttribute("multiple"),o=r&&h(i);if(void 0!==i){var s;n.forEach(function(t){var e=t._ractive?t._ractive.value:t.value,n=r?o&&Co(i,e):i==e;n&&(s=!0),t.selected=n}),s||r||this.binding&&this.binding.forceUpdate()}else this.binding&&this.binding.forceUpdate()}},e.prototype.update=function(){var e=this.dirty;t.prototype.update.call(this),e&&this.sync()},e}(Vp),qp=function(t){function e(e){var n=e.template;e.deferContent=!0,t.call(this,e),this.attributeByName.value||(n.f&&uo({template:n})?this.attributes.push(Ro({owner:this,template:{t:Lh,f:n.f,n:"value"},parentFragment:this.parentFragment})):this.fragment=new Cf({owner:this,cssIds:null,template:n.f}))}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bubble=function(){var t=this;this.dirty||(this.dirty=!0,this.rendered&&!this.binding&&this.fragment&&ia.scheduleTask(function(){t.dirty=!1,t.node.value=t.fragment.toString()}),this.parentFragment.bubble())},e}(Ip),Zp=function(t){function e(e){t.call(this,e),this.type=Th}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){},e.prototype.detach=function(){return n(this.node)},e.prototype.firstNode=function(){return this.node},e.prototype.render=function(t,e){if(!Nr())if(this.rendered=!0,e){var n=e[0];n&&3===n.nodeType?(e.shift(),n.nodeValue!==this.template&&(n.nodeValue=this.template)):(n=this.node=ms.createTextNode(this.template),e[0]?t.insertBefore(n,e[0]):t.appendChild(n)),this.node=n}else this.node=ms.createTextNode(this.template),t.appendChild(this.node)},e.prototype.toString=function(t){return t?An(this.template):this.template},e.prototype.unbind=function(){},e.prototype.unrender=function(t){this.rendered&&t&&this.detach(),this.rendered=!1},e.prototype.update=function(){},e.prototype.valueOf=function(){return this.template},e}(kc);if(gs){var Hp={},Qp=ys("div").style;Up=function(t){if(t=jo(t),!Hp[t])if(void 0!==Qp[t])Hp[t]=t;else for(var e=t.charAt(0).toUpperCase()+t.substring(1),n=Cs.length;n--;){var i=Cs[n];if(void 0!==Qp[i+e]){Hp[t]=i+e;break}}return Hp[t]}}else Up=null;var Gp,Yp=Up,Jp="hidden";if(ms){var Xp;if(Jp in ms)Xp="";else for(var tf=Cs.length;tf--;){var ef=Cs[tf];if((Jp=ef+"Hidden")in ms){Xp=ef;break}}void 0!==Xp?(ms.addEventListener(Xp+"visibilitychange",To),To()):("onfocusout"in ms?(ms.addEventListener("focusout",Fo),ms.addEventListener("focusin",No)):(ds.addEventListener("pagehide",Fo),ds.addEventListener("blur",Fo),ds.addEventListener("pageshow",No),ds.addEventListener("focus",No)),Gp=!0)}var nf,rf=new RegExp("^-(?:"+Cs.join("|")+")-"),of=new RegExp("^(?:"+Cs.join("|")+")([A-Z])");if(gs){var sf,af,hf,uf,lf,cf,pf=ys("div").style,ff=function(t){return t},df={},mf={};void 0!==pf.transition?(sf="transition",af="transitionend",hf=!0):void 0!==pf.webkitTransition?(sf="webkitTransition",af="webkitTransitionEnd",hf=!0):hf=!1,sf&&(uf=sf+"Duration",lf=sf+"Property",cf=sf+"TimingFunction"),nf=function(t,e,n,i,r){setTimeout(function(){function o(){clearTimeout(c)}function s(){u&&l&&(t.unregisterCompleteHandler(o),t.ractive.fire(t.name+":end",t.node,t.isIntro),r())}function a(t){var e=i.indexOf(jo(Po(t.propertyName)));-1!==e&&i.splice(e,1),i.length||(clearTimeout(c),h())}function h(){f[lf]=d.property,f[cf]=d.duration,f[uf]=d.timing,t.node.removeEventListener(af,a,!1),l=!0,s()}var u,l,c,p=(t.node.namespaceURI||"")+t.node.tagName,f=t.node.style,d={property:f[lf],timing:f[cf],duration:f[uf]};f[lf]=i.map(Yp).map(Vo).join(","),f[cf]=Vo(n.easing||"linear"),f[uf]=n.duration/1e3+"s",t.node.addEventListener(af,a,!1),c=setTimeout(function(){i=[],h()},n.duration+(n.delay||0)+50),t.registerCompleteHandler(o),setTimeout(function(){for(var r,o,h,c,d,m,g=i.length,v=[];g--;)c=i[g],r=p+c,hf&&!mf[r]&&(f[Yp(c)]=e[c],df[r]||(o=t.getStyle(c),df[r]=t.getStyle(c)!=e[c],mf[r]=!df[r],mf[r]&&(f[Yp(c)]=o))),hf&&!mf[r]||(void 0===o&&(o=t.getStyle(c)),h=i.indexOf(c),-1===h?y("Something very strange happened with transitions. Please raise an issue at https://github.com/ractivejs/ractive/issues - thanks!",{node:t.node}):i.splice(h,1),d=/[^\d]*$/.exec(e[c])[0],m=x(parseFloat(o),parseFloat(e[c]))||function(){return e[c]},v.push({name:Yp(c),interpolator:m,suffix:d}));if(v.length){var w;"string"==typeof n.easing?(w=t.ractive.easing[n.easing])||(b($s(n.easing,"easing")),w=ff):w="function"==typeof n.easing?n.easing:ff,new Fa({duration:n.duration,easing:w,step:function(e){for(var n=v.length;n--;){var i=v[n];t.node.style[i.name]=i.interpolator(e)+i.suffix}},complete:function(){u=!0,s()}})}else u=!0;i.length||(t.node.removeEventListener(af,a,!1),l=!0,s())},0)},n.delay||0)}}else nf=null;var gf=nf,vf=ds&&(ds.getComputedStyle||null.getComputedStyle),yf=Xs.resolve(),bf={t0:"intro-outro",t1:"intro",t2:"outro"},wf=function(t){this.owner=t.owner||t.parentFragment.owner||ur(t.parentFragment),this.element=this.owner.attributeByName?this.owner:ur(t.parentFragment),this.ractive=this.owner.ractive,this.template=t.template,this.parentFragment=t.parentFragment,this.options=t,this.onComplete=[]};wf.prototype.animateStyle=function(t,e,n){var i=this;if(4===arguments.length)throw new Error("t.animateStyle() returns a promise - use .then() instead of passing a callback");if(!Gp)return this.setStyle(t,e),yf;var r;return"string"==typeof t?(r={},r[t]=e):(r=t,n=e),n||(b('The "%s" transition does not supply an options object to `t.animateStyle()`. This will break in a future version of Ractive. For more info see https://github.com/RactiveJS/Ractive/issues/340',this.name),n=this),new Xs(function(t){if(!n.duration)return i.setStyle(r),void t();for(var e=Object.keys(r),o=[],s=vf(i.node),a=e.length;a--;){var h=e[a],u=s[Yp(h)];"0px"===u&&(u=0),u!=r[h]&&(o.push(h),i.node.style[Yp(h)]=u)}if(!o.length)return void t();gf(i,r,n,o,t)})},wf.prototype.bind=function(){var t=this,e=this.options,n=e.template&&e.template.v;n&&("t0"!==n&&"t1"!==n||(this.element._introTransition=this),"t0"!==n&&"t2"!==n||(this.element._outroTransition=this),this.eventName=bf[n]);var i=this.owner.ractive;if(e.name)this.name=e.name;else{var r=e.template.f;if("string"==typeof r.n&&(r=r.n),"string"!=typeof r){var o=new Cf({owner:this.owner,template:r.n}).bind();if(r=o.toString(),o.unbind(),""===r)return}this.name=r}if(e.params)this.params=e.params;else if(e.template.f.a&&!e.template.f.a.s)this.params=e.template.f.a;else if(e.template.f.d){var s=new Cf({owner:this.owner,template:e.template.f.d}).bind();this.params=s.getArgsList(),s.unbind()}"function"==typeof this.name?(this._fn=this.name,this.name=this._fn.name):this._fn=w("transitions",i,this.name),this._fn||b($s(this.name,"transition"),{ractive:i}),e.template&&this.template.f.a&&this.template.f.a.s&&(this.resolvers=[],this.models=this.template.f.a.r.map(function(e,n){var i,r=Ht(t.parentFragment,e);return r?r.register(t):(i=t.parentFragment.resolve(e,function(e){t.models[n]=e,j(t.resolvers,i),e.register(t)}),t.resolvers.push(i)),r}),this.argsFn=yn(this.template.f.a.s,this.template.f.a.r.length))},wf.prototype.destroyed=function(){},wf.prototype.getStyle=function(t){var e=vf(this.node);if("string"==typeof t){var n=e[Yp(t)];return"0px"===n?0:n}if(!h(t))throw new Error("Transition$getStyle must be passed a string, or an array of strings representing CSS properties");for(var i={},r=t.length;r--;){var o=t[r],s=e[Yp(o)];"0px"===s&&(s=0),i[o]=s}return i},wf.prototype.handleChange=function(){},wf.prototype.processParams=function(t,e){return"number"==typeof t?t={duration:t}:"string"==typeof t?t="slow"===t?{duration:600}:"fast"===t?{duration:200}:{duration:400}:t||(t={}),s({},e,t)},wf.prototype.rebinding=function(t,e){var n=this.models.indexOf(e);~n&&(t=Ut(this.template.f.a.r[n],t,e))!==e&&(e.unregister(this),this.models.splice(n,1,t),t&&t.addShuffleRegister(this,"mark"))},wf.prototype.registerCompleteHandler=function(t){_(this.onComplete,t)},wf.prototype.render=function(){},wf.prototype.setStyle=function(t,e){if("string"==typeof t)this.node.style[Yp(t)]=e;else{var n;for(n in t)t.hasOwnProperty(n)&&(this.node.style[Yp(n)]=t[n])}return this},wf.prototype.start=function(){var t,e=this,n=this.node=this.element.node,i=n.getAttribute("style"),r=this.params;if(this.complete=function(r){t||(e.onComplete.forEach(function(t){return t()}),!r&&e.isIntro&&Mo(n,i),e._manager.remove(e),t=!0)},!this._fn)return void this.complete();if(this.argsFn){var o=this.models.map(function(t){if(t)return t.get()});r=this.argsFn.apply(this.ractive,o)}var s=this._fn.apply(this.ractive,[this].concat(r));s&&s.then(this.complete)},wf.prototype.toString=function(){return""},wf.prototype.unbind=function(){if(this.resolvers&&this.resolvers.forEach(Vt),!this.element.attributes.unbinding){var t=this.options&&this.options.template&&this.options.template.v;"t0"!==t&&"t1"!==t||(this.element._introTransition=null),"t0"!==t&&"t2"!==t||(this.element._outroTransition=null)}},wf.prototype.unregisterCompleteHandler=function(t){j(this.onComplete,t)},wf.prototype.unrender=function(){},wf.prototype.update=function(){};var kf,xf,Ef={};try{ys("table").innerHTML="foo"}catch(t){kf=!0,xf={TABLE:['<table class="x">',"</table>"],THEAD:['<table><thead class="x">',"</thead></table>"],TBODY:['<table><tbody class="x">',"</tbody></table>"],TR:['<table><tr class="x">',"</tr></table>"],SELECT:['<select class="x">',"</select>"]}}var _f=function(e){function i(t){e.call(this,t)}return i.prototype=Object.create(e&&e.prototype),i.prototype.constructor=i,i.prototype.detach=function(){var e=t();return this.nodes.forEach(function(t){return e.appendChild(t)}),e},i.prototype.find=function(t){var e,n=this,i=this.nodes.length;for(e=0;e<i;e+=1){var r=n.nodes[e];if(1===r.nodeType){if(bs(r,t))return r;var o=r.querySelector(t);if(o)return o}}return null},i.prototype.findAll=function(t,e){var n,i=this,r=this.nodes.length;for(n=0;n<r;n+=1){var o=i.nodes[n];if(1===o.nodeType){e.test(o)&&e.add(o);var s=o.querySelectorAll(t);if(s){var a,h=s.length;for(a=0;a<h;a+=1)e.add(s[a])}}}},i.prototype.findComponent=function(){return null},i.prototype.firstNode=function(){return this.nodes[0]},i.prototype.render=function(t){var e=this.model?this.model.get():"";this.nodes=Bo(e,this.parentFragment.findParentNode(),t),this.rendered=!0},i.prototype.toString=function(){var t=this.model&&this.model.get();return t=null!=t?""+t:"",Tr()?_n(t):t},i.prototype.unrender=function(){this.nodes&&this.nodes.forEach(function(t){return n(t)}),this.rendered=!1},i.prototype.update=function(){if(this.rendered&&this.dirty){this.dirty=!1,this.unrender();var e=t();this.render(e);var n=this.parentFragment.findParentNode(),i=this.parentFragment.findNextNode(this);n.insertBefore(e,i)}else this.dirty=!1},i}(Bp),Af=function(t){function e(e){t.call(this,e),this.container=e.parentFragment.ractive,this.component=this.container.component,this.containerFragment=e.parentFragment,this.parentFragment=this.component.parentFragment,this.name=e.template.n||""}return e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.bind=function(){var t=this.name;(this.component.yielders[t]||(this.component.yielders[t]=[])).push(this);var e=this.container._inlinePartials[t||"content"];"string"==typeof e&&(e=Ii(e).t),e||(y('Could not find template for partial "'+t+'"',{ractive:this.ractive}),e=[]),this.fragment=new Cf({owner:this,ractive:this.container.parent,template:e}).bind()},e.prototype.bubble=function(){this.dirty||(this.containerFragment.bubble(),this.dirty=!0)},e.prototype.detach=function(){return this.fragment.detach()},e.prototype.find=function(t){return this.fragment.find(t)},e.prototype.findAll=function(t,e){this.fragment.findAll(t,e)},e.prototype.findComponent=function(t){return this.fragment.findComponent(t)},e.prototype.findAllComponents=function(t,e){this.fragment.findAllComponents(t,e)},e.prototype.findNextNode=function(){return this.containerFragment.findNextNode(this)},e.prototype.firstNode=function(t){return this.fragment.firstNode(t)},e.prototype.render=function(t,e){return this.fragment.render(t,e)},e.prototype.setTemplate=function(t){var e=this.parentFragment.ractive.partials[t];"string"==typeof e&&(e=Ii(e).t),this.partialTemplate=e||[]},e.prototype.toString=function(t){return this.fragment.toString(t)},e.prototype.unbind=function(){this.fragment.unbind(),j(this.component.yielders[this.name],this)},e.prototype.unrender=function(t){this.fragment.unrender(t)},e.prototype.update=function(){this.dirty=!1,this.fragment.update()},e}(kc),Of={};Of[qh]=Oc,Of[$h]=yp,Of[Fh]=Kp,Of[Kh]=Dp,Of[Ph]=zp,Of[Nh]=_f,Of[Uh]=Af,Of[Lh]=Vc,Of[bu]=Mc,Of[vu]=vp,Of[gu]=fp,Of[yu]=wf;var Sf={doctype:yp,form:Mp,input:Ip,option:Lp,select:$p,textarea:qp},Cf=function(t){this.owner=t.owner,this.isRoot=!t.owner.parentFragment,this.parent=this.isRoot?null:this.owner.parentFragment,this.ractive=t.ractive||(this.isRoot?t.owner:this.parent.ractive),this.componentParent=this.isRoot&&this.ractive.component?this.ractive.component.parentFragment:null,this.context=null,this.rendered=!1,this.cssIds="cssIds"in t?t.cssIds:this.parent?this.parent.cssIds:null,this.resolvers=[],this.dirty=!1,this.dirtyArgs=this.dirtyValue=!0,this.template=t.template||[],this.createItems()};Cf.prototype.bind=function(t){return this.context=t,this.items.forEach(At),this.bound=!0,this.dirty&&this.update(),this},Cf.prototype.bubble=function(){this.dirtyArgs=this.dirtyValue=!0,this.dirty||(this.dirty=!0,this.isRoot?this.ractive.component?this.ractive.component.bubble():this.bound&&ia.addFragment(this):this.owner.bubble())},Cf.prototype.createItems=function(){var t=this,e=this.template.length;this.items=[];for(var n=0;n<e;n++)t.items[n]=Ro({parentFragment:t,template:t.template[n],index:n})},Cf.prototype.destroyed=function(){this.items.forEach(function(t){return t.destroyed()})},Cf.prototype.detach=function(){var e=t();return this.items.forEach(function(t){return e.appendChild(t.detach())}),e},Cf.prototype.find=function(t){var e,n=this,i=this.items.length;for(e=0;e<i;e+=1){var r=n.items[e].find(t);if(r)return r}},Cf.prototype.findAll=function(t,e){var n=this;if(this.items){var i,r=this.items.length;for(i=0;i<r;i+=1){var o=n.items[i];o.findAll&&o.findAll(t,e)}}return e},Cf.prototype.findComponent=function(t){var e,n=this,i=this.items.length;for(e=0;e<i;e+=1){var r=n.items[e].findComponent(t);if(r)return r}},Cf.prototype.findAllComponents=function(t,e){var n=this;if(this.items){var i,r=this.items.length;for(i=0;i<r;i+=1){var o=n.items[i];o.findAllComponents&&o.findAllComponents(t,e)}}return e},Cf.prototype.findContext=function(){for(var t=this;t&&!t.context;)t=t.parent;return t?t.context:this.ractive.viewmodel},Cf.prototype.findNextNode=function(t){var e=this;if(t)for(var n=t.index+1;n<e.items.length;n++)if(e.items[n]){var i=e.items[n].firstNode(!0);if(i)return i}return this.isRoot?this.ractive.component?this.ractive.component.parentFragment.findNextNode(this.ractive.component):null:this.parent?this.owner.findNextNode(this):void 0},Cf.prototype.findParentNode=function(){var t=this;do{if(t.owner.type===Bh)return t.owner.node;if(t.isRoot&&!t.ractive.component)return t.ractive.el;t=t.owner.type===Uh?t.owner.containerFragment:t.componentParent||t.parent}while(t);throw new Error("Could not find parent node")},Cf.prototype.findRepeatingFragment=function(){for(var t=this;(t.parent||t.componentParent)&&!t.isIteration;)t=t.parent||t.componentParent;return t},Cf.prototype.firstNode=function(t){for(var e,n=this,i=0;i<n.items.length;i++)if(e=n.items[i].firstNode(!0))return e;return t?null:this.parent.findNextNode(this.owner)},Cf.prototype.getArgsList=function(){if(this.dirtyArgs){var t={},e=Lo(this.items,t,this.ractive._guid),n=Hn("["+e+"]",t);this.argsList=n?n.value:[this.toString()],this.dirtyArgs=!1}return this.argsList},Cf.prototype.rebinding=function(t){this.context=t},Cf.prototype.render=function(t,e){if(this.rendered)throw new Error("Fragment is already rendered!");this.rendered=!0,this.items.forEach(function(n){return n.render(t,e)})},Cf.prototype.resetTemplate=function(e){var n=this.bound,i=this.rendered;if(n&&(i&&this.unrender(!0),this.unbind()),this.template=e,this.createItems(),n&&(this.bind(this.context),i)){var r=this.findParentNode(),o=this.findNextNode();if(o){var s=t();this.render(s),r.insertBefore(s,o)}else this.render(r)}},Cf.prototype.resolve=function(t,e){if(!this.context&&this.parent.resolve)return this.parent.resolve(t,e);var n=new Qa(this,t,e);return this.resolvers.push(n),n},Cf.prototype.shuffled=function(){this.items.forEach(function(t){return t.shuffled()})},Cf.prototype.toHtml=function(){return this.toString()},Cf.prototype.toString=function(t){return this.items.map(t?Rt:It).join("")},Cf.prototype.unbind=function(){return this.items.forEach(Vt),this.resolvers.forEach(Vt),this.bound=!1,this},Cf.prototype.unrender=function(t){this.items.forEach(t?Do:Mt),this.rendered=!1},Cf.prototype.update=function(){this.dirty&&(this.updating?this.isRoot&&ia.addFragmentToRoot(this):(this.dirty=!1,this.updating=!0,this.items.forEach(Kt),this.updating=!1))},Cf.prototype.valueOf=function(){if(1===this.items.length)return this.items[0].valueOf();if(this.dirtyValue){var t={},e=Lo(this.items,t,this.ractive._guid),n=Hn(e,t);this.value=n?n.value:this.toString(),this.dirtyValue=!1}return this.value};var jf=Xt("reverse").path,Tf=Xt("shift").path,Ff=Xt("sort").path,Nf=Xt("splice").path,Pf=new Hs("teardown"),Vf=new Hs("unrender"),Mf=Xt("unshift").path,Bf={add:G,animate:X,detach:tt,find:et,findAll:st,findAllComponents:at,findComponent:ht,findContainer:ut,findParent:lt,fire:bt,get:Qt,getNodeInfo:Ie,insert:Re,link:De,merge:ne,observe:We,observeList:ze,observeOnce:qe,off:Qe,on:Ge,once:Ye,pop:th,push:eh,render:nn,reset:nr,resetPartial:or,resetTemplate:Wo,reverse:jf,set:Uo,shift:Tf,sort:Ff,splice:Nf,subtract:zo,teardown:$o,toggle:qo,toCSS:Zo,toCss:Zo,toHTML:Ho,toHtml:Ho,toText:Qo,transition:Go,unlink:Yo,unrender:Jo,unshift:Mf,update:re,updateModel:Xo};if("function"!=typeof Date.now||"function"!=typeof String.prototype.trim||"function"!=typeof Object.keys||"function"!=typeof Array.prototype.indexOf||"function"!=typeof Array.prototype.forEach||"function"!=typeof Array.prototype.map||"function"!=typeof Array.prototype.filter||ds&&"function"!=typeof ds.addEventListener)throw new Error("It looks like you're attempting to use Ractive.js in an older browser. You'll need to use one of the 'legacy builds' in order to continue - see http://docs.ractivejs.org/latest/legacy-builds for more information.");return s(ls.prototype,Bf,ps),ls.prototype.constructor=ls,ls.defaults=ls.prototype,Vs(ls,{DEBUG:{writable:!0,value:!0},DEBUG_PROMISES:{writable:!0,value:!0},extend:{value:ss},escapeKey:{value:D},getNodeInfo:{value:Ke},joinKeys:{value:hs},parse:{value:Ii},splitKeypath:{value:us},unescapeKey:{value:z},getCSS:{value:tn},Promise:{value:Xs},enhance:{writable:!0,value:!1},svg:{value:Ss},magic:{value:cs},VERSION:{value:"0.8.14"},adaptors:{writable:!0,value:{}},components:{writable:!0,value:{}},decorators:{writable:!0,value:{}},easing:{writable:!0,value:fs},events:{writable:!0,value:{}},interpolators:{writable:!0,value:qs},partials:{writable:!0,value:{}},transitions:{writable:!0,value:{}}}),ls});
//# sourceMappingURL=ractive.min.js.map
;/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = "./src/entries/dist.ts");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/src/index.js!./src/styles/style.css":
/*!******************************************************************************************************!*\
  !*** ./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/src!./src/styles/style.css ***!
  \******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../../node_modules/css-loader/dist/runtime/api.js */ "./node_modules/css-loader/dist/runtime/api.js");
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, ".h5p-advanced-blanks {\n    position: relative;\n}\n\n\n/* Text */\n\n.h5p-advanced-blanks #h5p-cloze-container p,\n.h5p-advanced-blanks #h5p-cloze-container div {\n    line-height: 1.8em;\n    margin: 0 0 1em;\n    text-align: justify;\n}\n\n@media only screen and (min-width: 480px) {\n    .h5p-advanced-blanks #h5p-cloze-container p,\n    .h5p-advanced-blanks #h5p-cloze-container div {\n        text-align: unset;\n    }\n}\n\n\n/* Input */\n\n.h5p-advanced-blanks .h5p-input-wrapper {\n    display: inline-block;\n    position: relative;\n}\n\n.h5p-advanced-blanks .blank .h5p-text-input {\n    font-family: H5PDroidSans, sans-serif;\n    font-size: 1em;\n    border-radius: 0.25em;\n    border: 1px solid #a0a0a0;\n    padding: 0.1875em 1.5em 0.1875em 0.5em;\n    text-overflow: ellipsis;\n    overflow: hidden;\n}\n\n.h5p-advanced-blanks .blank input.h5p-text-input {\n  max-width: calc(100vw - 64px);\n}\n\n.h5p-advanced-blanks .blank select.h5p-text-input {\n  max-width: calc(100vw - 36px);\n}\n\n/* IE + Chrome specific fixes */\n\n.h5p-text-input::-ms-clear {\n    display: none;\n}\n\n:not(.correct).blank.has-tip button {\n    cursor: pointer;\n}\n\n\n/* Select mode */\n\nselect.h5p-text-input {\n    appearance: button;\n    -moz-appearance: none;\n    -webkit-appearance: button;\n}\n\n\n/* Showing solution input */\n\n.h5p-advanced-blanks .blank.showing-solution .h5p-text-input {\n    border: 1px dashed #9dd8bb;\n    color: #255c41;\n    background: #FFFFFF;\n}\n\n\n/* Focussed input */\n\n.h5p-advanced-blanks .blank .h5p-text-input:focus {\n    outline: none;\n    box-shadow: 0 0 0.5em 0 #7fb8ff;\n    border-color: #7fb8ff;\n}\n\n\n/* Correctly answered input */\n\n.h5p-advanced-blanks .blank.correct .h5p-text-input {\n    background: #9dd8bb;\n    border: 1px solid #9dd8bb;\n    color: #255c41;\n}\n\n.h5p-advanced-blanks .blank.correct .h5p-input-wrapper:after {\n    position: absolute;\n    right: 0.5em;    \n    top: 50%;\n    transform: translateY(-50%);\n    text-decoration: none;\n    content: \"\\f00c\";\n    font-family: 'H5PFontAwesome4';\n    color: #255c41;\n}\n\n\n/* Incorrect answers */\n\n.h5p-advanced-blanks .blank.error .h5p-text-input {\n    background-color: #f7d0d0;\n    border: 1px solid #f7d0d0;\n    color: #b71c1c;\n    text-decoration: line-through;\n}\n\n.h5p-advanced-blanks .blank.error .h5p-input-wrapper:after {\n    position: absolute;\n    right: 0.5em;\n    top: 50%;\n    transform: translateY(-50%);\n    font-family: 'H5PFontAwesome4';\n    text-decoration: none;\n    content: \"\\f00d\";\n    color: #b71c1c;\n}\n\n\n/* Spelling errors */\n\n.h5p-advanced-blanks .blank.retry .h5p-text-input {\n    background-color: #ffff99;\n    border: 1px solid #ffff99;\n    color: black;\n}\n\n.h5p-advanced-blanks .blank.retry .h5p-input-wrapper:after {\n    position: absolute;\n    right: 0.5em;\n    top: 50%;\n    transform: translateY(-50%);\n    font-family: 'H5PFontAwesome4';\n    text-decoration: none;\n    content: \"\\f00d\";\n    color: #b71c1c;\n}\n\n\n/* Buttons */\n\n.h5p-advanced-blanks .blank button {\n    padding-left: 5px;\n    padding-right: 5px;\n    border: none;\n    background: none;\n}\n\n\n/* Highlight in spelling mistake marker */\n\n.spelling-mistake .missing-character,\n.spelling-mistake .mistaken-character {\n    color: red;\n    font-weight: bold;\n    -webkit-animation-duration: 500ms;\n            animation-duration: 500ms;\n    -webkit-animation-name: blink-color;\n            animation-name: blink-color;\n    -webkit-animation-iteration-count: 13;\n            animation-iteration-count: 13;\n    -webkit-animation-direction: alternate;\n            animation-direction: alternate;\n}\n\n@-webkit-keyframes blink-color {\n    from {\n        color: initial;\n    }\n    to {\n        color: red;\n    }\n}\n\n@keyframes blink-color {\n    from {\n        color: initial;\n    }\n    to {\n        color: red;\n    }\n}\n\n.spelling-mistake .mistaken-character {\n    text-decoration: line-through;\n}\n\n\n/* Highlights in text */\n\n.h5p-advanced-blanks .highlighted {\n    background-color: rgba(255, 0, 0, 0.2);\n    padding: 0.4em;\n    margin: -0.4em;\n    -webkit-animation-duration: 1000ms;\n            animation-duration: 1000ms;\n    -webkit-animation-name: blink-background-color;\n            animation-name: blink-background-color;\n    -webkit-animation-iteration-count: 3;\n            animation-iteration-count: 3;\n    -webkit-animation-direction: alternate;\n            animation-direction: alternate;\n}\n\n@-webkit-keyframes blink-background-color {\n    from {\n        background-color: initial;\n    }\n    to {\n        background-color: rgba(255, 0, 0, 0.2);\n    }\n}\n\n@keyframes blink-background-color {\n    from {\n        background-color: initial;\n    }\n    to {\n        background-color: rgba(255, 0, 0, 0.2);\n    }\n}\n\n\n/* Others */\n\n.h5p-advanced-blanks .invisible {\n    visibility: collapse;\n}\n\n\n/* Tips */\n\n.h5p-advanced-blanks .h5p-tip-container {\n  position: absolute;\n  top: 50%;\n  transform: translateY(-50%);\n  right: 0.4em;\n  font-size: 1em;\n}\n\n.h5p-advanced-blanks .blank.has-tip:not(.correct):not(.error):not(.retry) .h5p-text-input {\n    padding-right: 2.25em;\n}\n\n.h5p-advanced-blanks .blank.has-tip.correct .h5p-input-wrapper:after,\n.h5p-advanced-blanks .blank.has-tip.error .h5p-input-wrapper:after,\n.h5p-advanced-blanks .blank.has-tip.retry .h5p-input-wrapper:after {\n    right: 2.25em;\n}\n\n.h5p-advanced-blanks .blank.correct.has-tip .h5p-text-input,\n.h5p-advanced-blanks .blank.error.has-tip .h5p-text-input,\n.h5p-advanced-blanks .blank.retry.has-tip .h5p-text-input {\n    padding-right: 3.5em;\n}\n\n/* improves appearance of h5p tip shadows */\n.h5p-advanced-blanks .joubel-icon-tip-normal .h5p-icon-shadow:before {\n  color: black;\n  opacity: 0.13;\n}\n\n/* pending feedback marker */\n\n.h5p-advanced-blanks .h5p-advanced-blanks-select-mode .blank:not(.has-pending-feedback) button.h5p-notification {\n    display: none;\n}\n\n.h5p-advanced-blanks .h5p-advanced-blanks-select-mode .blank.has-pending-feedback button.h5p-notification {\n    font-size: large;    \n}\n\n.h5p-advanced-blanks .h5p-advanced-blanks-select-mode .blank.has-pending-feedback button.h5p-notification,\n.h5p-advanced-blanks .h5p-advanced-blanks-type-mode .blank.has-pending-feedback .h5p-input-wrapper:before {\n    font-family: 'H5PFontAwesome4';\n    text-decoration: none;\n    animation: shake 3s cubic-bezier(.36, .07, .19, .97) reverse;\n    -webkit-animation-iteration-count: 2;\n            animation-iteration-count: 2;\n    transform: translate3d(0, 0, 0);\n    -webkit-backface-visibility: hidden;\n            backface-visibility: hidden;\n    perspective: 1000px;\n}\n\n.h5p-advanced-blanks .h5p-advanced-blanks-type-mode .blank.has-pending-feedback .h5p-input-wrapper:before {\n    position: absolute;\n    left: -0.4em;\n    top: -0.7em;\n    content: \"\\f05a\";\n}\n\n.h5p-advanced-blanks .h5p-advanced-blanks-select-mode .blank.error.has-pending-feedback button.h5p-notification,\n.h5p-advanced-blanks .h5p-advanced-blanks-type-mode .blank.error.has-pending-feedback .h5p-input-wrapper:before {\n    color: #b71c1c;\n}\n\n.h5p-advanced-blanks .h5p-advanced-blanks-select-mode .blank.retry.has-pending-feedback button.h5p-notification,\n.h5p-advanced-blanks .h5p-advanced-blanks-type-mode .blank.retry.has-pending-feedback .h5p-input-wrapper:before {\n    color: #ffff00;\n    text-shadow: 0px 0px 0.5em black;\n}\n\n@-webkit-keyframes shake {\n    2%,\n    20% {\n        transform: translate3d(-0.5px, 0, 0);\n    }\n    4%,\n    17% {\n        transform: translate3d(1px, 0, 0);\n    }\n    6%,\n    10%,\n    15% {\n        transform: translate3d(-2px, 0, 0);\n    }\n    9%,\n    13% {\n        transform: translate3d(2px, 0, 0);\n    }\n}\n\n@keyframes shake {\n    2%,\n    20% {\n        transform: translate3d(-0.5px, 0, 0);\n    }\n    4%,\n    17% {\n        transform: translate3d(1px, 0, 0);\n    }\n    6%,\n    10%,\n    15% {\n        transform: translate3d(-2px, 0, 0);\n    }\n    9%,\n    13% {\n        transform: translate3d(2px, 0, 0);\n    }\n}", ""]);
// Exports
module.exports = exports;


/***/ }),

/***/ "./node_modules/css-loader/dist/runtime/api.js":
/*!*****************************************************!*\
  !*** ./node_modules/css-loader/dist/runtime/api.js ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function (useSourceMap) {
  var list = []; // return the list of modules as css string

  list.toString = function toString() {
    return this.map(function (item) {
      var content = cssWithMappingToString(item, useSourceMap);

      if (item[2]) {
        return "@media ".concat(item[2], " {").concat(content, "}");
      }

      return content;
    }).join('');
  }; // import a list of modules into the list
  // eslint-disable-next-line func-names


  list.i = function (modules, mediaQuery, dedupe) {
    if (typeof modules === 'string') {
      // eslint-disable-next-line no-param-reassign
      modules = [[null, modules, '']];
    }

    var alreadyImportedModules = {};

    if (dedupe) {
      for (var i = 0; i < this.length; i++) {
        // eslint-disable-next-line prefer-destructuring
        var id = this[i][0];

        if (id != null) {
          alreadyImportedModules[id] = true;
        }
      }
    }

    for (var _i = 0; _i < modules.length; _i++) {
      var item = [].concat(modules[_i]);

      if (dedupe && alreadyImportedModules[item[0]]) {
        // eslint-disable-next-line no-continue
        continue;
      }

      if (mediaQuery) {
        if (!item[2]) {
          item[2] = mediaQuery;
        } else {
          item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
        }
      }

      list.push(item);
    }
  };

  return list;
};

function cssWithMappingToString(item, useSourceMap) {
  var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring

  var cssMapping = item[3];

  if (!cssMapping) {
    return content;
  }

  if (useSourceMap && typeof btoa === 'function') {
    var sourceMapping = toComment(cssMapping);
    var sourceURLs = cssMapping.sources.map(function (source) {
      return "/*# sourceURL=".concat(cssMapping.sourceRoot || '').concat(source, " */");
    });
    return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
  }

  return [content].join('\n');
} // Adapted from convert-source-map (MIT)


function toComment(sourceMap) {
  // eslint-disable-next-line no-undef
  var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
  var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
  return "/*# ".concat(data, " */");
}

/***/ }),

/***/ "./node_modules/diff/dist/diff.js":
/*!****************************************!*\
  !*** ./node_modules/diff/dist/diff.js ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

(function (global, factory) {
   true ? factory(exports) :
  undefined;
}(this, (function (exports) { 'use strict';

  function Diff() {}
  Diff.prototype = {
    diff: function diff(oldString, newString) {
      var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      var callback = options.callback;

      if (typeof options === 'function') {
        callback = options;
        options = {};
      }

      this.options = options;
      var self = this;

      function done(value) {
        if (callback) {
          setTimeout(function () {
            callback(undefined, value);
          }, 0);
          return true;
        } else {
          return value;
        }
      } // Allow subclasses to massage the input prior to running


      oldString = this.castInput(oldString);
      newString = this.castInput(newString);
      oldString = this.removeEmpty(this.tokenize(oldString));
      newString = this.removeEmpty(this.tokenize(newString));
      var newLen = newString.length,
          oldLen = oldString.length;
      var editLength = 1;
      var maxEditLength = newLen + oldLen;
      var bestPath = [{
        newPos: -1,
        components: []
      }]; // Seed editLength = 0, i.e. the content starts with the same values

      var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);

      if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
        // Identity per the equality and tokenizer
        return done([{
          value: this.join(newString),
          count: newString.length
        }]);
      } // Main worker method. checks all permutations of a given edit length for acceptance.


      function execEditLength() {
        for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
          var basePath = void 0;

          var addPath = bestPath[diagonalPath - 1],
              removePath = bestPath[diagonalPath + 1],
              _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;

          if (addPath) {
            // No one else is going to attempt to use this value, clear it
            bestPath[diagonalPath - 1] = undefined;
          }

          var canAdd = addPath && addPath.newPos + 1 < newLen,
              canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;

          if (!canAdd && !canRemove) {
            // If this path is a terminal then prune
            bestPath[diagonalPath] = undefined;
            continue;
          } // Select the diagonal that we want to branch from. We select the prior
          // path whose position in the new string is the farthest from the origin
          // and does not pass the bounds of the diff graph


          if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
            basePath = clonePath(removePath);
            self.pushComponent(basePath.components, undefined, true);
          } else {
            basePath = addPath; // No need to clone, we've pulled it from the list

            basePath.newPos++;
            self.pushComponent(basePath.components, true, undefined);
          }

          _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done

          if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
            return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
          } else {
            // Otherwise track this path as a potential candidate and continue.
            bestPath[diagonalPath] = basePath;
          }
        }

        editLength++;
      } // Performs the length of edit iteration. Is a bit fugly as this has to support the
      // sync and async mode which is never fun. Loops over execEditLength until a value
      // is produced.


      if (callback) {
        (function exec() {
          setTimeout(function () {
            // This should not happen, but we want to be safe.

            /* istanbul ignore next */
            if (editLength > maxEditLength) {
              return callback();
            }

            if (!execEditLength()) {
              exec();
            }
          }, 0);
        })();
      } else {
        while (editLength <= maxEditLength) {
          var ret = execEditLength();

          if (ret) {
            return ret;
          }
        }
      }
    },
    pushComponent: function pushComponent(components, added, removed) {
      var last = components[components.length - 1];

      if (last && last.added === added && last.removed === removed) {
        // We need to clone here as the component clone operation is just
        // as shallow array clone
        components[components.length - 1] = {
          count: last.count + 1,
          added: added,
          removed: removed
        };
      } else {
        components.push({
          count: 1,
          added: added,
          removed: removed
        });
      }
    },
    extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
      var newLen = newString.length,
          oldLen = oldString.length,
          newPos = basePath.newPos,
          oldPos = newPos - diagonalPath,
          commonCount = 0;

      while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
        newPos++;
        oldPos++;
        commonCount++;
      }

      if (commonCount) {
        basePath.components.push({
          count: commonCount
        });
      }

      basePath.newPos = newPos;
      return oldPos;
    },
    equals: function equals(left, right) {
      if (this.options.comparator) {
        return this.options.comparator(left, right);
      } else {
        return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
      }
    },
    removeEmpty: function removeEmpty(array) {
      var ret = [];

      for (var i = 0; i < array.length; i++) {
        if (array[i]) {
          ret.push(array[i]);
        }
      }

      return ret;
    },
    castInput: function castInput(value) {
      return value;
    },
    tokenize: function tokenize(value) {
      return value.split('');
    },
    join: function join(chars) {
      return chars.join('');
    }
  };

  function buildValues(diff, components, newString, oldString, useLongestToken) {
    var componentPos = 0,
        componentLen = components.length,
        newPos = 0,
        oldPos = 0;

    for (; componentPos < componentLen; componentPos++) {
      var component = components[componentPos];

      if (!component.removed) {
        if (!component.added && useLongestToken) {
          var value = newString.slice(newPos, newPos + component.count);
          value = value.map(function (value, i) {
            var oldValue = oldString[oldPos + i];
            return oldValue.length > value.length ? oldValue : value;
          });
          component.value = diff.join(value);
        } else {
          component.value = diff.join(newString.slice(newPos, newPos + component.count));
        }

        newPos += component.count; // Common case

        if (!component.added) {
          oldPos += component.count;
        }
      } else {
        component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
        oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
        // The diffing algorithm is tied to add then remove output and this is the simplest
        // route to get the desired output with minimal overhead.

        if (componentPos && components[componentPos - 1].added) {
          var tmp = components[componentPos - 1];
          components[componentPos - 1] = components[componentPos];
          components[componentPos] = tmp;
        }
      }
    } // Special case handle for when one terminal is ignored (i.e. whitespace).
    // For this case we merge the terminal into the prior string and drop the change.
    // This is only available for string mode.


    var lastComponent = components[componentLen - 1];

    if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
      components[componentLen - 2].value += lastComponent.value;
      components.pop();
    }

    return components;
  }

  function clonePath(path) {
    return {
      newPos: path.newPos,
      components: path.components.slice(0)
    };
  }

  var characterDiff = new Diff();
  function diffChars(oldStr, newStr, options) {
    return characterDiff.diff(oldStr, newStr, options);
  }

  function generateOptions(options, defaults) {
    if (typeof options === 'function') {
      defaults.callback = options;
    } else if (options) {
      for (var name in options) {
        /* istanbul ignore else */
        if (options.hasOwnProperty(name)) {
          defaults[name] = options[name];
        }
      }
    }

    return defaults;
  }

  //
  // Ranges and exceptions:
  // Latin-1 Supplement, 0080–00FF
  //  - U+00D7  × Multiplication sign
  //  - U+00F7  ÷ Division sign
  // Latin Extended-A, 0100–017F
  // Latin Extended-B, 0180–024F
  // IPA Extensions, 0250–02AF
  // Spacing Modifier Letters, 02B0–02FF
  //  - U+02C7  ˇ &#711;  Caron
  //  - U+02D8  ˘ &#728;  Breve
  //  - U+02D9  ˙ &#729;  Dot Above
  //  - U+02DA  ˚ &#730;  Ring Above
  //  - U+02DB  ˛ &#731;  Ogonek
  //  - U+02DC  ˜ &#732;  Small Tilde
  //  - U+02DD  ˝ &#733;  Double Acute Accent
  // Latin Extended Additional, 1E00–1EFF

  var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
  var reWhitespace = /\S/;
  var wordDiff = new Diff();

  wordDiff.equals = function (left, right) {
    if (this.options.ignoreCase) {
      left = left.toLowerCase();
      right = right.toLowerCase();
    }

    return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
  };

  wordDiff.tokenize = function (value) {
    // All whitespace symbols except newline group into one token, each newline - in separate token
    var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.

    for (var i = 0; i < tokens.length - 1; i++) {
      // If we have an empty string in the next field and we have only word chars before and after, merge
      if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
        tokens[i] += tokens[i + 2];
        tokens.splice(i + 1, 2);
        i--;
      }
    }

    return tokens;
  };

  function diffWords(oldStr, newStr, options) {
    options = generateOptions(options, {
      ignoreWhitespace: true
    });
    return wordDiff.diff(oldStr, newStr, options);
  }
  function diffWordsWithSpace(oldStr, newStr, options) {
    return wordDiff.diff(oldStr, newStr, options);
  }

  var lineDiff = new Diff();

  lineDiff.tokenize = function (value) {
    var retLines = [],
        linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line

    if (!linesAndNewlines[linesAndNewlines.length - 1]) {
      linesAndNewlines.pop();
    } // Merge the content and line separators into single tokens


    for (var i = 0; i < linesAndNewlines.length; i++) {
      var line = linesAndNewlines[i];

      if (i % 2 && !this.options.newlineIsToken) {
        retLines[retLines.length - 1] += line;
      } else {
        if (this.options.ignoreWhitespace) {
          line = line.trim();
        }

        retLines.push(line);
      }
    }

    return retLines;
  };

  function diffLines(oldStr, newStr, callback) {
    return lineDiff.diff(oldStr, newStr, callback);
  }
  function diffTrimmedLines(oldStr, newStr, callback) {
    var options = generateOptions(callback, {
      ignoreWhitespace: true
    });
    return lineDiff.diff(oldStr, newStr, options);
  }

  var sentenceDiff = new Diff();

  sentenceDiff.tokenize = function (value) {
    return value.split(/(\S.+?[.!?])(?=\s+|$)/);
  };

  function diffSentences(oldStr, newStr, callback) {
    return sentenceDiff.diff(oldStr, newStr, callback);
  }

  var cssDiff = new Diff();

  cssDiff.tokenize = function (value) {
    return value.split(/([{}:;,]|\s+)/);
  };

  function diffCss(oldStr, newStr, callback) {
    return cssDiff.diff(oldStr, newStr, callback);
  }

  function _typeof(obj) {
    "@babel/helpers - typeof";

    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
      _typeof = function (obj) {
        return typeof obj;
      };
    } else {
      _typeof = function (obj) {
        return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
      };
    }

    return _typeof(obj);
  }

  function _toConsumableArray(arr) {
    return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  }

  function _arrayWithoutHoles(arr) {
    if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  }

  function _iterableToArray(iter) {
    if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
  }

  function _unsupportedIterableToArray(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _arrayLikeToArray(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(o);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  }

  function _arrayLikeToArray(arr, len) {
    if (len == null || len > arr.length) len = arr.length;

    for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];

    return arr2;
  }

  function _nonIterableSpread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }

  var objectPrototypeToString = Object.prototype.toString;
  var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
  // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:

  jsonDiff.useLongestToken = true;
  jsonDiff.tokenize = lineDiff.tokenize;

  jsonDiff.castInput = function (value) {
    var _this$options = this.options,
        undefinedReplacement = _this$options.undefinedReplacement,
        _this$options$stringi = _this$options.stringifyReplacer,
        stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
      return typeof v === 'undefined' ? undefinedReplacement : v;
    } : _this$options$stringi;
    return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, '  ');
  };

  jsonDiff.equals = function (left, right) {
    return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
  };

  function diffJson(oldObj, newObj, options) {
    return jsonDiff.diff(oldObj, newObj, options);
  } // This function handles the presence of circular references by bailing out when encountering an
  // object that is already on the "stack" of items being processed. Accepts an optional replacer

  function canonicalize(obj, stack, replacementStack, replacer, key) {
    stack = stack || [];
    replacementStack = replacementStack || [];

    if (replacer) {
      obj = replacer(key, obj);
    }

    var i;

    for (i = 0; i < stack.length; i += 1) {
      if (stack[i] === obj) {
        return replacementStack[i];
      }
    }

    var canonicalizedObj;

    if ('[object Array]' === objectPrototypeToString.call(obj)) {
      stack.push(obj);
      canonicalizedObj = new Array(obj.length);
      replacementStack.push(canonicalizedObj);

      for (i = 0; i < obj.length; i += 1) {
        canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
      }

      stack.pop();
      replacementStack.pop();
      return canonicalizedObj;
    }

    if (obj && obj.toJSON) {
      obj = obj.toJSON();
    }

    if (_typeof(obj) === 'object' && obj !== null) {
      stack.push(obj);
      canonicalizedObj = {};
      replacementStack.push(canonicalizedObj);

      var sortedKeys = [],
          _key;

      for (_key in obj) {
        /* istanbul ignore else */
        if (obj.hasOwnProperty(_key)) {
          sortedKeys.push(_key);
        }
      }

      sortedKeys.sort();

      for (i = 0; i < sortedKeys.length; i += 1) {
        _key = sortedKeys[i];
        canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
      }

      stack.pop();
      replacementStack.pop();
    } else {
      canonicalizedObj = obj;
    }

    return canonicalizedObj;
  }

  var arrayDiff = new Diff();

  arrayDiff.tokenize = function (value) {
    return value.slice();
  };

  arrayDiff.join = arrayDiff.removeEmpty = function (value) {
    return value;
  };

  function diffArrays(oldArr, newArr, callback) {
    return arrayDiff.diff(oldArr, newArr, callback);
  }

  function parsePatch(uniDiff) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
        delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
        list = [],
        i = 0;

    function parseIndex() {
      var index = {};
      list.push(index); // Parse diff metadata

      while (i < diffstr.length) {
        var line = diffstr[i]; // File header found, end parsing diff metadata

        if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
          break;
        } // Diff index


        var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);

        if (header) {
          index.index = header[1];
        }

        i++;
      } // Parse file headers if they are defined. Unified diff requires them, but
      // there's no technical issues to have an isolated hunk without file header


      parseFileHeader(index);
      parseFileHeader(index); // Parse hunks

      index.hunks = [];

      while (i < diffstr.length) {
        var _line = diffstr[i];

        if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
          break;
        } else if (/^@@/.test(_line)) {
          index.hunks.push(parseHunk());
        } else if (_line && options.strict) {
          // Ignore unexpected content unless in strict mode
          throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
        } else {
          i++;
        }
      }
    } // Parses the --- and +++ headers, if none are found, no lines
    // are consumed.


    function parseFileHeader(index) {
      var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);

      if (fileHeader) {
        var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
        var data = fileHeader[2].split('\t', 2);
        var fileName = data[0].replace(/\\\\/g, '\\');

        if (/^".*"$/.test(fileName)) {
          fileName = fileName.substr(1, fileName.length - 2);
        }

        index[keyPrefix + 'FileName'] = fileName;
        index[keyPrefix + 'Header'] = (data[1] || '').trim();
        i++;
      }
    } // Parses a hunk
    // This assumes that we are at the start of a hunk.


    function parseHunk() {
      var chunkHeaderIndex = i,
          chunkHeaderLine = diffstr[i++],
          chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
      var hunk = {
        oldStart: +chunkHeader[1],
        oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],
        newStart: +chunkHeader[3],
        newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],
        lines: [],
        linedelimiters: []
      }; // Unified Diff Format quirk: If the chunk size is 0,
      // the first number is one lower than one would expect.
      // https://www.artima.com/weblogs/viewpost.jsp?thread=164293

      if (hunk.oldLines === 0) {
        hunk.oldStart += 1;
      }

      if (hunk.newLines === 0) {
        hunk.newStart += 1;
      }

      var addCount = 0,
          removeCount = 0;

      for (; i < diffstr.length; i++) {
        // Lines starting with '---' could be mistaken for the "remove line" operation
        // But they could be the header for the next file. Therefore prune such cases out.
        if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
          break;
        }

        var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];

        if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
          hunk.lines.push(diffstr[i]);
          hunk.linedelimiters.push(delimiters[i] || '\n');

          if (operation === '+') {
            addCount++;
          } else if (operation === '-') {
            removeCount++;
          } else if (operation === ' ') {
            addCount++;
            removeCount++;
          }
        } else {
          break;
        }
      } // Handle the empty block count case


      if (!addCount && hunk.newLines === 1) {
        hunk.newLines = 0;
      }

      if (!removeCount && hunk.oldLines === 1) {
        hunk.oldLines = 0;
      } // Perform optional sanity checking


      if (options.strict) {
        if (addCount !== hunk.newLines) {
          throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
        }

        if (removeCount !== hunk.oldLines) {
          throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
        }
      }

      return hunk;
    }

    while (i < diffstr.length) {
      parseIndex();
    }

    return list;
  }

  // Iterator that traverses in the range of [min, max], stepping
  // by distance from a given start position. I.e. for [0, 4], with
  // start of 2, this will iterate 2, 3, 1, 4, 0.
  function distanceIterator (start, minLine, maxLine) {
    var wantForward = true,
        backwardExhausted = false,
        forwardExhausted = false,
        localOffset = 1;
    return function iterator() {
      if (wantForward && !forwardExhausted) {
        if (backwardExhausted) {
          localOffset++;
        } else {
          wantForward = false;
        } // Check if trying to fit beyond text length, and if not, check it fits
        // after offset location (or desired location on first iteration)


        if (start + localOffset <= maxLine) {
          return localOffset;
        }

        forwardExhausted = true;
      }

      if (!backwardExhausted) {
        if (!forwardExhausted) {
          wantForward = true;
        } // Check if trying to fit before text beginning, and if not, check it fits
        // before offset location


        if (minLine <= start - localOffset) {
          return -localOffset++;
        }

        backwardExhausted = true;
        return iterator();
      } // We tried to fit hunk before text beginning and beyond text length, then
      // hunk can't fit on the text. Return undefined

    };
  }

  function applyPatch(source, uniDiff) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

    if (typeof uniDiff === 'string') {
      uniDiff = parsePatch(uniDiff);
    }

    if (Array.isArray(uniDiff)) {
      if (uniDiff.length > 1) {
        throw new Error('applyPatch only works with a single input.');
      }

      uniDiff = uniDiff[0];
    } // Apply the diff to the input


    var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
        delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
        hunks = uniDiff.hunks,
        compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
      return line === patchContent;
    },
        errorCount = 0,
        fuzzFactor = options.fuzzFactor || 0,
        minLine = 0,
        offset = 0,
        removeEOFNL,
        addEOFNL;
    /**
     * Checks if the hunk exactly fits on the provided location
     */


    function hunkFits(hunk, toPos) {
      for (var j = 0; j < hunk.lines.length; j++) {
        var line = hunk.lines[j],
            operation = line.length > 0 ? line[0] : ' ',
            content = line.length > 0 ? line.substr(1) : line;

        if (operation === ' ' || operation === '-') {
          // Context sanity check
          if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
            errorCount++;

            if (errorCount > fuzzFactor) {
              return false;
            }
          }

          toPos++;
        }
      }

      return true;
    } // Search best fit offsets for each hunk based on the previous ones


    for (var i = 0; i < hunks.length; i++) {
      var hunk = hunks[i],
          maxLine = lines.length - hunk.oldLines,
          localOffset = 0,
          toPos = offset + hunk.oldStart - 1;
      var iterator = distanceIterator(toPos, minLine, maxLine);

      for (; localOffset !== undefined; localOffset = iterator()) {
        if (hunkFits(hunk, toPos + localOffset)) {
          hunk.offset = offset += localOffset;
          break;
        }
      }

      if (localOffset === undefined) {
        return false;
      } // Set lower text limit to end of the current hunk, so next ones don't try
      // to fit over already patched text


      minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
    } // Apply patch hunks


    var diffOffset = 0;

    for (var _i = 0; _i < hunks.length; _i++) {
      var _hunk = hunks[_i],
          _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;

      diffOffset += _hunk.newLines - _hunk.oldLines;

      for (var j = 0; j < _hunk.lines.length; j++) {
        var line = _hunk.lines[j],
            operation = line.length > 0 ? line[0] : ' ',
            content = line.length > 0 ? line.substr(1) : line,
            delimiter = _hunk.linedelimiters[j];

        if (operation === ' ') {
          _toPos++;
        } else if (operation === '-') {
          lines.splice(_toPos, 1);
          delimiters.splice(_toPos, 1);
          /* istanbul ignore else */
        } else if (operation === '+') {
          lines.splice(_toPos, 0, content);
          delimiters.splice(_toPos, 0, delimiter);
          _toPos++;
        } else if (operation === '\\') {
          var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;

          if (previousOperation === '+') {
            removeEOFNL = true;
          } else if (previousOperation === '-') {
            addEOFNL = true;
          }
        }
      }
    } // Handle EOFNL insertion/removal


    if (removeEOFNL) {
      while (!lines[lines.length - 1]) {
        lines.pop();
        delimiters.pop();
      }
    } else if (addEOFNL) {
      lines.push('');
      delimiters.push('\n');
    }

    for (var _k = 0; _k < lines.length - 1; _k++) {
      lines[_k] = lines[_k] + delimiters[_k];
    }

    return lines.join('');
  } // Wrapper that supports multiple file patches via callbacks.

  function applyPatches(uniDiff, options) {
    if (typeof uniDiff === 'string') {
      uniDiff = parsePatch(uniDiff);
    }

    var currentIndex = 0;

    function processIndex() {
      var index = uniDiff[currentIndex++];

      if (!index) {
        return options.complete();
      }

      options.loadFile(index, function (err, data) {
        if (err) {
          return options.complete(err);
        }

        var updatedContent = applyPatch(data, index, options);
        options.patched(index, updatedContent, function (err) {
          if (err) {
            return options.complete(err);
          }

          processIndex();
        });
      });
    }

    processIndex();
  }

  function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
    if (!options) {
      options = {};
    }

    if (typeof options.context === 'undefined') {
      options.context = 4;
    }

    var diff = diffLines(oldStr, newStr, options);
    diff.push({
      value: '',
      lines: []
    }); // Append an empty value to make cleanup easier

    function contextLines(lines) {
      return lines.map(function (entry) {
        return ' ' + entry;
      });
    }

    var hunks = [];
    var oldRangeStart = 0,
        newRangeStart = 0,
        curRange = [],
        oldLine = 1,
        newLine = 1;

    var _loop = function _loop(i) {
      var current = diff[i],
          lines = current.lines || current.value.replace(/\n$/, '').split('\n');
      current.lines = lines;

      if (current.added || current.removed) {
        var _curRange;

        // If we have previous context, start with that
        if (!oldRangeStart) {
          var prev = diff[i - 1];
          oldRangeStart = oldLine;
          newRangeStart = newLine;

          if (prev) {
            curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
            oldRangeStart -= curRange.length;
            newRangeStart -= curRange.length;
          }
        } // Output our changes


        (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
          return (current.added ? '+' : '-') + entry;
        }))); // Track the updated file position


        if (current.added) {
          newLine += lines.length;
        } else {
          oldLine += lines.length;
        }
      } else {
        // Identical context lines. Track line changes
        if (oldRangeStart) {
          // Close out any changes that have been output (or join overlapping)
          if (lines.length <= options.context * 2 && i < diff.length - 2) {
            var _curRange2;

            // Overlapping
            (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
          } else {
            var _curRange3;

            // end the range and output
            var contextSize = Math.min(lines.length, options.context);

            (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));

            var hunk = {
              oldStart: oldRangeStart,
              oldLines: oldLine - oldRangeStart + contextSize,
              newStart: newRangeStart,
              newLines: newLine - newRangeStart + contextSize,
              lines: curRange
            };

            if (i >= diff.length - 2 && lines.length <= options.context) {
              // EOF is inside this hunk
              var oldEOFNewline = /\n$/.test(oldStr);
              var newEOFNewline = /\n$/.test(newStr);
              var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;

              if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {
                // special case: old has no eol and no trailing context; no-nl can end up before adds
                // however, if the old file is empty, do not output the no-nl line
                curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
              }

              if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
                curRange.push('\\ No newline at end of file');
              }
            }

            hunks.push(hunk);
            oldRangeStart = 0;
            newRangeStart = 0;
            curRange = [];
          }
        }

        oldLine += lines.length;
        newLine += lines.length;
      }
    };

    for (var i = 0; i < diff.length; i++) {
      _loop(i);
    }

    return {
      oldFileName: oldFileName,
      newFileName: newFileName,
      oldHeader: oldHeader,
      newHeader: newHeader,
      hunks: hunks
    };
  }
  function formatPatch(diff) {
    var ret = [];

    if (diff.oldFileName == diff.newFileName) {
      ret.push('Index: ' + diff.oldFileName);
    }

    ret.push('===================================================================');
    ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
    ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));

    for (var i = 0; i < diff.hunks.length; i++) {
      var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0,
      // the first number is one lower than one would expect.
      // https://www.artima.com/weblogs/viewpost.jsp?thread=164293

      if (hunk.oldLines === 0) {
        hunk.oldStart -= 1;
      }

      if (hunk.newLines === 0) {
        hunk.newStart -= 1;
      }

      ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
      ret.push.apply(ret, hunk.lines);
    }

    return ret.join('\n') + '\n';
  }
  function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
    return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));
  }
  function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
    return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
  }

  function arrayEqual(a, b) {
    if (a.length !== b.length) {
      return false;
    }

    return arrayStartsWith(a, b);
  }
  function arrayStartsWith(array, start) {
    if (start.length > array.length) {
      return false;
    }

    for (var i = 0; i < start.length; i++) {
      if (start[i] !== array[i]) {
        return false;
      }
    }

    return true;
  }

  function calcLineCount(hunk) {
    var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
        oldLines = _calcOldNewLineCount.oldLines,
        newLines = _calcOldNewLineCount.newLines;

    if (oldLines !== undefined) {
      hunk.oldLines = oldLines;
    } else {
      delete hunk.oldLines;
    }

    if (newLines !== undefined) {
      hunk.newLines = newLines;
    } else {
      delete hunk.newLines;
    }
  }
  function merge(mine, theirs, base) {
    mine = loadPatch(mine, base);
    theirs = loadPatch(theirs, base);
    var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
    // Leaving sanity checks on this to the API consumer that may know more about the
    // meaning in their own context.

    if (mine.index || theirs.index) {
      ret.index = mine.index || theirs.index;
    }

    if (mine.newFileName || theirs.newFileName) {
      if (!fileNameChanged(mine)) {
        // No header or no change in ours, use theirs (and ours if theirs does not exist)
        ret.oldFileName = theirs.oldFileName || mine.oldFileName;
        ret.newFileName = theirs.newFileName || mine.newFileName;
        ret.oldHeader = theirs.oldHeader || mine.oldHeader;
        ret.newHeader = theirs.newHeader || mine.newHeader;
      } else if (!fileNameChanged(theirs)) {
        // No header or no change in theirs, use ours
        ret.oldFileName = mine.oldFileName;
        ret.newFileName = mine.newFileName;
        ret.oldHeader = mine.oldHeader;
        ret.newHeader = mine.newHeader;
      } else {
        // Both changed... figure it out
        ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
        ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
        ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
        ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
      }
    }

    ret.hunks = [];
    var mineIndex = 0,
        theirsIndex = 0,
        mineOffset = 0,
        theirsOffset = 0;

    while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
      var mineCurrent = mine.hunks[mineIndex] || {
        oldStart: Infinity
      },
          theirsCurrent = theirs.hunks[theirsIndex] || {
        oldStart: Infinity
      };

      if (hunkBefore(mineCurrent, theirsCurrent)) {
        // This patch does not overlap with any of the others, yay.
        ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
        mineIndex++;
        theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
      } else if (hunkBefore(theirsCurrent, mineCurrent)) {
        // This patch does not overlap with any of the others, yay.
        ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
        theirsIndex++;
        mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
      } else {
        // Overlap, merge as best we can
        var mergedHunk = {
          oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
          oldLines: 0,
          newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
          newLines: 0,
          lines: []
        };
        mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
        theirsIndex++;
        mineIndex++;
        ret.hunks.push(mergedHunk);
      }
    }

    return ret;
  }

  function loadPatch(param, base) {
    if (typeof param === 'string') {
      if (/^@@/m.test(param) || /^Index:/m.test(param)) {
        return parsePatch(param)[0];
      }

      if (!base) {
        throw new Error('Must provide a base reference or pass in a patch');
      }

      return structuredPatch(undefined, undefined, base, param);
    }

    return param;
  }

  function fileNameChanged(patch) {
    return patch.newFileName && patch.newFileName !== patch.oldFileName;
  }

  function selectField(index, mine, theirs) {
    if (mine === theirs) {
      return mine;
    } else {
      index.conflict = true;
      return {
        mine: mine,
        theirs: theirs
      };
    }
  }

  function hunkBefore(test, check) {
    return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
  }

  function cloneHunk(hunk, offset) {
    return {
      oldStart: hunk.oldStart,
      oldLines: hunk.oldLines,
      newStart: hunk.newStart + offset,
      newLines: hunk.newLines,
      lines: hunk.lines
    };
  }

  function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
    // This will generally result in a conflicted hunk, but there are cases where the context
    // is the only overlap where we can successfully merge the content here.
    var mine = {
      offset: mineOffset,
      lines: mineLines,
      index: 0
    },
        their = {
      offset: theirOffset,
      lines: theirLines,
      index: 0
    }; // Handle any leading content

    insertLeading(hunk, mine, their);
    insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.

    while (mine.index < mine.lines.length && their.index < their.lines.length) {
      var mineCurrent = mine.lines[mine.index],
          theirCurrent = their.lines[their.index];

      if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
        // Both modified ...
        mutualChange(hunk, mine, their);
      } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
        var _hunk$lines;

        // Mine inserted
        (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
      } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
        var _hunk$lines2;

        // Theirs inserted
        (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
      } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
        // Mine removed or edited
        removal(hunk, mine, their);
      } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
        // Their removed or edited
        removal(hunk, their, mine, true);
      } else if (mineCurrent === theirCurrent) {
        // Context identity
        hunk.lines.push(mineCurrent);
        mine.index++;
        their.index++;
      } else {
        // Context mismatch
        conflict(hunk, collectChange(mine), collectChange(their));
      }
    } // Now push anything that may be remaining


    insertTrailing(hunk, mine);
    insertTrailing(hunk, their);
    calcLineCount(hunk);
  }

  function mutualChange(hunk, mine, their) {
    var myChanges = collectChange(mine),
        theirChanges = collectChange(their);

    if (allRemoves(myChanges) && allRemoves(theirChanges)) {
      // Special case for remove changes that are supersets of one another
      if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
        var _hunk$lines3;

        (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));

        return;
      } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
        var _hunk$lines4;

        (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));

        return;
      }
    } else if (arrayEqual(myChanges, theirChanges)) {
      var _hunk$lines5;

      (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));

      return;
    }

    conflict(hunk, myChanges, theirChanges);
  }

  function removal(hunk, mine, their, swap) {
    var myChanges = collectChange(mine),
        theirChanges = collectContext(their, myChanges);

    if (theirChanges.merged) {
      var _hunk$lines6;

      (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
    } else {
      conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
    }
  }

  function conflict(hunk, mine, their) {
    hunk.conflict = true;
    hunk.lines.push({
      conflict: true,
      mine: mine,
      theirs: their
    });
  }

  function insertLeading(hunk, insert, their) {
    while (insert.offset < their.offset && insert.index < insert.lines.length) {
      var line = insert.lines[insert.index++];
      hunk.lines.push(line);
      insert.offset++;
    }
  }

  function insertTrailing(hunk, insert) {
    while (insert.index < insert.lines.length) {
      var line = insert.lines[insert.index++];
      hunk.lines.push(line);
    }
  }

  function collectChange(state) {
    var ret = [],
        operation = state.lines[state.index][0];

    while (state.index < state.lines.length) {
      var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.

      if (operation === '-' && line[0] === '+') {
        operation = '+';
      }

      if (operation === line[0]) {
        ret.push(line);
        state.index++;
      } else {
        break;
      }
    }

    return ret;
  }

  function collectContext(state, matchChanges) {
    var changes = [],
        merged = [],
        matchIndex = 0,
        contextChanges = false,
        conflicted = false;

    while (matchIndex < matchChanges.length && state.index < state.lines.length) {
      var change = state.lines[state.index],
          match = matchChanges[matchIndex]; // Once we've hit our add, then we are done

      if (match[0] === '+') {
        break;
      }

      contextChanges = contextChanges || change[0] !== ' ';
      merged.push(match);
      matchIndex++; // Consume any additions in the other block as a conflict to attempt
      // to pull in the remaining context after this

      if (change[0] === '+') {
        conflicted = true;

        while (change[0] === '+') {
          changes.push(change);
          change = state.lines[++state.index];
        }
      }

      if (match.substr(1) === change.substr(1)) {
        changes.push(change);
        state.index++;
      } else {
        conflicted = true;
      }
    }

    if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
      conflicted = true;
    }

    if (conflicted) {
      return changes;
    }

    while (matchIndex < matchChanges.length) {
      merged.push(matchChanges[matchIndex++]);
    }

    return {
      merged: merged,
      changes: changes
    };
  }

  function allRemoves(changes) {
    return changes.reduce(function (prev, change) {
      return prev && change[0] === '-';
    }, true);
  }

  function skipRemoveSuperset(state, removeChanges, delta) {
    for (var i = 0; i < delta; i++) {
      var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);

      if (state.lines[state.index + i] !== ' ' + changeContent) {
        return false;
      }
    }

    state.index += delta;
    return true;
  }

  function calcOldNewLineCount(lines) {
    var oldLines = 0;
    var newLines = 0;
    lines.forEach(function (line) {
      if (typeof line !== 'string') {
        var myCount = calcOldNewLineCount(line.mine);
        var theirCount = calcOldNewLineCount(line.theirs);

        if (oldLines !== undefined) {
          if (myCount.oldLines === theirCount.oldLines) {
            oldLines += myCount.oldLines;
          } else {
            oldLines = undefined;
          }
        }

        if (newLines !== undefined) {
          if (myCount.newLines === theirCount.newLines) {
            newLines += myCount.newLines;
          } else {
            newLines = undefined;
          }
        }
      } else {
        if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
          newLines++;
        }

        if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
          oldLines++;
        }
      }
    });
    return {
      oldLines: oldLines,
      newLines: newLines
    };
  }

  // See: http://code.google.com/p/google-diff-match-patch/wiki/API
  function convertChangesToDMP(changes) {
    var ret = [],
        change,
        operation;

    for (var i = 0; i < changes.length; i++) {
      change = changes[i];

      if (change.added) {
        operation = 1;
      } else if (change.removed) {
        operation = -1;
      } else {
        operation = 0;
      }

      ret.push([operation, change.value]);
    }

    return ret;
  }

  function convertChangesToXML(changes) {
    var ret = [];

    for (var i = 0; i < changes.length; i++) {
      var change = changes[i];

      if (change.added) {
        ret.push('<ins>');
      } else if (change.removed) {
        ret.push('<del>');
      }

      ret.push(escapeHTML(change.value));

      if (change.added) {
        ret.push('</ins>');
      } else if (change.removed) {
        ret.push('</del>');
      }
    }

    return ret.join('');
  }

  function escapeHTML(s) {
    var n = s;
    n = n.replace(/&/g, '&amp;');
    n = n.replace(/</g, '&lt;');
    n = n.replace(/>/g, '&gt;');
    n = n.replace(/"/g, '&quot;');
    return n;
  }

  exports.Diff = Diff;
  exports.applyPatch = applyPatch;
  exports.applyPatches = applyPatches;
  exports.canonicalize = canonicalize;
  exports.convertChangesToDMP = convertChangesToDMP;
  exports.convertChangesToXML = convertChangesToXML;
  exports.createPatch = createPatch;
  exports.createTwoFilesPatch = createTwoFilesPatch;
  exports.diffArrays = diffArrays;
  exports.diffChars = diffChars;
  exports.diffCss = diffCss;
  exports.diffJson = diffJson;
  exports.diffLines = diffLines;
  exports.diffSentences = diffSentences;
  exports.diffTrimmedLines = diffTrimmedLines;
  exports.diffWords = diffWords;
  exports.diffWordsWithSpace = diffWordsWithSpace;
  exports.merge = merge;
  exports.parsePatch = parsePatch;
  exports.structuredPatch = structuredPatch;

  Object.defineProperty(exports, '__esModule', { value: true });

})));


/***/ }),

/***/ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js":
/*!****************************************************************************!*\
  !*** ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***!
  \****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var isOldIE = function isOldIE() {
  var memo;
  return function memorize() {
    if (typeof memo === 'undefined') {
      // Test for IE <= 9 as proposed by Browserhacks
      // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
      // Tests for existence of standard globals is to allow style-loader
      // to operate correctly into non-standard environments
      // @see https://github.com/webpack-contrib/style-loader/issues/177
      memo = Boolean(window && document && document.all && !window.atob);
    }

    return memo;
  };
}();

var getTarget = function getTarget() {
  var memo = {};
  return function memorize(target) {
    if (typeof memo[target] === 'undefined') {
      var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself

      if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
        try {
          // This will throw an exception if access to iframe is blocked
          // due to cross-origin restrictions
          styleTarget = styleTarget.contentDocument.head;
        } catch (e) {
          // istanbul ignore next
          styleTarget = null;
        }
      }

      memo[target] = styleTarget;
    }

    return memo[target];
  };
}();

var stylesInDom = [];

function getIndexByIdentifier(identifier) {
  var result = -1;

  for (var i = 0; i < stylesInDom.length; i++) {
    if (stylesInDom[i].identifier === identifier) {
      result = i;
      break;
    }
  }

  return result;
}

function modulesToDom(list, options) {
  var idCountMap = {};
  var identifiers = [];

  for (var i = 0; i < list.length; i++) {
    var item = list[i];
    var id = options.base ? item[0] + options.base : item[0];
    var count = idCountMap[id] || 0;
    var identifier = "".concat(id, " ").concat(count);
    idCountMap[id] = count + 1;
    var index = getIndexByIdentifier(identifier);
    var obj = {
      css: item[1],
      media: item[2],
      sourceMap: item[3]
    };

    if (index !== -1) {
      stylesInDom[index].references++;
      stylesInDom[index].updater(obj);
    } else {
      stylesInDom.push({
        identifier: identifier,
        updater: addStyle(obj, options),
        references: 1
      });
    }

    identifiers.push(identifier);
  }

  return identifiers;
}

function insertStyleElement(options) {
  var style = document.createElement('style');
  var attributes = options.attributes || {};

  if (typeof attributes.nonce === 'undefined') {
    var nonce =  true ? __webpack_require__.nc : undefined;

    if (nonce) {
      attributes.nonce = nonce;
    }
  }

  Object.keys(attributes).forEach(function (key) {
    style.setAttribute(key, attributes[key]);
  });

  if (typeof options.insert === 'function') {
    options.insert(style);
  } else {
    var target = getTarget(options.insert || 'head');

    if (!target) {
      throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
    }

    target.appendChild(style);
  }

  return style;
}

function removeStyleElement(style) {
  // istanbul ignore if
  if (style.parentNode === null) {
    return false;
  }

  style.parentNode.removeChild(style);
}
/* istanbul ignore next  */


var replaceText = function replaceText() {
  var textStore = [];
  return function replace(index, replacement) {
    textStore[index] = replacement;
    return textStore.filter(Boolean).join('\n');
  };
}();

function applyToSingletonTag(style, index, remove, obj) {
  var css = remove ? '' : obj.media ? "@media ".concat(obj.media, " {").concat(obj.css, "}") : obj.css; // For old IE

  /* istanbul ignore if  */

  if (style.styleSheet) {
    style.styleSheet.cssText = replaceText(index, css);
  } else {
    var cssNode = document.createTextNode(css);
    var childNodes = style.childNodes;

    if (childNodes[index]) {
      style.removeChild(childNodes[index]);
    }

    if (childNodes.length) {
      style.insertBefore(cssNode, childNodes[index]);
    } else {
      style.appendChild(cssNode);
    }
  }
}

function applyToTag(style, options, obj) {
  var css = obj.css;
  var media = obj.media;
  var sourceMap = obj.sourceMap;

  if (media) {
    style.setAttribute('media', media);
  } else {
    style.removeAttribute('media');
  }

  if (sourceMap && typeof btoa !== 'undefined') {
    css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */");
  } // For old IE

  /* istanbul ignore if  */


  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    while (style.firstChild) {
      style.removeChild(style.firstChild);
    }

    style.appendChild(document.createTextNode(css));
  }
}

var singleton = null;
var singletonCounter = 0;

function addStyle(obj, options) {
  var style;
  var update;
  var remove;

  if (options.singleton) {
    var styleIndex = singletonCounter++;
    style = singleton || (singleton = insertStyleElement(options));
    update = applyToSingletonTag.bind(null, style, styleIndex, false);
    remove = applyToSingletonTag.bind(null, style, styleIndex, true);
  } else {
    style = insertStyleElement(options);
    update = applyToTag.bind(null, style, options);

    remove = function remove() {
      removeStyleElement(style);
    };
  }

  update(obj);
  return function updateStyle(newObj) {
    if (newObj) {
      if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) {
        return;
      }

      update(obj = newObj);
    } else {
      remove();
    }
  };
}

module.exports = function (list, options) {
  options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
  // tags it will allow on a page

  if (!options.singleton && typeof options.singleton !== 'boolean') {
    options.singleton = isOldIE();
  }

  list = list || [];
  var lastIdentifiers = modulesToDom(list, options);
  return function update(newList) {
    newList = newList || [];

    if (Object.prototype.toString.call(newList) !== '[object Array]') {
      return;
    }

    for (var i = 0; i < lastIdentifiers.length; i++) {
      var identifier = lastIdentifiers[i];
      var index = getIndexByIdentifier(identifier);
      stylesInDom[index].references--;
    }

    var newLastIdentifiers = modulesToDom(newList, options);

    for (var _i = 0; _i < lastIdentifiers.length; _i++) {
      var _identifier = lastIdentifiers[_i];

      var _index = getIndexByIdentifier(_identifier);

      if (stylesInDom[_index].references === 0) {
        stylesInDom[_index].updater();

        stylesInDom.splice(_index, 1);
      }
    }

    lastIdentifiers = newLastIdentifiers;
  };
};

/***/ }),

/***/ "./src/entries/dist.ts":
/*!*****************************!*\
  !*** ./src/entries/dist.ts ***!
  \*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(/*! ../styles/style.css */ "./src/styles/style.css");
var app_1 = __webpack_require__(/*! ../scripts/app */ "./src/scripts/app.ts");
// Load library
H5P = H5P || {};
H5P.AdvancedBlanks = app_1.default;


/***/ }),

/***/ "./src/lib/helpers.ts":
/*!****************************!*\
  !*** ./src/lib/helpers.ts ***!
  \****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.shuffleArray = exports.getLongestString = void 0;
function getLongestString(strings) {
    return strings.reduce(function (prev, current) { return current.length > prev.length ? current : prev; }, "");
}
exports.getLongestString = getLongestString;
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
exports.shuffleArray = shuffleArray;


/***/ }),

/***/ "./src/lib/ractive-events-keys.ts":
/*!****************************************!*\
  !*** ./src/lib/ractive-events-keys.ts ***!
  \****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.anykey = exports.uparrow = exports.downarrow = exports.rightarrow = exports.leftarrow = exports.space = exports.escape = exports.tab = exports.enter = void 0;
// TODO can we just declare the keydownHandler once? using `this`?
function makeKeyDefinition(code) {
    return function (node, fire) {
        function keydownHandler(event) {
            var which = event.which || event.keyCode;
            if (code && which === code) {
                event.preventDefault();
                fire({
                    node: node,
                    original: event
                });
            }
            else if (!code && [16, 17, 18, 35, 36, 13, 9, 27, 32, 37, 39, 40, 38].filter(function (c) { return c === which; }).length === 0) {
                fire({
                    node: node,
                    original: event
                });
            }
        }
        node.addEventListener('keydown', keydownHandler, false);
        return {
            teardown: function () {
                node.removeEventListener('keydown', keydownHandler, false);
            }
        };
    };
}
exports.enter = makeKeyDefinition(13);
exports.tab = makeKeyDefinition(9);
exports.escape = makeKeyDefinition(27);
exports.space = makeKeyDefinition(32);
exports.leftarrow = makeKeyDefinition(37);
exports.rightarrow = makeKeyDefinition(39);
exports.downarrow = makeKeyDefinition(40);
exports.uparrow = makeKeyDefinition(38);
exports.anykey = makeKeyDefinition();


/***/ }),

/***/ "./src/scripts/app.ts":
/*!****************************!*\
  !*** ./src/scripts/app.ts ***!
  \****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var blank_loader_1 = __webpack_require__(/*! ./content-loaders/blank-loader */ "./src/scripts/content-loaders/blank-loader.ts");
var data_repository_1 = __webpack_require__(/*! ./services/data-repository */ "./src/scripts/services/data-repository.ts");
var cloze_controller_1 = __webpack_require__(/*! ./controllers/cloze-controller */ "./src/scripts/controllers/cloze-controller.ts");
var localization_1 = __webpack_require__(/*! ./services/localization */ "./src/scripts/services/localization.ts");
var settings_1 = __webpack_require__(/*! ./services/settings */ "./src/scripts/services/settings.ts");
var message_service_1 = __webpack_require__(/*! ./services/message-service */ "./src/scripts/services/message-service.ts");
var unwrapper_1 = __webpack_require__(/*! ./helpers/unwrapper */ "./src/scripts/helpers/unwrapper.ts");
var xapi_1 = __webpack_require__(/*! ./models/xapi */ "./src/scripts/models/xapi.ts");
var extend_1 = __webpack_require__(/*! ./helpers/extend */ "./src/scripts/helpers/extend.ts");
var States;
(function (States) {
    States["ongoing"] = "ongoing";
    States["checking"] = "checking";
    States["showingSolutions"] = "showing-solution";
    States["finished"] = "finished";
    States["showingSolutionsEmbedded"] = "showing-solution-embedded";
})(States || (States = {}));
var XAPI_ALTERNATIVE_EXTENSION = 'https://h5p.org/x-api/alternatives';
var XAPI_CASE_SENSITIVITY = 'https://h5p.org/x-api/case-sensitivity';
var XAPI_REPORTING_VERSION_EXTENSION = 'https://h5p.org/x-api/h5p-reporting-version';
var AdvancedBlanks = /** @class */ (function (_super) {
    __extends(AdvancedBlanks, _super);
    /**
     * @constructor
     *
     * @param {object} config
     * @param {string} contentId
     * @param {object} contentData
     */
    function AdvancedBlanks(config, contentId, contentData) {
        if (contentData === void 0) { contentData = {}; }
        var _this = _super.call(this) || this;
        /**
         * Indicates if user has entered any answer so far.
         */
        _this.answered = false;
        /**
         * Called from outside when the score of the cloze has changed.
         */
        _this.onScoreChanged = function (score, maxScore) {
            if (_this.clozeController.isFullyFilledOut) {
                _this.transitionState();
                if (_this.state !== States.finished)
                    _this.state = States.checking;
                _this.showFeedback();
            }
            else {
                _this.setFeedback("", score, maxScore);
            }
            _this.transitionState();
            _this.toggleButtonVisibility(_this.state);
        };
        _this.onTyped = function () {
            if (_this.state === States.checking) {
                _this.state = States.ongoing;
                _this.toggleButtonVisibility(_this.state);
            }
            _this.answered = true;
        };
        _this.onAutoChecked = function () {
            _this.triggerXAPI('interacted');
            if (_this.clozeController.isFullyFilledOut) {
                _this.triggerXAPIAnswered();
            }
        };
        /**
         * Called by H5P.Question.attach(). Creates all content elements and registers them
         * with H5P.Question.
         */
        _this.registerDomElements = function () {
            this.registerMedia();
            this.setIntroduction(this.repository.getTaskDescription());
            this.container = this.jQuery("<div/>", { "class": "h5p-advanced-blanks" });
            this.setContent(this.container);
            this.registerButtons();
            this.moveToState(States.ongoing);
        };
        _this.onCheckAnswer = function () {
            _this.clozeController.checkAll();
            _this.triggerXAPI('interacted');
            _this.triggerXAPIAnswered();
            _this.transitionState();
            if (_this.state !== States.finished)
                _this.state = States.checking;
            _this.showFeedback();
            _this.toggleButtonVisibility(_this.state);
        };
        _this.transitionState = function () {
            if (_this.clozeController.isSolved) {
                _this.moveToState(States.finished);
            }
        };
        _this.onShowSolution = function () {
            _this.moveToState(States.showingSolutions);
            _this.clozeController.showSolutions();
            _this.showFeedback();
        };
        _this.onRetry = function () {
            _this.removeFeedback();
            _this.clozeController.reset();
            _this.answered = false;
            _this.moveToState(States.ongoing);
            // Reset timer
            _this.setActivityStarted(true);
        };
        _this.getCurrentState = function () {
            return _this.clozeController.serializeCloze();
        };
        /****************************************
         * Implementation of Question contract  *
         ****************************************/
        _this.getAnswerGiven = function () {
            return _this.answered || _this.clozeController.maxScore === 0;
        };
        _this.getScore = function () {
            return _this.clozeController.currentScore;
        };
        _this.getMaxScore = function () {
            return _this.clozeController.maxScore;
        };
        _this.showSolutions = function () {
            _this.onShowSolution();
            _this.moveToState(States.showingSolutionsEmbedded);
        };
        _this.resetTask = function () {
            _this.onRetry();
        };
        /***
         * XApi implementation
         */
        /**
         * Trigger xAPI answered event
         */
        _this.triggerXAPIAnswered = function () {
            _this.answered = true;
            var xAPIEvent = _this.createXAPIEventTemplate('answered');
            _this.addQuestionToXAPI(xAPIEvent);
            _this.addResponseToXAPI(xAPIEvent);
            _this.trigger(xAPIEvent);
        };
        /**
         * Get xAPI data.
         * Contract used by report rendering engine.
         *
         * @see contract at {@link https://h5p.org/documentation/developers/contracts#guides-header-6}
         */
        _this.getXAPIData = function () {
            var xAPIEvent = _this.createXAPIEventTemplate('answered');
            _this.addQuestionToXAPI(xAPIEvent);
            _this.addResponseToXAPI(xAPIEvent);
            return {
                statement: xAPIEvent.data.statement
            };
        };
        /**
         * Generate xAPI object definition used in xAPI statements.
         * @return {Object}
         */
        _this.getxAPIDefinition = function () {
            var definition = new xapi_1.XAPIActivityDefinition();
            definition.description = {
                'en-US': '<p>' + _this.repository.getTaskDescription() + '</p>' + _this.repository.getClozeText().replace(/__(_)+/g, '__________').replace(/!!/g, '')
            };
            definition.type = 'http://adlnet.gov/expapi/activities/cmi.interaction';
            definition.interactionType = 'fill-in'; // We use the 'fill-in' type even in select mode, as the xAPI format for selections doesn't really cater for sequences.
            var correctResponsesPatternPrefix = '{case_matters=' + _this.settings.caseSensitive + '}';
            var correctAnswerList = _this.clozeController.getCorrectAnswerList();
            // H5P uses extension instead of full correct responses pattern to counter complexity
            var firstAlternatives = correctAnswerList.reduce(function (result, list) {
                result.push(list[0]);
                return result;
            }, []).join('[,]');
            definition.correctResponsesPattern = ["" + correctResponsesPatternPrefix + firstAlternatives];
            // Add the H5P Alternative extension which provides all the combinations of different answers
            // Reporting software will need to support this extension for alternatives to work.
            definition.extensions = definition.extensions || {};
            definition.extensions[XAPI_CASE_SENSITIVITY] = _this.settings.caseSensitive;
            definition.extensions[XAPI_ALTERNATIVE_EXTENSION] = correctAnswerList;
            return definition;
        };
        /**
         * Add the question itself to the definition part of an xAPIEvent
         */
        _this.addQuestionToXAPI = function (xAPIEvent) {
            var definition = xAPIEvent.getVerifiedStatementValue(['object', 'definition']);
            _this.jQuery.extend(true, definition, _this.getxAPIDefinition());
            // Set reporting module version if alternative extension is used
            if (_this.clozeController.hasAlternatives) {
                var context = xAPIEvent.getVerifiedStatementValue(['context']);
                context.extensions = context.extensions || {};
                context.extensions[XAPI_REPORTING_VERSION_EXTENSION] = '1.0.0';
            }
        };
        /**
         * Add the response part to an xAPI event
         *
         * @param {H5P.XAPIEvent} xAPIEvent
         *  The xAPI event we will add a response to
         */
        _this.addResponseToXAPI = function (xAPIEvent) {
            xAPIEvent.setScoredResult(_this.clozeController.currentScore, _this.clozeController.maxScore, _this);
            xAPIEvent.data.statement.result.response = _this.getxAPIResponse();
        };
        /**
         * Generate xAPI user response, used in xAPI statements.
         * @return {string} User answers separated by the "[,]" pattern
         */
        _this.getxAPIResponse = function () {
            var usersAnswers = _this.getCurrentState();
            return usersAnswers.join('[,]');
        };
        // Set mandatory default values for editor widgets that create content type instances
        config = extend_1.extend({
            content: {
                blanksText: ''
            },
            behaviour: {
                mode: 'typing',
                selectAlternatives: 'alternatives'
            },
            submitAnswer: 'Submit',
        }, config);
        _this.jQuery = H5P.jQuery;
        _this.contentId = contentId;
        _this.contentData = contentData;
        var unwrapper = new unwrapper_1.Unrwapper(_this.jQuery);
        _this.settings = new settings_1.H5PSettings(config);
        _this.localization = new localization_1.H5PLocalization(config);
        _this.repository = new data_repository_1.H5PDataRepository(config, _this.settings, _this.localization, _this.jQuery, unwrapper);
        _this.messageService = new message_service_1.MessageService(_this.jQuery);
        blank_loader_1.BlankLoader.initialize(_this.settings, _this.localization, _this.jQuery, _this.messageService);
        _this.clozeController = new cloze_controller_1.ClozeController(_this.repository, _this.settings, _this.localization, _this.messageService);
        _this.clozeController.onScoreChanged = _this.onScoreChanged;
        _this.clozeController.onSolved = _this.onSolved;
        _this.clozeController.onAutoChecked = _this.onAutoChecked;
        _this.clozeController.onTyped = _this.onTyped;
        _this.clozeController.onTextChanged = function () { return _this.triggerXAPI('interacted'); };
        if (contentData && contentData.previousState)
            _this.previousState = contentData.previousState;
        /**
        * Overrides the attach method of the superclass (H5P.Question) and calls it
        * at the same time. (equivalent to super.attach($container)).
        * This is necessary, as Ractive needs to be initialized with an existing DOM
        * element. DOM elements are created in H5P.Question.attach, so initializing
        * Ractive in registerDomElements doesn't work.
        */
        _this.attach = (function (original) {
            return function ($container) {
                original($container);
                _this.clozeController.initialize(_this.container.get(0), $container);
                if (_this.clozeController.deserializeCloze(_this.previousState)) {
                    _this.answered = _this.clozeController.isFilledOut;
                    if (_this.settings.autoCheck)
                        _this.onCheckAnswer();
                    _this.toggleButtonVisibility(_this.state);
                }
            };
        })(_this.attach);
        return _this;
    }
    AdvancedBlanks.prototype.onSolved = function () {
    };
    /**
     * @returns JQuery - The outer h5p container. The library can add dialogues to this
     * element.
     */
    AdvancedBlanks.prototype.getH5pContainer = function () {
        var $content = this.jQuery('[data-content-id="' + this.contentId + '"].h5p-content');
        var $containerParents = $content.parents('.h5p-container');
        // select find container to attach dialogs to
        var $container;
        if ($containerParents.length !== 0) {
            // use parent highest up if any
            $container = $containerParents.last();
        }
        else if ($content.length !== 0) {
            $container = $content;
        }
        else {
            $container = this.jQuery(document.body);
        }
        return $container;
    };
    AdvancedBlanks.prototype.registerMedia = function () {
        var media = this.repository.getMedia();
        if (!media || !media.library)
            return;
        var type = media.library.split(' ')[0];
        if (type === 'H5P.Image') {
            if (media.params.file) {
                this.setImage(media.params.file.path, {
                    disableImageZooming: this.settings.disableImageZooming,
                    alt: media.params.alt
                });
            }
        }
        else if (type === 'H5P.Video') {
            if (media.params.sources) {
                this.setVideo(media);
            }
        }
    };
    AdvancedBlanks.prototype.registerButtons = function () {
        var $container = this.getH5pContainer();
        if (!this.settings.autoCheck) {
            // Check answer button
            this.addButton('check-answer', this.localization.getTextFromLabel(localization_1.LocalizationLabels.checkAllButton), this.onCheckAnswer, true, {}, {
                confirmationDialog: {
                    enable: this.settings.confirmCheckDialog,
                    l10n: this.localization.getObjectForStructure(localization_1.LocalizationStructures.confirmCheck),
                    instance: this,
                    $parentElement: $container,
                },
                contentData: this.contentData,
                textIfSubmitting: this.localization.getTextFromLabel(localization_1.LocalizationLabels.submitAllButton),
            });
        }
        // Show solution button
        this.addButton('show-solution', this.localization.getTextFromLabel(localization_1.LocalizationLabels.showSolutionButton), this.onShowSolution, this.settings.enableSolutionsButton);
        // Try again button
        if (this.settings.enableRetry === true) {
            this.addButton('try-again', this.localization.getTextFromLabel(localization_1.LocalizationLabels.retryButton), this.onRetry, true, {}, {
                confirmationDialog: {
                    enable: this.settings.confirmRetryDialog,
                    l10n: this.localization.getObjectForStructure(localization_1.LocalizationStructures.confirmRetry),
                    instance: this,
                    $parentElement: $container
                }
            });
        }
    };
    AdvancedBlanks.prototype.showFeedback = function () {
        var scoreText = H5P.Question.determineOverallFeedback(this.localization.getObjectForStructure(localization_1.LocalizationStructures.overallFeedback), this.clozeController.currentScore / this.clozeController.maxScore).replace('@score', this.clozeController.currentScore).replace('@total', this.clozeController.maxScore);
        this.setFeedback(scoreText, this.clozeController.currentScore, this.clozeController.maxScore, this.localization.getTextFromLabel(localization_1.LocalizationLabels.scoreBarLabel));
    };
    /**
     * Shows are hides buttons depending on the current state and settings made
     * by the content creator.
     * @param  {States} state
     */
    AdvancedBlanks.prototype.moveToState = function (state) {
        this.state = state;
        this.toggleButtonVisibility(state);
    };
    AdvancedBlanks.prototype.toggleButtonVisibility = function (state) {
        if (this.settings.enableSolutionsButton) {
            if (((state === States.checking)
                || (this.settings.autoCheck && state === States.ongoing))
                && (!this.settings.showSolutionsRequiresInput || this.clozeController.allBlanksEntered)) {
                this.showButton('show-solution');
            }
            else {
                this.hideButton('show-solution');
            }
        }
        if (this.settings.enableRetry && (state === States.checking || state === States.finished || state === States.showingSolutions)) {
            this.showButton('try-again');
        }
        else {
            this.hideButton('try-again');
        }
        if (state === States.ongoing && this.settings.enableCheckButton) {
            this.showButton('check-answer');
        }
        else {
            this.hideButton('check-answer');
        }
        if (state === States.showingSolutionsEmbedded) {
            this.hideButton('check-answer');
            this.hideButton('try-again');
            this.hideButton('show-solution');
        }
        this.trigger('resize');
    };
    return AdvancedBlanks;
}(H5P.Question));
exports.default = AdvancedBlanks;


/***/ }),

/***/ "./src/scripts/content-loaders/blank-loader.ts":
/*!*****************************************************!*\
  !*** ./src/scripts/content-loaders/blank-loader.ts ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.BlankLoader = void 0;
var answer_1 = __webpack_require__(/*! ../models/answer */ "./src/scripts/models/answer.ts");
var blank_1 = __webpack_require__(/*! ../models/blank */ "./src/scripts/models/blank.ts");
var message_1 = __webpack_require__(/*! ../models/message */ "./src/scripts/models/message.ts");
var BlankLoader = /** @class */ (function () {
    function BlankLoader(settings, localization, jquery, messageService) {
        this.settings = settings;
        this.localization = localization;
        this.jquery = jquery;
        this.messageService = messageService;
    }
    BlankLoader.initialize = function (settings, localization, jquery, messageService) {
        this._instance = new BlankLoader(settings, localization, jquery, messageService);
        return this._instance;
    };
    Object.defineProperty(BlankLoader, "instance", {
        get: function () {
            if (this._instance)
                return this._instance;
            throw "BlankLoader must be initialized before use.";
        },
        enumerable: false,
        configurable: true
    });
    BlankLoader.prototype.decodeHtml = function (html) {
        var elem = document.createElement('textarea');
        elem.innerHTML = html;
        return elem.value;
    };
    BlankLoader.prototype.createBlank = function (id, correctText, hintText, incorrectAnswers) {
        var blank = new blank_1.Blank(this.settings, this.localization, this.jquery, this.messageService, id);
        if (correctText) {
            correctText = this.decodeHtml(correctText);
            blank.addCorrectAnswer(new answer_1.Answer(correctText, "", false, 0, this.settings));
        }
        blank.setHint(new message_1.Message(hintText ? hintText : "", false, 0));
        if (incorrectAnswers) {
            for (var _i = 0, incorrectAnswers_1 = incorrectAnswers; _i < incorrectAnswers_1.length; _i++) {
                var h5pIncorrectAnswer = incorrectAnswers_1[_i];
                blank.addIncorrectAnswer(this.decodeHtml(h5pIncorrectAnswer.incorrectAnswerText), h5pIncorrectAnswer.incorrectAnswerFeedback, h5pIncorrectAnswer.showHighlight, h5pIncorrectAnswer.highlight);
            }
        }
        return blank;
    };
    BlankLoader.prototype.replaceSnippets = function (blank, snippets) {
        var _this = this;
        blank.correctAnswers.concat(blank.incorrectAnswers)
            .forEach(function (answer) { return answer.message.text = _this.getStringWithSnippets(answer.message.text, snippets); });
        blank.hint.text = this.getStringWithSnippets(blank.hint.text, snippets);
    };
    BlankLoader.prototype.getStringWithSnippets = function (text, snippets) {
        if (!text || text === undefined)
            return "";
        if (!snippets)
            return text;
        for (var _i = 0, snippets_1 = snippets; _i < snippets_1.length; _i++) {
            var snippet = snippets_1[_i];
            if (snippet.name === undefined || snippet.name === "" || snippet.text === undefined || snippet.text === "")
                continue;
            text = text.replace("@" + snippet.name, snippet.text);
        }
        return text;
    };
    /**
     * Adds the highlight objects to the answers in the correct and incorrect answer list.
     * @param  {Highlight[]} highlightsBefore - All highlights coming before the blank.
     * @param  {Highlight[]} highlightsAfter - All highlights coming after the blank.
     */
    BlankLoader.prototype.linkHighlightIdToObject = function (blank, highlightsBefore, highlightsAfter) {
        for (var _i = 0, _a = blank.correctAnswers; _i < _a.length; _i++) {
            var answer = _a[_i];
            answer.linkHighlightIdToObject(highlightsBefore, highlightsAfter);
        }
        for (var _b = 0, _c = blank.incorrectAnswers; _b < _c.length; _b++) {
            var answer = _c[_b];
            answer.linkHighlightIdToObject(highlightsBefore, highlightsAfter);
        }
        blank.hint.linkHighlight(highlightsBefore, highlightsAfter);
    };
    return BlankLoader;
}());
exports.BlankLoader = BlankLoader;


/***/ }),

/***/ "./src/scripts/content-loaders/cloze-loader.ts":
/*!*****************************************************!*\
  !*** ./src/scripts/content-loaders/cloze-loader.ts ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.ClozeLoader = void 0;
var blank_loader_1 = __webpack_require__(/*! ./blank-loader */ "./src/scripts/content-loaders/blank-loader.ts");
var cloze_element_1 = __webpack_require__(/*! ../models/cloze-element */ "./src/scripts/models/cloze-element.ts");
var highlight_1 = __webpack_require__(/*! ../models/highlight */ "./src/scripts/models/highlight.ts");
var cloze_1 = __webpack_require__(/*! ../models/cloze */ "./src/scripts/models/cloze.ts");
/**
 * Loads a cloze object.
 */
var ClozeLoader = /** @class */ (function () {
    function ClozeLoader() {
    }
    /**
     * @param  {string} html - The html string that contains the cloze with blanks marking and highlight markings.
     * @param  {Blank[]} blanks - All blanks as entered by the content author.
     * @returns Cloze
     */
    ClozeLoader.createCloze = function (html, blanks) {
        var orderedAllElementsList = new Array();
        var highlightInstances = new Array();
        var blanksInstances = new Array();
        html = ClozeLoader.normalizeBlankMarkings(html);
        var conversionResult = ClozeLoader.convertMarkupToSpans(html, blanks);
        html = conversionResult.html;
        orderedAllElementsList = conversionResult.orderedAllElementsList;
        highlightInstances = conversionResult.highlightInstances;
        blanksInstances = conversionResult.blanksInstances;
        ClozeLoader.linkHighlightsObjects(orderedAllElementsList, highlightInstances, blanksInstances);
        var cloze = new cloze_1.Cloze();
        cloze.html = html;
        cloze.blanks = blanksInstances;
        cloze.highlights = highlightInstances;
        return cloze;
    };
    /**
    * Converts !!signal!! highlight markup and ___  blank markup into <span>...</span>.
    * Returns the resulting html string and three lists of all active elements used in the cloze:
    *    orderedAllElements: highlights and blanks in the order of appearance in the html.
    *    highlightInstances: only highlights in the order of appearance
    *    blanksInstances: only blanks in the order of appearance
    * @param  {string} html
    * @param  {Blank[]} blanks
    * @returns Lists of active elements (see description).
    */
    ClozeLoader.convertMarkupToSpans = function (html, blanks) {
        var orderedAllElementsList = new Array();
        var highlightInstances = new Array();
        var blanksInstances = new Array();
        var exclamationMarkRegExp = /!!(.{1,40}?)!!/i;
        var highlightCounter = 0;
        var blankCounter = 0;
        // Searches the html string for highlights and blanks and inserts spans. 
        do {
            var nextHighlightMatch = html.match(exclamationMarkRegExp);
            var nextBlankIndex = html.indexOf(ClozeLoader.normalizedBlankMarker);
            if (nextHighlightMatch && ((nextHighlightMatch.index < nextBlankIndex) || (nextBlankIndex < 0))) {
                // next active element is a highlight
                var highlight = new highlight_1.Highlight(nextHighlightMatch[1], "highlight_" + highlightCounter);
                highlightInstances.push(highlight);
                orderedAllElementsList.push(highlight);
                html = html.replace(exclamationMarkRegExp, "<span id='container_highlight_" + highlightCounter + "'></span>");
                highlightCounter++;
            }
            else if (nextBlankIndex >= 0) {
                // next active element is a blank
                if (blankCounter >= blanks.length) {
                    // if the blank is not in the repository (The content author has marked too many blanks in the text, but not entered correct answers.)
                    html = html.replace(ClozeLoader.normalizedBlankMarker, "<span></span>");
                }
                else {
                    var blank = blanks[blankCounter];
                    blanksInstances.push(blank);
                    orderedAllElementsList.push(blank);
                    html = html.replace(ClozeLoader.normalizedBlankMarker, "<span id='container_" + blank.id + "'></span>");
                    blankCounter++;
                }
            }
        } while (nextHighlightMatch || (nextBlankIndex >= 0));
        return {
            html: html,
            orderedAllElementsList: orderedAllElementsList,
            highlightInstances: highlightInstances,
            blanksInstances: blanksInstances
        };
    };
    /**
     * Looks for all instances of marked blanks and replaces them with ___.
     * @param  {string} html
     * @returns string
     */
    ClozeLoader.normalizeBlankMarkings = function (html) {
        var underlineBlankRegEx = /_{3,}/g;
        html = html.replace(underlineBlankRegEx, ClozeLoader.normalizedBlankMarker);
        return html;
    };
    /**
    * Iterates through all blanks and calls their linkHighlightIdsToObjects(...).
    * @param orderedAllElementsList
    * @param highlightInstances
    * @param blanksInstances
    */
    ClozeLoader.linkHighlightsObjects = function (orderedAllElementsList, highlightInstances, blanksInstances) {
        for (var _i = 0, blanksInstances_1 = blanksInstances; _i < blanksInstances_1.length; _i++) {
            var blank = blanksInstances_1[_i];
            var nextBlankIndexInArray = orderedAllElementsList.indexOf(blank);
            var highlightsBeforeBlank = orderedAllElementsList
                .slice(0, nextBlankIndexInArray)
                .filter(function (e) { return e.type === cloze_element_1.ClozeElementType.Highlight; })
                .map(function (e) { return e; })
                .reverse();
            var highlightsAfterBlank = orderedAllElementsList
                .slice(nextBlankIndexInArray + 1)
                .filter(function (e) { return e.type === cloze_element_1.ClozeElementType.Highlight; })
                .map(function (e) { return e; });
            blank_loader_1.BlankLoader.instance.linkHighlightIdToObject(blank, highlightsBeforeBlank, highlightsAfterBlank);
        }
    };
    ClozeLoader.normalizedBlankMarker = '___';
    return ClozeLoader;
}());
exports.ClozeLoader = ClozeLoader;


/***/ }),

/***/ "./src/scripts/controllers/cloze-controller.ts":
/*!*****************************************************!*\
  !*** ./src/scripts/controllers/cloze-controller.ts ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.ClozeController = void 0;
var blank_loader_1 = __webpack_require__(/*! ../content-loaders/blank-loader */ "./src/scripts/content-loaders/blank-loader.ts");
var cloze_loader_1 = __webpack_require__(/*! ../content-loaders/cloze-loader */ "./src/scripts/content-loaders/cloze-loader.ts");
var enums_1 = __webpack_require__(/*! ../models/enums */ "./src/scripts/models/enums.ts");
var answer_1 = __webpack_require__(/*! ../models/answer */ "./src/scripts/models/answer.ts");
var RactiveEventsKeys = __webpack_require__(/*! ../../lib/ractive-events-keys */ "./src/lib/ractive-events-keys.ts");
var ClozeController = /** @class */ (function () {
    function ClozeController(repository, settings, localization, MessageService) {
        var _this = this;
        this.repository = repository;
        this.settings = settings;
        this.localization = localization;
        this.MessageService = MessageService;
        // Storage of the ractive objects that link models and views
        this.highlightRactives = {};
        this.blankRactives = {};
        this.checkAll = function () {
            _this.cloze.hideAllHighlights();
            for (var _i = 0, _a = _this.cloze.blanks; _i < _a.length; _i++) {
                var blank = _a[_i];
                if ((!blank.isCorrect) && blank.enteredText !== "")
                    blank.evaluateAttempt(true, true);
            }
            _this.refreshCloze();
            _this.checkAndNotifyCompleteness();
        };
        this.textTyped = function (blank) {
            blank.onTyped();
            if (_this.onTyped)
                _this.onTyped();
            _this.refreshCloze();
        };
        this.focus = function (blank) {
            blank.onFocussed();
            _this.refreshCloze();
        };
        this.displayFeedback = function (blank) {
            blank.onDisplayFeedback();
            _this.refreshCloze();
        };
        this.showHint = function (blank) {
            _this.cloze.hideAllHighlights();
            blank.showHint();
            _this.refreshCloze();
        };
        this.requestCloseTooltip = function (blank) {
            blank.removeTooltip();
            _this.refreshCloze();
            _this.jquery.find("#" + blank.id).focus();
        };
        this.checkBlank = function (blank, cause) {
            if ((cause === 'blur' || cause === 'change')) {
                blank.lostFocus();
            }
            if (cause === 'change' && _this.onTyped) {
                _this.onTyped();
            }
            if (_this.settings.autoCheck) {
                if (!blank.enteredText || blank.enteredText === "")
                    return;
                _this.cloze.hideAllHighlights();
                blank.evaluateAttempt(false);
                _this.checkAndNotifyCompleteness();
                _this.refreshCloze();
                _this.onAutoChecked();
            }
            if ((cause === 'enter')
                && ((_this.settings.autoCheck && blank.isCorrect && !_this.isSolved)
                    || !_this.settings.autoCheck)) {
                // move to next blank
                var index = _this.cloze.blanks.indexOf(blank);
                var nextId;
                while (index < _this.cloze.blanks.length - 1 && !nextId) {
                    index++;
                    if (!_this.cloze.blanks[index].isCorrect)
                        nextId = _this.cloze.blanks[index].id;
                }
                if (nextId)
                    _this.jquery.find("#" + nextId).focus();
            }
        };
        this.reset = function () {
            _this.cloze.reset();
            _this.refreshCloze();
        };
        this.showSolutions = function () {
            _this.cloze.showSolutions();
            _this.refreshCloze();
        };
        this.checkAndNotifyCompleteness = function () {
            if (_this.onScoreChanged)
                _this.onScoreChanged(_this.currentScore, _this.maxScore);
            if (_this.cloze.isSolved) {
                if (_this.onSolved)
                    _this.onSolved();
                return true;
            }
            return false;
        };
    }
    Object.defineProperty(ClozeController.prototype, "maxScore", {
        get: function () {
            return this.cloze.blanks.length;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ClozeController.prototype, "hasAlternatives", {
        /**
         * Detect whether there are blanks with more than one solution.
         * @return {boolean} True if there is at least one blank with more than one solution.
         */
        get: function () {
            return this.cloze.blanks.some(function (b) { return b.correctAnswers[0].alternatives.length > 1; });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ClozeController.prototype, "currentScore", {
        get: function () {
            var _this = this;
            var score = this.cloze.blanks.reduce(function (score, b) {
                var notShowingSolution = !b.isShowingSolution;
                var correctAnswerGiven = b.correctAnswers[0].alternatives.indexOf(b.enteredText || '') !== -1;
                // Detect small mistakes
                var closeCorrectMatches = b.correctAnswers
                    .map(function (answer) { return answer.evaluateAttempt(b.enteredText); })
                    .filter(function (evaluation) { return evaluation.correctness === answer_1.Correctness.CloseMatch; });
                var similarAnswerGiven = _this.settings.acceptSpellingErrors && closeCorrectMatches.length > 0;
                return score += (notShowingSolution && (correctAnswerGiven || similarAnswerGiven)) ? 1 : 0;
            }, 0);
            return Math.max(0, score);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ClozeController.prototype, "allBlanksEntered", {
        get: function () {
            if (this.cloze)
                return this.cloze.blanks.every(function (blank) { return blank.isError || blank.isCorrect || blank.isRetry; });
            return false;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ClozeController.prototype, "isSolved", {
        get: function () {
            return this.cloze.isSolved;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ClozeController.prototype, "isFilledOut", {
        get: function () {
            if (!this.cloze || this.cloze.blanks.length === 0)
                return true;
            return this.cloze.blanks.some(function (b) { return b.enteredText !== ''; });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ClozeController.prototype, "isFullyFilledOut", {
        get: function () {
            if (!this.cloze || this.cloze.blanks.length === 0)
                return true;
            return this.cloze.blanks.every(function (b) { return b.enteredText !== ''; });
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Sets up all blanks, the cloze itself and the ractive bindings.
     * @param  {HTMLElement} root
     */
    ClozeController.prototype.initialize = function (root, jquery) {
        this.jquery = jquery;
        this.isSelectCloze = this.settings.clozeType === enums_1.ClozeType.Select ? true : false;
        var blanks = this.repository.getBlanks();
        // Stop ractive debug mode
        Ractive.DEBUG = false;
        if (this.isSelectCloze && this.settings.selectAlternatives === enums_1.SelectAlternatives.All) {
            for (var _i = 0, blanks_1 = blanks; _i < blanks_1.length; _i++) {
                var blank = blanks_1[_i];
                var otherBlanks = blanks.filter(function (v) { return v !== blank; });
                blank.loadChoicesFromOtherBlanks(otherBlanks);
            }
        }
        var snippets = this.repository.getSnippets();
        blanks.forEach(function (blank) { return blank_loader_1.BlankLoader.instance.replaceSnippets(blank, snippets); });
        this.cloze = cloze_loader_1.ClozeLoader.createCloze(this.repository.getClozeText(), blanks);
        var containers = this.createAndAddContainers(root);
        containers.cloze.innerHTML = this.cloze.html;
        this.createRactiveBindings();
    };
    ClozeController.prototype.createAndAddContainers = function (addTo) {
        var clozeContainerElement = document.createElement('div');
        clozeContainerElement.id = 'h5p-cloze-container';
        if (this.settings.clozeType === enums_1.ClozeType.Select) {
            clozeContainerElement.className = 'h5p-advanced-blanks-select-mode';
        }
        else {
            clozeContainerElement.className = 'h5p-advanced-blanks-type-mode';
        }
        addTo.appendChild(clozeContainerElement);
        return {
            cloze: clozeContainerElement
        };
    };
    ClozeController.prototype.createHighlightBinding = function (highlight) {
        this.highlightRactives[highlight.id] = new Ractive({
            el: '#container_' + highlight.id,
            template: __webpack_require__(/*! ../views/highlight.ractive.html */ "./src/scripts/views/highlight.ractive.html"),
            data: {
                object: highlight
            }
        });
    };
    ClozeController.prototype.createBlankBinding = function (blank) {
        var ractive = new Ractive({
            el: '#container_' + blank.id,
            template: __webpack_require__(/*! ../views/blank.ractive.html */ "./src/scripts/views/blank.ractive.html"),
            data: {
                isSelectCloze: this.isSelectCloze,
                blank: blank
            },
            events: {
                enter: RactiveEventsKeys.enter,
                escape: RactiveEventsKeys.escape,
                anykey: RactiveEventsKeys.anykey
            }
        });
        ractive.on("checkBlank", this.checkBlank);
        ractive.on("showHint", this.showHint);
        ractive.on("textTyped", this.textTyped);
        ractive.on("textChanged", this.onTextChanged);
        ractive.on("closeMessage", this.requestCloseTooltip);
        ractive.on("focus", this.focus);
        ractive.on("displayFeedback", this.displayFeedback);
        this.blankRactives[blank.id] = ractive;
    };
    ClozeController.prototype.createRactiveBindings = function () {
        for (var _i = 0, _a = this.cloze.highlights; _i < _a.length; _i++) {
            var highlight = _a[_i];
            this.createHighlightBinding(highlight);
        }
        for (var _b = 0, _c = this.cloze.blanks; _b < _c.length; _b++) {
            var blank = _c[_b];
            this.createBlankBinding(blank);
        }
    };
    /**
     * Updates all views of highlights and blanks. Can be called when a model
     * was changed
     */
    ClozeController.prototype.refreshCloze = function () {
        for (var _i = 0, _a = this.cloze.highlights; _i < _a.length; _i++) {
            var highlight = _a[_i];
            var highlightRactive = this.highlightRactives[highlight.id];
            highlightRactive.set("object", highlight);
        }
        for (var _b = 0, _c = this.cloze.blanks; _b < _c.length; _b++) {
            var blank = _c[_b];
            var blankRactive = this.blankRactives[blank.id];
            blankRactive.set("blank", blank);
        }
    };
    ClozeController.prototype.serializeCloze = function () {
        return this.cloze.serialize();
    };
    ClozeController.prototype.deserializeCloze = function (data) {
        if (!this.cloze || !data)
            return false;
        this.cloze.deserialize(data);
        this.refreshCloze();
        return true;
    };
    ClozeController.prototype.getCorrectAnswerList = function () {
        if (!this.cloze || this.cloze.blanks.length === 0)
            return [[]];
        var result = [];
        for (var _i = 0, _a = this.cloze.blanks; _i < _a.length; _i++) {
            var blank = _a[_i];
            result.push(blank.getCorrectAnswers());
        }
        return result;
    };
    return ClozeController;
}());
exports.ClozeController = ClozeController;


/***/ }),

/***/ "./src/scripts/helpers/extend.ts":
/*!***************************************!*\
  !*** ./src/scripts/helpers/extend.ts ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.extend = void 0;
/**
 * Extend an array just like JQuery's extend.
 * @param {object} arguments Objects to be merged.
 * @return {object} Merged objects.
 */
function extend() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    for (var i = 1; i < args.length; i++) {
        for (var key in args[i]) {
            if (args[i].hasOwnProperty(key)) {
                if (typeof args[0][key] === 'object' && typeof args[i][key] === 'object') {
                    this.extend(args[0][key], args[i][key]);
                }
                else {
                    args[0][key] = args[i][key];
                }
            }
        }
    }
    return args[0];
}
exports.extend = extend;


/***/ }),

/***/ "./src/scripts/helpers/unwrapper.ts":
/*!******************************************!*\
  !*** ./src/scripts/helpers/unwrapper.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Unrwapper = void 0;
/**
 * This class cleans html strings.
 */
var Unrwapper = /** @class */ (function () {
    function Unrwapper(jquery) {
        this.jquery = jquery;
    }
    /**
     * Cleans html strings by removing the outmost html tag of the string if there is only one tag.
     * Examples:  "<p>my text</p>"" becomes "my text"
     *            "<p>text 1</p><p>text 2</p2>" stays
     * @param html The html string
     * @returns the cleaned html string
     */
    Unrwapper.prototype.unwrap = function (html) {
        var parsed = this.jquery(html);
        if (parsed.length !== 1) {
            return html;
        }
        var unwrapped = parsed.unwrap().html();
        return unwrapped;
    };
    return Unrwapper;
}());
exports.Unrwapper = Unrwapper;


/***/ }),

/***/ "./src/scripts/models/answer.ts":
/*!**************************************!*\
  !*** ./src/scripts/models/answer.ts ***!
  \**************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Answer = exports.Evaluation = exports.Correctness = void 0;
var message_1 = __webpack_require__(/*! ./message */ "./src/scripts/models/message.ts");
var jsdiff = __webpack_require__(/*! diff */ "./node_modules/diff/dist/diff.js");
var Correctness;
(function (Correctness) {
    Correctness[Correctness["ExactMatch"] = 0] = "ExactMatch";
    Correctness[Correctness["CloseMatch"] = 1] = "CloseMatch";
    Correctness[Correctness["NoMatch"] = 2] = "NoMatch";
})(Correctness = exports.Correctness || (exports.Correctness = {}));
var Evaluation = /** @class */ (function () {
    function Evaluation(usedAnswer) {
        this.usedAnswer = usedAnswer;
        this.correctness = Correctness.NoMatch;
        this.characterDifferenceCount = 0;
        this.usedAlternative = "";
    }
    return Evaluation;
}());
exports.Evaluation = Evaluation;
/**
 * Represents a possible answer the content author enters for a blank, e.g. the correct or an incorrect answer.
 */
var Answer = /** @class */ (function () {
    /**
     * @param  {string} answerText - The expected answer. Alternatives are separated by | or ; . (e.g. "Alternative 1|Alternative 2|Alternative 3|..."  -or- "Alternative 1;Alternative 2;Alternative 3")
     * @param  {string} reaction - The tooltip that should be displayed. Format: Tooltip Text;!!-1!! !!+1!!
     */
    function Answer(answerText, reaction, showHighlight, highlight, settings) {
        this.settings = settings;
        this.alternatives = answerText.split(/\//).map(function (s) { return s.trim(); });
        this.message = new message_1.Message(reaction, showHighlight, highlight);
        if (answerText.trim() === "") {
            this.appliesAlways = true;
        }
        else {
            this.appliesAlways = false;
        }
    }
    /**
     * Looks through the object's message ids and stores the references to the highlight object for these ids.
     * @param  {Highlight[]} highlightsBefore
     * @param  {Highlight[]} highlightsAfter
     */
    Answer.prototype.linkHighlightIdToObject = function (highlightsBefore, highlightsAfter) {
        this.message.linkHighlight(highlightsBefore, highlightsAfter);
    };
    /**
     * Turns on the highlights set by the content author for this answer.
     */
    Answer.prototype.activateHighlight = function () {
        if (this.message.highlightedElement)
            this.message.highlightedElement.isHighlighted = true;
    };
    Answer.prototype.cleanString = function (text) {
        text = text.trim();
        return text.replace(/\s{2,}/g, " ");
    };
    /**
     * Looks through the diff and checks how many character change operations are needed to turn one string into the other. Should return the same results as the Levensthein distance.
     * @param  {[{added?:boolean, boolean: removed?, string: value}]} diff - as returned by jsdiff
     * @returns number - the count of changes (replace, add, delete) needed to change the text from one string to the other
     */
    Answer.prototype.getChangesCountFromDiff = function (diff) {
        var totalChangesCount = 0;
        var lastType = "";
        var lastCount = 0;
        for (var _i = 0, diff_1 = diff; _i < diff_1.length; _i++) {
            var element = diff_1[_i];
            if (element.removed) {
                totalChangesCount += element.value.length;
                lastType = "removed";
            }
            else if (element.added) {
                if (lastType === "removed") {
                    if (lastCount < element.value.length) {
                        totalChangesCount += element.value.length - lastCount;
                    }
                }
                else {
                    totalChangesCount += element.value.length;
                }
                lastType = "added";
            }
            else {
                lastType = "same";
            }
            lastCount = element.value.length;
        }
        return totalChangesCount;
    };
    /**
     * Returns how many characters can be wrong to still be counted as a spelling mistake.
     * If spelling mistakes are turned off through the settings, it will return 0.
     * @param  {string} text
     * @returns number
     */
    Answer.prototype.getAcceptableSpellingMistakes = function (text) {
        var acceptableTypoCount;
        if (this.settings.warnSpellingErrors || this.settings.acceptSpellingErrors) // TODO: consider removal
            acceptableTypoCount = Math.floor(text.length / 10) + 1;
        else
            acceptableTypoCount = 0;
        return acceptableTypoCount;
    };
    /**
     * Checks if the text entered by the user in an ettempt is matched by the answer,
     * @param  {string} attempt The text entered by the user.
     * @returns Evaluation indicates if the entered text is matched by the answer.
     */
    Answer.prototype.evaluateAttempt = function (attempt) {
        var cleanedAttempt = this.cleanString(attempt);
        var evaluation = new Evaluation(this);
        for (var _i = 0, _a = this.alternatives; _i < _a.length; _i++) {
            var alternative = _a[_i];
            var cleanedAlternative = this.cleanString(alternative);
            var diff = jsdiff.diffChars(cleanedAlternative, cleanedAttempt, { ignoreCase: !this.settings.caseSensitive });
            var changeCount = this.getChangesCountFromDiff(diff);
            if (changeCount === 0) {
                evaluation.usedAlternative = cleanedAlternative;
                evaluation.correctness = Correctness.ExactMatch;
                return evaluation;
            }
            if (changeCount <= this.getAcceptableSpellingMistakes(alternative)
                && (evaluation.characterDifferenceCount === 0 || changeCount < evaluation.characterDifferenceCount)) {
                evaluation.usedAlternative = cleanedAlternative;
                evaluation.correctness = Correctness.CloseMatch;
                evaluation.characterDifferenceCount = changeCount;
            }
        }
        return evaluation;
    };
    return Answer;
}());
exports.Answer = Answer;


/***/ }),

/***/ "./src/scripts/models/blank.ts":
/*!*************************************!*\
  !*** ./src/scripts/models/blank.ts ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Blank = void 0;
var cloze_element_1 = __webpack_require__(/*! ./cloze-element */ "./src/scripts/models/cloze-element.ts");
var answer_1 = __webpack_require__(/*! ./answer */ "./src/scripts/models/answer.ts");
var enums_1 = __webpack_require__(/*! ./enums */ "./src/scripts/models/enums.ts");
var localization_1 = __webpack_require__(/*! ../services/localization */ "./src/scripts/services/localization.ts");
var helpers_1 = __webpack_require__(/*! ../../lib/helpers */ "./src/lib/helpers.ts");
var jsdiff = __webpack_require__(/*! diff */ "./node_modules/diff/dist/diff.js");
var Blank = /** @class */ (function (_super) {
    __extends(Blank, _super);
    /**
     * Add incorrect answers after initializing the object. Call finishInitialization()
     * when done.
     * @param  {ISettings} settings
     * @param  {string} id
     * @param  {string} correctText?
     * @param  {string} hintText?
     */
    function Blank(settings, localization, jquery, messageService, id) {
        var _this = _super.call(this) || this;
        _this.settings = settings;
        _this.localization = localization;
        _this.jquery = jquery;
        _this.messageService = messageService;
        _this.enteredText = "";
        _this.correctAnswers = new Array();
        _this.incorrectAnswers = new Array();
        _this.choices = new Array();
        _this.type = cloze_element_1.ClozeElementType.Blank;
        _this.id = id;
        return _this;
    }
    /**
    * Call this method when all incorrect answers have been added.
    */
    Blank.prototype.finishInitialization = function () {
        if (this.settings.clozeType === enums_1.ClozeType.Select && this.settings.selectAlternatives === enums_1.SelectAlternatives.Alternatives) {
            this.loadChoicesFromOwnAlternatives();
        }
        this.calculateMinTextLength();
    };
    Blank.prototype.addCorrectAnswer = function (answer) {
        this.correctAnswers.push(answer);
    };
    Blank.prototype.getCorrectAnswers = function () {
        var result = [];
        for (var _i = 0, _a = this.correctAnswers; _i < _a.length; _i++) {
            var answer = _a[_i];
            result = result.concat(answer.alternatives);
        }
        return result;
    };
    Blank.prototype.setHint = function (message) {
        this.hint = message;
        this.hasHint = this.hint.text !== "";
    };
    /**
     * Adds the incorrect answer to the list.
     * @param text - What the user must enter.
     * @param reaction  - What the user gets displayed when he enteres the text.
     */
    Blank.prototype.addIncorrectAnswer = function (text, reaction, showHighlight, highlight) {
        this.incorrectAnswers.push(new answer_1.Answer(text, reaction, showHighlight, highlight, this.settings));
    };
    /**
     * Returns how many characters the input box must have be to allow for all correct answers.
     */
    // TODO: refactor
    Blank.prototype.calculateMinTextLength = function () {
        var answers = new Array();
        for (var _i = 0, _a = this.correctAnswers; _i < _a.length; _i++) {
            var correctAnswer = _a[_i];
            answers.push(helpers_1.getLongestString(correctAnswer.alternatives));
        }
        if (this.settings.clozeType === enums_1.ClozeType.Select) {
            for (var _b = 0, _c = this.incorrectAnswers; _b < _c.length; _b++) {
                var incorrectAnswer = _c[_b];
                answers.push(helpers_1.getLongestString(incorrectAnswer.alternatives));
            }
        }
        var longestAnswer = helpers_1.getLongestString(answers);
        var l = longestAnswer.length;
        this.minTextLength = Math.max(10, l - (l % 10) + 10);
    };
    /**
     * Creates a list of choices from all alternatives provided by
     * the correct and incorrect answers.
     */
    Blank.prototype.loadChoicesFromOwnAlternatives = function () {
        this.choices = new Array();
        for (var _i = 0, _a = this.correctAnswers; _i < _a.length; _i++) {
            var answer = _a[_i];
            for (var _b = 0, _c = answer.alternatives; _b < _c.length; _b++) {
                var alternative = _c[_b];
                this.choices.push(alternative);
            }
        }
        for (var _d = 0, _e = this.incorrectAnswers; _d < _e.length; _d++) {
            var answer = _e[_d];
            for (var _f = 0, _g = answer.alternatives; _f < _g.length; _f++) {
                var alternative = _g[_f];
                this.choices.push(alternative);
            }
        }
        this.choices = helpers_1.shuffleArray(this.choices);
        this.choices.unshift("");
        return this.choices;
    };
    /**
     * Creates a list of choices from all correct answers of the cloze.
     * @param otherBlanks All OTHER blanks in the cloze. (excludes the current one!)
     */
    Blank.prototype.loadChoicesFromOtherBlanks = function (otherBlanks) {
        var ownChoices = new Array();
        for (var _i = 0, _a = this.correctAnswers; _i < _a.length; _i++) {
            var answer = _a[_i];
            for (var _b = 0, _c = answer.alternatives; _b < _c.length; _b++) {
                var alternative = _c[_b];
                ownChoices.push(alternative);
            }
        }
        var otherChoices = new Array();
        for (var _d = 0, otherBlanks_1 = otherBlanks; _d < otherBlanks_1.length; _d++) {
            var otherBlank = otherBlanks_1[_d];
            for (var _e = 0, _f = otherBlank.correctAnswers; _e < _f.length; _e++) {
                var answer = _f[_e];
                for (var _g = 0, _h = answer.alternatives; _g < _h.length; _g++) {
                    var alternative = _h[_g];
                    otherChoices.push(alternative);
                }
            }
        }
        otherChoices = helpers_1.shuffleArray(otherChoices);
        var maxChoices = this.settings.selectAlternativeRestriction;
        if (maxChoices === undefined || maxChoices === 0)
            maxChoices = ownChoices.length + otherChoices.length;
        var leftOverChoices = maxChoices - ownChoices.length;
        for (var x = 0; x < leftOverChoices && x < otherChoices.length; x++) {
            if (ownChoices.indexOf(otherChoices[x]) >= 0) {
                leftOverChoices++;
            }
            else {
                ownChoices.push(otherChoices[x]);
            }
        }
        this.choices = helpers_1.shuffleArray(ownChoices);
        this.choices.unshift("");
        return this.choices;
    };
    /**
    * Clears the blank from all entered text and hides popups.
    */
    Blank.prototype.reset = function () {
        this.enteredText = "";
        this.lastCheckedText = "";
        this.removeTooltip();
        this.setAnswerState(enums_1.MessageType.None);
        this.hasPendingFeedback = false;
    };
    /**
     * Sets the blank to a state in which the correct solution if shown if the user
     * hasn't entered a correct one so far.
     */
    Blank.prototype.showSolution = function () {
        this.evaluateAttempt(true);
        this.removeTooltip();
        if (this.isCorrect)
            return;
        this.enteredText = this.correctAnswers[0].alternatives[0];
        this.setAnswerState(enums_1.MessageType.ShowSolution);
    };
    Blank.prototype.onFocussed = function () {
        if (this.hasPendingFeedback) {
            this.evaluateAttempt(false);
        }
        if (this.settings.clozeType === enums_1.ClozeType.Select) {
            this.setAnswerState(enums_1.MessageType.None);
            this.lastCheckedText = "";
        }
    };
    Blank.prototype.onDisplayFeedback = function () {
        if (this.hasPendingFeedback) {
            this.evaluateAttempt(false);
        }
    };
    Blank.prototype.displayTooltip = function (message, type, surpressTooltip, id) {
        if (!surpressTooltip)
            this.messageService.show(id ? id : this.id, message, this, type);
        else {
            this.hasPendingFeedback = true;
        }
    };
    Blank.prototype.removeTooltip = function () {
        this.messageService.hide();
    };
    Blank.prototype.setTooltipErrorText = function (message, surpressTooltip) {
        if (message.highlightedElement) {
            this.displayTooltip(message.text, enums_1.MessageType.Error, surpressTooltip, message.highlightedElement.id);
        }
        else {
            this.displayTooltip(message.text, enums_1.MessageType.Error, surpressTooltip);
        }
    };
    Blank.prototype.getSpellingMistakeMessage = function (expectedText, enteredText) {
        var message = this.localization.getTextFromLabel(localization_1.LocalizationLabels.typoMessage);
        var diff = jsdiff.diffChars(expectedText, enteredText, { ignoreCase: !this.settings.caseSensitive });
        var mistakeSpan = this.jquery("<span/>", { "class": "spelling-mistake" });
        for (var index = 0; index < diff.length; index++) {
            var part = diff[index];
            var spanClass = '';
            if (part.removed) {
                if (index === diff.length - 1 || !diff[index + 1].added) {
                    part.value = part.value.replace(/./g, "_");
                    spanClass = 'missing-character';
                }
                else {
                    continue;
                }
            }
            if (part.added) {
                spanClass = 'mistaken-character';
            }
            var span = this.jquery("<span/>", { "class": spanClass, "html": part.value.replace(" ", "&nbsp;") });
            mistakeSpan.append(span);
        }
        message = message.replace("@mistake", this.jquery("<span/>").append(mistakeSpan).html());
        return message;
    };
    /**
     * Checks if the entered text is the correct answer or one of the
     * incorrect ones and gives the user feedback accordingly.
     */
    Blank.prototype.evaluateAttempt = function (surpressTooltips, forceCheck) {
        var _this = this;
        if (!this.hasPendingFeedback && this.lastCheckedText === this.enteredText && !forceCheck)
            return;
        this.lastCheckedText = this.enteredText.toString();
        this.hasPendingFeedback = false;
        this.removeTooltip();
        var exactCorrectMatches = this.correctAnswers.map(function (answer) { return answer.evaluateAttempt(_this.enteredText); }).filter(function (evaluation) { return evaluation.correctness === answer_1.Correctness.ExactMatch; }).sort(function (evaluation) { return evaluation.characterDifferenceCount; });
        var closeCorrectMatches = this.correctAnswers.map(function (answer) { return answer.evaluateAttempt(_this.enteredText); }).filter(function (evaluation) { return evaluation.correctness === answer_1.Correctness.CloseMatch; }).sort(function (evaluation) { return evaluation.characterDifferenceCount; });
        var exactIncorrectMatches = this.incorrectAnswers.map(function (answer) { return answer.evaluateAttempt(_this.enteredText); }).filter(function (evaluation) { return evaluation.correctness === answer_1.Correctness.ExactMatch; }).sort(function (evaluation) { return evaluation.characterDifferenceCount; });
        var closeIncorrectMatches = this.incorrectAnswers.map(function (answer) { return answer.evaluateAttempt(_this.enteredText); }).filter(function (evaluation) { return evaluation.correctness === answer_1.Correctness.CloseMatch; }).sort(function (evaluation) { return evaluation.characterDifferenceCount; });
        if (exactCorrectMatches.length > 0) {
            this.setAnswerState(enums_1.MessageType.Correct);
            if (!this.settings.caseSensitive) {
                this.enteredText = exactCorrectMatches[0].usedAlternative;
            }
            return;
        }
        if (exactIncorrectMatches.length > 0) {
            this.setAnswerState(enums_1.MessageType.Error);
            this.showErrorTooltip(exactIncorrectMatches[0].usedAnswer, surpressTooltips);
            return;
        }
        if (closeCorrectMatches.length > 0) {
            if (this.settings.warnSpellingErrors) {
                this.displayTooltip(this.getSpellingMistakeMessage(closeCorrectMatches[0].usedAlternative, this.enteredText), enums_1.MessageType.Retry, surpressTooltips);
                this.setAnswerState(enums_1.MessageType.Retry);
                return;
            }
            if (this.settings.acceptSpellingErrors) {
                this.setAnswerState(enums_1.MessageType.Correct);
                this.enteredText = closeCorrectMatches[0].usedAlternative;
                return;
            }
        }
        if (closeIncorrectMatches.length > 0) {
            this.setAnswerState(enums_1.MessageType.Error);
            this.showErrorTooltip(closeIncorrectMatches[0].usedAnswer, surpressTooltips);
            return;
        }
        var alwaysApplyingAnswers = this.incorrectAnswers.filter(function (a) { return a.appliesAlways; });
        if (alwaysApplyingAnswers && alwaysApplyingAnswers.length > 0) {
            this.showErrorTooltip(alwaysApplyingAnswers[0], surpressTooltips);
        }
        this.setAnswerState(enums_1.MessageType.Error);
    };
    Blank.prototype.onTyped = function () {
        this.setAnswerState(enums_1.MessageType.None);
        this.lastCheckedText = "";
        this.removeTooltip();
    };
    Blank.prototype.lostFocus = function () {
        if (this.messageService.isActive(this)) {
            this.messageService.hide();
        }
    };
    /**
     * Sets the boolean properties isCorrect, is Error and isRetry according to thepassed  messageType.
     * @param messageType
     */
    Blank.prototype.setAnswerState = function (messageType) {
        this.isCorrect = false;
        this.isError = false;
        this.isRetry = false;
        this.isShowingSolution = false;
        switch (messageType) {
            case enums_1.MessageType.Correct:
                this.isCorrect = true;
                break;
            case enums_1.MessageType.Error:
                this.isError = true;
                break;
            case enums_1.MessageType.Retry:
                this.isRetry = true;
                break;
            case enums_1.MessageType.ShowSolution:
                this.isShowingSolution = true;
                break;
        }
    };
    Blank.prototype.showErrorTooltip = function (answer, surpressTooltip) {
        if (answer.message && answer.message.text) {
            this.setTooltipErrorText(answer.message, surpressTooltip);
        }
        if (!surpressTooltip) {
            answer.activateHighlight();
        }
    };
    /**
     * Displays the hint in the tooltip.
     */
    Blank.prototype.showHint = function () {
        if (this.isShowingSolution || this.isCorrect)
            return;
        this.removeTooltip();
        if (this.hint && this.hint.text !== "") {
            this.displayTooltip(this.hint.text, enums_1.MessageType.Retry, false);
            if (this.hint.highlightedElement) {
                this.hint.highlightedElement.isHighlighted = true;
            }
        }
    };
    Blank.prototype.serialize = function () {
        return this.enteredText;
    };
    Blank.prototype.deserialize = function (data) {
        this.enteredText = data;
    };
    return Blank;
}(cloze_element_1.ClozeElement));
exports.Blank = Blank;


/***/ }),

/***/ "./src/scripts/models/cloze-element.ts":
/*!*********************************************!*\
  !*** ./src/scripts/models/cloze-element.ts ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.ClozeElement = exports.ClozeElementType = void 0;
var ClozeElementType;
(function (ClozeElementType) {
    ClozeElementType[ClozeElementType["Blank"] = 0] = "Blank";
    ClozeElementType[ClozeElementType["Highlight"] = 1] = "Highlight";
})(ClozeElementType = exports.ClozeElementType || (exports.ClozeElementType = {}));
var ClozeElement = /** @class */ (function () {
    function ClozeElement() {
    }
    return ClozeElement;
}());
exports.ClozeElement = ClozeElement;


/***/ }),

/***/ "./src/scripts/models/cloze.ts":
/*!*************************************!*\
  !*** ./src/scripts/models/cloze.ts ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Cloze = void 0;
/**
 * Represents the cloze. Instantiate with static createCloze().
 */
var Cloze = /** @class */ (function () {
    function Cloze() {
    }
    Object.defineProperty(Cloze.prototype, "isSolved", {
        /**
         * Returns true if all blanks were entered correctly.
         * @returns boolean
         */
        get: function () {
            return this.blanks.every(function (b) { return b.isCorrect === true; });
        },
        enumerable: false,
        configurable: true
    });
    Cloze.prototype.hideAllHighlights = function () {
        for (var _i = 0, _a = this.highlights; _i < _a.length; _i++) {
            var highlight = _a[_i];
            highlight.isHighlighted = false;
        }
    };
    Cloze.prototype.reset = function () {
        this.hideAllHighlights();
        for (var _i = 0, _a = this.blanks; _i < _a.length; _i++) {
            var blank = _a[_i];
            blank.reset();
        }
    };
    Cloze.prototype.showSolutions = function () {
        for (var _i = 0, _a = this.blanks; _i < _a.length; _i++) {
            var blank = _a[_i];
            blank.showSolution();
        }
        this.hideAllHighlights();
    };
    Cloze.prototype.serialize = function () {
        var cloze = [];
        for (var _i = 0, _a = this.blanks; _i < _a.length; _i++) {
            var blank = _a[_i];
            cloze.push(blank.serialize());
        }
        return cloze;
    };
    Cloze.prototype.deserialize = function (data) {
        for (var index = 0; index < data.length; index++) {
            if (index >= this.blanks.length)
                return;
            var blank = this.blanks[index];
            blank.deserialize(data[index]);
        }
    };
    return Cloze;
}());
exports.Cloze = Cloze;


/***/ }),

/***/ "./src/scripts/models/enums.ts":
/*!*************************************!*\
  !*** ./src/scripts/models/enums.ts ***!
  \*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.SelectAlternatives = exports.ClozeType = exports.MessageType = void 0;
var MessageType;
(function (MessageType) {
    MessageType[MessageType["Error"] = 0] = "Error";
    MessageType[MessageType["Correct"] = 1] = "Correct";
    MessageType[MessageType["Retry"] = 2] = "Retry";
    MessageType[MessageType["ShowSolution"] = 3] = "ShowSolution";
    MessageType[MessageType["None"] = 4] = "None";
})(MessageType = exports.MessageType || (exports.MessageType = {}));
var ClozeType;
(function (ClozeType) {
    ClozeType[ClozeType["Type"] = 0] = "Type";
    ClozeType[ClozeType["Select"] = 1] = "Select";
})(ClozeType = exports.ClozeType || (exports.ClozeType = {}));
var SelectAlternatives;
(function (SelectAlternatives) {
    SelectAlternatives[SelectAlternatives["Alternatives"] = 0] = "Alternatives";
    SelectAlternatives[SelectAlternatives["All"] = 1] = "All";
})(SelectAlternatives = exports.SelectAlternatives || (exports.SelectAlternatives = {}));


/***/ }),

/***/ "./src/scripts/models/highlight.ts":
/*!*****************************************!*\
  !*** ./src/scripts/models/highlight.ts ***!
  \*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Highlight = void 0;
var cloze_element_1 = __webpack_require__(/*! ./cloze-element */ "./src/scripts/models/cloze-element.ts");
/**
 * Represents a highlight in the cloze.
 */
var Highlight = /** @class */ (function (_super) {
    __extends(Highlight, _super);
    function Highlight(text, id) {
        var _this = _super.call(this) || this;
        _this.type = cloze_element_1.ClozeElementType.Highlight;
        _this.text = text;
        _this.id = id;
        _this.isHighlighted = false;
        return _this;
    }
    return Highlight;
}(cloze_element_1.ClozeElement));
exports.Highlight = Highlight;


/***/ }),

/***/ "./src/scripts/models/message.ts":
/*!***************************************!*\
  !*** ./src/scripts/models/message.ts ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Message = void 0;
/**
 * Represents a message that the content author has specified to be a reaction
 * to an user's answer.
 */
var Message = /** @class */ (function () {
    function Message(text, showHighlight, relativeHighlightPosition) {
        var _this = this;
        this.text = text;
        this.relativeHighlightPosition = relativeHighlightPosition;
        this.linkHighlight = function (highlightsBefore, highlightsAfter) {
            if (!_this.relativeHighlightPosition)
                return;
            if (_this.relativeHighlightPosition < 0 && (0 - _this.relativeHighlightPosition - 1) < highlightsBefore.length) {
                _this.highlightedElement = highlightsBefore[0 - _this.relativeHighlightPosition - 1];
            }
            else if (_this.relativeHighlightPosition > 0 && (_this.relativeHighlightPosition - 1 < highlightsAfter.length)) {
                _this.highlightedElement = highlightsAfter[_this.relativeHighlightPosition - 1];
            }
        };
        if (!showHighlight)
            this.relativeHighlightPosition = undefined;
    }
    return Message;
}());
exports.Message = Message;


/***/ }),

/***/ "./src/scripts/models/snippet.ts":
/*!***************************************!*\
  !*** ./src/scripts/models/snippet.ts ***!
  \***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Snippet = void 0;
/**
 * A snippet is a text block that is put into placed marked in feedback texts or hints.
 */
var Snippet = /** @class */ (function () {
    /**
     * Constructs the snippet.
     * @param name The name of the snippet that is used when it is referenced in a feedbacktext (without the snippet marker @)
     * @param text The snippet itself (html)
     */
    function Snippet(name, text) {
        this.name = name;
        this.text = text;
    }
    return Snippet;
}());
exports.Snippet = Snippet;


/***/ }),

/***/ "./src/scripts/models/xapi.ts":
/*!************************************!*\
  !*** ./src/scripts/models/xapi.ts ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.XAPIActivityDefinition = void 0;
var XAPIActivityDefinition = /** @class */ (function () {
    function XAPIActivityDefinition() {
    }
    return XAPIActivityDefinition;
}());
exports.XAPIActivityDefinition = XAPIActivityDefinition;


/***/ }),

/***/ "./src/scripts/services/data-repository.ts":
/*!*************************************************!*\
  !*** ./src/scripts/services/data-repository.ts ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.H5PDataRepository = void 0;
var blank_loader_1 = __webpack_require__(/*! ../content-loaders/blank-loader */ "./src/scripts/content-loaders/blank-loader.ts");
var snippet_1 = __webpack_require__(/*! ../models/snippet */ "./src/scripts/models/snippet.ts");
/**
 * Wraps around the h5p config object and provides access to the content.
 */
var H5PDataRepository = /** @class */ (function () {
    function H5PDataRepository(h5pConfigData, settings, localization, jquery, unwrapper) {
        this.h5pConfigData = h5pConfigData;
        this.settings = settings;
        this.localization = localization;
        this.jquery = jquery;
        this.unwrapper = unwrapper;
    }
    /**
     * Returns the blank text of the cloze (as HTML markup).
     */
    H5PDataRepository.prototype.getClozeText = function () {
        return this.h5pConfigData.content.blanksText;
    };
    // TODO: remove or implement
    H5PDataRepository.prototype.getFeedbackText = function () {
        return "";
    };
    H5PDataRepository.prototype.getMedia = function () {
        return this.h5pConfigData.media.type;
    };
    H5PDataRepository.prototype.getTaskDescription = function () {
        return this.h5pConfigData.content.task;
    };
    H5PDataRepository.prototype.getBlanks = function () {
        var blanks = new Array();
        if (!this.h5pConfigData.content.blanksList)
            return blanks;
        for (var i = 0; i < this.h5pConfigData.content.blanksList.length; i++) {
            var h5pBlank = this.h5pConfigData.content.blanksList[i];
            var correctText = h5pBlank.correctAnswerText;
            if (correctText === "" || correctText === undefined)
                continue;
            var blank = blank_loader_1.BlankLoader.instance.createBlank("cloze" + i, correctText, h5pBlank.hint, h5pBlank.incorrectAnswersList);
            blank.finishInitialization();
            blanks.push(blank);
        }
        return blanks;
    };
    H5PDataRepository.prototype.getSnippets = function () {
        var snippets = new Array();
        if (!this.h5pConfigData.snippets)
            return snippets;
        for (var i = 0; i < this.h5pConfigData.snippets.length; i++) {
            var raw_snippet = this.h5pConfigData.snippets[i];
            var snippet = new snippet_1.Snippet(raw_snippet.snippetName, this.unwrapper.unwrap(raw_snippet.snippetText));
            snippets.push(snippet);
        }
        return snippets;
    };
    return H5PDataRepository;
}());
exports.H5PDataRepository = H5PDataRepository;


/***/ }),

/***/ "./src/scripts/services/localization.ts":
/*!**********************************************!*\
  !*** ./src/scripts/services/localization.ts ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.H5PLocalization = exports.LocalizationStructures = exports.LocalizationLabels = void 0;
var LocalizationLabels;
(function (LocalizationLabels) {
    LocalizationLabels["showSolutionButton"] = "showSolutions";
    LocalizationLabels["retryButton"] = "tryAgain";
    LocalizationLabels["checkAllButton"] = "checkAnswer";
    LocalizationLabels["submitAllButton"] = "submitAnswer";
    LocalizationLabels["notFilledOutWarning"] = "notFilledOut";
    LocalizationLabels["tipButton"] = "tipLabel";
    LocalizationLabels["typoMessage"] = "spellingMistakeWarning";
    LocalizationLabels["scoreBarLabel"] = "scoreBarLabel";
})(LocalizationLabels = exports.LocalizationLabels || (exports.LocalizationLabels = {}));
var LocalizationStructures;
(function (LocalizationStructures) {
    LocalizationStructures["confirmCheck"] = "confirmCheck";
    LocalizationStructures["confirmRetry"] = "confirmRetry";
    LocalizationStructures["overallFeedback"] = "overallFeedback";
})(LocalizationStructures = exports.LocalizationStructures || (exports.LocalizationStructures = {}));
/**
 * Provides localization services.
 */
var H5PLocalization = /** @class */ (function () {
    function H5PLocalization(h5pConfiguration) {
        this.h5pConfiguration = h5pConfiguration;
    }
    /**
     * Returns the localized string that is represented by the identifier.
     * @param  {string} localizableStringIdentifier
     * @returns string
     */
    H5PLocalization.prototype.getText = function (localizableStringIdentifier) {
        return this.h5pConfiguration[localizableStringIdentifier];
    };
    H5PLocalization.prototype.labelToString = function (label) {
        return label.toString();
    };
    /**
     * Returns the localized string for the label.
     * @param  {LocalizationLabels} label
     * @returns string
     */
    H5PLocalization.prototype.getTextFromLabel = function (label) {
        return this.getText(this.labelToString(label));
    };
    H5PLocalization.prototype.getObjectForStructure = function (structure) {
        return this.h5pConfiguration[structure.toString()];
    };
    return H5PLocalization;
}());
exports.H5PLocalization = H5PLocalization;


/***/ }),

/***/ "./src/scripts/services/message-service.ts":
/*!*************************************************!*\
  !*** ./src/scripts/services/message-service.ts ***!
  \*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageService = void 0;
var enums_1 = __webpack_require__(/*! ../models/enums */ "./src/scripts/models/enums.ts");
var MessageService = /** @class */ (function () {
    function MessageService(jQuery) {
        this.jQuery = jQuery;
    }
    MessageService.prototype.show = function (elementId, message, blank, type) {
        if (!type)
            type = enums_1.MessageType.None;
        var elements = this.jQuery("#" + elementId);
        if (elements.length > 0) {
            this.speechBubble = new H5P.JoubelSpeechBubble(elements, message);
            this.associatedBlank = blank;
        }
    };
    MessageService.prototype.hide = function () {
        if (this.speechBubble) {
            try {
                this.speechBubble.remove();
            }
            catch (exception) {
            }
        }
        this.speechBubble = undefined;
        this.associatedBlank = undefined;
    };
    MessageService.prototype.isActive = function (blank) {
        return this.associatedBlank === blank;
    };
    return MessageService;
}());
exports.MessageService = MessageService;


/***/ }),

/***/ "./src/scripts/services/settings.ts":
/*!******************************************!*\
  !*** ./src/scripts/services/settings.ts ***!
  \******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.H5PSettings = void 0;
var enums_1 = __webpack_require__(/*! ../models/enums */ "./src/scripts/models/enums.ts");
var H5PSettings = /** @class */ (function () {
    function H5PSettings(h5pConfigData) {
        this.clozeType = enums_1.ClozeType.Type;
        this.selectAlternatives = enums_1.SelectAlternatives.Alternatives;
        this.selectAlternativeRestriction = 5;
        this.enableRetry = true;
        this.enableSolutionsButton = true;
        this.enableCheckButton = true;
        this.autoCheck = false;
        this.caseSensitive = false;
        this.warnSpellingErrors = true;
        this.acceptSpellingErrors = false;
        this.showSolutionsRequiresInput = true;
        this.confirmCheckDialog = false;
        this.confirmRetryDialog = false;
        this.disableImageZooming = false;
        if (h5pConfigData.behaviour.mode === 'selection') {
            this.clozeType = enums_1.ClozeType.Select;
        }
        else {
            this.clozeType = enums_1.ClozeType.Type;
        }
        if (h5pConfigData.behaviour.selectAlternatives === 'all') {
            this.selectAlternatives = enums_1.SelectAlternatives.All;
        }
        else if (h5pConfigData.behaviour.selectAlternatives === 'alternatives') {
            this.selectAlternatives = enums_1.SelectAlternatives.Alternatives;
        }
        else {
            this.selectAlternatives = enums_1.SelectAlternatives.All;
        }
        this.selectAlternativeRestriction = h5pConfigData.behaviour.selectAlternativeRestriction;
        this.enableRetry = h5pConfigData.behaviour.enableRetry;
        this.enableSolutionsButton = h5pConfigData.behaviour.enableSolutionsButton;
        this.enableCheckButton = h5pConfigData.behaviour.enableCheckButton;
        this.autoCheck = h5pConfigData.behaviour.autoCheck;
        this.caseSensitive = h5pConfigData.behaviour.caseSensitive;
        this.warnSpellingErrors = h5pConfigData.behaviour.spellingErrorBehaviour === "warn";
        this.acceptSpellingErrors = h5pConfigData.behaviour.spellingErrorBehaviour === "accept";
        this.showSolutionsRequiresInput = h5pConfigData.behaviour.showSolutionsRequiresInput;
        this.confirmCheckDialog = h5pConfigData.behaviour.confirmCheckDialog;
        this.confirmRetryDialog = h5pConfigData.behaviour.confirmRetryDialog;
        this.disableImageZooming = h5pConfigData.media.disableImageZooming;
        this.enforceLogic();
    }
    /**
     * This method sets sensible default values for settings hidden with showWhen
     */
    H5PSettings.prototype.enforceLogic = function () {
        if (this.clozeType === enums_1.ClozeType.Type) {
            this.selectAlternatives = enums_1.SelectAlternatives.All;
            this.selectAlternativeRestriction = 0;
        }
        else {
            if (this.selectAlternativeRestriction === enums_1.SelectAlternatives.Alternatives) {
                this.selectAlternativeRestriction = 0;
            }
            this.warnSpellingErrors = false;
            this.acceptSpellingErrors = false;
            this.caseSensitive = false;
        }
    };
    return H5PSettings;
}());
exports.H5PSettings = H5PSettings;


/***/ }),

/***/ "./src/scripts/views/blank.ractive.html":
/*!**********************************************!*\
  !*** ./src/scripts/views/blank.ractive.html ***!
  \**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = "<span id=\"container{{id}}\" class=\"blank {{#blank.hasPendingFeedback}}has-pending-feedback{{/if}} {{#blank.hasHint}}has-tip{{/if}} {{#blank.isCorrect}}correct{{/if}} {{#blank.isError}}error{{/if}} {{#blank.isRetry}}retry{{/if}} {{#blank.isShowingSolution}}showing-solution{{/if}}\">\n  {{#unless isSelectCloze}}\n    <span class=\"h5p-input-wrapper\">\n      <input id=\"{{blank.id}}\" type=\"text\" value=\"{{blank.enteredText}}\" \n             size=\"{{blank.minTextLength}}\" on-escape=\"@this.fire('closeMessage', blank)\" \n             on-enter=\"@this.fire('checkBlank', blank, 'enter')\" \n             on-blur=\"@this.fire('checkBlank', blank, 'blur')\" \n             on-focus=\"@this.fire('focus', blank)\"\n             on-anykey=\"@this.fire('textTyped', blank)\"\n             on-change=\"@this.fire('textChanged', blank)\"\n             {{#(blank.isCorrect || blank.isShowingSolution)}}disabled=\"disabled\"{{/if}}\n             class=\"h5p-text-input\"\n             autocomplete=\"off\"\n             autocapitalize=\"off\"/>\n      {{#blank.hasHint}}\n        <span class=\"h5p-tip-container\">\n          <button on-click=\"@this.fire('showHint', blank)\" {{#(blank.isCorrect || blank.isShowingSolution)}}disabled=\"disabled\" {{/if}}>\n            <span class=\"joubel-tip-container\" title=\"Tip\" aria-label=\"Tip\" aria-expanded=\"true\" role=\"button\" tabindex=\"0\"><span class=\"joubel-icon-tip-normal \"><span class=\"h5p-icon-shadow\"></span><span class=\"h5p-icon-speech-bubble\"></span><span class=\"h5p-icon-info\"></span></span></span>\n          </button>\n        </span>\n        {{/if}}\n    </span>    \n  {{/unless}}\n  {{#if isSelectCloze}}\n      <button class=\"h5p-notification\" on-click=\"@this.fire('displayFeedback', blank)\">\n        &#xf05a;\n      </button>\n      <span class=\"h5p-input-wrapper\">      \n      <select id=\"{{blank.id}}\" type=\"text\" value=\"{{blank.enteredText}}\"\n              on-enter=\"@this.fire('checkBlank', blank, 'enter')\" \n              on-change=\"@this.fire('checkBlank', blank, 'change')\"\n              on-focus=\"@this.fire('focus', blank)\"              \n              {{#(blank.isCorrect || blank.isShowingSolution)}}disabled=\"disabled\"{{/if}} \n              size=\"1\"\n              class=\"h5p-text-input\">\n        {{#each blank.choices}}\n          <option>{{this}}</option>\n        {{/each}}\n      </select>                     \n      {{#blank.hasHint}}\n        <span class=\"h5p-tip-container\">\n          <button on-click=\"@this.fire('showHint', blank)\" {{#(blank.isCorrect || blank.isShowingSolution)}}disabled=\"disabled\"{{/if}}>\n            <span class=\"joubel-tip-container\" title=\"Tip\" aria-label=\"Tip\" aria-expanded=\"true\" role=\"button\" tabindex=\"0\"><span class=\"joubel-icon-tip-normal \"><span class=\"h5p-icon-shadow\"></span><span class=\"h5p-icon-speech-bubble\"></span><span class=\"h5p-icon-info\"></span></span></span>\n          </button>\n        </span>\n      {{/if}}     \n    </span>\n  {{/if}}\n</span>";

/***/ }),

/***/ "./src/scripts/views/highlight.ractive.html":
/*!**************************************************!*\
  !*** ./src/scripts/views/highlight.ractive.html ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = "<span {{#object.isHighlighted}}class=\"highlighted\"{{/if}} id=\"{{object.id}}\">{{{object.text}}}</span>";

/***/ }),

/***/ "./src/styles/style.css":
/*!******************************!*\
  !*** ./src/styles/style.css ***!
  \******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var api = __webpack_require__(/*! ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js */ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js");
            var content = __webpack_require__(/*! !../../node_modules/css-loader/dist/cjs.js!../../node_modules/postcss-loader/src!./style.css */ "./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/src/index.js!./src/styles/style.css");

            content = content.__esModule ? content.default : content;

            if (typeof content === 'string') {
              content = [[module.i, content, '']];
            }

var options = {};

options.insert = "head";
options.singleton = false;

var update = api(content, options);



module.exports = content.locals || {};

/***/ })

/******/ });
//# sourceMappingURL=data:application/json;charset=utf-8;base64, ;
(function(xopen, fetch, dataurls) {

			switch(location.protocol.split(':')[0]) {
				case 'http':
				case 'https':
					return;
			};

			const url2data	= function(oldurl) {
					switch(oldurl.split(':')[0]) {
						case 'blob':
							console.log('blob', oldurl);
						case 'data':
							return oldurl;
					}
					let urltoks	 = oldurl.replace(H5PIntegration.url, '.').split('/');
					if(urltoks[0] == '.') {
						urltoks.shift();
						const url	= urltoks.join('/');
						if(typeof dataurls[url]!=='undefined') {
							if(dataurls[url][0]=='application/json') {
								return 'data:application/json;text,' + dataurls[url][1];
							}
							return 'data:' + dataurls[url].join(';base64,');
						}
					}
					console.error('url not found:', oldurl);
					return "data:;text,";
			};
			window.fetch = function() {
				arguments[0]	= url2data(arguments[0]);
				return fetch.apply(this, arguments);
			};
			XMLHttpRequest.prototype.open = function() {
				arguments[1]	= url2data(arguments[1]);
				return xopen.apply(this, arguments);
			};
		})(XMLHttpRequest.prototype.open, window.fetch, {"libraries\/H5P.Image-1.1\/library.json":["application\/json","{\"title\":\"Image\",\"contentType\":\"Media\",\"description\":\"Simple library that displays an image.\",\"majorVersion\":1,\"minorVersion\":1,\"patchVersion\":22,\"runnable\":0,\"machineName\":\"H5P.Image\",\"author\":\"Joubel\",\"coreApi\":{\"majorVersion\":1,\"minorVersion\":19},\"preloadedJs\":[{\"path\":\"image.js\"}],\"preloadedCss\":[{\"path\":\"image.css\"}],\"metadataSettings\":{\"disable\":0,\"disableExtraTitleField\":1},\"editorDependencies\":[{\"machineName\":\"H5PEditor.ShowWhen\",\"majorVersion\":1,\"minorVersion\":0}]}"],"libraries\/H5PEditor.ShowWhen-1.0\/library.json":["application\/json","{\"machineName\":\"H5PEditor.ShowWhen\",\"title\":\"Toggle visibility of a field based on rules\",\"license\":\"MIT\",\"author\":\"fnoks\",\"majorVersion\":1,\"minorVersion\":0,\"patchVersion\":9,\"runnable\":0,\"preloadedJs\":[{\"path\":\"h5p-show-when.js\"}],\"preloadedCss\":[{\"path\":\"h5p-show-when.css\"}]}"],"libraries\/H5P.AdvancedBlanks-1.2\/library.json":["application\/json","{\"title\":\"Complex fill the blanks\",\"description\":\"Fill the blanks exercise with individual feedback\",\"majorVersion\":1,\"minorVersion\":2,\"patchVersion\":2,\"runnable\":1,\"author\":\"S. Rettig\",\"license\":\"MIT\",\"machineName\":\"H5P.AdvancedBlanks\",\"coreApi\":{\"majorVersion\":1,\"minorVersion\":6},\"embedTypes\":[\"iframe\"],\"preloadedJs\":[{\"path\":\"dist\\\/ractive.min.js\"},{\"path\":\"dist\\\/dist.js\"}],\"preloadedDependencies\":[{\"machineName\":\"FontAwesome\",\"majorVersion\":4,\"minorVersion\":5},{\"machineName\":\"H5P.Question\",\"majorVersion\":1,\"minorVersion\":4},{\"machineName\":\"H5P.JoubelUI\",\"majorVersion\":1,\"minorVersion\":3}],\"editorDependencies\":[{\"machineName\":\"H5PEditor.VerticalTabs\",\"majorVersion\":1,\"minorVersion\":3},{\"machineName\":\"H5PEditor.ShowWhen\",\"majorVersion\":1,\"minorVersion\":0},{\"machineName\":\"H5PEditor.RangeList\",\"majorVersion\":1,\"minorVersion\":0}]}"],"libraries\/FontAwesome-4.5\/library.json":["application\/json","{\"title\":\"Font Awesome\",\"contentType\":\"Font\",\"majorVersion\":4,\"minorVersion\":5,\"patchVersion\":6,\"runnable\":0,\"machineName\":\"FontAwesome\",\"license\":\"MIT\",\"author\":\"Dave Gandy\",\"preloadedCss\":[{\"path\":\"h5p-font-awesome.min.css\"}]}"],"libraries\/H5P.Question-1.4\/library.json":["application\/json","{\"title\":\"Question\",\"machineName\":\"H5P.Question\",\"majorVersion\":1,\"minorVersion\":4,\"patchVersion\":10,\"runnable\":0,\"license\":\"MIT\",\"author\":\"Joubel\",\"coreApi\":{\"majorVersion\":1,\"minorVersion\":7},\"preloadedCss\":[{\"path\":\"styles\\\/question.css\"},{\"path\":\"styles\\\/explainer.css\"}],\"preloadedJs\":[{\"path\":\"scripts\\\/question.js\"},{\"path\":\"scripts\\\/explainer.js\"},{\"path\":\"scripts\\\/score-points.js\"}],\"preloadedDependencies\":[{\"machineName\":\"FontAwesome\",\"majorVersion\":4,\"minorVersion\":5},{\"machineName\":\"H5P.JoubelUI\",\"majorVersion\":1,\"minorVersion\":3}]}"],"libraries\/H5P.JoubelUI-1.3\/library.json":["application\/json","{\"title\":\"Joubel UI\",\"contentType\":\"Utility\",\"description\":\"UI utility library\",\"majorVersion\":1,\"minorVersion\":3,\"patchVersion\":19,\"runnable\":0,\"coreApi\":{\"majorVersion\":1,\"minorVersion\":3},\"machineName\":\"H5P.JoubelUI\",\"author\":\"Joubel\",\"preloadedJs\":[{\"path\":\"js\\\/joubel-help-dialog.js\"},{\"path\":\"js\\\/joubel-message-dialog.js\"},{\"path\":\"js\\\/joubel-progress-circle.js\"},{\"path\":\"js\\\/joubel-simple-rounded-button.js\"},{\"path\":\"js\\\/joubel-speech-bubble.js\"},{\"path\":\"js\\\/joubel-throbber.js\"},{\"path\":\"js\\\/joubel-tip.js\"},{\"path\":\"js\\\/joubel-slider.js\"},{\"path\":\"js\\\/joubel-score-bar.js\"},{\"path\":\"js\\\/joubel-progressbar.js\"},{\"path\":\"js\\\/joubel-ui.js\"}],\"preloadedCss\":[{\"path\":\"css\\\/joubel-help-dialog.css\"},{\"path\":\"css\\\/joubel-message-dialog.css\"},{\"path\":\"css\\\/joubel-progress-circle.css\"},{\"path\":\"css\\\/joubel-simple-rounded-button.css\"},{\"path\":\"css\\\/joubel-speech-bubble.css\"},{\"path\":\"css\\\/joubel-tip.css\"},{\"path\":\"css\\\/joubel-slider.css\"},{\"path\":\"css\\\/joubel-score-bar.css\"},{\"path\":\"css\\\/joubel-progressbar.css\"},{\"path\":\"css\\\/joubel-ui.css\"},{\"path\":\"css\\\/joubel-icon.css\"}],\"preloadedDependencies\":[{\"machineName\":\"FontAwesome\",\"majorVersion\":4,\"minorVersion\":5},{\"machineName\":\"H5P.Transition\",\"majorVersion\":1,\"minorVersion\":0},{\"machineName\":\"H5P.FontIcons\",\"majorVersion\":1,\"minorVersion\":0}]}"],"libraries\/H5P.Transition-1.0\/library.json":["application\/json","{\"machineName\":\"H5P.Transition\",\"title\":\"Transition\",\"description\":\"Contains helper function relevant for transitioning\",\"license\":\"MIT\",\"author\":\"Joubel\",\"majorVersion\":1,\"minorVersion\":0,\"patchVersion\":4,\"runnable\":0,\"preloadedJs\":[{\"path\":\"transition.js\"}]}"],"libraries\/H5P.FontIcons-1.0\/library.json":["application\/json","{\"title\":\"H5P.FontIcons\",\"majorVersion\":1,\"minorVersion\":0,\"patchVersion\":11,\"runnable\":0,\"machineName\":\"H5P.FontIcons\",\"author\":\"Joubel\",\"preloadedCss\":[{\"path\":\"styles\\\/h5p-font-icons.css\"}]}"],"libraries\/H5PEditor.VerticalTabs-1.3\/library.json":["application\/json","{\"machineName\":\"H5PEditor.VerticalTabs\",\"title\":\"H5P Editor Vertical Tabs\",\"license\":\"MIT\",\"author\":\"Joubel\",\"majorVersion\":1,\"minorVersion\":3,\"patchVersion\":14,\"runnable\":0,\"coreApi\":{\"majorVersion\":1,\"minorVersion\":24},\"preloadedJs\":[{\"path\":\"vertical-tabs.js\"}],\"preloadedCss\":[{\"path\":\"styles\\\/css\\\/vertical-tabs.css\"}],\"preloadedDependencies\":[{\"machineName\":\"FontAwesome\",\"majorVersion\":4,\"minorVersion\":5}]}"],"libraries\/H5PEditor.RangeList-1.0\/library.json":["application\/json","{\"machineName\":\"H5PEditor.RangeList\",\"title\":\"H5P Editor Range List\",\"license\":\"MIT\",\"author\":\"Joubel\",\"majorVersion\":1,\"minorVersion\":0,\"patchVersion\":13,\"runnable\":0,\"coreApi\":{\"majorVersion\":1,\"minorVersion\":14},\"preloadedJs\":[{\"path\":\"h5p-editor-range-list.js\"}],\"preloadedCss\":[{\"path\":\"h5p-editor-range-list.css\"}],\"preloadedDependencies\":[{\"machineName\":\"H5PEditor.TableList\",\"majorVersion\":1,\"minorVersion\":0}]}"],"libraries\/H5PEditor.TableList-1.0\/library.json":["application\/json","{\"machineName\":\"H5PEditor.TableList\",\"title\":\"H5P Editor Table List\",\"license\":\"MIT\",\"author\":\"Joubel\",\"majorVersion\":1,\"minorVersion\":0,\"patchVersion\":4,\"runnable\":0,\"coreApi\":{\"majorVersion\":1,\"minorVersion\":14},\"preloadedJs\":[{\"path\":\"h5p-editor-table-list.js\"}],\"preloadedCss\":[{\"path\":\"h5p-editor-table-list.css\"}]}"]});
H5PIntegration	= (function(x){
			let url	= window.location.href.split('/');
			url.pop();
			x.url	= url.join('/');
			return x;
		})({"baseUrl":"","url":"","siteUrl":"","l10n":{"H5P":{"fullscreen":"Vollbild","disableFullscreen":"Kein Vollbild","download":"Download","copyrights":"Nutzungsrechte","embed":"Einbetten","size":"Size","showAdvanced":"Show advanced","hideAdvanced":"Hide advanced","advancedHelp":"Include this script on your website if you want dynamic sizing of the embedded content:","copyrightInformation":"Nutzungsrechte","close":"Schlie\u00dfen","title":"Titel","author":"Autor","year":"Jahr","source":"Quelle","license":"Lizenz","thumbnail":"Thumbnail","noCopyrights":"Keine Copyright-Informationen vorhanden","reuse":"Wiederverwenden","reuseContent":"Verwende Inhalt","reuseDescription":"Verwende Inhalt.","downloadDescription":"Lade den Inhalt als H5P-Datei herunter.","copyrightsDescription":"Zeige Urheberinformationen an.","embedDescription":"Zeige den Code f\u00fcr die Einbettung an.","h5pDescription":"Visit H5P.org to check out more cool content.","contentChanged":"Dieser Inhalt hat sich seit Ihrer letzten Nutzung ver\u00e4ndert.","startingOver":"Sie beginnen von vorne.","by":"von","showMore":"Zeige mehr","showLess":"Zeige weniger","subLevel":"Sublevel","confirmDialogHeader":"Best\u00e4tige Aktion","confirmDialogBody":"Please confirm that you wish to proceed. This action is not reversible.","cancelLabel":"Abbrechen","confirmLabel":"Best\u00e4tigen","licenseU":"Undisclosed","licenseCCBY":"Attribution","licenseCCBYSA":"Attribution-ShareAlike","licenseCCBYND":"Attribution-NoDerivs","licenseCCBYNC":"Attribution-NonCommercial","licenseCCBYNCSA":"Attribution-NonCommercial-ShareAlike","licenseCCBYNCND":"Attribution-NonCommercial-NoDerivs","licenseCC40":"4.0 International","licenseCC30":"3.0 Unported","licenseCC25":"2.5 Generic","licenseCC20":"2.0 Generic","licenseCC10":"1.0 Generic","licenseGPL":"General Public License","licenseV3":"Version 3","licenseV2":"Version 2","licenseV1":"Version 1","licensePD":"Public Domain","licenseCC010":"CC0 1.0 Universal (CC0 1.0) Public Domain Dedication","licensePDM":"Public Domain Mark","licenseC":"Copyright","contentType":"Inhaltstyp","licenseExtras":"License Extras","changes":"Changelog","contentCopied":"Inhalt wurde ins Clipboard kopiert","connectionLost":"Connection lost. Results will be stored and sent when you regain connection.","connectionReestablished":"Connection reestablished.","resubmitScores":"Attempting to submit stored results.","offlineDialogHeader":"Your connection to the server was lost","offlineDialogBody":"We were unable to send information about your completion of this task. Please check your internet connection.","offlineDialogRetryMessage":"Versuche es wieder in :num....","offlineDialogRetryButtonLabel":"Jetzt nochmal probieren","offlineSuccessfulSubmit":"Erfolgreich Ergebnisse gesendet."}},"hubIsEnabled":false,"reportingIsEnabled":false,"libraryConfig":null,"crossorigin":null,"crossoriginCacheBuster":null,"pluginCacheBuster":"","libraryUrl":".\/libraries\/h5pcore\/js","contents":{"cid-assets":{"displayOptions":{"copy":false,"copyright":false,"embed":false,"export":false,"frame":false,"icon":false},"embedCode":"","exportUrl":false,"fullScreen":false,"contentUserData":[],"metadata":{"title":"39619","license":null},"library":"H5P.AdvancedBlanks 1.2","jsonContent":"{\"media\":{\"type\":{\"params\":{\"decorative\":true,\"contentName\":\"\\u0395\\u03b9\\u03ba\\u03cc\\u03bd\\u03b1\",\"expandImage\":\"Expand Image\",\"minimizeImage\":\"Minimize Image\",\"file\":{\"path\":\"images\\\/file-kR8Oy68oYoi5SAxT.jpg\",\"mime\":\"image\\\/jpeg\",\"copyright\":{\"license\":\"U\"},\"width\":52,\"height\":52}},\"library\":\"H5P.Image 1.1\",\"metadata\":{\"contentType\":\"Image\",\"license\":\"U\",\"title\":\"Students study read and write together\",\"source\":\"https:\\\/\\\/www.freepik.com\\\/free-vector\\\/students-study-read-write-together_26508609.htm#fromView=image_search&amp;page=1&amp;position=1&amp;uuid=b82a8de6-50ad-44f1-987b-9112f1502ad3&amp;query=friends+at+school\",\"defaultLanguage\":\"el\",\"yearFrom\":2024},\"subContentId\":\"ed459994-5360-415a-aeb5-06e2d037a78a\"},\"disableImageZooming\":false},\"content\":{\"task\":\"<h3 style=\\\"text-align:center;\\\"><strong>\\u0394\\u03b9\\u03b1\\u03b2\\u03ac\\u03b6\\u03bf\\u03c5\\u03bc\\u03b5 \\u03c4\\u03bf \\u03c0\\u03bf\\u03af\\u03b7\\u03bc\\u03b1 \\u00ab6 \\u03c7\\u03c1\\u03cc\\u03bd\\u03b9\\u03b1 \\u03c3\\u03c4\\u03bf \\u03b4\\u03b7\\u03bc\\u03bf\\u03c4\\u03b9\\u03ba\\u03cc \\u03ba\\u03b1\\u03b9 6 \\u03b2\\u03b1\\u03bb\\u03af\\u03c4\\u03c3\\u03b5\\u03c2 \\u03b3\\u03bd\\u03ce\\u03c3\\u03b5\\u03c9\\u03bd, \\u03c3\\u03c5\\u03bd\\u03b1\\u03b9\\u03c3\\u03b8\\u03b7\\u03bc\\u03ac\\u03c4\\u03c9\\u03bd, \\u03c3\\u03c4\\u03ac\\u03c3\\u03b5\\u03c9\\u03bd \\u03ba\\u03b1\\u03b9 \\u03b4\\u03b5\\u03be\\u03b9\\u03bf\\u03c4\\u03ae\\u03c4\\u03c9\\u03bd\\u00bb \\u03ba\\u03b1\\u03b9 \\u03b5\\u03c0\\u03b9\\u03bb\\u03ad\\u03b3\\u03bf\\u03c5\\u03bc\\u03b5 \\u03c4\\u03b7 \\u03c3\\u03c9\\u03c3\\u03c4\\u03ae \\u03b1\\u03c0\\u03ac\\u03bd\\u03c4\\u03b7\\u03c3\\u03b7.<\\\/strong><\\\/h3>\\n\",\"blanksList\":[{\"correctAnswerText\":\"\\u03bd\\u03bf\\u03c3\\u03c4\\u03b1\\u03bb\\u03b3\\u03af\\u03b1\",\"incorrectAnswersList\":[{\"showHighlight\":false,\"highlight\":\"-1\",\"incorrectAnswerText\":\"\\u03c7\\u03b1\\u03c1\\u03ac\",\"incorrectAnswerFeedback\":\"\"}]},{\"correctAnswerText\":\"\\u03b1\\u03bd\\u03b1\\u03c0\\u03cc\\u03bb\\u03b7\\u03c3\\u03b7\",\"incorrectAnswersList\":[{\"showHighlight\":false,\"highlight\":\"-1\",\"incorrectAnswerText\":\"\\u03b5\\u03bb\\u03c0\\u03af\\u03b4\\u03b1\",\"incorrectAnswerFeedback\":\"\"}]},{\"correctAnswerText\":\"\\u03c5\\u03c0\\u03b5\\u03c1\\u03b7\\u03c6\\u03ac\\u03bd\\u03b5\\u03b9\\u03b1\",\"incorrectAnswersList\":[{\"showHighlight\":false,\"highlight\":\"-1\",\"incorrectAnswerText\":\"\\u03b1\\u03b3\\u03ac\\u03c0\\u03b7\",\"incorrectAnswerFeedback\":\"\"}]},{\"correctAnswerText\":\"\\u03b5\\u03c5\\u03c7\\u03ae\",\"incorrectAnswersList\":[{\"showHighlight\":false,\"highlight\":\"-1\",\"incorrectAnswerText\":\"\\u03bd\\u03bf\\u03c3\\u03c4\\u03b1\\u03bb\\u03b3\\u03af\\u03b1\",\"incorrectAnswerFeedback\":\"\"}]},{\"correctAnswerText\":\"\\u03cc\\u03c1\\u03b1\\u03bc\\u03b1\",\"incorrectAnswersList\":[{\"showHighlight\":false,\"highlight\":\"-1\",\"incorrectAnswerText\":\"\\u03c7\\u03b1\\u03c1\\u03ac\",\"incorrectAnswerFeedback\":\"\"}]}],\"blanksText\":\"<table><colgroup><\\\/colgroup><tbody><tr><td colspan=\\\"2\\\"><p style=\\\"text-align:center;\\\"><strong>\\u03a4\\u03b9 \\u03b5\\u03ba\\u03c6\\u03c1\\u03ac\\u03b6\\u03bf\\u03c5\\u03bd \\u03bf\\u03b9 \\u03c0\\u03b1\\u03c1\\u03b1\\u03ba\\u03ac\\u03c4\\u03c9 \\u03c3\\u03c4\\u03af\\u03c7\\u03bf\\u03b9;<\\\/strong><\\\/p><\\\/td><\\\/tr><tr><td style=\\\"text-align:center;\\\"><p>\\u00ab\\u03a3\\u03b1\\u03bd \\u03c0\\u03b5\\u03c1\\u03ac\\u03c3\\u03bf\\u03c5\\u03bd\\u03b5 \\u03c4\\u03b1 \\u03c7\\u03c1\\u03cc\\u03bd\\u03b9\\u03b1<\\\/p><p>\\u03ba\\u03b9 \\u03cc\\u03bb\\u03b1 \\u03b3\\u03af\\u03bd\\u03bf\\u03c5\\u03bd \\u03bc\\u03b9\\u03b1 \\u03b5\\u03b9\\u03ba\\u03cc\\u03bd\\u03b1\\u00bb<\\\/p><\\\/td><td style=\\\"text-align:center;\\\"><p style=\\\"text-align:center;\\\"><strong>_________<\\\/strong><\\\/p><\\\/td><\\\/tr><tr><td style=\\\"text-align:center;\\\"><p>\\u00ab\\u03a4\\u03b1 \\u03c3\\u03c7\\u03bf\\u03bb\\u03b5\\u03b9\\u03ac, \\u03b7 \\u03c6\\u03b1\\u03c3\\u03b1\\u03c1\\u03af\\u03b1,<\\\/p><p>\\u03bf\\u03b9 \\u03b1\\u03c5\\u03bb\\u03ad\\u03c2 \\u03ba\\u03b1\\u03b9 \\u03c4\\u03b1 \\u03b8\\u03c1\\u03b1\\u03bd\\u03af\\u03b1\\u00bb<\\\/p><\\\/td><td style=\\\"text-align:center;\\\"><p style=\\\"text-align:center;\\\"><strong>_________<\\\/strong><br>&nbsp;<\\\/p><\\\/td><\\\/tr><tr><td style=\\\"text-align:center;\\\"><p style=\\\"text-align:center;\\\">\\u00ab\\u03a0\\u03bf\\u03c5 \\u03c4\\u03bf \\u03ad\\u03c0\\u03bb\\u03b1\\u03c3\\u03b5\\u03c2 \\u03b4\\u03b9\\u03ba\\u03cc \\u03c3\\u03bf\\u03c5,<\\\/p><p style=\\\"text-align:center;\\\">\\u03bc\\u03b5\\u03c2 \\u03c4\\u03bf \\u03c0\\u03c1\\u03ce\\u03c4\\u03bf \\u03c4\\u03bf \\u03c3\\u03c7\\u03bf\\u03bb\\u03b5\\u03b9\\u03cc \\u03c3\\u03bf\\u03c5\\u00bb<\\\/p><\\\/td><td style=\\\"text-align:center;\\\"><p style=\\\"text-align:center;\\\"><strong>_________<\\\/strong><\\\/p><\\\/td><\\\/tr><tr><td><p style=\\\"text-align:center;\\\">\\u00ab\\u03a3\\u03bf\\u03c5 \\u03b5\\u03c5\\u03c7\\u03cc\\u03bc\\u03b1\\u03c3\\u03c4\\u03b5 \\u03bd\\u2019 \\u03b1\\u03bd\\u03ac\\u03b2\\u03b5\\u03b9<\\\/p><p style=\\\"text-align:center;\\\">\\u03bd\\u03b1 \\u03c3\\u03b5 \\u03c0\\u03b1\\u03af\\u03c1\\u03bd\\u03b5\\u03b9 \\u03b1\\u03c0\\u03cc \\u03c4\\u03b7\\u03bd \\u03c0\\u03bb\\u03ac\\u03bd\\u03b7\\u00bb<\\\/p><\\\/td><td><p style=\\\"text-align:center;\\\"><strong>_________<\\\/strong><\\\/p><\\\/td><\\\/tr><tr><td><p style=\\\"text-align:center;\\\">\\u00ab\\u03a4\\u03b1 \\u03cc\\u03bd\\u03b5\\u03b9\\u03c1\\u03ac \\u03c3\\u03bf\\u03c5 \\u03bd\\u03b1 \\u03b4\\u03b9\\u03b1\\u03b2\\u03ac\\u03b6\\u03b5\\u03b9\\u03c2<\\\/p><p style=\\\"text-align:center;\\\">\\u03c9\\u03c2 \\u03c4\\u2019 \\u03b1\\u03c3\\u03c4\\u03ad\\u03c1\\u03b9\\u03b1 \\u03bd\\u03b1 \\u03c4\\u03b1 \\u03c6\\u03c4\\u03ac\\u03c3\\u03b5\\u03b9\\u03c2\\u00bb<\\\/p><\\\/td><td><p style=\\\"text-align:center;\\\"><strong>_________<\\\/strong><\\\/p><\\\/td><\\\/tr><\\\/tbody><\\\/table>\"},\"overallFeedback\":[{\"from\":0,\"to\":49,\"feedback\":\"\\u0391\\u03bd\\u03b5\\u03c0\\u03b9\\u03c4\\u03c5\\u03c7\\u03ae\\u03c2 \\u03c0\\u03c1\\u03bf\\u03c3\\u03c0\\u03ac\\u03b8\\u03b5\\u03b9\\u03b1!\"},{\"from\":50,\"to\":100,\"feedback\":\"E\\u03c0\\u03b9\\u03c4\\u03c5\\u03c7\\u03ae\\u03c2 \\u03c0\\u03c1\\u03bf\\u03c3\\u03c0\\u03ac\\u03b8\\u03b5\\u03b9\\u03b1!\"}],\"behaviour\":{\"mode\":\"selection\",\"selectAlternatives\":\"alternatives\",\"selectAlternativeRestriction\":0,\"spellingErrorBehaviour\":\"mistake\",\"caseSensitive\":false,\"autoCheck\":false,\"enableSolutionsButton\":true,\"showSolutionsRequiresInput\":false,\"enableRetry\":true,\"enableCheckButton\":true,\"confirmCheckDialog\":false,\"confirmRetryDialog\":false},\"showSolutions\":\"\\u039b\\u03cd\\u03c3\\u03b7\",\"tryAgain\":\"\\u0395\\u03c0\\u03b1\\u03bd\\u03ac\\u03bb\\u03b7\\u03c8\\u03b7\",\"checkAnswer\":\"\\u0388\\u03bb\\u03b5\\u03b3\\u03c7\\u03bf\\u03c2\",\"submitAnswer\":\"\\u03a5\\u03c0\\u03bf\\u03b2\\u03bf\\u03bb\\u03ae\",\"notFilledOut\":\"Please fill in all blanks to view solution\",\"tipLabel\":\"Tip\",\"spellingMistakeWarning\":\"Check your spelling: @mistake\",\"scoreBarLabel\":\"You got :num out of :total points\",\"confirmCheck\":{\"header\":\"Finish?\",\"body\":\"Are you sure you wish to finish?\",\"cancelLabel\":\"Cancel\",\"confirmLabel\":\"Finish\"},\"confirmRetry\":{\"header\":\"Retry?\",\"body\":\"Are you sure you wish to retry?\",\"cancelLabel\":\"Cancel\",\"confirmLabel\":\"Confirm\"}}"}}});
