• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * @license
3 * Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
4 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
5 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
6 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
7 * Code distributed by Google as part of the polymer project is also
8 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
9 */
10// @version 0.6.1
11window.WebComponents = window.WebComponents || {};
12
13(function(scope) {
14  var flags = scope.flags || {};
15  var file = "webcomponents.js";
16  var script = document.querySelector('script[src*="' + file + '"]');
17  if (!flags.noOpts) {
18    location.search.slice(1).split("&").forEach(function(o) {
19      o = o.split("=");
20      o[0] && (flags[o[0]] = o[1] || true);
21    });
22    if (script) {
23      for (var i = 0, a; a = script.attributes[i]; i++) {
24        if (a.name !== "src") {
25          flags[a.name] = a.value || true;
26        }
27      }
28    }
29    if (flags.log && flags.log.split) {
30      var parts = flags.log.split(",");
31      flags.log = {};
32      parts.forEach(function(f) {
33        flags.log[f] = true;
34      });
35    } else {
36      flags.log = {};
37    }
38  }
39  flags.shadow = flags.shadow || flags.shadowdom || flags.polyfill;
40  if (flags.shadow === "native") {
41    flags.shadow = false;
42  } else {
43    flags.shadow = flags.shadow || !HTMLElement.prototype.createShadowRoot;
44  }
45  if (flags.register) {
46    window.CustomElements = window.CustomElements || {
47      flags: {}
48    };
49    window.CustomElements.flags.register = flags.register;
50  }
51  scope.flags = flags;
52})(WebComponents);
53
54if (WebComponents.flags.shadow) {
55  if (typeof WeakMap === "undefined") {
56    (function() {
57      var defineProperty = Object.defineProperty;
58      var counter = Date.now() % 1e9;
59      var WeakMap = function() {
60        this.name = "__st" + (Math.random() * 1e9 >>> 0) + (counter++ + "__");
61      };
62      WeakMap.prototype = {
63        set: function(key, value) {
64          var entry = key[this.name];
65          if (entry && entry[0] === key) entry[1] = value; else defineProperty(key, this.name, {
66            value: [ key, value ],
67            writable: true
68          });
69          return this;
70        },
71        get: function(key) {
72          var entry;
73          return (entry = key[this.name]) && entry[0] === key ? entry[1] : undefined;
74        },
75        "delete": function(key) {
76          var entry = key[this.name];
77          if (!entry || entry[0] !== key) return false;
78          entry[0] = entry[1] = undefined;
79          return true;
80        },
81        has: function(key) {
82          var entry = key[this.name];
83          if (!entry) return false;
84          return entry[0] === key;
85        }
86      };
87      window.WeakMap = WeakMap;
88    })();
89  }
90  window.ShadowDOMPolyfill = {};
91  (function(scope) {
92    "use strict";
93    var constructorTable = new WeakMap();
94    var nativePrototypeTable = new WeakMap();
95    var wrappers = Object.create(null);
96    function detectEval() {
97      if (typeof chrome !== "undefined" && chrome.app && chrome.app.runtime) {
98        return false;
99      }
100      if (navigator.getDeviceStorage) {
101        return false;
102      }
103      try {
104        var f = new Function("return true;");
105        return f();
106      } catch (ex) {
107        return false;
108      }
109    }
110    var hasEval = detectEval();
111    function assert(b) {
112      if (!b) throw new Error("Assertion failed");
113    }
114    var defineProperty = Object.defineProperty;
115    var getOwnPropertyNames = Object.getOwnPropertyNames;
116    var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
117    function mixin(to, from) {
118      var names = getOwnPropertyNames(from);
119      for (var i = 0; i < names.length; i++) {
120        var name = names[i];
121        defineProperty(to, name, getOwnPropertyDescriptor(from, name));
122      }
123      return to;
124    }
125    function mixinStatics(to, from) {
126      var names = getOwnPropertyNames(from);
127      for (var i = 0; i < names.length; i++) {
128        var name = names[i];
129        switch (name) {
130         case "arguments":
131         case "caller":
132         case "length":
133         case "name":
134         case "prototype":
135         case "toString":
136          continue;
137        }
138        defineProperty(to, name, getOwnPropertyDescriptor(from, name));
139      }
140      return to;
141    }
142    function oneOf(object, propertyNames) {
143      for (var i = 0; i < propertyNames.length; i++) {
144        if (propertyNames[i] in object) return propertyNames[i];
145      }
146    }
147    var nonEnumerableDataDescriptor = {
148      value: undefined,
149      configurable: true,
150      enumerable: false,
151      writable: true
152    };
153    function defineNonEnumerableDataProperty(object, name, value) {
154      nonEnumerableDataDescriptor.value = value;
155      defineProperty(object, name, nonEnumerableDataDescriptor);
156    }
157    getOwnPropertyNames(window);
158    function getWrapperConstructor(node) {
159      var nativePrototype = node.__proto__ || Object.getPrototypeOf(node);
160      if (isFirefox) {
161        try {
162          getOwnPropertyNames(nativePrototype);
163        } catch (error) {
164          nativePrototype = nativePrototype.__proto__;
165        }
166      }
167      var wrapperConstructor = constructorTable.get(nativePrototype);
168      if (wrapperConstructor) return wrapperConstructor;
169      var parentWrapperConstructor = getWrapperConstructor(nativePrototype);
170      var GeneratedWrapper = createWrapperConstructor(parentWrapperConstructor);
171      registerInternal(nativePrototype, GeneratedWrapper, node);
172      return GeneratedWrapper;
173    }
174    function addForwardingProperties(nativePrototype, wrapperPrototype) {
175      installProperty(nativePrototype, wrapperPrototype, true);
176    }
177    function registerInstanceProperties(wrapperPrototype, instanceObject) {
178      installProperty(instanceObject, wrapperPrototype, false);
179    }
180    var isFirefox = /Firefox/.test(navigator.userAgent);
181    var dummyDescriptor = {
182      get: function() {},
183      set: function(v) {},
184      configurable: true,
185      enumerable: true
186    };
187    function isEventHandlerName(name) {
188      return /^on[a-z]+$/.test(name);
189    }
190    function isIdentifierName(name) {
191      return /^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(name);
192    }
193    function getGetter(name) {
194      return hasEval && isIdentifierName(name) ? new Function("return this.__impl4cf1e782hg__." + name) : function() {
195        return this.__impl4cf1e782hg__[name];
196      };
197    }
198    function getSetter(name) {
199      return hasEval && isIdentifierName(name) ? new Function("v", "this.__impl4cf1e782hg__." + name + " = v") : function(v) {
200        this.__impl4cf1e782hg__[name] = v;
201      };
202    }
203    function getMethod(name) {
204      return hasEval && isIdentifierName(name) ? new Function("return this.__impl4cf1e782hg__." + name + ".apply(this.__impl4cf1e782hg__, arguments)") : function() {
205        return this.__impl4cf1e782hg__[name].apply(this.__impl4cf1e782hg__, arguments);
206      };
207    }
208    function getDescriptor(source, name) {
209      try {
210        return Object.getOwnPropertyDescriptor(source, name);
211      } catch (ex) {
212        return dummyDescriptor;
213      }
214    }
215    var isBrokenSafari = function() {
216      var descr = Object.getOwnPropertyDescriptor(Node.prototype, "nodeType");
217      return descr && !descr.get && !descr.set;
218    }();
219    function installProperty(source, target, allowMethod, opt_blacklist) {
220      var names = getOwnPropertyNames(source);
221      for (var i = 0; i < names.length; i++) {
222        var name = names[i];
223        if (name === "polymerBlackList_") continue;
224        if (name in target) continue;
225        if (source.polymerBlackList_ && source.polymerBlackList_[name]) continue;
226        if (isFirefox) {
227          source.__lookupGetter__(name);
228        }
229        var descriptor = getDescriptor(source, name);
230        var getter, setter;
231        if (allowMethod && typeof descriptor.value === "function") {
232          target[name] = getMethod(name);
233          continue;
234        }
235        var isEvent = isEventHandlerName(name);
236        if (isEvent) getter = scope.getEventHandlerGetter(name); else getter = getGetter(name);
237        if (descriptor.writable || descriptor.set || isBrokenSafari) {
238          if (isEvent) setter = scope.getEventHandlerSetter(name); else setter = getSetter(name);
239        }
240        var configurable = isBrokenSafari || descriptor.configurable;
241        defineProperty(target, name, {
242          get: getter,
243          set: setter,
244          configurable: configurable,
245          enumerable: descriptor.enumerable
246        });
247      }
248    }
249    function register(nativeConstructor, wrapperConstructor, opt_instance) {
250      var nativePrototype = nativeConstructor.prototype;
251      registerInternal(nativePrototype, wrapperConstructor, opt_instance);
252      mixinStatics(wrapperConstructor, nativeConstructor);
253    }
254    function registerInternal(nativePrototype, wrapperConstructor, opt_instance) {
255      var wrapperPrototype = wrapperConstructor.prototype;
256      assert(constructorTable.get(nativePrototype) === undefined);
257      constructorTable.set(nativePrototype, wrapperConstructor);
258      nativePrototypeTable.set(wrapperPrototype, nativePrototype);
259      addForwardingProperties(nativePrototype, wrapperPrototype);
260      if (opt_instance) registerInstanceProperties(wrapperPrototype, opt_instance);
261      defineNonEnumerableDataProperty(wrapperPrototype, "constructor", wrapperConstructor);
262      wrapperConstructor.prototype = wrapperPrototype;
263    }
264    function isWrapperFor(wrapperConstructor, nativeConstructor) {
265      return constructorTable.get(nativeConstructor.prototype) === wrapperConstructor;
266    }
267    function registerObject(object) {
268      var nativePrototype = Object.getPrototypeOf(object);
269      var superWrapperConstructor = getWrapperConstructor(nativePrototype);
270      var GeneratedWrapper = createWrapperConstructor(superWrapperConstructor);
271      registerInternal(nativePrototype, GeneratedWrapper, object);
272      return GeneratedWrapper;
273    }
274    function createWrapperConstructor(superWrapperConstructor) {
275      function GeneratedWrapper(node) {
276        superWrapperConstructor.call(this, node);
277      }
278      var p = Object.create(superWrapperConstructor.prototype);
279      p.constructor = GeneratedWrapper;
280      GeneratedWrapper.prototype = p;
281      return GeneratedWrapper;
282    }
283    function isWrapper(object) {
284      return object && object.__impl4cf1e782hg__;
285    }
286    function isNative(object) {
287      return !isWrapper(object);
288    }
289    function wrap(impl) {
290      if (impl === null) return null;
291      assert(isNative(impl));
292      return impl.__wrapper8e3dd93a60__ || (impl.__wrapper8e3dd93a60__ = new (getWrapperConstructor(impl))(impl));
293    }
294    function unwrap(wrapper) {
295      if (wrapper === null) return null;
296      assert(isWrapper(wrapper));
297      return wrapper.__impl4cf1e782hg__;
298    }
299    function unsafeUnwrap(wrapper) {
300      return wrapper.__impl4cf1e782hg__;
301    }
302    function setWrapper(impl, wrapper) {
303      wrapper.__impl4cf1e782hg__ = impl;
304      impl.__wrapper8e3dd93a60__ = wrapper;
305    }
306    function unwrapIfNeeded(object) {
307      return object && isWrapper(object) ? unwrap(object) : object;
308    }
309    function wrapIfNeeded(object) {
310      return object && !isWrapper(object) ? wrap(object) : object;
311    }
312    function rewrap(node, wrapper) {
313      if (wrapper === null) return;
314      assert(isNative(node));
315      assert(wrapper === undefined || isWrapper(wrapper));
316      node.__wrapper8e3dd93a60__ = wrapper;
317    }
318    var getterDescriptor = {
319      get: undefined,
320      configurable: true,
321      enumerable: true
322    };
323    function defineGetter(constructor, name, getter) {
324      getterDescriptor.get = getter;
325      defineProperty(constructor.prototype, name, getterDescriptor);
326    }
327    function defineWrapGetter(constructor, name) {
328      defineGetter(constructor, name, function() {
329        return wrap(this.__impl4cf1e782hg__[name]);
330      });
331    }
332    function forwardMethodsToWrapper(constructors, names) {
333      constructors.forEach(function(constructor) {
334        names.forEach(function(name) {
335          constructor.prototype[name] = function() {
336            var w = wrapIfNeeded(this);
337            return w[name].apply(w, arguments);
338          };
339        });
340      });
341    }
342    scope.assert = assert;
343    scope.constructorTable = constructorTable;
344    scope.defineGetter = defineGetter;
345    scope.defineWrapGetter = defineWrapGetter;
346    scope.forwardMethodsToWrapper = forwardMethodsToWrapper;
347    scope.isIdentifierName = isIdentifierName;
348    scope.isWrapper = isWrapper;
349    scope.isWrapperFor = isWrapperFor;
350    scope.mixin = mixin;
351    scope.nativePrototypeTable = nativePrototypeTable;
352    scope.oneOf = oneOf;
353    scope.registerObject = registerObject;
354    scope.registerWrapper = register;
355    scope.rewrap = rewrap;
356    scope.setWrapper = setWrapper;
357    scope.unsafeUnwrap = unsafeUnwrap;
358    scope.unwrap = unwrap;
359    scope.unwrapIfNeeded = unwrapIfNeeded;
360    scope.wrap = wrap;
361    scope.wrapIfNeeded = wrapIfNeeded;
362    scope.wrappers = wrappers;
363  })(window.ShadowDOMPolyfill);
364  (function(scope) {
365    "use strict";
366    function newSplice(index, removed, addedCount) {
367      return {
368        index: index,
369        removed: removed,
370        addedCount: addedCount
371      };
372    }
373    var EDIT_LEAVE = 0;
374    var EDIT_UPDATE = 1;
375    var EDIT_ADD = 2;
376    var EDIT_DELETE = 3;
377    function ArraySplice() {}
378    ArraySplice.prototype = {
379      calcEditDistances: function(current, currentStart, currentEnd, old, oldStart, oldEnd) {
380        var rowCount = oldEnd - oldStart + 1;
381        var columnCount = currentEnd - currentStart + 1;
382        var distances = new Array(rowCount);
383        for (var i = 0; i < rowCount; i++) {
384          distances[i] = new Array(columnCount);
385          distances[i][0] = i;
386        }
387        for (var j = 0; j < columnCount; j++) distances[0][j] = j;
388        for (var i = 1; i < rowCount; i++) {
389          for (var j = 1; j < columnCount; j++) {
390            if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1])) distances[i][j] = distances[i - 1][j - 1]; else {
391              var north = distances[i - 1][j] + 1;
392              var west = distances[i][j - 1] + 1;
393              distances[i][j] = north < west ? north : west;
394            }
395          }
396        }
397        return distances;
398      },
399      spliceOperationsFromEditDistances: function(distances) {
400        var i = distances.length - 1;
401        var j = distances[0].length - 1;
402        var current = distances[i][j];
403        var edits = [];
404        while (i > 0 || j > 0) {
405          if (i == 0) {
406            edits.push(EDIT_ADD);
407            j--;
408            continue;
409          }
410          if (j == 0) {
411            edits.push(EDIT_DELETE);
412            i--;
413            continue;
414          }
415          var northWest = distances[i - 1][j - 1];
416          var west = distances[i - 1][j];
417          var north = distances[i][j - 1];
418          var min;
419          if (west < north) min = west < northWest ? west : northWest; else min = north < northWest ? north : northWest;
420          if (min == northWest) {
421            if (northWest == current) {
422              edits.push(EDIT_LEAVE);
423            } else {
424              edits.push(EDIT_UPDATE);
425              current = northWest;
426            }
427            i--;
428            j--;
429          } else if (min == west) {
430            edits.push(EDIT_DELETE);
431            i--;
432            current = west;
433          } else {
434            edits.push(EDIT_ADD);
435            j--;
436            current = north;
437          }
438        }
439        edits.reverse();
440        return edits;
441      },
442      calcSplices: function(current, currentStart, currentEnd, old, oldStart, oldEnd) {
443        var prefixCount = 0;
444        var suffixCount = 0;
445        var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart);
446        if (currentStart == 0 && oldStart == 0) prefixCount = this.sharedPrefix(current, old, minLength);
447        if (currentEnd == current.length && oldEnd == old.length) suffixCount = this.sharedSuffix(current, old, minLength - prefixCount);
448        currentStart += prefixCount;
449        oldStart += prefixCount;
450        currentEnd -= suffixCount;
451        oldEnd -= suffixCount;
452        if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return [];
453        if (currentStart == currentEnd) {
454          var splice = newSplice(currentStart, [], 0);
455          while (oldStart < oldEnd) splice.removed.push(old[oldStart++]);
456          return [ splice ];
457        } else if (oldStart == oldEnd) return [ newSplice(currentStart, [], currentEnd - currentStart) ];
458        var ops = this.spliceOperationsFromEditDistances(this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd));
459        var splice = undefined;
460        var splices = [];
461        var index = currentStart;
462        var oldIndex = oldStart;
463        for (var i = 0; i < ops.length; i++) {
464          switch (ops[i]) {
465           case EDIT_LEAVE:
466            if (splice) {
467              splices.push(splice);
468              splice = undefined;
469            }
470            index++;
471            oldIndex++;
472            break;
473
474           case EDIT_UPDATE:
475            if (!splice) splice = newSplice(index, [], 0);
476            splice.addedCount++;
477            index++;
478            splice.removed.push(old[oldIndex]);
479            oldIndex++;
480            break;
481
482           case EDIT_ADD:
483            if (!splice) splice = newSplice(index, [], 0);
484            splice.addedCount++;
485            index++;
486            break;
487
488           case EDIT_DELETE:
489            if (!splice) splice = newSplice(index, [], 0);
490            splice.removed.push(old[oldIndex]);
491            oldIndex++;
492            break;
493          }
494        }
495        if (splice) {
496          splices.push(splice);
497        }
498        return splices;
499      },
500      sharedPrefix: function(current, old, searchLength) {
501        for (var i = 0; i < searchLength; i++) if (!this.equals(current[i], old[i])) return i;
502        return searchLength;
503      },
504      sharedSuffix: function(current, old, searchLength) {
505        var index1 = current.length;
506        var index2 = old.length;
507        var count = 0;
508        while (count < searchLength && this.equals(current[--index1], old[--index2])) count++;
509        return count;
510      },
511      calculateSplices: function(current, previous) {
512        return this.calcSplices(current, 0, current.length, previous, 0, previous.length);
513      },
514      equals: function(currentValue, previousValue) {
515        return currentValue === previousValue;
516      }
517    };
518    scope.ArraySplice = ArraySplice;
519  })(window.ShadowDOMPolyfill);
520  (function(context) {
521    "use strict";
522    var OriginalMutationObserver = window.MutationObserver;
523    var callbacks = [];
524    var pending = false;
525    var timerFunc;
526    function handle() {
527      pending = false;
528      var copies = callbacks.slice(0);
529      callbacks = [];
530      for (var i = 0; i < copies.length; i++) {
531        (0, copies[i])();
532      }
533    }
534    if (OriginalMutationObserver) {
535      var counter = 1;
536      var observer = new OriginalMutationObserver(handle);
537      var textNode = document.createTextNode(counter);
538      observer.observe(textNode, {
539        characterData: true
540      });
541      timerFunc = function() {
542        counter = (counter + 1) % 2;
543        textNode.data = counter;
544      };
545    } else {
546      timerFunc = window.setTimeout;
547    }
548    function setEndOfMicrotask(func) {
549      callbacks.push(func);
550      if (pending) return;
551      pending = true;
552      timerFunc(handle, 0);
553    }
554    context.setEndOfMicrotask = setEndOfMicrotask;
555  })(window.ShadowDOMPolyfill);
556  (function(scope) {
557    "use strict";
558    var setEndOfMicrotask = scope.setEndOfMicrotask;
559    var wrapIfNeeded = scope.wrapIfNeeded;
560    var wrappers = scope.wrappers;
561    var registrationsTable = new WeakMap();
562    var globalMutationObservers = [];
563    var isScheduled = false;
564    function scheduleCallback(observer) {
565      if (observer.scheduled_) return;
566      observer.scheduled_ = true;
567      globalMutationObservers.push(observer);
568      if (isScheduled) return;
569      setEndOfMicrotask(notifyObservers);
570      isScheduled = true;
571    }
572    function notifyObservers() {
573      isScheduled = false;
574      while (globalMutationObservers.length) {
575        var notifyList = globalMutationObservers;
576        globalMutationObservers = [];
577        notifyList.sort(function(x, y) {
578          return x.uid_ - y.uid_;
579        });
580        for (var i = 0; i < notifyList.length; i++) {
581          var mo = notifyList[i];
582          mo.scheduled_ = false;
583          var queue = mo.takeRecords();
584          removeTransientObserversFor(mo);
585          if (queue.length) {
586            mo.callback_(queue, mo);
587          }
588        }
589      }
590    }
591    function MutationRecord(type, target) {
592      this.type = type;
593      this.target = target;
594      this.addedNodes = new wrappers.NodeList();
595      this.removedNodes = new wrappers.NodeList();
596      this.previousSibling = null;
597      this.nextSibling = null;
598      this.attributeName = null;
599      this.attributeNamespace = null;
600      this.oldValue = null;
601    }
602    function registerTransientObservers(ancestor, node) {
603      for (;ancestor; ancestor = ancestor.parentNode) {
604        var registrations = registrationsTable.get(ancestor);
605        if (!registrations) continue;
606        for (var i = 0; i < registrations.length; i++) {
607          var registration = registrations[i];
608          if (registration.options.subtree) registration.addTransientObserver(node);
609        }
610      }
611    }
612    function removeTransientObserversFor(observer) {
613      for (var i = 0; i < observer.nodes_.length; i++) {
614        var node = observer.nodes_[i];
615        var registrations = registrationsTable.get(node);
616        if (!registrations) return;
617        for (var j = 0; j < registrations.length; j++) {
618          var registration = registrations[j];
619          if (registration.observer === observer) registration.removeTransientObservers();
620        }
621      }
622    }
623    function enqueueMutation(target, type, data) {
624      var interestedObservers = Object.create(null);
625      var associatedStrings = Object.create(null);
626      for (var node = target; node; node = node.parentNode) {
627        var registrations = registrationsTable.get(node);
628        if (!registrations) continue;
629        for (var j = 0; j < registrations.length; j++) {
630          var registration = registrations[j];
631          var options = registration.options;
632          if (node !== target && !options.subtree) continue;
633          if (type === "attributes" && !options.attributes) continue;
634          if (type === "attributes" && options.attributeFilter && (data.namespace !== null || options.attributeFilter.indexOf(data.name) === -1)) {
635            continue;
636          }
637          if (type === "characterData" && !options.characterData) continue;
638          if (type === "childList" && !options.childList) continue;
639          var observer = registration.observer;
640          interestedObservers[observer.uid_] = observer;
641          if (type === "attributes" && options.attributeOldValue || type === "characterData" && options.characterDataOldValue) {
642            associatedStrings[observer.uid_] = data.oldValue;
643          }
644        }
645      }
646      for (var uid in interestedObservers) {
647        var observer = interestedObservers[uid];
648        var record = new MutationRecord(type, target);
649        if ("name" in data && "namespace" in data) {
650          record.attributeName = data.name;
651          record.attributeNamespace = data.namespace;
652        }
653        if (data.addedNodes) record.addedNodes = data.addedNodes;
654        if (data.removedNodes) record.removedNodes = data.removedNodes;
655        if (data.previousSibling) record.previousSibling = data.previousSibling;
656        if (data.nextSibling) record.nextSibling = data.nextSibling;
657        if (associatedStrings[uid] !== undefined) record.oldValue = associatedStrings[uid];
658        scheduleCallback(observer);
659        observer.records_.push(record);
660      }
661    }
662    var slice = Array.prototype.slice;
663    function MutationObserverOptions(options) {
664      this.childList = !!options.childList;
665      this.subtree = !!options.subtree;
666      if (!("attributes" in options) && ("attributeOldValue" in options || "attributeFilter" in options)) {
667        this.attributes = true;
668      } else {
669        this.attributes = !!options.attributes;
670      }
671      if ("characterDataOldValue" in options && !("characterData" in options)) this.characterData = true; else this.characterData = !!options.characterData;
672      if (!this.attributes && (options.attributeOldValue || "attributeFilter" in options) || !this.characterData && options.characterDataOldValue) {
673        throw new TypeError();
674      }
675      this.characterData = !!options.characterData;
676      this.attributeOldValue = !!options.attributeOldValue;
677      this.characterDataOldValue = !!options.characterDataOldValue;
678      if ("attributeFilter" in options) {
679        if (options.attributeFilter == null || typeof options.attributeFilter !== "object") {
680          throw new TypeError();
681        }
682        this.attributeFilter = slice.call(options.attributeFilter);
683      } else {
684        this.attributeFilter = null;
685      }
686    }
687    var uidCounter = 0;
688    function MutationObserver(callback) {
689      this.callback_ = callback;
690      this.nodes_ = [];
691      this.records_ = [];
692      this.uid_ = ++uidCounter;
693      this.scheduled_ = false;
694    }
695    MutationObserver.prototype = {
696      constructor: MutationObserver,
697      observe: function(target, options) {
698        target = wrapIfNeeded(target);
699        var newOptions = new MutationObserverOptions(options);
700        var registration;
701        var registrations = registrationsTable.get(target);
702        if (!registrations) registrationsTable.set(target, registrations = []);
703        for (var i = 0; i < registrations.length; i++) {
704          if (registrations[i].observer === this) {
705            registration = registrations[i];
706            registration.removeTransientObservers();
707            registration.options = newOptions;
708          }
709        }
710        if (!registration) {
711          registration = new Registration(this, target, newOptions);
712          registrations.push(registration);
713          this.nodes_.push(target);
714        }
715      },
716      disconnect: function() {
717        this.nodes_.forEach(function(node) {
718          var registrations = registrationsTable.get(node);
719          for (var i = 0; i < registrations.length; i++) {
720            var registration = registrations[i];
721            if (registration.observer === this) {
722              registrations.splice(i, 1);
723              break;
724            }
725          }
726        }, this);
727        this.records_ = [];
728      },
729      takeRecords: function() {
730        var copyOfRecords = this.records_;
731        this.records_ = [];
732        return copyOfRecords;
733      }
734    };
735    function Registration(observer, target, options) {
736      this.observer = observer;
737      this.target = target;
738      this.options = options;
739      this.transientObservedNodes = [];
740    }
741    Registration.prototype = {
742      addTransientObserver: function(node) {
743        if (node === this.target) return;
744        scheduleCallback(this.observer);
745        this.transientObservedNodes.push(node);
746        var registrations = registrationsTable.get(node);
747        if (!registrations) registrationsTable.set(node, registrations = []);
748        registrations.push(this);
749      },
750      removeTransientObservers: function() {
751        var transientObservedNodes = this.transientObservedNodes;
752        this.transientObservedNodes = [];
753        for (var i = 0; i < transientObservedNodes.length; i++) {
754          var node = transientObservedNodes[i];
755          var registrations = registrationsTable.get(node);
756          for (var j = 0; j < registrations.length; j++) {
757            if (registrations[j] === this) {
758              registrations.splice(j, 1);
759              break;
760            }
761          }
762        }
763      }
764    };
765    scope.enqueueMutation = enqueueMutation;
766    scope.registerTransientObservers = registerTransientObservers;
767    scope.wrappers.MutationObserver = MutationObserver;
768    scope.wrappers.MutationRecord = MutationRecord;
769  })(window.ShadowDOMPolyfill);
770  (function(scope) {
771    "use strict";
772    function TreeScope(root, parent) {
773      this.root = root;
774      this.parent = parent;
775    }
776    TreeScope.prototype = {
777      get renderer() {
778        if (this.root instanceof scope.wrappers.ShadowRoot) {
779          return scope.getRendererForHost(this.root.host);
780        }
781        return null;
782      },
783      contains: function(treeScope) {
784        for (;treeScope; treeScope = treeScope.parent) {
785          if (treeScope === this) return true;
786        }
787        return false;
788      }
789    };
790    function setTreeScope(node, treeScope) {
791      if (node.treeScope_ !== treeScope) {
792        node.treeScope_ = treeScope;
793        for (var sr = node.shadowRoot; sr; sr = sr.olderShadowRoot) {
794          sr.treeScope_.parent = treeScope;
795        }
796        for (var child = node.firstChild; child; child = child.nextSibling) {
797          setTreeScope(child, treeScope);
798        }
799      }
800    }
801    function getTreeScope(node) {
802      if (node instanceof scope.wrappers.Window) {
803        debugger;
804      }
805      if (node.treeScope_) return node.treeScope_;
806      var parent = node.parentNode;
807      var treeScope;
808      if (parent) treeScope = getTreeScope(parent); else treeScope = new TreeScope(node, null);
809      return node.treeScope_ = treeScope;
810    }
811    scope.TreeScope = TreeScope;
812    scope.getTreeScope = getTreeScope;
813    scope.setTreeScope = setTreeScope;
814  })(window.ShadowDOMPolyfill);
815  (function(scope) {
816    "use strict";
817    var forwardMethodsToWrapper = scope.forwardMethodsToWrapper;
818    var getTreeScope = scope.getTreeScope;
819    var mixin = scope.mixin;
820    var registerWrapper = scope.registerWrapper;
821    var setWrapper = scope.setWrapper;
822    var unsafeUnwrap = scope.unsafeUnwrap;
823    var unwrap = scope.unwrap;
824    var wrap = scope.wrap;
825    var wrappers = scope.wrappers;
826    var wrappedFuns = new WeakMap();
827    var listenersTable = new WeakMap();
828    var handledEventsTable = new WeakMap();
829    var currentlyDispatchingEvents = new WeakMap();
830    var targetTable = new WeakMap();
831    var currentTargetTable = new WeakMap();
832    var relatedTargetTable = new WeakMap();
833    var eventPhaseTable = new WeakMap();
834    var stopPropagationTable = new WeakMap();
835    var stopImmediatePropagationTable = new WeakMap();
836    var eventHandlersTable = new WeakMap();
837    var eventPathTable = new WeakMap();
838    function isShadowRoot(node) {
839      return node instanceof wrappers.ShadowRoot;
840    }
841    function rootOfNode(node) {
842      return getTreeScope(node).root;
843    }
844    function getEventPath(node, event) {
845      var path = [];
846      var current = node;
847      path.push(current);
848      while (current) {
849        var destinationInsertionPoints = getDestinationInsertionPoints(current);
850        if (destinationInsertionPoints && destinationInsertionPoints.length > 0) {
851          for (var i = 0; i < destinationInsertionPoints.length; i++) {
852            var insertionPoint = destinationInsertionPoints[i];
853            if (isShadowInsertionPoint(insertionPoint)) {
854              var shadowRoot = rootOfNode(insertionPoint);
855              var olderShadowRoot = shadowRoot.olderShadowRoot;
856              if (olderShadowRoot) path.push(olderShadowRoot);
857            }
858            path.push(insertionPoint);
859          }
860          current = destinationInsertionPoints[destinationInsertionPoints.length - 1];
861        } else {
862          if (isShadowRoot(current)) {
863            if (inSameTree(node, current) && eventMustBeStopped(event)) {
864              break;
865            }
866            current = current.host;
867            path.push(current);
868          } else {
869            current = current.parentNode;
870            if (current) path.push(current);
871          }
872        }
873      }
874      return path;
875    }
876    function eventMustBeStopped(event) {
877      if (!event) return false;
878      switch (event.type) {
879       case "abort":
880       case "error":
881       case "select":
882       case "change":
883       case "load":
884       case "reset":
885       case "resize":
886       case "scroll":
887       case "selectstart":
888        return true;
889      }
890      return false;
891    }
892    function isShadowInsertionPoint(node) {
893      return node instanceof HTMLShadowElement;
894    }
895    function getDestinationInsertionPoints(node) {
896      return scope.getDestinationInsertionPoints(node);
897    }
898    function eventRetargetting(path, currentTarget) {
899      if (path.length === 0) return currentTarget;
900      if (currentTarget instanceof wrappers.Window) currentTarget = currentTarget.document;
901      var currentTargetTree = getTreeScope(currentTarget);
902      var originalTarget = path[0];
903      var originalTargetTree = getTreeScope(originalTarget);
904      var relativeTargetTree = lowestCommonInclusiveAncestor(currentTargetTree, originalTargetTree);
905      for (var i = 0; i < path.length; i++) {
906        var node = path[i];
907        if (getTreeScope(node) === relativeTargetTree) return node;
908      }
909      return path[path.length - 1];
910    }
911    function getTreeScopeAncestors(treeScope) {
912      var ancestors = [];
913      for (;treeScope; treeScope = treeScope.parent) {
914        ancestors.push(treeScope);
915      }
916      return ancestors;
917    }
918    function lowestCommonInclusiveAncestor(tsA, tsB) {
919      var ancestorsA = getTreeScopeAncestors(tsA);
920      var ancestorsB = getTreeScopeAncestors(tsB);
921      var result = null;
922      while (ancestorsA.length > 0 && ancestorsB.length > 0) {
923        var a = ancestorsA.pop();
924        var b = ancestorsB.pop();
925        if (a === b) result = a; else break;
926      }
927      return result;
928    }
929    function getTreeScopeRoot(ts) {
930      if (!ts.parent) return ts;
931      return getTreeScopeRoot(ts.parent);
932    }
933    function relatedTargetResolution(event, currentTarget, relatedTarget) {
934      if (currentTarget instanceof wrappers.Window) currentTarget = currentTarget.document;
935      var currentTargetTree = getTreeScope(currentTarget);
936      var relatedTargetTree = getTreeScope(relatedTarget);
937      var relatedTargetEventPath = getEventPath(relatedTarget, event);
938      var lowestCommonAncestorTree;
939      var lowestCommonAncestorTree = lowestCommonInclusiveAncestor(currentTargetTree, relatedTargetTree);
940      if (!lowestCommonAncestorTree) lowestCommonAncestorTree = relatedTargetTree.root;
941      for (var commonAncestorTree = lowestCommonAncestorTree; commonAncestorTree; commonAncestorTree = commonAncestorTree.parent) {
942        var adjustedRelatedTarget;
943        for (var i = 0; i < relatedTargetEventPath.length; i++) {
944          var node = relatedTargetEventPath[i];
945          if (getTreeScope(node) === commonAncestorTree) return node;
946        }
947      }
948      return null;
949    }
950    function inSameTree(a, b) {
951      return getTreeScope(a) === getTreeScope(b);
952    }
953    var NONE = 0;
954    var CAPTURING_PHASE = 1;
955    var AT_TARGET = 2;
956    var BUBBLING_PHASE = 3;
957    var pendingError;
958    function dispatchOriginalEvent(originalEvent) {
959      if (handledEventsTable.get(originalEvent)) return;
960      handledEventsTable.set(originalEvent, true);
961      dispatchEvent(wrap(originalEvent), wrap(originalEvent.target));
962      if (pendingError) {
963        var err = pendingError;
964        pendingError = null;
965        throw err;
966      }
967    }
968    function isLoadLikeEvent(event) {
969      switch (event.type) {
970       case "load":
971       case "beforeunload":
972       case "unload":
973        return true;
974      }
975      return false;
976    }
977    function dispatchEvent(event, originalWrapperTarget) {
978      if (currentlyDispatchingEvents.get(event)) throw new Error("InvalidStateError");
979      currentlyDispatchingEvents.set(event, true);
980      scope.renderAllPending();
981      var eventPath;
982      var overrideTarget;
983      var win;
984      if (isLoadLikeEvent(event) && !event.bubbles) {
985        var doc = originalWrapperTarget;
986        if (doc instanceof wrappers.Document && (win = doc.defaultView)) {
987          overrideTarget = doc;
988          eventPath = [];
989        }
990      }
991      if (!eventPath) {
992        if (originalWrapperTarget instanceof wrappers.Window) {
993          win = originalWrapperTarget;
994          eventPath = [];
995        } else {
996          eventPath = getEventPath(originalWrapperTarget, event);
997          if (!isLoadLikeEvent(event)) {
998            var doc = eventPath[eventPath.length - 1];
999            if (doc instanceof wrappers.Document) win = doc.defaultView;
1000          }
1001        }
1002      }
1003      eventPathTable.set(event, eventPath);
1004      if (dispatchCapturing(event, eventPath, win, overrideTarget)) {
1005        if (dispatchAtTarget(event, eventPath, win, overrideTarget)) {
1006          dispatchBubbling(event, eventPath, win, overrideTarget);
1007        }
1008      }
1009      eventPhaseTable.set(event, NONE);
1010      currentTargetTable.delete(event, null);
1011      currentlyDispatchingEvents.delete(event);
1012      return event.defaultPrevented;
1013    }
1014    function dispatchCapturing(event, eventPath, win, overrideTarget) {
1015      var phase = CAPTURING_PHASE;
1016      if (win) {
1017        if (!invoke(win, event, phase, eventPath, overrideTarget)) return false;
1018      }
1019      for (var i = eventPath.length - 1; i > 0; i--) {
1020        if (!invoke(eventPath[i], event, phase, eventPath, overrideTarget)) return false;
1021      }
1022      return true;
1023    }
1024    function dispatchAtTarget(event, eventPath, win, overrideTarget) {
1025      var phase = AT_TARGET;
1026      var currentTarget = eventPath[0] || win;
1027      return invoke(currentTarget, event, phase, eventPath, overrideTarget);
1028    }
1029    function dispatchBubbling(event, eventPath, win, overrideTarget) {
1030      var phase = BUBBLING_PHASE;
1031      for (var i = 1; i < eventPath.length; i++) {
1032        if (!invoke(eventPath[i], event, phase, eventPath, overrideTarget)) return;
1033      }
1034      if (win && eventPath.length > 0) {
1035        invoke(win, event, phase, eventPath, overrideTarget);
1036      }
1037    }
1038    function invoke(currentTarget, event, phase, eventPath, overrideTarget) {
1039      var listeners = listenersTable.get(currentTarget);
1040      if (!listeners) return true;
1041      var target = overrideTarget || eventRetargetting(eventPath, currentTarget);
1042      if (target === currentTarget) {
1043        if (phase === CAPTURING_PHASE) return true;
1044        if (phase === BUBBLING_PHASE) phase = AT_TARGET;
1045      } else if (phase === BUBBLING_PHASE && !event.bubbles) {
1046        return true;
1047      }
1048      if ("relatedTarget" in event) {
1049        var originalEvent = unwrap(event);
1050        var unwrappedRelatedTarget = originalEvent.relatedTarget;
1051        if (unwrappedRelatedTarget) {
1052          if (unwrappedRelatedTarget instanceof Object && unwrappedRelatedTarget.addEventListener) {
1053            var relatedTarget = wrap(unwrappedRelatedTarget);
1054            var adjusted = relatedTargetResolution(event, currentTarget, relatedTarget);
1055            if (adjusted === target) return true;
1056          } else {
1057            adjusted = null;
1058          }
1059          relatedTargetTable.set(event, adjusted);
1060        }
1061      }
1062      eventPhaseTable.set(event, phase);
1063      var type = event.type;
1064      var anyRemoved = false;
1065      targetTable.set(event, target);
1066      currentTargetTable.set(event, currentTarget);
1067      listeners.depth++;
1068      for (var i = 0, len = listeners.length; i < len; i++) {
1069        var listener = listeners[i];
1070        if (listener.removed) {
1071          anyRemoved = true;
1072          continue;
1073        }
1074        if (listener.type !== type || !listener.capture && phase === CAPTURING_PHASE || listener.capture && phase === BUBBLING_PHASE) {
1075          continue;
1076        }
1077        try {
1078          if (typeof listener.handler === "function") listener.handler.call(currentTarget, event); else listener.handler.handleEvent(event);
1079          if (stopImmediatePropagationTable.get(event)) return false;
1080        } catch (ex) {
1081          if (!pendingError) pendingError = ex;
1082        }
1083      }
1084      listeners.depth--;
1085      if (anyRemoved && listeners.depth === 0) {
1086        var copy = listeners.slice();
1087        listeners.length = 0;
1088        for (var i = 0; i < copy.length; i++) {
1089          if (!copy[i].removed) listeners.push(copy[i]);
1090        }
1091      }
1092      return !stopPropagationTable.get(event);
1093    }
1094    function Listener(type, handler, capture) {
1095      this.type = type;
1096      this.handler = handler;
1097      this.capture = Boolean(capture);
1098    }
1099    Listener.prototype = {
1100      equals: function(that) {
1101        return this.handler === that.handler && this.type === that.type && this.capture === that.capture;
1102      },
1103      get removed() {
1104        return this.handler === null;
1105      },
1106      remove: function() {
1107        this.handler = null;
1108      }
1109    };
1110    var OriginalEvent = window.Event;
1111    OriginalEvent.prototype.polymerBlackList_ = {
1112      returnValue: true,
1113      keyLocation: true
1114    };
1115    function Event(type, options) {
1116      if (type instanceof OriginalEvent) {
1117        var impl = type;
1118        if (!OriginalBeforeUnloadEvent && impl.type === "beforeunload" && !(this instanceof BeforeUnloadEvent)) {
1119          return new BeforeUnloadEvent(impl);
1120        }
1121        setWrapper(impl, this);
1122      } else {
1123        return wrap(constructEvent(OriginalEvent, "Event", type, options));
1124      }
1125    }
1126    Event.prototype = {
1127      get target() {
1128        return targetTable.get(this);
1129      },
1130      get currentTarget() {
1131        return currentTargetTable.get(this);
1132      },
1133      get eventPhase() {
1134        return eventPhaseTable.get(this);
1135      },
1136      get path() {
1137        var eventPath = eventPathTable.get(this);
1138        if (!eventPath) return [];
1139        return eventPath.slice();
1140      },
1141      stopPropagation: function() {
1142        stopPropagationTable.set(this, true);
1143      },
1144      stopImmediatePropagation: function() {
1145        stopPropagationTable.set(this, true);
1146        stopImmediatePropagationTable.set(this, true);
1147      }
1148    };
1149    registerWrapper(OriginalEvent, Event, document.createEvent("Event"));
1150    function unwrapOptions(options) {
1151      if (!options || !options.relatedTarget) return options;
1152      return Object.create(options, {
1153        relatedTarget: {
1154          value: unwrap(options.relatedTarget)
1155        }
1156      });
1157    }
1158    function registerGenericEvent(name, SuperEvent, prototype) {
1159      var OriginalEvent = window[name];
1160      var GenericEvent = function(type, options) {
1161        if (type instanceof OriginalEvent) setWrapper(type, this); else return wrap(constructEvent(OriginalEvent, name, type, options));
1162      };
1163      GenericEvent.prototype = Object.create(SuperEvent.prototype);
1164      if (prototype) mixin(GenericEvent.prototype, prototype);
1165      if (OriginalEvent) {
1166        try {
1167          registerWrapper(OriginalEvent, GenericEvent, new OriginalEvent("temp"));
1168        } catch (ex) {
1169          registerWrapper(OriginalEvent, GenericEvent, document.createEvent(name));
1170        }
1171      }
1172      return GenericEvent;
1173    }
1174    var UIEvent = registerGenericEvent("UIEvent", Event);
1175    var CustomEvent = registerGenericEvent("CustomEvent", Event);
1176    var relatedTargetProto = {
1177      get relatedTarget() {
1178        var relatedTarget = relatedTargetTable.get(this);
1179        if (relatedTarget !== undefined) return relatedTarget;
1180        return wrap(unwrap(this).relatedTarget);
1181      }
1182    };
1183    function getInitFunction(name, relatedTargetIndex) {
1184      return function() {
1185        arguments[relatedTargetIndex] = unwrap(arguments[relatedTargetIndex]);
1186        var impl = unwrap(this);
1187        impl[name].apply(impl, arguments);
1188      };
1189    }
1190    var mouseEventProto = mixin({
1191      initMouseEvent: getInitFunction("initMouseEvent", 14)
1192    }, relatedTargetProto);
1193    var focusEventProto = mixin({
1194      initFocusEvent: getInitFunction("initFocusEvent", 5)
1195    }, relatedTargetProto);
1196    var MouseEvent = registerGenericEvent("MouseEvent", UIEvent, mouseEventProto);
1197    var FocusEvent = registerGenericEvent("FocusEvent", UIEvent, focusEventProto);
1198    var defaultInitDicts = Object.create(null);
1199    var supportsEventConstructors = function() {
1200      try {
1201        new window.FocusEvent("focus");
1202      } catch (ex) {
1203        return false;
1204      }
1205      return true;
1206    }();
1207    function constructEvent(OriginalEvent, name, type, options) {
1208      if (supportsEventConstructors) return new OriginalEvent(type, unwrapOptions(options));
1209      var event = unwrap(document.createEvent(name));
1210      var defaultDict = defaultInitDicts[name];
1211      var args = [ type ];
1212      Object.keys(defaultDict).forEach(function(key) {
1213        var v = options != null && key in options ? options[key] : defaultDict[key];
1214        if (key === "relatedTarget") v = unwrap(v);
1215        args.push(v);
1216      });
1217      event["init" + name].apply(event, args);
1218      return event;
1219    }
1220    if (!supportsEventConstructors) {
1221      var configureEventConstructor = function(name, initDict, superName) {
1222        if (superName) {
1223          var superDict = defaultInitDicts[superName];
1224          initDict = mixin(mixin({}, superDict), initDict);
1225        }
1226        defaultInitDicts[name] = initDict;
1227      };
1228      configureEventConstructor("Event", {
1229        bubbles: false,
1230        cancelable: false
1231      });
1232      configureEventConstructor("CustomEvent", {
1233        detail: null
1234      }, "Event");
1235      configureEventConstructor("UIEvent", {
1236        view: null,
1237        detail: 0
1238      }, "Event");
1239      configureEventConstructor("MouseEvent", {
1240        screenX: 0,
1241        screenY: 0,
1242        clientX: 0,
1243        clientY: 0,
1244        ctrlKey: false,
1245        altKey: false,
1246        shiftKey: false,
1247        metaKey: false,
1248        button: 0,
1249        relatedTarget: null
1250      }, "UIEvent");
1251      configureEventConstructor("FocusEvent", {
1252        relatedTarget: null
1253      }, "UIEvent");
1254    }
1255    var OriginalBeforeUnloadEvent = window.BeforeUnloadEvent;
1256    function BeforeUnloadEvent(impl) {
1257      Event.call(this, impl);
1258    }
1259    BeforeUnloadEvent.prototype = Object.create(Event.prototype);
1260    mixin(BeforeUnloadEvent.prototype, {
1261      get returnValue() {
1262        return unsafeUnwrap(this).returnValue;
1263      },
1264      set returnValue(v) {
1265        unsafeUnwrap(this).returnValue = v;
1266      }
1267    });
1268    if (OriginalBeforeUnloadEvent) registerWrapper(OriginalBeforeUnloadEvent, BeforeUnloadEvent);
1269    function isValidListener(fun) {
1270      if (typeof fun === "function") return true;
1271      return fun && fun.handleEvent;
1272    }
1273    function isMutationEvent(type) {
1274      switch (type) {
1275       case "DOMAttrModified":
1276       case "DOMAttributeNameChanged":
1277       case "DOMCharacterDataModified":
1278       case "DOMElementNameChanged":
1279       case "DOMNodeInserted":
1280       case "DOMNodeInsertedIntoDocument":
1281       case "DOMNodeRemoved":
1282       case "DOMNodeRemovedFromDocument":
1283       case "DOMSubtreeModified":
1284        return true;
1285      }
1286      return false;
1287    }
1288    var OriginalEventTarget = window.EventTarget;
1289    function EventTarget(impl) {
1290      setWrapper(impl, this);
1291    }
1292    var methodNames = [ "addEventListener", "removeEventListener", "dispatchEvent" ];
1293    [ Node, Window ].forEach(function(constructor) {
1294      var p = constructor.prototype;
1295      methodNames.forEach(function(name) {
1296        Object.defineProperty(p, name + "_", {
1297          value: p[name]
1298        });
1299      });
1300    });
1301    function getTargetToListenAt(wrapper) {
1302      if (wrapper instanceof wrappers.ShadowRoot) wrapper = wrapper.host;
1303      return unwrap(wrapper);
1304    }
1305    EventTarget.prototype = {
1306      addEventListener: function(type, fun, capture) {
1307        if (!isValidListener(fun) || isMutationEvent(type)) return;
1308        var listener = new Listener(type, fun, capture);
1309        var listeners = listenersTable.get(this);
1310        if (!listeners) {
1311          listeners = [];
1312          listeners.depth = 0;
1313          listenersTable.set(this, listeners);
1314        } else {
1315          for (var i = 0; i < listeners.length; i++) {
1316            if (listener.equals(listeners[i])) return;
1317          }
1318        }
1319        listeners.push(listener);
1320        var target = getTargetToListenAt(this);
1321        target.addEventListener_(type, dispatchOriginalEvent, true);
1322      },
1323      removeEventListener: function(type, fun, capture) {
1324        capture = Boolean(capture);
1325        var listeners = listenersTable.get(this);
1326        if (!listeners) return;
1327        var count = 0, found = false;
1328        for (var i = 0; i < listeners.length; i++) {
1329          if (listeners[i].type === type && listeners[i].capture === capture) {
1330            count++;
1331            if (listeners[i].handler === fun) {
1332              found = true;
1333              listeners[i].remove();
1334            }
1335          }
1336        }
1337        if (found && count === 1) {
1338          var target = getTargetToListenAt(this);
1339          target.removeEventListener_(type, dispatchOriginalEvent, true);
1340        }
1341      },
1342      dispatchEvent: function(event) {
1343        var nativeEvent = unwrap(event);
1344        var eventType = nativeEvent.type;
1345        handledEventsTable.set(nativeEvent, false);
1346        scope.renderAllPending();
1347        var tempListener;
1348        if (!hasListenerInAncestors(this, eventType)) {
1349          tempListener = function() {};
1350          this.addEventListener(eventType, tempListener, true);
1351        }
1352        try {
1353          return unwrap(this).dispatchEvent_(nativeEvent);
1354        } finally {
1355          if (tempListener) this.removeEventListener(eventType, tempListener, true);
1356        }
1357      }
1358    };
1359    function hasListener(node, type) {
1360      var listeners = listenersTable.get(node);
1361      if (listeners) {
1362        for (var i = 0; i < listeners.length; i++) {
1363          if (!listeners[i].removed && listeners[i].type === type) return true;
1364        }
1365      }
1366      return false;
1367    }
1368    function hasListenerInAncestors(target, type) {
1369      for (var node = unwrap(target); node; node = node.parentNode) {
1370        if (hasListener(wrap(node), type)) return true;
1371      }
1372      return false;
1373    }
1374    if (OriginalEventTarget) registerWrapper(OriginalEventTarget, EventTarget);
1375    function wrapEventTargetMethods(constructors) {
1376      forwardMethodsToWrapper(constructors, methodNames);
1377    }
1378    var originalElementFromPoint = document.elementFromPoint;
1379    function elementFromPoint(self, document, x, y) {
1380      scope.renderAllPending();
1381      var element = wrap(originalElementFromPoint.call(unsafeUnwrap(document), x, y));
1382      if (!element) return null;
1383      var path = getEventPath(element, null);
1384      var idx = path.lastIndexOf(self);
1385      if (idx == -1) return null; else path = path.slice(0, idx);
1386      return eventRetargetting(path, self);
1387    }
1388    function getEventHandlerGetter(name) {
1389      return function() {
1390        var inlineEventHandlers = eventHandlersTable.get(this);
1391        return inlineEventHandlers && inlineEventHandlers[name] && inlineEventHandlers[name].value || null;
1392      };
1393    }
1394    function getEventHandlerSetter(name) {
1395      var eventType = name.slice(2);
1396      return function(value) {
1397        var inlineEventHandlers = eventHandlersTable.get(this);
1398        if (!inlineEventHandlers) {
1399          inlineEventHandlers = Object.create(null);
1400          eventHandlersTable.set(this, inlineEventHandlers);
1401        }
1402        var old = inlineEventHandlers[name];
1403        if (old) this.removeEventListener(eventType, old.wrapped, false);
1404        if (typeof value === "function") {
1405          var wrapped = function(e) {
1406            var rv = value.call(this, e);
1407            if (rv === false) e.preventDefault(); else if (name === "onbeforeunload" && typeof rv === "string") e.returnValue = rv;
1408          };
1409          this.addEventListener(eventType, wrapped, false);
1410          inlineEventHandlers[name] = {
1411            value: value,
1412            wrapped: wrapped
1413          };
1414        }
1415      };
1416    }
1417    scope.elementFromPoint = elementFromPoint;
1418    scope.getEventHandlerGetter = getEventHandlerGetter;
1419    scope.getEventHandlerSetter = getEventHandlerSetter;
1420    scope.wrapEventTargetMethods = wrapEventTargetMethods;
1421    scope.wrappers.BeforeUnloadEvent = BeforeUnloadEvent;
1422    scope.wrappers.CustomEvent = CustomEvent;
1423    scope.wrappers.Event = Event;
1424    scope.wrappers.EventTarget = EventTarget;
1425    scope.wrappers.FocusEvent = FocusEvent;
1426    scope.wrappers.MouseEvent = MouseEvent;
1427    scope.wrappers.UIEvent = UIEvent;
1428  })(window.ShadowDOMPolyfill);
1429  (function(scope) {
1430    "use strict";
1431    var UIEvent = scope.wrappers.UIEvent;
1432    var mixin = scope.mixin;
1433    var registerWrapper = scope.registerWrapper;
1434    var setWrapper = scope.setWrapper;
1435    var unsafeUnwrap = scope.unsafeUnwrap;
1436    var wrap = scope.wrap;
1437    var OriginalTouchEvent = window.TouchEvent;
1438    if (!OriginalTouchEvent) return;
1439    var nativeEvent;
1440    try {
1441      nativeEvent = document.createEvent("TouchEvent");
1442    } catch (ex) {
1443      return;
1444    }
1445    var nonEnumDescriptor = {
1446      enumerable: false
1447    };
1448    function nonEnum(obj, prop) {
1449      Object.defineProperty(obj, prop, nonEnumDescriptor);
1450    }
1451    function Touch(impl) {
1452      setWrapper(impl, this);
1453    }
1454    Touch.prototype = {
1455      get target() {
1456        return wrap(unsafeUnwrap(this).target);
1457      }
1458    };
1459    var descr = {
1460      configurable: true,
1461      enumerable: true,
1462      get: null
1463    };
1464    [ "clientX", "clientY", "screenX", "screenY", "pageX", "pageY", "identifier", "webkitRadiusX", "webkitRadiusY", "webkitRotationAngle", "webkitForce" ].forEach(function(name) {
1465      descr.get = function() {
1466        return unsafeUnwrap(this)[name];
1467      };
1468      Object.defineProperty(Touch.prototype, name, descr);
1469    });
1470    function TouchList() {
1471      this.length = 0;
1472      nonEnum(this, "length");
1473    }
1474    TouchList.prototype = {
1475      item: function(index) {
1476        return this[index];
1477      }
1478    };
1479    function wrapTouchList(nativeTouchList) {
1480      var list = new TouchList();
1481      for (var i = 0; i < nativeTouchList.length; i++) {
1482        list[i] = new Touch(nativeTouchList[i]);
1483      }
1484      list.length = i;
1485      return list;
1486    }
1487    function TouchEvent(impl) {
1488      UIEvent.call(this, impl);
1489    }
1490    TouchEvent.prototype = Object.create(UIEvent.prototype);
1491    mixin(TouchEvent.prototype, {
1492      get touches() {
1493        return wrapTouchList(unsafeUnwrap(this).touches);
1494      },
1495      get targetTouches() {
1496        return wrapTouchList(unsafeUnwrap(this).targetTouches);
1497      },
1498      get changedTouches() {
1499        return wrapTouchList(unsafeUnwrap(this).changedTouches);
1500      },
1501      initTouchEvent: function() {
1502        throw new Error("Not implemented");
1503      }
1504    });
1505    registerWrapper(OriginalTouchEvent, TouchEvent, nativeEvent);
1506    scope.wrappers.Touch = Touch;
1507    scope.wrappers.TouchEvent = TouchEvent;
1508    scope.wrappers.TouchList = TouchList;
1509  })(window.ShadowDOMPolyfill);
1510  (function(scope) {
1511    "use strict";
1512    var unsafeUnwrap = scope.unsafeUnwrap;
1513    var wrap = scope.wrap;
1514    var nonEnumDescriptor = {
1515      enumerable: false
1516    };
1517    function nonEnum(obj, prop) {
1518      Object.defineProperty(obj, prop, nonEnumDescriptor);
1519    }
1520    function NodeList() {
1521      this.length = 0;
1522      nonEnum(this, "length");
1523    }
1524    NodeList.prototype = {
1525      item: function(index) {
1526        return this[index];
1527      }
1528    };
1529    nonEnum(NodeList.prototype, "item");
1530    function wrapNodeList(list) {
1531      if (list == null) return list;
1532      var wrapperList = new NodeList();
1533      for (var i = 0, length = list.length; i < length; i++) {
1534        wrapperList[i] = wrap(list[i]);
1535      }
1536      wrapperList.length = length;
1537      return wrapperList;
1538    }
1539    function addWrapNodeListMethod(wrapperConstructor, name) {
1540      wrapperConstructor.prototype[name] = function() {
1541        return wrapNodeList(unsafeUnwrap(this)[name].apply(unsafeUnwrap(this), arguments));
1542      };
1543    }
1544    scope.wrappers.NodeList = NodeList;
1545    scope.addWrapNodeListMethod = addWrapNodeListMethod;
1546    scope.wrapNodeList = wrapNodeList;
1547  })(window.ShadowDOMPolyfill);
1548  (function(scope) {
1549    "use strict";
1550    scope.wrapHTMLCollection = scope.wrapNodeList;
1551    scope.wrappers.HTMLCollection = scope.wrappers.NodeList;
1552  })(window.ShadowDOMPolyfill);
1553  (function(scope) {
1554    "use strict";
1555    var EventTarget = scope.wrappers.EventTarget;
1556    var NodeList = scope.wrappers.NodeList;
1557    var TreeScope = scope.TreeScope;
1558    var assert = scope.assert;
1559    var defineWrapGetter = scope.defineWrapGetter;
1560    var enqueueMutation = scope.enqueueMutation;
1561    var getTreeScope = scope.getTreeScope;
1562    var isWrapper = scope.isWrapper;
1563    var mixin = scope.mixin;
1564    var registerTransientObservers = scope.registerTransientObservers;
1565    var registerWrapper = scope.registerWrapper;
1566    var setTreeScope = scope.setTreeScope;
1567    var unsafeUnwrap = scope.unsafeUnwrap;
1568    var unwrap = scope.unwrap;
1569    var unwrapIfNeeded = scope.unwrapIfNeeded;
1570    var wrap = scope.wrap;
1571    var wrapIfNeeded = scope.wrapIfNeeded;
1572    var wrappers = scope.wrappers;
1573    function assertIsNodeWrapper(node) {
1574      assert(node instanceof Node);
1575    }
1576    function createOneElementNodeList(node) {
1577      var nodes = new NodeList();
1578      nodes[0] = node;
1579      nodes.length = 1;
1580      return nodes;
1581    }
1582    var surpressMutations = false;
1583    function enqueueRemovalForInsertedNodes(node, parent, nodes) {
1584      enqueueMutation(parent, "childList", {
1585        removedNodes: nodes,
1586        previousSibling: node.previousSibling,
1587        nextSibling: node.nextSibling
1588      });
1589    }
1590    function enqueueRemovalForInsertedDocumentFragment(df, nodes) {
1591      enqueueMutation(df, "childList", {
1592        removedNodes: nodes
1593      });
1594    }
1595    function collectNodes(node, parentNode, previousNode, nextNode) {
1596      if (node instanceof DocumentFragment) {
1597        var nodes = collectNodesForDocumentFragment(node);
1598        surpressMutations = true;
1599        for (var i = nodes.length - 1; i >= 0; i--) {
1600          node.removeChild(nodes[i]);
1601          nodes[i].parentNode_ = parentNode;
1602        }
1603        surpressMutations = false;
1604        for (var i = 0; i < nodes.length; i++) {
1605          nodes[i].previousSibling_ = nodes[i - 1] || previousNode;
1606          nodes[i].nextSibling_ = nodes[i + 1] || nextNode;
1607        }
1608        if (previousNode) previousNode.nextSibling_ = nodes[0];
1609        if (nextNode) nextNode.previousSibling_ = nodes[nodes.length - 1];
1610        return nodes;
1611      }
1612      var nodes = createOneElementNodeList(node);
1613      var oldParent = node.parentNode;
1614      if (oldParent) {
1615        oldParent.removeChild(node);
1616      }
1617      node.parentNode_ = parentNode;
1618      node.previousSibling_ = previousNode;
1619      node.nextSibling_ = nextNode;
1620      if (previousNode) previousNode.nextSibling_ = node;
1621      if (nextNode) nextNode.previousSibling_ = node;
1622      return nodes;
1623    }
1624    function collectNodesNative(node) {
1625      if (node instanceof DocumentFragment) return collectNodesForDocumentFragment(node);
1626      var nodes = createOneElementNodeList(node);
1627      var oldParent = node.parentNode;
1628      if (oldParent) enqueueRemovalForInsertedNodes(node, oldParent, nodes);
1629      return nodes;
1630    }
1631    function collectNodesForDocumentFragment(node) {
1632      var nodes = new NodeList();
1633      var i = 0;
1634      for (var child = node.firstChild; child; child = child.nextSibling) {
1635        nodes[i++] = child;
1636      }
1637      nodes.length = i;
1638      enqueueRemovalForInsertedDocumentFragment(node, nodes);
1639      return nodes;
1640    }
1641    function snapshotNodeList(nodeList) {
1642      return nodeList;
1643    }
1644    function nodeWasAdded(node, treeScope) {
1645      setTreeScope(node, treeScope);
1646      node.nodeIsInserted_();
1647    }
1648    function nodesWereAdded(nodes, parent) {
1649      var treeScope = getTreeScope(parent);
1650      for (var i = 0; i < nodes.length; i++) {
1651        nodeWasAdded(nodes[i], treeScope);
1652      }
1653    }
1654    function nodeWasRemoved(node) {
1655      setTreeScope(node, new TreeScope(node, null));
1656    }
1657    function nodesWereRemoved(nodes) {
1658      for (var i = 0; i < nodes.length; i++) {
1659        nodeWasRemoved(nodes[i]);
1660      }
1661    }
1662    function ensureSameOwnerDocument(parent, child) {
1663      var ownerDoc = parent.nodeType === Node.DOCUMENT_NODE ? parent : parent.ownerDocument;
1664      if (ownerDoc !== child.ownerDocument) ownerDoc.adoptNode(child);
1665    }
1666    function adoptNodesIfNeeded(owner, nodes) {
1667      if (!nodes.length) return;
1668      var ownerDoc = owner.ownerDocument;
1669      if (ownerDoc === nodes[0].ownerDocument) return;
1670      for (var i = 0; i < nodes.length; i++) {
1671        scope.adoptNodeNoRemove(nodes[i], ownerDoc);
1672      }
1673    }
1674    function unwrapNodesForInsertion(owner, nodes) {
1675      adoptNodesIfNeeded(owner, nodes);
1676      var length = nodes.length;
1677      if (length === 1) return unwrap(nodes[0]);
1678      var df = unwrap(owner.ownerDocument.createDocumentFragment());
1679      for (var i = 0; i < length; i++) {
1680        df.appendChild(unwrap(nodes[i]));
1681      }
1682      return df;
1683    }
1684    function clearChildNodes(wrapper) {
1685      if (wrapper.firstChild_ !== undefined) {
1686        var child = wrapper.firstChild_;
1687        while (child) {
1688          var tmp = child;
1689          child = child.nextSibling_;
1690          tmp.parentNode_ = tmp.previousSibling_ = tmp.nextSibling_ = undefined;
1691        }
1692      }
1693      wrapper.firstChild_ = wrapper.lastChild_ = undefined;
1694    }
1695    function removeAllChildNodes(wrapper) {
1696      if (wrapper.invalidateShadowRenderer()) {
1697        var childWrapper = wrapper.firstChild;
1698        while (childWrapper) {
1699          assert(childWrapper.parentNode === wrapper);
1700          var nextSibling = childWrapper.nextSibling;
1701          var childNode = unwrap(childWrapper);
1702          var parentNode = childNode.parentNode;
1703          if (parentNode) originalRemoveChild.call(parentNode, childNode);
1704          childWrapper.previousSibling_ = childWrapper.nextSibling_ = childWrapper.parentNode_ = null;
1705          childWrapper = nextSibling;
1706        }
1707        wrapper.firstChild_ = wrapper.lastChild_ = null;
1708      } else {
1709        var node = unwrap(wrapper);
1710        var child = node.firstChild;
1711        var nextSibling;
1712        while (child) {
1713          nextSibling = child.nextSibling;
1714          originalRemoveChild.call(node, child);
1715          child = nextSibling;
1716        }
1717      }
1718    }
1719    function invalidateParent(node) {
1720      var p = node.parentNode;
1721      return p && p.invalidateShadowRenderer();
1722    }
1723    function cleanupNodes(nodes) {
1724      for (var i = 0, n; i < nodes.length; i++) {
1725        n = nodes[i];
1726        n.parentNode.removeChild(n);
1727      }
1728    }
1729    var originalImportNode = document.importNode;
1730    var originalCloneNode = window.Node.prototype.cloneNode;
1731    function cloneNode(node, deep, opt_doc) {
1732      var clone;
1733      if (opt_doc) clone = wrap(originalImportNode.call(opt_doc, unsafeUnwrap(node), false)); else clone = wrap(originalCloneNode.call(unsafeUnwrap(node), false));
1734      if (deep) {
1735        for (var child = node.firstChild; child; child = child.nextSibling) {
1736          clone.appendChild(cloneNode(child, true, opt_doc));
1737        }
1738        if (node instanceof wrappers.HTMLTemplateElement) {
1739          var cloneContent = clone.content;
1740          for (var child = node.content.firstChild; child; child = child.nextSibling) {
1741            cloneContent.appendChild(cloneNode(child, true, opt_doc));
1742          }
1743        }
1744      }
1745      return clone;
1746    }
1747    function contains(self, child) {
1748      if (!child || getTreeScope(self) !== getTreeScope(child)) return false;
1749      for (var node = child; node; node = node.parentNode) {
1750        if (node === self) return true;
1751      }
1752      return false;
1753    }
1754    var OriginalNode = window.Node;
1755    function Node(original) {
1756      assert(original instanceof OriginalNode);
1757      EventTarget.call(this, original);
1758      this.parentNode_ = undefined;
1759      this.firstChild_ = undefined;
1760      this.lastChild_ = undefined;
1761      this.nextSibling_ = undefined;
1762      this.previousSibling_ = undefined;
1763      this.treeScope_ = undefined;
1764    }
1765    var OriginalDocumentFragment = window.DocumentFragment;
1766    var originalAppendChild = OriginalNode.prototype.appendChild;
1767    var originalCompareDocumentPosition = OriginalNode.prototype.compareDocumentPosition;
1768    var originalIsEqualNode = OriginalNode.prototype.isEqualNode;
1769    var originalInsertBefore = OriginalNode.prototype.insertBefore;
1770    var originalRemoveChild = OriginalNode.prototype.removeChild;
1771    var originalReplaceChild = OriginalNode.prototype.replaceChild;
1772    var isIe = /Trident|Edge/.test(navigator.userAgent);
1773    var removeChildOriginalHelper = isIe ? function(parent, child) {
1774      try {
1775        originalRemoveChild.call(parent, child);
1776      } catch (ex) {
1777        if (!(parent instanceof OriginalDocumentFragment)) throw ex;
1778      }
1779    } : function(parent, child) {
1780      originalRemoveChild.call(parent, child);
1781    };
1782    Node.prototype = Object.create(EventTarget.prototype);
1783    mixin(Node.prototype, {
1784      appendChild: function(childWrapper) {
1785        return this.insertBefore(childWrapper, null);
1786      },
1787      insertBefore: function(childWrapper, refWrapper) {
1788        assertIsNodeWrapper(childWrapper);
1789        var refNode;
1790        if (refWrapper) {
1791          if (isWrapper(refWrapper)) {
1792            refNode = unwrap(refWrapper);
1793          } else {
1794            refNode = refWrapper;
1795            refWrapper = wrap(refNode);
1796          }
1797        } else {
1798          refWrapper = null;
1799          refNode = null;
1800        }
1801        refWrapper && assert(refWrapper.parentNode === this);
1802        var nodes;
1803        var previousNode = refWrapper ? refWrapper.previousSibling : this.lastChild;
1804        var useNative = !this.invalidateShadowRenderer() && !invalidateParent(childWrapper);
1805        if (useNative) nodes = collectNodesNative(childWrapper); else nodes = collectNodes(childWrapper, this, previousNode, refWrapper);
1806        if (useNative) {
1807          ensureSameOwnerDocument(this, childWrapper);
1808          clearChildNodes(this);
1809          originalInsertBefore.call(unsafeUnwrap(this), unwrap(childWrapper), refNode);
1810        } else {
1811          if (!previousNode) this.firstChild_ = nodes[0];
1812          if (!refWrapper) {
1813            this.lastChild_ = nodes[nodes.length - 1];
1814            if (this.firstChild_ === undefined) this.firstChild_ = this.firstChild;
1815          }
1816          var parentNode = refNode ? refNode.parentNode : unsafeUnwrap(this);
1817          if (parentNode) {
1818            originalInsertBefore.call(parentNode, unwrapNodesForInsertion(this, nodes), refNode);
1819          } else {
1820            adoptNodesIfNeeded(this, nodes);
1821          }
1822        }
1823        enqueueMutation(this, "childList", {
1824          addedNodes: nodes,
1825          nextSibling: refWrapper,
1826          previousSibling: previousNode
1827        });
1828        nodesWereAdded(nodes, this);
1829        return childWrapper;
1830      },
1831      removeChild: function(childWrapper) {
1832        assertIsNodeWrapper(childWrapper);
1833        if (childWrapper.parentNode !== this) {
1834          var found = false;
1835          var childNodes = this.childNodes;
1836          for (var ieChild = this.firstChild; ieChild; ieChild = ieChild.nextSibling) {
1837            if (ieChild === childWrapper) {
1838              found = true;
1839              break;
1840            }
1841          }
1842          if (!found) {
1843            throw new Error("NotFoundError");
1844          }
1845        }
1846        var childNode = unwrap(childWrapper);
1847        var childWrapperNextSibling = childWrapper.nextSibling;
1848        var childWrapperPreviousSibling = childWrapper.previousSibling;
1849        if (this.invalidateShadowRenderer()) {
1850          var thisFirstChild = this.firstChild;
1851          var thisLastChild = this.lastChild;
1852          var parentNode = childNode.parentNode;
1853          if (parentNode) removeChildOriginalHelper(parentNode, childNode);
1854          if (thisFirstChild === childWrapper) this.firstChild_ = childWrapperNextSibling;
1855          if (thisLastChild === childWrapper) this.lastChild_ = childWrapperPreviousSibling;
1856          if (childWrapperPreviousSibling) childWrapperPreviousSibling.nextSibling_ = childWrapperNextSibling;
1857          if (childWrapperNextSibling) {
1858            childWrapperNextSibling.previousSibling_ = childWrapperPreviousSibling;
1859          }
1860          childWrapper.previousSibling_ = childWrapper.nextSibling_ = childWrapper.parentNode_ = undefined;
1861        } else {
1862          clearChildNodes(this);
1863          removeChildOriginalHelper(unsafeUnwrap(this), childNode);
1864        }
1865        if (!surpressMutations) {
1866          enqueueMutation(this, "childList", {
1867            removedNodes: createOneElementNodeList(childWrapper),
1868            nextSibling: childWrapperNextSibling,
1869            previousSibling: childWrapperPreviousSibling
1870          });
1871        }
1872        registerTransientObservers(this, childWrapper);
1873        return childWrapper;
1874      },
1875      replaceChild: function(newChildWrapper, oldChildWrapper) {
1876        assertIsNodeWrapper(newChildWrapper);
1877        var oldChildNode;
1878        if (isWrapper(oldChildWrapper)) {
1879          oldChildNode = unwrap(oldChildWrapper);
1880        } else {
1881          oldChildNode = oldChildWrapper;
1882          oldChildWrapper = wrap(oldChildNode);
1883        }
1884        if (oldChildWrapper.parentNode !== this) {
1885          throw new Error("NotFoundError");
1886        }
1887        var nextNode = oldChildWrapper.nextSibling;
1888        var previousNode = oldChildWrapper.previousSibling;
1889        var nodes;
1890        var useNative = !this.invalidateShadowRenderer() && !invalidateParent(newChildWrapper);
1891        if (useNative) {
1892          nodes = collectNodesNative(newChildWrapper);
1893        } else {
1894          if (nextNode === newChildWrapper) nextNode = newChildWrapper.nextSibling;
1895          nodes = collectNodes(newChildWrapper, this, previousNode, nextNode);
1896        }
1897        if (!useNative) {
1898          if (this.firstChild === oldChildWrapper) this.firstChild_ = nodes[0];
1899          if (this.lastChild === oldChildWrapper) this.lastChild_ = nodes[nodes.length - 1];
1900          oldChildWrapper.previousSibling_ = oldChildWrapper.nextSibling_ = oldChildWrapper.parentNode_ = undefined;
1901          if (oldChildNode.parentNode) {
1902            originalReplaceChild.call(oldChildNode.parentNode, unwrapNodesForInsertion(this, nodes), oldChildNode);
1903          }
1904        } else {
1905          ensureSameOwnerDocument(this, newChildWrapper);
1906          clearChildNodes(this);
1907          originalReplaceChild.call(unsafeUnwrap(this), unwrap(newChildWrapper), oldChildNode);
1908        }
1909        enqueueMutation(this, "childList", {
1910          addedNodes: nodes,
1911          removedNodes: createOneElementNodeList(oldChildWrapper),
1912          nextSibling: nextNode,
1913          previousSibling: previousNode
1914        });
1915        nodeWasRemoved(oldChildWrapper);
1916        nodesWereAdded(nodes, this);
1917        return oldChildWrapper;
1918      },
1919      nodeIsInserted_: function() {
1920        for (var child = this.firstChild; child; child = child.nextSibling) {
1921          child.nodeIsInserted_();
1922        }
1923      },
1924      hasChildNodes: function() {
1925        return this.firstChild !== null;
1926      },
1927      get parentNode() {
1928        return this.parentNode_ !== undefined ? this.parentNode_ : wrap(unsafeUnwrap(this).parentNode);
1929      },
1930      get firstChild() {
1931        return this.firstChild_ !== undefined ? this.firstChild_ : wrap(unsafeUnwrap(this).firstChild);
1932      },
1933      get lastChild() {
1934        return this.lastChild_ !== undefined ? this.lastChild_ : wrap(unsafeUnwrap(this).lastChild);
1935      },
1936      get nextSibling() {
1937        return this.nextSibling_ !== undefined ? this.nextSibling_ : wrap(unsafeUnwrap(this).nextSibling);
1938      },
1939      get previousSibling() {
1940        return this.previousSibling_ !== undefined ? this.previousSibling_ : wrap(unsafeUnwrap(this).previousSibling);
1941      },
1942      get parentElement() {
1943        var p = this.parentNode;
1944        while (p && p.nodeType !== Node.ELEMENT_NODE) {
1945          p = p.parentNode;
1946        }
1947        return p;
1948      },
1949      get textContent() {
1950        var s = "";
1951        for (var child = this.firstChild; child; child = child.nextSibling) {
1952          if (child.nodeType != Node.COMMENT_NODE) {
1953            s += child.textContent;
1954          }
1955        }
1956        return s;
1957      },
1958      set textContent(textContent) {
1959        if (textContent == null) textContent = "";
1960        var removedNodes = snapshotNodeList(this.childNodes);
1961        if (this.invalidateShadowRenderer()) {
1962          removeAllChildNodes(this);
1963          if (textContent !== "") {
1964            var textNode = unsafeUnwrap(this).ownerDocument.createTextNode(textContent);
1965            this.appendChild(textNode);
1966          }
1967        } else {
1968          clearChildNodes(this);
1969          unsafeUnwrap(this).textContent = textContent;
1970        }
1971        var addedNodes = snapshotNodeList(this.childNodes);
1972        enqueueMutation(this, "childList", {
1973          addedNodes: addedNodes,
1974          removedNodes: removedNodes
1975        });
1976        nodesWereRemoved(removedNodes);
1977        nodesWereAdded(addedNodes, this);
1978      },
1979      get childNodes() {
1980        var wrapperList = new NodeList();
1981        var i = 0;
1982        for (var child = this.firstChild; child; child = child.nextSibling) {
1983          wrapperList[i++] = child;
1984        }
1985        wrapperList.length = i;
1986        return wrapperList;
1987      },
1988      cloneNode: function(deep) {
1989        return cloneNode(this, deep);
1990      },
1991      contains: function(child) {
1992        return contains(this, wrapIfNeeded(child));
1993      },
1994      compareDocumentPosition: function(otherNode) {
1995        return originalCompareDocumentPosition.call(unsafeUnwrap(this), unwrapIfNeeded(otherNode));
1996      },
1997      isEqualNode: function(otherNode) {
1998        return originalIsEqualNode.call(unsafeUnwrap(this), unwrapIfNeeded(otherNode));
1999      },
2000      normalize: function() {
2001        var nodes = snapshotNodeList(this.childNodes);
2002        var remNodes = [];
2003        var s = "";
2004        var modNode;
2005        for (var i = 0, n; i < nodes.length; i++) {
2006          n = nodes[i];
2007          if (n.nodeType === Node.TEXT_NODE) {
2008            if (!modNode && !n.data.length) this.removeChild(n); else if (!modNode) modNode = n; else {
2009              s += n.data;
2010              remNodes.push(n);
2011            }
2012          } else {
2013            if (modNode && remNodes.length) {
2014              modNode.data += s;
2015              cleanupNodes(remNodes);
2016            }
2017            remNodes = [];
2018            s = "";
2019            modNode = null;
2020            if (n.childNodes.length) n.normalize();
2021          }
2022        }
2023        if (modNode && remNodes.length) {
2024          modNode.data += s;
2025          cleanupNodes(remNodes);
2026        }
2027      }
2028    });
2029    defineWrapGetter(Node, "ownerDocument");
2030    registerWrapper(OriginalNode, Node, document.createDocumentFragment());
2031    delete Node.prototype.querySelector;
2032    delete Node.prototype.querySelectorAll;
2033    Node.prototype = mixin(Object.create(EventTarget.prototype), Node.prototype);
2034    scope.cloneNode = cloneNode;
2035    scope.nodeWasAdded = nodeWasAdded;
2036    scope.nodeWasRemoved = nodeWasRemoved;
2037    scope.nodesWereAdded = nodesWereAdded;
2038    scope.nodesWereRemoved = nodesWereRemoved;
2039    scope.originalInsertBefore = originalInsertBefore;
2040    scope.originalRemoveChild = originalRemoveChild;
2041    scope.snapshotNodeList = snapshotNodeList;
2042    scope.wrappers.Node = Node;
2043  })(window.ShadowDOMPolyfill);
2044  (function(scope) {
2045    "use strict";
2046    var HTMLCollection = scope.wrappers.HTMLCollection;
2047    var NodeList = scope.wrappers.NodeList;
2048    var getTreeScope = scope.getTreeScope;
2049    var unsafeUnwrap = scope.unsafeUnwrap;
2050    var wrap = scope.wrap;
2051    var originalDocumentQuerySelector = document.querySelector;
2052    var originalElementQuerySelector = document.documentElement.querySelector;
2053    var originalDocumentQuerySelectorAll = document.querySelectorAll;
2054    var originalElementQuerySelectorAll = document.documentElement.querySelectorAll;
2055    var originalDocumentGetElementsByTagName = document.getElementsByTagName;
2056    var originalElementGetElementsByTagName = document.documentElement.getElementsByTagName;
2057    var originalDocumentGetElementsByTagNameNS = document.getElementsByTagNameNS;
2058    var originalElementGetElementsByTagNameNS = document.documentElement.getElementsByTagNameNS;
2059    var OriginalElement = window.Element;
2060    var OriginalDocument = window.HTMLDocument || window.Document;
2061    function filterNodeList(list, index, result, deep) {
2062      var wrappedItem = null;
2063      var root = null;
2064      for (var i = 0, length = list.length; i < length; i++) {
2065        wrappedItem = wrap(list[i]);
2066        if (!deep && (root = getTreeScope(wrappedItem).root)) {
2067          if (root instanceof scope.wrappers.ShadowRoot) {
2068            continue;
2069          }
2070        }
2071        result[index++] = wrappedItem;
2072      }
2073      return index;
2074    }
2075    function shimSelector(selector) {
2076      return String(selector).replace(/\/deep\/|::shadow|>>>/g, " ");
2077    }
2078    function shimMatchesSelector(selector) {
2079      return String(selector).replace(/:host\(([^\s]+)\)/g, "$1").replace(/([^\s]):host/g, "$1").replace(":host", "*").replace(/\^|\/shadow\/|\/shadow-deep\/|::shadow|\/deep\/|::content|>>>/g, " ");
2080    }
2081    function findOne(node, selector) {
2082      var m, el = node.firstElementChild;
2083      while (el) {
2084        if (el.matches(selector)) return el;
2085        m = findOne(el, selector);
2086        if (m) return m;
2087        el = el.nextElementSibling;
2088      }
2089      return null;
2090    }
2091    function matchesSelector(el, selector) {
2092      return el.matches(selector);
2093    }
2094    var XHTML_NS = "http://www.w3.org/1999/xhtml";
2095    function matchesTagName(el, localName, localNameLowerCase) {
2096      var ln = el.localName;
2097      return ln === localName || ln === localNameLowerCase && el.namespaceURI === XHTML_NS;
2098    }
2099    function matchesEveryThing() {
2100      return true;
2101    }
2102    function matchesLocalNameOnly(el, ns, localName) {
2103      return el.localName === localName;
2104    }
2105    function matchesNameSpace(el, ns) {
2106      return el.namespaceURI === ns;
2107    }
2108    function matchesLocalNameNS(el, ns, localName) {
2109      return el.namespaceURI === ns && el.localName === localName;
2110    }
2111    function findElements(node, index, result, p, arg0, arg1) {
2112      var el = node.firstElementChild;
2113      while (el) {
2114        if (p(el, arg0, arg1)) result[index++] = el;
2115        index = findElements(el, index, result, p, arg0, arg1);
2116        el = el.nextElementSibling;
2117      }
2118      return index;
2119    }
2120    function querySelectorAllFiltered(p, index, result, selector, deep) {
2121      var target = unsafeUnwrap(this);
2122      var list;
2123      var root = getTreeScope(this).root;
2124      if (root instanceof scope.wrappers.ShadowRoot) {
2125        return findElements(this, index, result, p, selector, null);
2126      } else if (target instanceof OriginalElement) {
2127        list = originalElementQuerySelectorAll.call(target, selector);
2128      } else if (target instanceof OriginalDocument) {
2129        list = originalDocumentQuerySelectorAll.call(target, selector);
2130      } else {
2131        return findElements(this, index, result, p, selector, null);
2132      }
2133      return filterNodeList(list, index, result, deep);
2134    }
2135    var SelectorsInterface = {
2136      querySelector: function(selector) {
2137        var shimmed = shimSelector(selector);
2138        var deep = shimmed !== selector;
2139        selector = shimmed;
2140        var target = unsafeUnwrap(this);
2141        var wrappedItem;
2142        var root = getTreeScope(this).root;
2143        if (root instanceof scope.wrappers.ShadowRoot) {
2144          return findOne(this, selector);
2145        } else if (target instanceof OriginalElement) {
2146          wrappedItem = wrap(originalElementQuerySelector.call(target, selector));
2147        } else if (target instanceof OriginalDocument) {
2148          wrappedItem = wrap(originalDocumentQuerySelector.call(target, selector));
2149        } else {
2150          return findOne(this, selector);
2151        }
2152        if (!wrappedItem) {
2153          return wrappedItem;
2154        } else if (!deep && (root = getTreeScope(wrappedItem).root)) {
2155          if (root instanceof scope.wrappers.ShadowRoot) {
2156            return findOne(this, selector);
2157          }
2158        }
2159        return wrappedItem;
2160      },
2161      querySelectorAll: function(selector) {
2162        var shimmed = shimSelector(selector);
2163        var deep = shimmed !== selector;
2164        selector = shimmed;
2165        var result = new NodeList();
2166        result.length = querySelectorAllFiltered.call(this, matchesSelector, 0, result, selector, deep);
2167        return result;
2168      }
2169    };
2170    var MatchesInterface = {
2171      matches: function(selector) {
2172        selector = shimMatchesSelector(selector);
2173        return scope.originalMatches.call(unsafeUnwrap(this), selector);
2174      }
2175    };
2176    function getElementsByTagNameFiltered(p, index, result, localName, lowercase) {
2177      var target = unsafeUnwrap(this);
2178      var list;
2179      var root = getTreeScope(this).root;
2180      if (root instanceof scope.wrappers.ShadowRoot) {
2181        return findElements(this, index, result, p, localName, lowercase);
2182      } else if (target instanceof OriginalElement) {
2183        list = originalElementGetElementsByTagName.call(target, localName, lowercase);
2184      } else if (target instanceof OriginalDocument) {
2185        list = originalDocumentGetElementsByTagName.call(target, localName, lowercase);
2186      } else {
2187        return findElements(this, index, result, p, localName, lowercase);
2188      }
2189      return filterNodeList(list, index, result, false);
2190    }
2191    function getElementsByTagNameNSFiltered(p, index, result, ns, localName) {
2192      var target = unsafeUnwrap(this);
2193      var list;
2194      var root = getTreeScope(this).root;
2195      if (root instanceof scope.wrappers.ShadowRoot) {
2196        return findElements(this, index, result, p, ns, localName);
2197      } else if (target instanceof OriginalElement) {
2198        list = originalElementGetElementsByTagNameNS.call(target, ns, localName);
2199      } else if (target instanceof OriginalDocument) {
2200        list = originalDocumentGetElementsByTagNameNS.call(target, ns, localName);
2201      } else {
2202        return findElements(this, index, result, p, ns, localName);
2203      }
2204      return filterNodeList(list, index, result, false);
2205    }
2206    var GetElementsByInterface = {
2207      getElementsByTagName: function(localName) {
2208        var result = new HTMLCollection();
2209        var match = localName === "*" ? matchesEveryThing : matchesTagName;
2210        result.length = getElementsByTagNameFiltered.call(this, match, 0, result, localName, localName.toLowerCase());
2211        return result;
2212      },
2213      getElementsByClassName: function(className) {
2214        return this.querySelectorAll("." + className);
2215      },
2216      getElementsByTagNameNS: function(ns, localName) {
2217        var result = new HTMLCollection();
2218        var match = null;
2219        if (ns === "*") {
2220          match = localName === "*" ? matchesEveryThing : matchesLocalNameOnly;
2221        } else {
2222          match = localName === "*" ? matchesNameSpace : matchesLocalNameNS;
2223        }
2224        result.length = getElementsByTagNameNSFiltered.call(this, match, 0, result, ns || null, localName);
2225        return result;
2226      }
2227    };
2228    scope.GetElementsByInterface = GetElementsByInterface;
2229    scope.SelectorsInterface = SelectorsInterface;
2230    scope.MatchesInterface = MatchesInterface;
2231  })(window.ShadowDOMPolyfill);
2232  (function(scope) {
2233    "use strict";
2234    var NodeList = scope.wrappers.NodeList;
2235    function forwardElement(node) {
2236      while (node && node.nodeType !== Node.ELEMENT_NODE) {
2237        node = node.nextSibling;
2238      }
2239      return node;
2240    }
2241    function backwardsElement(node) {
2242      while (node && node.nodeType !== Node.ELEMENT_NODE) {
2243        node = node.previousSibling;
2244      }
2245      return node;
2246    }
2247    var ParentNodeInterface = {
2248      get firstElementChild() {
2249        return forwardElement(this.firstChild);
2250      },
2251      get lastElementChild() {
2252        return backwardsElement(this.lastChild);
2253      },
2254      get childElementCount() {
2255        var count = 0;
2256        for (var child = this.firstElementChild; child; child = child.nextElementSibling) {
2257          count++;
2258        }
2259        return count;
2260      },
2261      get children() {
2262        var wrapperList = new NodeList();
2263        var i = 0;
2264        for (var child = this.firstElementChild; child; child = child.nextElementSibling) {
2265          wrapperList[i++] = child;
2266        }
2267        wrapperList.length = i;
2268        return wrapperList;
2269      },
2270      remove: function() {
2271        var p = this.parentNode;
2272        if (p) p.removeChild(this);
2273      }
2274    };
2275    var ChildNodeInterface = {
2276      get nextElementSibling() {
2277        return forwardElement(this.nextSibling);
2278      },
2279      get previousElementSibling() {
2280        return backwardsElement(this.previousSibling);
2281      }
2282    };
2283    scope.ChildNodeInterface = ChildNodeInterface;
2284    scope.ParentNodeInterface = ParentNodeInterface;
2285  })(window.ShadowDOMPolyfill);
2286  (function(scope) {
2287    "use strict";
2288    var ChildNodeInterface = scope.ChildNodeInterface;
2289    var Node = scope.wrappers.Node;
2290    var enqueueMutation = scope.enqueueMutation;
2291    var mixin = scope.mixin;
2292    var registerWrapper = scope.registerWrapper;
2293    var unsafeUnwrap = scope.unsafeUnwrap;
2294    var OriginalCharacterData = window.CharacterData;
2295    function CharacterData(node) {
2296      Node.call(this, node);
2297    }
2298    CharacterData.prototype = Object.create(Node.prototype);
2299    mixin(CharacterData.prototype, {
2300      get nodeValue() {
2301        return this.data;
2302      },
2303      set nodeValue(data) {
2304        this.data = data;
2305      },
2306      get textContent() {
2307        return this.data;
2308      },
2309      set textContent(value) {
2310        this.data = value;
2311      },
2312      get data() {
2313        return unsafeUnwrap(this).data;
2314      },
2315      set data(value) {
2316        var oldValue = unsafeUnwrap(this).data;
2317        enqueueMutation(this, "characterData", {
2318          oldValue: oldValue
2319        });
2320        unsafeUnwrap(this).data = value;
2321      }
2322    });
2323    mixin(CharacterData.prototype, ChildNodeInterface);
2324    registerWrapper(OriginalCharacterData, CharacterData, document.createTextNode(""));
2325    scope.wrappers.CharacterData = CharacterData;
2326  })(window.ShadowDOMPolyfill);
2327  (function(scope) {
2328    "use strict";
2329    var CharacterData = scope.wrappers.CharacterData;
2330    var enqueueMutation = scope.enqueueMutation;
2331    var mixin = scope.mixin;
2332    var registerWrapper = scope.registerWrapper;
2333    function toUInt32(x) {
2334      return x >>> 0;
2335    }
2336    var OriginalText = window.Text;
2337    function Text(node) {
2338      CharacterData.call(this, node);
2339    }
2340    Text.prototype = Object.create(CharacterData.prototype);
2341    mixin(Text.prototype, {
2342      splitText: function(offset) {
2343        offset = toUInt32(offset);
2344        var s = this.data;
2345        if (offset > s.length) throw new Error("IndexSizeError");
2346        var head = s.slice(0, offset);
2347        var tail = s.slice(offset);
2348        this.data = head;
2349        var newTextNode = this.ownerDocument.createTextNode(tail);
2350        if (this.parentNode) this.parentNode.insertBefore(newTextNode, this.nextSibling);
2351        return newTextNode;
2352      }
2353    });
2354    registerWrapper(OriginalText, Text, document.createTextNode(""));
2355    scope.wrappers.Text = Text;
2356  })(window.ShadowDOMPolyfill);
2357  (function(scope) {
2358    "use strict";
2359    if (!window.DOMTokenList) {
2360      console.warn("Missing DOMTokenList prototype, please include a " + "compatible classList polyfill such as http://goo.gl/uTcepH.");
2361      return;
2362    }
2363    var unsafeUnwrap = scope.unsafeUnwrap;
2364    var enqueueMutation = scope.enqueueMutation;
2365    function getClass(el) {
2366      return unsafeUnwrap(el).getAttribute("class");
2367    }
2368    function enqueueClassAttributeChange(el, oldValue) {
2369      enqueueMutation(el, "attributes", {
2370        name: "class",
2371        namespace: null,
2372        oldValue: oldValue
2373      });
2374    }
2375    function invalidateClass(el) {
2376      scope.invalidateRendererBasedOnAttribute(el, "class");
2377    }
2378    function changeClass(tokenList, method, args) {
2379      var ownerElement = tokenList.ownerElement_;
2380      if (ownerElement == null) {
2381        return method.apply(tokenList, args);
2382      }
2383      var oldValue = getClass(ownerElement);
2384      var retv = method.apply(tokenList, args);
2385      if (getClass(ownerElement) !== oldValue) {
2386        enqueueClassAttributeChange(ownerElement, oldValue);
2387        invalidateClass(ownerElement);
2388      }
2389      return retv;
2390    }
2391    var oldAdd = DOMTokenList.prototype.add;
2392    DOMTokenList.prototype.add = function() {
2393      changeClass(this, oldAdd, arguments);
2394    };
2395    var oldRemove = DOMTokenList.prototype.remove;
2396    DOMTokenList.prototype.remove = function() {
2397      changeClass(this, oldRemove, arguments);
2398    };
2399    var oldToggle = DOMTokenList.prototype.toggle;
2400    DOMTokenList.prototype.toggle = function() {
2401      return changeClass(this, oldToggle, arguments);
2402    };
2403  })(window.ShadowDOMPolyfill);
2404  (function(scope) {
2405    "use strict";
2406    var ChildNodeInterface = scope.ChildNodeInterface;
2407    var GetElementsByInterface = scope.GetElementsByInterface;
2408    var Node = scope.wrappers.Node;
2409    var ParentNodeInterface = scope.ParentNodeInterface;
2410    var SelectorsInterface = scope.SelectorsInterface;
2411    var MatchesInterface = scope.MatchesInterface;
2412    var addWrapNodeListMethod = scope.addWrapNodeListMethod;
2413    var enqueueMutation = scope.enqueueMutation;
2414    var mixin = scope.mixin;
2415    var oneOf = scope.oneOf;
2416    var registerWrapper = scope.registerWrapper;
2417    var unsafeUnwrap = scope.unsafeUnwrap;
2418    var wrappers = scope.wrappers;
2419    var OriginalElement = window.Element;
2420    var matchesNames = [ "matches", "mozMatchesSelector", "msMatchesSelector", "webkitMatchesSelector" ].filter(function(name) {
2421      return OriginalElement.prototype[name];
2422    });
2423    var matchesName = matchesNames[0];
2424    var originalMatches = OriginalElement.prototype[matchesName];
2425    function invalidateRendererBasedOnAttribute(element, name) {
2426      var p = element.parentNode;
2427      if (!p || !p.shadowRoot) return;
2428      var renderer = scope.getRendererForHost(p);
2429      if (renderer.dependsOnAttribute(name)) renderer.invalidate();
2430    }
2431    function enqueAttributeChange(element, name, oldValue) {
2432      enqueueMutation(element, "attributes", {
2433        name: name,
2434        namespace: null,
2435        oldValue: oldValue
2436      });
2437    }
2438    var classListTable = new WeakMap();
2439    function Element(node) {
2440      Node.call(this, node);
2441    }
2442    Element.prototype = Object.create(Node.prototype);
2443    mixin(Element.prototype, {
2444      createShadowRoot: function() {
2445        var newShadowRoot = new wrappers.ShadowRoot(this);
2446        unsafeUnwrap(this).polymerShadowRoot_ = newShadowRoot;
2447        var renderer = scope.getRendererForHost(this);
2448        renderer.invalidate();
2449        return newShadowRoot;
2450      },
2451      get shadowRoot() {
2452        return unsafeUnwrap(this).polymerShadowRoot_ || null;
2453      },
2454      setAttribute: function(name, value) {
2455        var oldValue = unsafeUnwrap(this).getAttribute(name);
2456        unsafeUnwrap(this).setAttribute(name, value);
2457        enqueAttributeChange(this, name, oldValue);
2458        invalidateRendererBasedOnAttribute(this, name);
2459      },
2460      removeAttribute: function(name) {
2461        var oldValue = unsafeUnwrap(this).getAttribute(name);
2462        unsafeUnwrap(this).removeAttribute(name);
2463        enqueAttributeChange(this, name, oldValue);
2464        invalidateRendererBasedOnAttribute(this, name);
2465      },
2466      get classList() {
2467        var list = classListTable.get(this);
2468        if (!list) {
2469          list = unsafeUnwrap(this).classList;
2470          if (!list) return;
2471          list.ownerElement_ = this;
2472          classListTable.set(this, list);
2473        }
2474        return list;
2475      },
2476      get className() {
2477        return unsafeUnwrap(this).className;
2478      },
2479      set className(v) {
2480        this.setAttribute("class", v);
2481      },
2482      get id() {
2483        return unsafeUnwrap(this).id;
2484      },
2485      set id(v) {
2486        this.setAttribute("id", v);
2487      }
2488    });
2489    matchesNames.forEach(function(name) {
2490      if (name !== "matches") {
2491        Element.prototype[name] = function(selector) {
2492          return this.matches(selector);
2493        };
2494      }
2495    });
2496    if (OriginalElement.prototype.webkitCreateShadowRoot) {
2497      Element.prototype.webkitCreateShadowRoot = Element.prototype.createShadowRoot;
2498    }
2499    mixin(Element.prototype, ChildNodeInterface);
2500    mixin(Element.prototype, GetElementsByInterface);
2501    mixin(Element.prototype, ParentNodeInterface);
2502    mixin(Element.prototype, SelectorsInterface);
2503    mixin(Element.prototype, MatchesInterface);
2504    registerWrapper(OriginalElement, Element, document.createElementNS(null, "x"));
2505    scope.invalidateRendererBasedOnAttribute = invalidateRendererBasedOnAttribute;
2506    scope.matchesNames = matchesNames;
2507    scope.originalMatches = originalMatches;
2508    scope.wrappers.Element = Element;
2509  })(window.ShadowDOMPolyfill);
2510  (function(scope) {
2511    "use strict";
2512    var Element = scope.wrappers.Element;
2513    var defineGetter = scope.defineGetter;
2514    var enqueueMutation = scope.enqueueMutation;
2515    var mixin = scope.mixin;
2516    var nodesWereAdded = scope.nodesWereAdded;
2517    var nodesWereRemoved = scope.nodesWereRemoved;
2518    var registerWrapper = scope.registerWrapper;
2519    var snapshotNodeList = scope.snapshotNodeList;
2520    var unsafeUnwrap = scope.unsafeUnwrap;
2521    var unwrap = scope.unwrap;
2522    var wrap = scope.wrap;
2523    var wrappers = scope.wrappers;
2524    var escapeAttrRegExp = /[&\u00A0"]/g;
2525    var escapeDataRegExp = /[&\u00A0<>]/g;
2526    function escapeReplace(c) {
2527      switch (c) {
2528       case "&":
2529        return "&amp;";
2530
2531       case "<":
2532        return "&lt;";
2533
2534       case ">":
2535        return "&gt;";
2536
2537       case '"':
2538        return "&quot;";
2539
2540       case " ":
2541        return "&nbsp;";
2542      }
2543    }
2544    function escapeAttr(s) {
2545      return s.replace(escapeAttrRegExp, escapeReplace);
2546    }
2547    function escapeData(s) {
2548      return s.replace(escapeDataRegExp, escapeReplace);
2549    }
2550    function makeSet(arr) {
2551      var set = {};
2552      for (var i = 0; i < arr.length; i++) {
2553        set[arr[i]] = true;
2554      }
2555      return set;
2556    }
2557    var voidElements = makeSet([ "area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr" ]);
2558    var plaintextParents = makeSet([ "style", "script", "xmp", "iframe", "noembed", "noframes", "plaintext", "noscript" ]);
2559    function getOuterHTML(node, parentNode) {
2560      switch (node.nodeType) {
2561       case Node.ELEMENT_NODE:
2562        var tagName = node.tagName.toLowerCase();
2563        var s = "<" + tagName;
2564        var attrs = node.attributes;
2565        for (var i = 0, attr; attr = attrs[i]; i++) {
2566          s += " " + attr.name + '="' + escapeAttr(attr.value) + '"';
2567        }
2568        s += ">";
2569        if (voidElements[tagName]) return s;
2570        return s + getInnerHTML(node) + "</" + tagName + ">";
2571
2572       case Node.TEXT_NODE:
2573        var data = node.data;
2574        if (parentNode && plaintextParents[parentNode.localName]) return data;
2575        return escapeData(data);
2576
2577       case Node.COMMENT_NODE:
2578        return "<!--" + node.data + "-->";
2579
2580       default:
2581        console.error(node);
2582        throw new Error("not implemented");
2583      }
2584    }
2585    function getInnerHTML(node) {
2586      if (node instanceof wrappers.HTMLTemplateElement) node = node.content;
2587      var s = "";
2588      for (var child = node.firstChild; child; child = child.nextSibling) {
2589        s += getOuterHTML(child, node);
2590      }
2591      return s;
2592    }
2593    function setInnerHTML(node, value, opt_tagName) {
2594      var tagName = opt_tagName || "div";
2595      node.textContent = "";
2596      var tempElement = unwrap(node.ownerDocument.createElement(tagName));
2597      tempElement.innerHTML = value;
2598      var firstChild;
2599      while (firstChild = tempElement.firstChild) {
2600        node.appendChild(wrap(firstChild));
2601      }
2602    }
2603    var oldIe = /MSIE/.test(navigator.userAgent);
2604    var OriginalHTMLElement = window.HTMLElement;
2605    var OriginalHTMLTemplateElement = window.HTMLTemplateElement;
2606    function HTMLElement(node) {
2607      Element.call(this, node);
2608    }
2609    HTMLElement.prototype = Object.create(Element.prototype);
2610    mixin(HTMLElement.prototype, {
2611      get innerHTML() {
2612        return getInnerHTML(this);
2613      },
2614      set innerHTML(value) {
2615        if (oldIe && plaintextParents[this.localName]) {
2616          this.textContent = value;
2617          return;
2618        }
2619        var removedNodes = snapshotNodeList(this.childNodes);
2620        if (this.invalidateShadowRenderer()) {
2621          if (this instanceof wrappers.HTMLTemplateElement) setInnerHTML(this.content, value); else setInnerHTML(this, value, this.tagName);
2622        } else if (!OriginalHTMLTemplateElement && this instanceof wrappers.HTMLTemplateElement) {
2623          setInnerHTML(this.content, value);
2624        } else {
2625          unsafeUnwrap(this).innerHTML = value;
2626        }
2627        var addedNodes = snapshotNodeList(this.childNodes);
2628        enqueueMutation(this, "childList", {
2629          addedNodes: addedNodes,
2630          removedNodes: removedNodes
2631        });
2632        nodesWereRemoved(removedNodes);
2633        nodesWereAdded(addedNodes, this);
2634      },
2635      get outerHTML() {
2636        return getOuterHTML(this, this.parentNode);
2637      },
2638      set outerHTML(value) {
2639        var p = this.parentNode;
2640        if (p) {
2641          p.invalidateShadowRenderer();
2642          var df = frag(p, value);
2643          p.replaceChild(df, this);
2644        }
2645      },
2646      insertAdjacentHTML: function(position, text) {
2647        var contextElement, refNode;
2648        switch (String(position).toLowerCase()) {
2649         case "beforebegin":
2650          contextElement = this.parentNode;
2651          refNode = this;
2652          break;
2653
2654         case "afterend":
2655          contextElement = this.parentNode;
2656          refNode = this.nextSibling;
2657          break;
2658
2659         case "afterbegin":
2660          contextElement = this;
2661          refNode = this.firstChild;
2662          break;
2663
2664         case "beforeend":
2665          contextElement = this;
2666          refNode = null;
2667          break;
2668
2669         default:
2670          return;
2671        }
2672        var df = frag(contextElement, text);
2673        contextElement.insertBefore(df, refNode);
2674      },
2675      get hidden() {
2676        return this.hasAttribute("hidden");
2677      },
2678      set hidden(v) {
2679        if (v) {
2680          this.setAttribute("hidden", "");
2681        } else {
2682          this.removeAttribute("hidden");
2683        }
2684      }
2685    });
2686    function frag(contextElement, html) {
2687      var p = unwrap(contextElement.cloneNode(false));
2688      p.innerHTML = html;
2689      var df = unwrap(document.createDocumentFragment());
2690      var c;
2691      while (c = p.firstChild) {
2692        df.appendChild(c);
2693      }
2694      return wrap(df);
2695    }
2696    function getter(name) {
2697      return function() {
2698        scope.renderAllPending();
2699        return unsafeUnwrap(this)[name];
2700      };
2701    }
2702    function getterRequiresRendering(name) {
2703      defineGetter(HTMLElement, name, getter(name));
2704    }
2705    [ "clientHeight", "clientLeft", "clientTop", "clientWidth", "offsetHeight", "offsetLeft", "offsetTop", "offsetWidth", "scrollHeight", "scrollWidth" ].forEach(getterRequiresRendering);
2706    function getterAndSetterRequiresRendering(name) {
2707      Object.defineProperty(HTMLElement.prototype, name, {
2708        get: getter(name),
2709        set: function(v) {
2710          scope.renderAllPending();
2711          unsafeUnwrap(this)[name] = v;
2712        },
2713        configurable: true,
2714        enumerable: true
2715      });
2716    }
2717    [ "scrollLeft", "scrollTop" ].forEach(getterAndSetterRequiresRendering);
2718    function methodRequiresRendering(name) {
2719      Object.defineProperty(HTMLElement.prototype, name, {
2720        value: function() {
2721          scope.renderAllPending();
2722          return unsafeUnwrap(this)[name].apply(unsafeUnwrap(this), arguments);
2723        },
2724        configurable: true,
2725        enumerable: true
2726      });
2727    }
2728    [ "getBoundingClientRect", "getClientRects", "scrollIntoView" ].forEach(methodRequiresRendering);
2729    registerWrapper(OriginalHTMLElement, HTMLElement, document.createElement("b"));
2730    scope.wrappers.HTMLElement = HTMLElement;
2731    scope.getInnerHTML = getInnerHTML;
2732    scope.setInnerHTML = setInnerHTML;
2733  })(window.ShadowDOMPolyfill);
2734  (function(scope) {
2735    "use strict";
2736    var HTMLElement = scope.wrappers.HTMLElement;
2737    var mixin = scope.mixin;
2738    var registerWrapper = scope.registerWrapper;
2739    var unsafeUnwrap = scope.unsafeUnwrap;
2740    var wrap = scope.wrap;
2741    var OriginalHTMLCanvasElement = window.HTMLCanvasElement;
2742    function HTMLCanvasElement(node) {
2743      HTMLElement.call(this, node);
2744    }
2745    HTMLCanvasElement.prototype = Object.create(HTMLElement.prototype);
2746    mixin(HTMLCanvasElement.prototype, {
2747      getContext: function() {
2748        var context = unsafeUnwrap(this).getContext.apply(unsafeUnwrap(this), arguments);
2749        return context && wrap(context);
2750      }
2751    });
2752    registerWrapper(OriginalHTMLCanvasElement, HTMLCanvasElement, document.createElement("canvas"));
2753    scope.wrappers.HTMLCanvasElement = HTMLCanvasElement;
2754  })(window.ShadowDOMPolyfill);
2755  (function(scope) {
2756    "use strict";
2757    var HTMLElement = scope.wrappers.HTMLElement;
2758    var mixin = scope.mixin;
2759    var registerWrapper = scope.registerWrapper;
2760    var OriginalHTMLContentElement = window.HTMLContentElement;
2761    function HTMLContentElement(node) {
2762      HTMLElement.call(this, node);
2763    }
2764    HTMLContentElement.prototype = Object.create(HTMLElement.prototype);
2765    mixin(HTMLContentElement.prototype, {
2766      constructor: HTMLContentElement,
2767      get select() {
2768        return this.getAttribute("select");
2769      },
2770      set select(value) {
2771        this.setAttribute("select", value);
2772      },
2773      setAttribute: function(n, v) {
2774        HTMLElement.prototype.setAttribute.call(this, n, v);
2775        if (String(n).toLowerCase() === "select") this.invalidateShadowRenderer(true);
2776      }
2777    });
2778    if (OriginalHTMLContentElement) registerWrapper(OriginalHTMLContentElement, HTMLContentElement);
2779    scope.wrappers.HTMLContentElement = HTMLContentElement;
2780  })(window.ShadowDOMPolyfill);
2781  (function(scope) {
2782    "use strict";
2783    var HTMLElement = scope.wrappers.HTMLElement;
2784    var mixin = scope.mixin;
2785    var registerWrapper = scope.registerWrapper;
2786    var wrapHTMLCollection = scope.wrapHTMLCollection;
2787    var unwrap = scope.unwrap;
2788    var OriginalHTMLFormElement = window.HTMLFormElement;
2789    function HTMLFormElement(node) {
2790      HTMLElement.call(this, node);
2791    }
2792    HTMLFormElement.prototype = Object.create(HTMLElement.prototype);
2793    mixin(HTMLFormElement.prototype, {
2794      get elements() {
2795        return wrapHTMLCollection(unwrap(this).elements);
2796      }
2797    });
2798    registerWrapper(OriginalHTMLFormElement, HTMLFormElement, document.createElement("form"));
2799    scope.wrappers.HTMLFormElement = HTMLFormElement;
2800  })(window.ShadowDOMPolyfill);
2801  (function(scope) {
2802    "use strict";
2803    var HTMLElement = scope.wrappers.HTMLElement;
2804    var registerWrapper = scope.registerWrapper;
2805    var unwrap = scope.unwrap;
2806    var rewrap = scope.rewrap;
2807    var OriginalHTMLImageElement = window.HTMLImageElement;
2808    function HTMLImageElement(node) {
2809      HTMLElement.call(this, node);
2810    }
2811    HTMLImageElement.prototype = Object.create(HTMLElement.prototype);
2812    registerWrapper(OriginalHTMLImageElement, HTMLImageElement, document.createElement("img"));
2813    function Image(width, height) {
2814      if (!(this instanceof Image)) {
2815        throw new TypeError("DOM object constructor cannot be called as a function.");
2816      }
2817      var node = unwrap(document.createElement("img"));
2818      HTMLElement.call(this, node);
2819      rewrap(node, this);
2820      if (width !== undefined) node.width = width;
2821      if (height !== undefined) node.height = height;
2822    }
2823    Image.prototype = HTMLImageElement.prototype;
2824    scope.wrappers.HTMLImageElement = HTMLImageElement;
2825    scope.wrappers.Image = Image;
2826  })(window.ShadowDOMPolyfill);
2827  (function(scope) {
2828    "use strict";
2829    var HTMLElement = scope.wrappers.HTMLElement;
2830    var mixin = scope.mixin;
2831    var NodeList = scope.wrappers.NodeList;
2832    var registerWrapper = scope.registerWrapper;
2833    var OriginalHTMLShadowElement = window.HTMLShadowElement;
2834    function HTMLShadowElement(node) {
2835      HTMLElement.call(this, node);
2836    }
2837    HTMLShadowElement.prototype = Object.create(HTMLElement.prototype);
2838    HTMLShadowElement.prototype.constructor = HTMLShadowElement;
2839    if (OriginalHTMLShadowElement) registerWrapper(OriginalHTMLShadowElement, HTMLShadowElement);
2840    scope.wrappers.HTMLShadowElement = HTMLShadowElement;
2841  })(window.ShadowDOMPolyfill);
2842  (function(scope) {
2843    "use strict";
2844    var HTMLElement = scope.wrappers.HTMLElement;
2845    var mixin = scope.mixin;
2846    var registerWrapper = scope.registerWrapper;
2847    var unsafeUnwrap = scope.unsafeUnwrap;
2848    var unwrap = scope.unwrap;
2849    var wrap = scope.wrap;
2850    var contentTable = new WeakMap();
2851    var templateContentsOwnerTable = new WeakMap();
2852    function getTemplateContentsOwner(doc) {
2853      if (!doc.defaultView) return doc;
2854      var d = templateContentsOwnerTable.get(doc);
2855      if (!d) {
2856        d = doc.implementation.createHTMLDocument("");
2857        while (d.lastChild) {
2858          d.removeChild(d.lastChild);
2859        }
2860        templateContentsOwnerTable.set(doc, d);
2861      }
2862      return d;
2863    }
2864    function extractContent(templateElement) {
2865      var doc = getTemplateContentsOwner(templateElement.ownerDocument);
2866      var df = unwrap(doc.createDocumentFragment());
2867      var child;
2868      while (child = templateElement.firstChild) {
2869        df.appendChild(child);
2870      }
2871      return df;
2872    }
2873    var OriginalHTMLTemplateElement = window.HTMLTemplateElement;
2874    function HTMLTemplateElement(node) {
2875      HTMLElement.call(this, node);
2876      if (!OriginalHTMLTemplateElement) {
2877        var content = extractContent(node);
2878        contentTable.set(this, wrap(content));
2879      }
2880    }
2881    HTMLTemplateElement.prototype = Object.create(HTMLElement.prototype);
2882    mixin(HTMLTemplateElement.prototype, {
2883      constructor: HTMLTemplateElement,
2884      get content() {
2885        if (OriginalHTMLTemplateElement) return wrap(unsafeUnwrap(this).content);
2886        return contentTable.get(this);
2887      }
2888    });
2889    if (OriginalHTMLTemplateElement) registerWrapper(OriginalHTMLTemplateElement, HTMLTemplateElement);
2890    scope.wrappers.HTMLTemplateElement = HTMLTemplateElement;
2891  })(window.ShadowDOMPolyfill);
2892  (function(scope) {
2893    "use strict";
2894    var HTMLElement = scope.wrappers.HTMLElement;
2895    var registerWrapper = scope.registerWrapper;
2896    var OriginalHTMLMediaElement = window.HTMLMediaElement;
2897    if (!OriginalHTMLMediaElement) return;
2898    function HTMLMediaElement(node) {
2899      HTMLElement.call(this, node);
2900    }
2901    HTMLMediaElement.prototype = Object.create(HTMLElement.prototype);
2902    registerWrapper(OriginalHTMLMediaElement, HTMLMediaElement, document.createElement("audio"));
2903    scope.wrappers.HTMLMediaElement = HTMLMediaElement;
2904  })(window.ShadowDOMPolyfill);
2905  (function(scope) {
2906    "use strict";
2907    var HTMLMediaElement = scope.wrappers.HTMLMediaElement;
2908    var registerWrapper = scope.registerWrapper;
2909    var unwrap = scope.unwrap;
2910    var rewrap = scope.rewrap;
2911    var OriginalHTMLAudioElement = window.HTMLAudioElement;
2912    if (!OriginalHTMLAudioElement) return;
2913    function HTMLAudioElement(node) {
2914      HTMLMediaElement.call(this, node);
2915    }
2916    HTMLAudioElement.prototype = Object.create(HTMLMediaElement.prototype);
2917    registerWrapper(OriginalHTMLAudioElement, HTMLAudioElement, document.createElement("audio"));
2918    function Audio(src) {
2919      if (!(this instanceof Audio)) {
2920        throw new TypeError("DOM object constructor cannot be called as a function.");
2921      }
2922      var node = unwrap(document.createElement("audio"));
2923      HTMLMediaElement.call(this, node);
2924      rewrap(node, this);
2925      node.setAttribute("preload", "auto");
2926      if (src !== undefined) node.setAttribute("src", src);
2927    }
2928    Audio.prototype = HTMLAudioElement.prototype;
2929    scope.wrappers.HTMLAudioElement = HTMLAudioElement;
2930    scope.wrappers.Audio = Audio;
2931  })(window.ShadowDOMPolyfill);
2932  (function(scope) {
2933    "use strict";
2934    var HTMLElement = scope.wrappers.HTMLElement;
2935    var mixin = scope.mixin;
2936    var registerWrapper = scope.registerWrapper;
2937    var rewrap = scope.rewrap;
2938    var unwrap = scope.unwrap;
2939    var wrap = scope.wrap;
2940    var OriginalHTMLOptionElement = window.HTMLOptionElement;
2941    function trimText(s) {
2942      return s.replace(/\s+/g, " ").trim();
2943    }
2944    function HTMLOptionElement(node) {
2945      HTMLElement.call(this, node);
2946    }
2947    HTMLOptionElement.prototype = Object.create(HTMLElement.prototype);
2948    mixin(HTMLOptionElement.prototype, {
2949      get text() {
2950        return trimText(this.textContent);
2951      },
2952      set text(value) {
2953        this.textContent = trimText(String(value));
2954      },
2955      get form() {
2956        return wrap(unwrap(this).form);
2957      }
2958    });
2959    registerWrapper(OriginalHTMLOptionElement, HTMLOptionElement, document.createElement("option"));
2960    function Option(text, value, defaultSelected, selected) {
2961      if (!(this instanceof Option)) {
2962        throw new TypeError("DOM object constructor cannot be called as a function.");
2963      }
2964      var node = unwrap(document.createElement("option"));
2965      HTMLElement.call(this, node);
2966      rewrap(node, this);
2967      if (text !== undefined) node.text = text;
2968      if (value !== undefined) node.setAttribute("value", value);
2969      if (defaultSelected === true) node.setAttribute("selected", "");
2970      node.selected = selected === true;
2971    }
2972    Option.prototype = HTMLOptionElement.prototype;
2973    scope.wrappers.HTMLOptionElement = HTMLOptionElement;
2974    scope.wrappers.Option = Option;
2975  })(window.ShadowDOMPolyfill);
2976  (function(scope) {
2977    "use strict";
2978    var HTMLElement = scope.wrappers.HTMLElement;
2979    var mixin = scope.mixin;
2980    var registerWrapper = scope.registerWrapper;
2981    var unwrap = scope.unwrap;
2982    var wrap = scope.wrap;
2983    var OriginalHTMLSelectElement = window.HTMLSelectElement;
2984    function HTMLSelectElement(node) {
2985      HTMLElement.call(this, node);
2986    }
2987    HTMLSelectElement.prototype = Object.create(HTMLElement.prototype);
2988    mixin(HTMLSelectElement.prototype, {
2989      add: function(element, before) {
2990        if (typeof before === "object") before = unwrap(before);
2991        unwrap(this).add(unwrap(element), before);
2992      },
2993      remove: function(indexOrNode) {
2994        if (indexOrNode === undefined) {
2995          HTMLElement.prototype.remove.call(this);
2996          return;
2997        }
2998        if (typeof indexOrNode === "object") indexOrNode = unwrap(indexOrNode);
2999        unwrap(this).remove(indexOrNode);
3000      },
3001      get form() {
3002        return wrap(unwrap(this).form);
3003      }
3004    });
3005    registerWrapper(OriginalHTMLSelectElement, HTMLSelectElement, document.createElement("select"));
3006    scope.wrappers.HTMLSelectElement = HTMLSelectElement;
3007  })(window.ShadowDOMPolyfill);
3008  (function(scope) {
3009    "use strict";
3010    var HTMLElement = scope.wrappers.HTMLElement;
3011    var mixin = scope.mixin;
3012    var registerWrapper = scope.registerWrapper;
3013    var unwrap = scope.unwrap;
3014    var wrap = scope.wrap;
3015    var wrapHTMLCollection = scope.wrapHTMLCollection;
3016    var OriginalHTMLTableElement = window.HTMLTableElement;
3017    function HTMLTableElement(node) {
3018      HTMLElement.call(this, node);
3019    }
3020    HTMLTableElement.prototype = Object.create(HTMLElement.prototype);
3021    mixin(HTMLTableElement.prototype, {
3022      get caption() {
3023        return wrap(unwrap(this).caption);
3024      },
3025      createCaption: function() {
3026        return wrap(unwrap(this).createCaption());
3027      },
3028      get tHead() {
3029        return wrap(unwrap(this).tHead);
3030      },
3031      createTHead: function() {
3032        return wrap(unwrap(this).createTHead());
3033      },
3034      createTFoot: function() {
3035        return wrap(unwrap(this).createTFoot());
3036      },
3037      get tFoot() {
3038        return wrap(unwrap(this).tFoot);
3039      },
3040      get tBodies() {
3041        return wrapHTMLCollection(unwrap(this).tBodies);
3042      },
3043      createTBody: function() {
3044        return wrap(unwrap(this).createTBody());
3045      },
3046      get rows() {
3047        return wrapHTMLCollection(unwrap(this).rows);
3048      },
3049      insertRow: function(index) {
3050        return wrap(unwrap(this).insertRow(index));
3051      }
3052    });
3053    registerWrapper(OriginalHTMLTableElement, HTMLTableElement, document.createElement("table"));
3054    scope.wrappers.HTMLTableElement = HTMLTableElement;
3055  })(window.ShadowDOMPolyfill);
3056  (function(scope) {
3057    "use strict";
3058    var HTMLElement = scope.wrappers.HTMLElement;
3059    var mixin = scope.mixin;
3060    var registerWrapper = scope.registerWrapper;
3061    var wrapHTMLCollection = scope.wrapHTMLCollection;
3062    var unwrap = scope.unwrap;
3063    var wrap = scope.wrap;
3064    var OriginalHTMLTableSectionElement = window.HTMLTableSectionElement;
3065    function HTMLTableSectionElement(node) {
3066      HTMLElement.call(this, node);
3067    }
3068    HTMLTableSectionElement.prototype = Object.create(HTMLElement.prototype);
3069    mixin(HTMLTableSectionElement.prototype, {
3070      constructor: HTMLTableSectionElement,
3071      get rows() {
3072        return wrapHTMLCollection(unwrap(this).rows);
3073      },
3074      insertRow: function(index) {
3075        return wrap(unwrap(this).insertRow(index));
3076      }
3077    });
3078    registerWrapper(OriginalHTMLTableSectionElement, HTMLTableSectionElement, document.createElement("thead"));
3079    scope.wrappers.HTMLTableSectionElement = HTMLTableSectionElement;
3080  })(window.ShadowDOMPolyfill);
3081  (function(scope) {
3082    "use strict";
3083    var HTMLElement = scope.wrappers.HTMLElement;
3084    var mixin = scope.mixin;
3085    var registerWrapper = scope.registerWrapper;
3086    var wrapHTMLCollection = scope.wrapHTMLCollection;
3087    var unwrap = scope.unwrap;
3088    var wrap = scope.wrap;
3089    var OriginalHTMLTableRowElement = window.HTMLTableRowElement;
3090    function HTMLTableRowElement(node) {
3091      HTMLElement.call(this, node);
3092    }
3093    HTMLTableRowElement.prototype = Object.create(HTMLElement.prototype);
3094    mixin(HTMLTableRowElement.prototype, {
3095      get cells() {
3096        return wrapHTMLCollection(unwrap(this).cells);
3097      },
3098      insertCell: function(index) {
3099        return wrap(unwrap(this).insertCell(index));
3100      }
3101    });
3102    registerWrapper(OriginalHTMLTableRowElement, HTMLTableRowElement, document.createElement("tr"));
3103    scope.wrappers.HTMLTableRowElement = HTMLTableRowElement;
3104  })(window.ShadowDOMPolyfill);
3105  (function(scope) {
3106    "use strict";
3107    var HTMLContentElement = scope.wrappers.HTMLContentElement;
3108    var HTMLElement = scope.wrappers.HTMLElement;
3109    var HTMLShadowElement = scope.wrappers.HTMLShadowElement;
3110    var HTMLTemplateElement = scope.wrappers.HTMLTemplateElement;
3111    var mixin = scope.mixin;
3112    var registerWrapper = scope.registerWrapper;
3113    var OriginalHTMLUnknownElement = window.HTMLUnknownElement;
3114    function HTMLUnknownElement(node) {
3115      switch (node.localName) {
3116       case "content":
3117        return new HTMLContentElement(node);
3118
3119       case "shadow":
3120        return new HTMLShadowElement(node);
3121
3122       case "template":
3123        return new HTMLTemplateElement(node);
3124      }
3125      HTMLElement.call(this, node);
3126    }
3127    HTMLUnknownElement.prototype = Object.create(HTMLElement.prototype);
3128    registerWrapper(OriginalHTMLUnknownElement, HTMLUnknownElement);
3129    scope.wrappers.HTMLUnknownElement = HTMLUnknownElement;
3130  })(window.ShadowDOMPolyfill);
3131  (function(scope) {
3132    "use strict";
3133    var Element = scope.wrappers.Element;
3134    var HTMLElement = scope.wrappers.HTMLElement;
3135    var registerObject = scope.registerObject;
3136    var defineWrapGetter = scope.defineWrapGetter;
3137    var SVG_NS = "http://www.w3.org/2000/svg";
3138    var svgTitleElement = document.createElementNS(SVG_NS, "title");
3139    var SVGTitleElement = registerObject(svgTitleElement);
3140    var SVGElement = Object.getPrototypeOf(SVGTitleElement.prototype).constructor;
3141    if (!("classList" in svgTitleElement)) {
3142      var descr = Object.getOwnPropertyDescriptor(Element.prototype, "classList");
3143      Object.defineProperty(HTMLElement.prototype, "classList", descr);
3144      delete Element.prototype.classList;
3145    }
3146    defineWrapGetter(SVGElement, "ownerSVGElement");
3147    scope.wrappers.SVGElement = SVGElement;
3148  })(window.ShadowDOMPolyfill);
3149  (function(scope) {
3150    "use strict";
3151    var mixin = scope.mixin;
3152    var registerWrapper = scope.registerWrapper;
3153    var unwrap = scope.unwrap;
3154    var wrap = scope.wrap;
3155    var OriginalSVGUseElement = window.SVGUseElement;
3156    var SVG_NS = "http://www.w3.org/2000/svg";
3157    var gWrapper = wrap(document.createElementNS(SVG_NS, "g"));
3158    var useElement = document.createElementNS(SVG_NS, "use");
3159    var SVGGElement = gWrapper.constructor;
3160    var parentInterfacePrototype = Object.getPrototypeOf(SVGGElement.prototype);
3161    var parentInterface = parentInterfacePrototype.constructor;
3162    function SVGUseElement(impl) {
3163      parentInterface.call(this, impl);
3164    }
3165    SVGUseElement.prototype = Object.create(parentInterfacePrototype);
3166    if ("instanceRoot" in useElement) {
3167      mixin(SVGUseElement.prototype, {
3168        get instanceRoot() {
3169          return wrap(unwrap(this).instanceRoot);
3170        },
3171        get animatedInstanceRoot() {
3172          return wrap(unwrap(this).animatedInstanceRoot);
3173        }
3174      });
3175    }
3176    registerWrapper(OriginalSVGUseElement, SVGUseElement, useElement);
3177    scope.wrappers.SVGUseElement = SVGUseElement;
3178  })(window.ShadowDOMPolyfill);
3179  (function(scope) {
3180    "use strict";
3181    var EventTarget = scope.wrappers.EventTarget;
3182    var mixin = scope.mixin;
3183    var registerWrapper = scope.registerWrapper;
3184    var unsafeUnwrap = scope.unsafeUnwrap;
3185    var wrap = scope.wrap;
3186    var OriginalSVGElementInstance = window.SVGElementInstance;
3187    if (!OriginalSVGElementInstance) return;
3188    function SVGElementInstance(impl) {
3189      EventTarget.call(this, impl);
3190    }
3191    SVGElementInstance.prototype = Object.create(EventTarget.prototype);
3192    mixin(SVGElementInstance.prototype, {
3193      get correspondingElement() {
3194        return wrap(unsafeUnwrap(this).correspondingElement);
3195      },
3196      get correspondingUseElement() {
3197        return wrap(unsafeUnwrap(this).correspondingUseElement);
3198      },
3199      get parentNode() {
3200        return wrap(unsafeUnwrap(this).parentNode);
3201      },
3202      get childNodes() {
3203        throw new Error("Not implemented");
3204      },
3205      get firstChild() {
3206        return wrap(unsafeUnwrap(this).firstChild);
3207      },
3208      get lastChild() {
3209        return wrap(unsafeUnwrap(this).lastChild);
3210      },
3211      get previousSibling() {
3212        return wrap(unsafeUnwrap(this).previousSibling);
3213      },
3214      get nextSibling() {
3215        return wrap(unsafeUnwrap(this).nextSibling);
3216      }
3217    });
3218    registerWrapper(OriginalSVGElementInstance, SVGElementInstance);
3219    scope.wrappers.SVGElementInstance = SVGElementInstance;
3220  })(window.ShadowDOMPolyfill);
3221  (function(scope) {
3222    "use strict";
3223    var mixin = scope.mixin;
3224    var registerWrapper = scope.registerWrapper;
3225    var setWrapper = scope.setWrapper;
3226    var unsafeUnwrap = scope.unsafeUnwrap;
3227    var unwrap = scope.unwrap;
3228    var unwrapIfNeeded = scope.unwrapIfNeeded;
3229    var wrap = scope.wrap;
3230    var OriginalCanvasRenderingContext2D = window.CanvasRenderingContext2D;
3231    function CanvasRenderingContext2D(impl) {
3232      setWrapper(impl, this);
3233    }
3234    mixin(CanvasRenderingContext2D.prototype, {
3235      get canvas() {
3236        return wrap(unsafeUnwrap(this).canvas);
3237      },
3238      drawImage: function() {
3239        arguments[0] = unwrapIfNeeded(arguments[0]);
3240        unsafeUnwrap(this).drawImage.apply(unsafeUnwrap(this), arguments);
3241      },
3242      createPattern: function() {
3243        arguments[0] = unwrap(arguments[0]);
3244        return unsafeUnwrap(this).createPattern.apply(unsafeUnwrap(this), arguments);
3245      }
3246    });
3247    registerWrapper(OriginalCanvasRenderingContext2D, CanvasRenderingContext2D, document.createElement("canvas").getContext("2d"));
3248    scope.wrappers.CanvasRenderingContext2D = CanvasRenderingContext2D;
3249  })(window.ShadowDOMPolyfill);
3250  (function(scope) {
3251    "use strict";
3252    var mixin = scope.mixin;
3253    var registerWrapper = scope.registerWrapper;
3254    var setWrapper = scope.setWrapper;
3255    var unsafeUnwrap = scope.unsafeUnwrap;
3256    var unwrapIfNeeded = scope.unwrapIfNeeded;
3257    var wrap = scope.wrap;
3258    var OriginalWebGLRenderingContext = window.WebGLRenderingContext;
3259    if (!OriginalWebGLRenderingContext) return;
3260    function WebGLRenderingContext(impl) {
3261      setWrapper(impl, this);
3262    }
3263    mixin(WebGLRenderingContext.prototype, {
3264      get canvas() {
3265        return wrap(unsafeUnwrap(this).canvas);
3266      },
3267      texImage2D: function() {
3268        arguments[5] = unwrapIfNeeded(arguments[5]);
3269        unsafeUnwrap(this).texImage2D.apply(unsafeUnwrap(this), arguments);
3270      },
3271      texSubImage2D: function() {
3272        arguments[6] = unwrapIfNeeded(arguments[6]);
3273        unsafeUnwrap(this).texSubImage2D.apply(unsafeUnwrap(this), arguments);
3274      }
3275    });
3276    var instanceProperties = /WebKit/.test(navigator.userAgent) ? {
3277      drawingBufferHeight: null,
3278      drawingBufferWidth: null
3279    } : {};
3280    registerWrapper(OriginalWebGLRenderingContext, WebGLRenderingContext, instanceProperties);
3281    scope.wrappers.WebGLRenderingContext = WebGLRenderingContext;
3282  })(window.ShadowDOMPolyfill);
3283  (function(scope) {
3284    "use strict";
3285    var GetElementsByInterface = scope.GetElementsByInterface;
3286    var ParentNodeInterface = scope.ParentNodeInterface;
3287    var SelectorsInterface = scope.SelectorsInterface;
3288    var mixin = scope.mixin;
3289    var registerObject = scope.registerObject;
3290    var DocumentFragment = registerObject(document.createDocumentFragment());
3291    mixin(DocumentFragment.prototype, ParentNodeInterface);
3292    mixin(DocumentFragment.prototype, SelectorsInterface);
3293    mixin(DocumentFragment.prototype, GetElementsByInterface);
3294    var Comment = registerObject(document.createComment(""));
3295    scope.wrappers.Comment = Comment;
3296    scope.wrappers.DocumentFragment = DocumentFragment;
3297  })(window.ShadowDOMPolyfill);
3298  (function(scope) {
3299    "use strict";
3300    var DocumentFragment = scope.wrappers.DocumentFragment;
3301    var TreeScope = scope.TreeScope;
3302    var elementFromPoint = scope.elementFromPoint;
3303    var getInnerHTML = scope.getInnerHTML;
3304    var getTreeScope = scope.getTreeScope;
3305    var mixin = scope.mixin;
3306    var rewrap = scope.rewrap;
3307    var setInnerHTML = scope.setInnerHTML;
3308    var unsafeUnwrap = scope.unsafeUnwrap;
3309    var unwrap = scope.unwrap;
3310    var shadowHostTable = new WeakMap();
3311    var nextOlderShadowTreeTable = new WeakMap();
3312    var spaceCharRe = /[ \t\n\r\f]/;
3313    function ShadowRoot(hostWrapper) {
3314      var node = unwrap(unsafeUnwrap(hostWrapper).ownerDocument.createDocumentFragment());
3315      DocumentFragment.call(this, node);
3316      rewrap(node, this);
3317      var oldShadowRoot = hostWrapper.shadowRoot;
3318      nextOlderShadowTreeTable.set(this, oldShadowRoot);
3319      this.treeScope_ = new TreeScope(this, getTreeScope(oldShadowRoot || hostWrapper));
3320      shadowHostTable.set(this, hostWrapper);
3321    }
3322    ShadowRoot.prototype = Object.create(DocumentFragment.prototype);
3323    mixin(ShadowRoot.prototype, {
3324      constructor: ShadowRoot,
3325      get innerHTML() {
3326        return getInnerHTML(this);
3327      },
3328      set innerHTML(value) {
3329        setInnerHTML(this, value);
3330        this.invalidateShadowRenderer();
3331      },
3332      get olderShadowRoot() {
3333        return nextOlderShadowTreeTable.get(this) || null;
3334      },
3335      get host() {
3336        return shadowHostTable.get(this) || null;
3337      },
3338      invalidateShadowRenderer: function() {
3339        return shadowHostTable.get(this).invalidateShadowRenderer();
3340      },
3341      elementFromPoint: function(x, y) {
3342        return elementFromPoint(this, this.ownerDocument, x, y);
3343      },
3344      getElementById: function(id) {
3345        if (spaceCharRe.test(id)) return null;
3346        return this.querySelector('[id="' + id + '"]');
3347      }
3348    });
3349    scope.wrappers.ShadowRoot = ShadowRoot;
3350  })(window.ShadowDOMPolyfill);
3351  (function(scope) {
3352    "use strict";
3353    var registerWrapper = scope.registerWrapper;
3354    var setWrapper = scope.setWrapper;
3355    var unsafeUnwrap = scope.unsafeUnwrap;
3356    var unwrap = scope.unwrap;
3357    var unwrapIfNeeded = scope.unwrapIfNeeded;
3358    var wrap = scope.wrap;
3359    var getTreeScope = scope.getTreeScope;
3360    var OriginalRange = window.Range;
3361    var ShadowRoot = scope.wrappers.ShadowRoot;
3362    function getHost(node) {
3363      var root = getTreeScope(node).root;
3364      if (root instanceof ShadowRoot) {
3365        return root.host;
3366      }
3367      return null;
3368    }
3369    function hostNodeToShadowNode(refNode, offset) {
3370      if (refNode.shadowRoot) {
3371        offset = Math.min(refNode.childNodes.length - 1, offset);
3372        var child = refNode.childNodes[offset];
3373        if (child) {
3374          var insertionPoint = scope.getDestinationInsertionPoints(child);
3375          if (insertionPoint.length > 0) {
3376            var parentNode = insertionPoint[0].parentNode;
3377            if (parentNode.nodeType == Node.ELEMENT_NODE) {
3378              refNode = parentNode;
3379            }
3380          }
3381        }
3382      }
3383      return refNode;
3384    }
3385    function shadowNodeToHostNode(node) {
3386      node = wrap(node);
3387      return getHost(node) || node;
3388    }
3389    function Range(impl) {
3390      setWrapper(impl, this);
3391    }
3392    Range.prototype = {
3393      get startContainer() {
3394        return shadowNodeToHostNode(unsafeUnwrap(this).startContainer);
3395      },
3396      get endContainer() {
3397        return shadowNodeToHostNode(unsafeUnwrap(this).endContainer);
3398      },
3399      get commonAncestorContainer() {
3400        return shadowNodeToHostNode(unsafeUnwrap(this).commonAncestorContainer);
3401      },
3402      setStart: function(refNode, offset) {
3403        refNode = hostNodeToShadowNode(refNode, offset);
3404        unsafeUnwrap(this).setStart(unwrapIfNeeded(refNode), offset);
3405      },
3406      setEnd: function(refNode, offset) {
3407        refNode = hostNodeToShadowNode(refNode, offset);
3408        unsafeUnwrap(this).setEnd(unwrapIfNeeded(refNode), offset);
3409      },
3410      setStartBefore: function(refNode) {
3411        unsafeUnwrap(this).setStartBefore(unwrapIfNeeded(refNode));
3412      },
3413      setStartAfter: function(refNode) {
3414        unsafeUnwrap(this).setStartAfter(unwrapIfNeeded(refNode));
3415      },
3416      setEndBefore: function(refNode) {
3417        unsafeUnwrap(this).setEndBefore(unwrapIfNeeded(refNode));
3418      },
3419      setEndAfter: function(refNode) {
3420        unsafeUnwrap(this).setEndAfter(unwrapIfNeeded(refNode));
3421      },
3422      selectNode: function(refNode) {
3423        unsafeUnwrap(this).selectNode(unwrapIfNeeded(refNode));
3424      },
3425      selectNodeContents: function(refNode) {
3426        unsafeUnwrap(this).selectNodeContents(unwrapIfNeeded(refNode));
3427      },
3428      compareBoundaryPoints: function(how, sourceRange) {
3429        return unsafeUnwrap(this).compareBoundaryPoints(how, unwrap(sourceRange));
3430      },
3431      extractContents: function() {
3432        return wrap(unsafeUnwrap(this).extractContents());
3433      },
3434      cloneContents: function() {
3435        return wrap(unsafeUnwrap(this).cloneContents());
3436      },
3437      insertNode: function(node) {
3438        unsafeUnwrap(this).insertNode(unwrapIfNeeded(node));
3439      },
3440      surroundContents: function(newParent) {
3441        unsafeUnwrap(this).surroundContents(unwrapIfNeeded(newParent));
3442      },
3443      cloneRange: function() {
3444        return wrap(unsafeUnwrap(this).cloneRange());
3445      },
3446      isPointInRange: function(node, offset) {
3447        return unsafeUnwrap(this).isPointInRange(unwrapIfNeeded(node), offset);
3448      },
3449      comparePoint: function(node, offset) {
3450        return unsafeUnwrap(this).comparePoint(unwrapIfNeeded(node), offset);
3451      },
3452      intersectsNode: function(node) {
3453        return unsafeUnwrap(this).intersectsNode(unwrapIfNeeded(node));
3454      },
3455      toString: function() {
3456        return unsafeUnwrap(this).toString();
3457      }
3458    };
3459    if (OriginalRange.prototype.createContextualFragment) {
3460      Range.prototype.createContextualFragment = function(html) {
3461        return wrap(unsafeUnwrap(this).createContextualFragment(html));
3462      };
3463    }
3464    registerWrapper(window.Range, Range, document.createRange());
3465    scope.wrappers.Range = Range;
3466  })(window.ShadowDOMPolyfill);
3467  (function(scope) {
3468    "use strict";
3469    var Element = scope.wrappers.Element;
3470    var HTMLContentElement = scope.wrappers.HTMLContentElement;
3471    var HTMLShadowElement = scope.wrappers.HTMLShadowElement;
3472    var Node = scope.wrappers.Node;
3473    var ShadowRoot = scope.wrappers.ShadowRoot;
3474    var assert = scope.assert;
3475    var getTreeScope = scope.getTreeScope;
3476    var mixin = scope.mixin;
3477    var oneOf = scope.oneOf;
3478    var unsafeUnwrap = scope.unsafeUnwrap;
3479    var unwrap = scope.unwrap;
3480    var wrap = scope.wrap;
3481    var ArraySplice = scope.ArraySplice;
3482    function updateWrapperUpAndSideways(wrapper) {
3483      wrapper.previousSibling_ = wrapper.previousSibling;
3484      wrapper.nextSibling_ = wrapper.nextSibling;
3485      wrapper.parentNode_ = wrapper.parentNode;
3486    }
3487    function updateWrapperDown(wrapper) {
3488      wrapper.firstChild_ = wrapper.firstChild;
3489      wrapper.lastChild_ = wrapper.lastChild;
3490    }
3491    function updateAllChildNodes(parentNodeWrapper) {
3492      assert(parentNodeWrapper instanceof Node);
3493      for (var childWrapper = parentNodeWrapper.firstChild; childWrapper; childWrapper = childWrapper.nextSibling) {
3494        updateWrapperUpAndSideways(childWrapper);
3495      }
3496      updateWrapperDown(parentNodeWrapper);
3497    }
3498    function insertBefore(parentNodeWrapper, newChildWrapper, refChildWrapper) {
3499      var parentNode = unwrap(parentNodeWrapper);
3500      var newChild = unwrap(newChildWrapper);
3501      var refChild = refChildWrapper ? unwrap(refChildWrapper) : null;
3502      remove(newChildWrapper);
3503      updateWrapperUpAndSideways(newChildWrapper);
3504      if (!refChildWrapper) {
3505        parentNodeWrapper.lastChild_ = parentNodeWrapper.lastChild;
3506        if (parentNodeWrapper.lastChild === parentNodeWrapper.firstChild) parentNodeWrapper.firstChild_ = parentNodeWrapper.firstChild;
3507        var lastChildWrapper = wrap(parentNode.lastChild);
3508        if (lastChildWrapper) lastChildWrapper.nextSibling_ = lastChildWrapper.nextSibling;
3509      } else {
3510        if (parentNodeWrapper.firstChild === refChildWrapper) parentNodeWrapper.firstChild_ = refChildWrapper;
3511        refChildWrapper.previousSibling_ = refChildWrapper.previousSibling;
3512      }
3513      scope.originalInsertBefore.call(parentNode, newChild, refChild);
3514    }
3515    function remove(nodeWrapper) {
3516      var node = unwrap(nodeWrapper);
3517      var parentNode = node.parentNode;
3518      if (!parentNode) return;
3519      var parentNodeWrapper = wrap(parentNode);
3520      updateWrapperUpAndSideways(nodeWrapper);
3521      if (nodeWrapper.previousSibling) nodeWrapper.previousSibling.nextSibling_ = nodeWrapper;
3522      if (nodeWrapper.nextSibling) nodeWrapper.nextSibling.previousSibling_ = nodeWrapper;
3523      if (parentNodeWrapper.lastChild === nodeWrapper) parentNodeWrapper.lastChild_ = nodeWrapper;
3524      if (parentNodeWrapper.firstChild === nodeWrapper) parentNodeWrapper.firstChild_ = nodeWrapper;
3525      scope.originalRemoveChild.call(parentNode, node);
3526    }
3527    var distributedNodesTable = new WeakMap();
3528    var destinationInsertionPointsTable = new WeakMap();
3529    var rendererForHostTable = new WeakMap();
3530    function resetDistributedNodes(insertionPoint) {
3531      distributedNodesTable.set(insertionPoint, []);
3532    }
3533    function getDistributedNodes(insertionPoint) {
3534      var rv = distributedNodesTable.get(insertionPoint);
3535      if (!rv) distributedNodesTable.set(insertionPoint, rv = []);
3536      return rv;
3537    }
3538    function getChildNodesSnapshot(node) {
3539      var result = [], i = 0;
3540      for (var child = node.firstChild; child; child = child.nextSibling) {
3541        result[i++] = child;
3542      }
3543      return result;
3544    }
3545    var request = oneOf(window, [ "requestAnimationFrame", "mozRequestAnimationFrame", "webkitRequestAnimationFrame", "setTimeout" ]);
3546    var pendingDirtyRenderers = [];
3547    var renderTimer;
3548    function renderAllPending() {
3549      for (var i = 0; i < pendingDirtyRenderers.length; i++) {
3550        var renderer = pendingDirtyRenderers[i];
3551        var parentRenderer = renderer.parentRenderer;
3552        if (parentRenderer && parentRenderer.dirty) continue;
3553        renderer.render();
3554      }
3555      pendingDirtyRenderers = [];
3556    }
3557    function handleRequestAnimationFrame() {
3558      renderTimer = null;
3559      renderAllPending();
3560    }
3561    function getRendererForHost(host) {
3562      var renderer = rendererForHostTable.get(host);
3563      if (!renderer) {
3564        renderer = new ShadowRenderer(host);
3565        rendererForHostTable.set(host, renderer);
3566      }
3567      return renderer;
3568    }
3569    function getShadowRootAncestor(node) {
3570      var root = getTreeScope(node).root;
3571      if (root instanceof ShadowRoot) return root;
3572      return null;
3573    }
3574    function getRendererForShadowRoot(shadowRoot) {
3575      return getRendererForHost(shadowRoot.host);
3576    }
3577    var spliceDiff = new ArraySplice();
3578    spliceDiff.equals = function(renderNode, rawNode) {
3579      return unwrap(renderNode.node) === rawNode;
3580    };
3581    function RenderNode(node) {
3582      this.skip = false;
3583      this.node = node;
3584      this.childNodes = [];
3585    }
3586    RenderNode.prototype = {
3587      append: function(node) {
3588        var rv = new RenderNode(node);
3589        this.childNodes.push(rv);
3590        return rv;
3591      },
3592      sync: function(opt_added) {
3593        if (this.skip) return;
3594        var nodeWrapper = this.node;
3595        var newChildren = this.childNodes;
3596        var oldChildren = getChildNodesSnapshot(unwrap(nodeWrapper));
3597        var added = opt_added || new WeakMap();
3598        var splices = spliceDiff.calculateSplices(newChildren, oldChildren);
3599        var newIndex = 0, oldIndex = 0;
3600        var lastIndex = 0;
3601        for (var i = 0; i < splices.length; i++) {
3602          var splice = splices[i];
3603          for (;lastIndex < splice.index; lastIndex++) {
3604            oldIndex++;
3605            newChildren[newIndex++].sync(added);
3606          }
3607          var removedCount = splice.removed.length;
3608          for (var j = 0; j < removedCount; j++) {
3609            var wrapper = wrap(oldChildren[oldIndex++]);
3610            if (!added.get(wrapper)) remove(wrapper);
3611          }
3612          var addedCount = splice.addedCount;
3613          var refNode = oldChildren[oldIndex] && wrap(oldChildren[oldIndex]);
3614          for (var j = 0; j < addedCount; j++) {
3615            var newChildRenderNode = newChildren[newIndex++];
3616            var newChildWrapper = newChildRenderNode.node;
3617            insertBefore(nodeWrapper, newChildWrapper, refNode);
3618            added.set(newChildWrapper, true);
3619            newChildRenderNode.sync(added);
3620          }
3621          lastIndex += addedCount;
3622        }
3623        for (var i = lastIndex; i < newChildren.length; i++) {
3624          newChildren[i].sync(added);
3625        }
3626      }
3627    };
3628    function ShadowRenderer(host) {
3629      this.host = host;
3630      this.dirty = false;
3631      this.invalidateAttributes();
3632      this.associateNode(host);
3633    }
3634    ShadowRenderer.prototype = {
3635      render: function(opt_renderNode) {
3636        if (!this.dirty) return;
3637        this.invalidateAttributes();
3638        var host = this.host;
3639        this.distribution(host);
3640        var renderNode = opt_renderNode || new RenderNode(host);
3641        this.buildRenderTree(renderNode, host);
3642        var topMostRenderer = !opt_renderNode;
3643        if (topMostRenderer) renderNode.sync();
3644        this.dirty = false;
3645      },
3646      get parentRenderer() {
3647        return getTreeScope(this.host).renderer;
3648      },
3649      invalidate: function() {
3650        if (!this.dirty) {
3651          this.dirty = true;
3652          var parentRenderer = this.parentRenderer;
3653          if (parentRenderer) parentRenderer.invalidate();
3654          pendingDirtyRenderers.push(this);
3655          if (renderTimer) return;
3656          renderTimer = window[request](handleRequestAnimationFrame, 0);
3657        }
3658      },
3659      distribution: function(root) {
3660        this.resetAllSubtrees(root);
3661        this.distributionResolution(root);
3662      },
3663      resetAll: function(node) {
3664        if (isInsertionPoint(node)) resetDistributedNodes(node); else resetDestinationInsertionPoints(node);
3665        this.resetAllSubtrees(node);
3666      },
3667      resetAllSubtrees: function(node) {
3668        for (var child = node.firstChild; child; child = child.nextSibling) {
3669          this.resetAll(child);
3670        }
3671        if (node.shadowRoot) this.resetAll(node.shadowRoot);
3672        if (node.olderShadowRoot) this.resetAll(node.olderShadowRoot);
3673      },
3674      distributionResolution: function(node) {
3675        if (isShadowHost(node)) {
3676          var shadowHost = node;
3677          var pool = poolPopulation(shadowHost);
3678          var shadowTrees = getShadowTrees(shadowHost);
3679          for (var i = 0; i < shadowTrees.length; i++) {
3680            this.poolDistribution(shadowTrees[i], pool);
3681          }
3682          for (var i = shadowTrees.length - 1; i >= 0; i--) {
3683            var shadowTree = shadowTrees[i];
3684            var shadow = getShadowInsertionPoint(shadowTree);
3685            if (shadow) {
3686              var olderShadowRoot = shadowTree.olderShadowRoot;
3687              if (olderShadowRoot) {
3688                pool = poolPopulation(olderShadowRoot);
3689              }
3690              for (var j = 0; j < pool.length; j++) {
3691                destributeNodeInto(pool[j], shadow);
3692              }
3693            }
3694            this.distributionResolution(shadowTree);
3695          }
3696        }
3697        for (var child = node.firstChild; child; child = child.nextSibling) {
3698          this.distributionResolution(child);
3699        }
3700      },
3701      poolDistribution: function(node, pool) {
3702        if (node instanceof HTMLShadowElement) return;
3703        if (node instanceof HTMLContentElement) {
3704          var content = node;
3705          this.updateDependentAttributes(content.getAttribute("select"));
3706          var anyDistributed = false;
3707          for (var i = 0; i < pool.length; i++) {
3708            var node = pool[i];
3709            if (!node) continue;
3710            if (matches(node, content)) {
3711              destributeNodeInto(node, content);
3712              pool[i] = undefined;
3713              anyDistributed = true;
3714            }
3715          }
3716          if (!anyDistributed) {
3717            for (var child = content.firstChild; child; child = child.nextSibling) {
3718              destributeNodeInto(child, content);
3719            }
3720          }
3721          return;
3722        }
3723        for (var child = node.firstChild; child; child = child.nextSibling) {
3724          this.poolDistribution(child, pool);
3725        }
3726      },
3727      buildRenderTree: function(renderNode, node) {
3728        var children = this.compose(node);
3729        for (var i = 0; i < children.length; i++) {
3730          var child = children[i];
3731          var childRenderNode = renderNode.append(child);
3732          this.buildRenderTree(childRenderNode, child);
3733        }
3734        if (isShadowHost(node)) {
3735          var renderer = getRendererForHost(node);
3736          renderer.dirty = false;
3737        }
3738      },
3739      compose: function(node) {
3740        var children = [];
3741        var p = node.shadowRoot || node;
3742        for (var child = p.firstChild; child; child = child.nextSibling) {
3743          if (isInsertionPoint(child)) {
3744            this.associateNode(p);
3745            var distributedNodes = getDistributedNodes(child);
3746            for (var j = 0; j < distributedNodes.length; j++) {
3747              var distributedNode = distributedNodes[j];
3748              if (isFinalDestination(child, distributedNode)) children.push(distributedNode);
3749            }
3750          } else {
3751            children.push(child);
3752          }
3753        }
3754        return children;
3755      },
3756      invalidateAttributes: function() {
3757        this.attributes = Object.create(null);
3758      },
3759      updateDependentAttributes: function(selector) {
3760        if (!selector) return;
3761        var attributes = this.attributes;
3762        if (/\.\w+/.test(selector)) attributes["class"] = true;
3763        if (/#\w+/.test(selector)) attributes["id"] = true;
3764        selector.replace(/\[\s*([^\s=\|~\]]+)/g, function(_, name) {
3765          attributes[name] = true;
3766        });
3767      },
3768      dependsOnAttribute: function(name) {
3769        return this.attributes[name];
3770      },
3771      associateNode: function(node) {
3772        unsafeUnwrap(node).polymerShadowRenderer_ = this;
3773      }
3774    };
3775    function poolPopulation(node) {
3776      var pool = [];
3777      for (var child = node.firstChild; child; child = child.nextSibling) {
3778        if (isInsertionPoint(child)) {
3779          pool.push.apply(pool, getDistributedNodes(child));
3780        } else {
3781          pool.push(child);
3782        }
3783      }
3784      return pool;
3785    }
3786    function getShadowInsertionPoint(node) {
3787      if (node instanceof HTMLShadowElement) return node;
3788      if (node instanceof HTMLContentElement) return null;
3789      for (var child = node.firstChild; child; child = child.nextSibling) {
3790        var res = getShadowInsertionPoint(child);
3791        if (res) return res;
3792      }
3793      return null;
3794    }
3795    function destributeNodeInto(child, insertionPoint) {
3796      getDistributedNodes(insertionPoint).push(child);
3797      var points = destinationInsertionPointsTable.get(child);
3798      if (!points) destinationInsertionPointsTable.set(child, [ insertionPoint ]); else points.push(insertionPoint);
3799    }
3800    function getDestinationInsertionPoints(node) {
3801      return destinationInsertionPointsTable.get(node);
3802    }
3803    function resetDestinationInsertionPoints(node) {
3804      destinationInsertionPointsTable.set(node, undefined);
3805    }
3806    var selectorStartCharRe = /^(:not\()?[*.#[a-zA-Z_|]/;
3807    function matches(node, contentElement) {
3808      var select = contentElement.getAttribute("select");
3809      if (!select) return true;
3810      select = select.trim();
3811      if (!select) return true;
3812      if (!(node instanceof Element)) return false;
3813      if (!selectorStartCharRe.test(select)) return false;
3814      try {
3815        return node.matches(select);
3816      } catch (ex) {
3817        return false;
3818      }
3819    }
3820    function isFinalDestination(insertionPoint, node) {
3821      var points = getDestinationInsertionPoints(node);
3822      return points && points[points.length - 1] === insertionPoint;
3823    }
3824    function isInsertionPoint(node) {
3825      return node instanceof HTMLContentElement || node instanceof HTMLShadowElement;
3826    }
3827    function isShadowHost(shadowHost) {
3828      return shadowHost.shadowRoot;
3829    }
3830    function getShadowTrees(host) {
3831      var trees = [];
3832      for (var tree = host.shadowRoot; tree; tree = tree.olderShadowRoot) {
3833        trees.push(tree);
3834      }
3835      return trees;
3836    }
3837    function render(host) {
3838      new ShadowRenderer(host).render();
3839    }
3840    Node.prototype.invalidateShadowRenderer = function(force) {
3841      var renderer = unsafeUnwrap(this).polymerShadowRenderer_;
3842      if (renderer) {
3843        renderer.invalidate();
3844        return true;
3845      }
3846      return false;
3847    };
3848    HTMLContentElement.prototype.getDistributedNodes = HTMLShadowElement.prototype.getDistributedNodes = function() {
3849      renderAllPending();
3850      return getDistributedNodes(this);
3851    };
3852    Element.prototype.getDestinationInsertionPoints = function() {
3853      renderAllPending();
3854      return getDestinationInsertionPoints(this) || [];
3855    };
3856    HTMLContentElement.prototype.nodeIsInserted_ = HTMLShadowElement.prototype.nodeIsInserted_ = function() {
3857      this.invalidateShadowRenderer();
3858      var shadowRoot = getShadowRootAncestor(this);
3859      var renderer;
3860      if (shadowRoot) renderer = getRendererForShadowRoot(shadowRoot);
3861      unsafeUnwrap(this).polymerShadowRenderer_ = renderer;
3862      if (renderer) renderer.invalidate();
3863    };
3864    scope.getRendererForHost = getRendererForHost;
3865    scope.getShadowTrees = getShadowTrees;
3866    scope.renderAllPending = renderAllPending;
3867    scope.getDestinationInsertionPoints = getDestinationInsertionPoints;
3868    scope.visual = {
3869      insertBefore: insertBefore,
3870      remove: remove
3871    };
3872  })(window.ShadowDOMPolyfill);
3873  (function(scope) {
3874    "use strict";
3875    var HTMLElement = scope.wrappers.HTMLElement;
3876    var assert = scope.assert;
3877    var mixin = scope.mixin;
3878    var registerWrapper = scope.registerWrapper;
3879    var unwrap = scope.unwrap;
3880    var wrap = scope.wrap;
3881    var elementsWithFormProperty = [ "HTMLButtonElement", "HTMLFieldSetElement", "HTMLInputElement", "HTMLKeygenElement", "HTMLLabelElement", "HTMLLegendElement", "HTMLObjectElement", "HTMLOutputElement", "HTMLTextAreaElement" ];
3882    function createWrapperConstructor(name) {
3883      if (!window[name]) return;
3884      assert(!scope.wrappers[name]);
3885      var GeneratedWrapper = function(node) {
3886        HTMLElement.call(this, node);
3887      };
3888      GeneratedWrapper.prototype = Object.create(HTMLElement.prototype);
3889      mixin(GeneratedWrapper.prototype, {
3890        get form() {
3891          return wrap(unwrap(this).form);
3892        }
3893      });
3894      registerWrapper(window[name], GeneratedWrapper, document.createElement(name.slice(4, -7)));
3895      scope.wrappers[name] = GeneratedWrapper;
3896    }
3897    elementsWithFormProperty.forEach(createWrapperConstructor);
3898  })(window.ShadowDOMPolyfill);
3899  (function(scope) {
3900    "use strict";
3901    var registerWrapper = scope.registerWrapper;
3902    var setWrapper = scope.setWrapper;
3903    var unsafeUnwrap = scope.unsafeUnwrap;
3904    var unwrap = scope.unwrap;
3905    var unwrapIfNeeded = scope.unwrapIfNeeded;
3906    var wrap = scope.wrap;
3907    var OriginalSelection = window.Selection;
3908    function Selection(impl) {
3909      setWrapper(impl, this);
3910    }
3911    Selection.prototype = {
3912      get anchorNode() {
3913        return wrap(unsafeUnwrap(this).anchorNode);
3914      },
3915      get focusNode() {
3916        return wrap(unsafeUnwrap(this).focusNode);
3917      },
3918      addRange: function(range) {
3919        unsafeUnwrap(this).addRange(unwrapIfNeeded(range));
3920      },
3921      collapse: function(node, index) {
3922        unsafeUnwrap(this).collapse(unwrapIfNeeded(node), index);
3923      },
3924      containsNode: function(node, allowPartial) {
3925        return unsafeUnwrap(this).containsNode(unwrapIfNeeded(node), allowPartial);
3926      },
3927      getRangeAt: function(index) {
3928        return wrap(unsafeUnwrap(this).getRangeAt(index));
3929      },
3930      removeRange: function(range) {
3931        unsafeUnwrap(this).removeRange(unwrap(range));
3932      },
3933      selectAllChildren: function(node) {
3934        unsafeUnwrap(this).selectAllChildren(unwrapIfNeeded(node));
3935      },
3936      toString: function() {
3937        return unsafeUnwrap(this).toString();
3938      }
3939    };
3940    if (OriginalSelection.prototype.extend) {
3941      Selection.prototype.extend = function(node, offset) {
3942        unsafeUnwrap(this).extend(unwrapIfNeeded(node), offset);
3943      };
3944    }
3945    registerWrapper(window.Selection, Selection, window.getSelection());
3946    scope.wrappers.Selection = Selection;
3947  })(window.ShadowDOMPolyfill);
3948  (function(scope) {
3949    "use strict";
3950    var registerWrapper = scope.registerWrapper;
3951    var setWrapper = scope.setWrapper;
3952    var unsafeUnwrap = scope.unsafeUnwrap;
3953    var unwrapIfNeeded = scope.unwrapIfNeeded;
3954    var wrap = scope.wrap;
3955    var OriginalTreeWalker = window.TreeWalker;
3956    function TreeWalker(impl) {
3957      setWrapper(impl, this);
3958    }
3959    TreeWalker.prototype = {
3960      get root() {
3961        return wrap(unsafeUnwrap(this).root);
3962      },
3963      get currentNode() {
3964        return wrap(unsafeUnwrap(this).currentNode);
3965      },
3966      set currentNode(node) {
3967        unsafeUnwrap(this).currentNode = unwrapIfNeeded(node);
3968      },
3969      get filter() {
3970        return unsafeUnwrap(this).filter;
3971      },
3972      parentNode: function() {
3973        return wrap(unsafeUnwrap(this).parentNode());
3974      },
3975      firstChild: function() {
3976        return wrap(unsafeUnwrap(this).firstChild());
3977      },
3978      lastChild: function() {
3979        return wrap(unsafeUnwrap(this).lastChild());
3980      },
3981      previousSibling: function() {
3982        return wrap(unsafeUnwrap(this).previousSibling());
3983      },
3984      previousNode: function() {
3985        return wrap(unsafeUnwrap(this).previousNode());
3986      },
3987      nextNode: function() {
3988        return wrap(unsafeUnwrap(this).nextNode());
3989      }
3990    };
3991    registerWrapper(OriginalTreeWalker, TreeWalker);
3992    scope.wrappers.TreeWalker = TreeWalker;
3993  })(window.ShadowDOMPolyfill);
3994  (function(scope) {
3995    "use strict";
3996    var GetElementsByInterface = scope.GetElementsByInterface;
3997    var Node = scope.wrappers.Node;
3998    var ParentNodeInterface = scope.ParentNodeInterface;
3999    var Selection = scope.wrappers.Selection;
4000    var SelectorsInterface = scope.SelectorsInterface;
4001    var ShadowRoot = scope.wrappers.ShadowRoot;
4002    var TreeScope = scope.TreeScope;
4003    var cloneNode = scope.cloneNode;
4004    var defineWrapGetter = scope.defineWrapGetter;
4005    var elementFromPoint = scope.elementFromPoint;
4006    var forwardMethodsToWrapper = scope.forwardMethodsToWrapper;
4007    var matchesNames = scope.matchesNames;
4008    var mixin = scope.mixin;
4009    var registerWrapper = scope.registerWrapper;
4010    var renderAllPending = scope.renderAllPending;
4011    var rewrap = scope.rewrap;
4012    var setWrapper = scope.setWrapper;
4013    var unsafeUnwrap = scope.unsafeUnwrap;
4014    var unwrap = scope.unwrap;
4015    var wrap = scope.wrap;
4016    var wrapEventTargetMethods = scope.wrapEventTargetMethods;
4017    var wrapNodeList = scope.wrapNodeList;
4018    var implementationTable = new WeakMap();
4019    function Document(node) {
4020      Node.call(this, node);
4021      this.treeScope_ = new TreeScope(this, null);
4022    }
4023    Document.prototype = Object.create(Node.prototype);
4024    defineWrapGetter(Document, "documentElement");
4025    defineWrapGetter(Document, "body");
4026    defineWrapGetter(Document, "head");
4027    function wrapMethod(name) {
4028      var original = document[name];
4029      Document.prototype[name] = function() {
4030        return wrap(original.apply(unsafeUnwrap(this), arguments));
4031      };
4032    }
4033    [ "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode", "getElementById" ].forEach(wrapMethod);
4034    var originalAdoptNode = document.adoptNode;
4035    function adoptNodeNoRemove(node, doc) {
4036      originalAdoptNode.call(unsafeUnwrap(doc), unwrap(node));
4037      adoptSubtree(node, doc);
4038    }
4039    function adoptSubtree(node, doc) {
4040      if (node.shadowRoot) doc.adoptNode(node.shadowRoot);
4041      if (node instanceof ShadowRoot) adoptOlderShadowRoots(node, doc);
4042      for (var child = node.firstChild; child; child = child.nextSibling) {
4043        adoptSubtree(child, doc);
4044      }
4045    }
4046    function adoptOlderShadowRoots(shadowRoot, doc) {
4047      var oldShadowRoot = shadowRoot.olderShadowRoot;
4048      if (oldShadowRoot) doc.adoptNode(oldShadowRoot);
4049    }
4050    var originalGetSelection = document.getSelection;
4051    mixin(Document.prototype, {
4052      adoptNode: function(node) {
4053        if (node.parentNode) node.parentNode.removeChild(node);
4054        adoptNodeNoRemove(node, this);
4055        return node;
4056      },
4057      elementFromPoint: function(x, y) {
4058        return elementFromPoint(this, this, x, y);
4059      },
4060      importNode: function(node, deep) {
4061        return cloneNode(node, deep, unsafeUnwrap(this));
4062      },
4063      getSelection: function() {
4064        renderAllPending();
4065        return new Selection(originalGetSelection.call(unwrap(this)));
4066      },
4067      getElementsByName: function(name) {
4068        return SelectorsInterface.querySelectorAll.call(this, "[name=" + JSON.stringify(String(name)) + "]");
4069      }
4070    });
4071    var originalCreateTreeWalker = document.createTreeWalker;
4072    var TreeWalkerWrapper = scope.wrappers.TreeWalker;
4073    Document.prototype.createTreeWalker = function(root, whatToShow, filter, expandEntityReferences) {
4074      var newFilter = null;
4075      if (filter) {
4076        if (filter.acceptNode && typeof filter.acceptNode === "function") {
4077          newFilter = {
4078            acceptNode: function(node) {
4079              return filter.acceptNode(wrap(node));
4080            }
4081          };
4082        } else if (typeof filter === "function") {
4083          newFilter = function(node) {
4084            return filter(wrap(node));
4085          };
4086        }
4087      }
4088      return new TreeWalkerWrapper(originalCreateTreeWalker.call(unwrap(this), unwrap(root), whatToShow, newFilter, expandEntityReferences));
4089    };
4090    if (document.registerElement) {
4091      var originalRegisterElement = document.registerElement;
4092      Document.prototype.registerElement = function(tagName, object) {
4093        var prototype, extendsOption;
4094        if (object !== undefined) {
4095          prototype = object.prototype;
4096          extendsOption = object.extends;
4097        }
4098        if (!prototype) prototype = Object.create(HTMLElement.prototype);
4099        if (scope.nativePrototypeTable.get(prototype)) {
4100          throw new Error("NotSupportedError");
4101        }
4102        var proto = Object.getPrototypeOf(prototype);
4103        var nativePrototype;
4104        var prototypes = [];
4105        while (proto) {
4106          nativePrototype = scope.nativePrototypeTable.get(proto);
4107          if (nativePrototype) break;
4108          prototypes.push(proto);
4109          proto = Object.getPrototypeOf(proto);
4110        }
4111        if (!nativePrototype) {
4112          throw new Error("NotSupportedError");
4113        }
4114        var newPrototype = Object.create(nativePrototype);
4115        for (var i = prototypes.length - 1; i >= 0; i--) {
4116          newPrototype = Object.create(newPrototype);
4117        }
4118        [ "createdCallback", "attachedCallback", "detachedCallback", "attributeChangedCallback" ].forEach(function(name) {
4119          var f = prototype[name];
4120          if (!f) return;
4121          newPrototype[name] = function() {
4122            if (!(wrap(this) instanceof CustomElementConstructor)) {
4123              rewrap(this);
4124            }
4125            f.apply(wrap(this), arguments);
4126          };
4127        });
4128        var p = {
4129          prototype: newPrototype
4130        };
4131        if (extendsOption) p.extends = extendsOption;
4132        function CustomElementConstructor(node) {
4133          if (!node) {
4134            if (extendsOption) {
4135              return document.createElement(extendsOption, tagName);
4136            } else {
4137              return document.createElement(tagName);
4138            }
4139          }
4140          setWrapper(node, this);
4141        }
4142        CustomElementConstructor.prototype = prototype;
4143        CustomElementConstructor.prototype.constructor = CustomElementConstructor;
4144        scope.constructorTable.set(newPrototype, CustomElementConstructor);
4145        scope.nativePrototypeTable.set(prototype, newPrototype);
4146        var nativeConstructor = originalRegisterElement.call(unwrap(this), tagName, p);
4147        return CustomElementConstructor;
4148      };
4149      forwardMethodsToWrapper([ window.HTMLDocument || window.Document ], [ "registerElement" ]);
4150    }
4151    forwardMethodsToWrapper([ window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement, window.HTMLHtmlElement ], [ "appendChild", "compareDocumentPosition", "contains", "getElementsByClassName", "getElementsByTagName", "getElementsByTagNameNS", "insertBefore", "querySelector", "querySelectorAll", "removeChild", "replaceChild" ]);
4152    forwardMethodsToWrapper([ window.HTMLBodyElement, window.HTMLHeadElement, window.HTMLHtmlElement ], matchesNames);
4153    forwardMethodsToWrapper([ window.HTMLDocument || window.Document ], [ "adoptNode", "importNode", "contains", "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode", "createTreeWalker", "elementFromPoint", "getElementById", "getElementsByName", "getSelection" ]);
4154    mixin(Document.prototype, GetElementsByInterface);
4155    mixin(Document.prototype, ParentNodeInterface);
4156    mixin(Document.prototype, SelectorsInterface);
4157    mixin(Document.prototype, {
4158      get implementation() {
4159        var implementation = implementationTable.get(this);
4160        if (implementation) return implementation;
4161        implementation = new DOMImplementation(unwrap(this).implementation);
4162        implementationTable.set(this, implementation);
4163        return implementation;
4164      },
4165      get defaultView() {
4166        return wrap(unwrap(this).defaultView);
4167      }
4168    });
4169    registerWrapper(window.Document, Document, document.implementation.createHTMLDocument(""));
4170    if (window.HTMLDocument) registerWrapper(window.HTMLDocument, Document);
4171    wrapEventTargetMethods([ window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement ]);
4172    function DOMImplementation(impl) {
4173      setWrapper(impl, this);
4174    }
4175    function wrapImplMethod(constructor, name) {
4176      var original = document.implementation[name];
4177      constructor.prototype[name] = function() {
4178        return wrap(original.apply(unsafeUnwrap(this), arguments));
4179      };
4180    }
4181    function forwardImplMethod(constructor, name) {
4182      var original = document.implementation[name];
4183      constructor.prototype[name] = function() {
4184        return original.apply(unsafeUnwrap(this), arguments);
4185      };
4186    }
4187    wrapImplMethod(DOMImplementation, "createDocumentType");
4188    wrapImplMethod(DOMImplementation, "createDocument");
4189    wrapImplMethod(DOMImplementation, "createHTMLDocument");
4190    forwardImplMethod(DOMImplementation, "hasFeature");
4191    registerWrapper(window.DOMImplementation, DOMImplementation);
4192    forwardMethodsToWrapper([ window.DOMImplementation ], [ "createDocumentType", "createDocument", "createHTMLDocument", "hasFeature" ]);
4193    scope.adoptNodeNoRemove = adoptNodeNoRemove;
4194    scope.wrappers.DOMImplementation = DOMImplementation;
4195    scope.wrappers.Document = Document;
4196  })(window.ShadowDOMPolyfill);
4197  (function(scope) {
4198    "use strict";
4199    var EventTarget = scope.wrappers.EventTarget;
4200    var Selection = scope.wrappers.Selection;
4201    var mixin = scope.mixin;
4202    var registerWrapper = scope.registerWrapper;
4203    var renderAllPending = scope.renderAllPending;
4204    var unwrap = scope.unwrap;
4205    var unwrapIfNeeded = scope.unwrapIfNeeded;
4206    var wrap = scope.wrap;
4207    var OriginalWindow = window.Window;
4208    var originalGetComputedStyle = window.getComputedStyle;
4209    var originalGetDefaultComputedStyle = window.getDefaultComputedStyle;
4210    var originalGetSelection = window.getSelection;
4211    function Window(impl) {
4212      EventTarget.call(this, impl);
4213    }
4214    Window.prototype = Object.create(EventTarget.prototype);
4215    OriginalWindow.prototype.getComputedStyle = function(el, pseudo) {
4216      return wrap(this || window).getComputedStyle(unwrapIfNeeded(el), pseudo);
4217    };
4218    if (originalGetDefaultComputedStyle) {
4219      OriginalWindow.prototype.getDefaultComputedStyle = function(el, pseudo) {
4220        return wrap(this || window).getDefaultComputedStyle(unwrapIfNeeded(el), pseudo);
4221      };
4222    }
4223    OriginalWindow.prototype.getSelection = function() {
4224      return wrap(this || window).getSelection();
4225    };
4226    delete window.getComputedStyle;
4227    delete window.getDefaultComputedStyle;
4228    delete window.getSelection;
4229    [ "addEventListener", "removeEventListener", "dispatchEvent" ].forEach(function(name) {
4230      OriginalWindow.prototype[name] = function() {
4231        var w = wrap(this || window);
4232        return w[name].apply(w, arguments);
4233      };
4234      delete window[name];
4235    });
4236    mixin(Window.prototype, {
4237      getComputedStyle: function(el, pseudo) {
4238        renderAllPending();
4239        return originalGetComputedStyle.call(unwrap(this), unwrapIfNeeded(el), pseudo);
4240      },
4241      getSelection: function() {
4242        renderAllPending();
4243        return new Selection(originalGetSelection.call(unwrap(this)));
4244      },
4245      get document() {
4246        return wrap(unwrap(this).document);
4247      }
4248    });
4249    if (originalGetDefaultComputedStyle) {
4250      Window.prototype.getDefaultComputedStyle = function(el, pseudo) {
4251        renderAllPending();
4252        return originalGetDefaultComputedStyle.call(unwrap(this), unwrapIfNeeded(el), pseudo);
4253      };
4254    }
4255    registerWrapper(OriginalWindow, Window, window);
4256    scope.wrappers.Window = Window;
4257  })(window.ShadowDOMPolyfill);
4258  (function(scope) {
4259    "use strict";
4260    var unwrap = scope.unwrap;
4261    var OriginalDataTransfer = window.DataTransfer || window.Clipboard;
4262    var OriginalDataTransferSetDragImage = OriginalDataTransfer.prototype.setDragImage;
4263    if (OriginalDataTransferSetDragImage) {
4264      OriginalDataTransfer.prototype.setDragImage = function(image, x, y) {
4265        OriginalDataTransferSetDragImage.call(this, unwrap(image), x, y);
4266      };
4267    }
4268  })(window.ShadowDOMPolyfill);
4269  (function(scope) {
4270    "use strict";
4271    var registerWrapper = scope.registerWrapper;
4272    var setWrapper = scope.setWrapper;
4273    var unwrap = scope.unwrap;
4274    var OriginalFormData = window.FormData;
4275    if (!OriginalFormData) return;
4276    function FormData(formElement) {
4277      var impl;
4278      if (formElement instanceof OriginalFormData) {
4279        impl = formElement;
4280      } else {
4281        impl = new OriginalFormData(formElement && unwrap(formElement));
4282      }
4283      setWrapper(impl, this);
4284    }
4285    registerWrapper(OriginalFormData, FormData, new OriginalFormData());
4286    scope.wrappers.FormData = FormData;
4287  })(window.ShadowDOMPolyfill);
4288  (function(scope) {
4289    "use strict";
4290    var unwrapIfNeeded = scope.unwrapIfNeeded;
4291    var originalSend = XMLHttpRequest.prototype.send;
4292    XMLHttpRequest.prototype.send = function(obj) {
4293      return originalSend.call(this, unwrapIfNeeded(obj));
4294    };
4295  })(window.ShadowDOMPolyfill);
4296  (function(scope) {
4297    "use strict";
4298    var isWrapperFor = scope.isWrapperFor;
4299    var elements = {
4300      a: "HTMLAnchorElement",
4301      area: "HTMLAreaElement",
4302      audio: "HTMLAudioElement",
4303      base: "HTMLBaseElement",
4304      body: "HTMLBodyElement",
4305      br: "HTMLBRElement",
4306      button: "HTMLButtonElement",
4307      canvas: "HTMLCanvasElement",
4308      caption: "HTMLTableCaptionElement",
4309      col: "HTMLTableColElement",
4310      content: "HTMLContentElement",
4311      data: "HTMLDataElement",
4312      datalist: "HTMLDataListElement",
4313      del: "HTMLModElement",
4314      dir: "HTMLDirectoryElement",
4315      div: "HTMLDivElement",
4316      dl: "HTMLDListElement",
4317      embed: "HTMLEmbedElement",
4318      fieldset: "HTMLFieldSetElement",
4319      font: "HTMLFontElement",
4320      form: "HTMLFormElement",
4321      frame: "HTMLFrameElement",
4322      frameset: "HTMLFrameSetElement",
4323      h1: "HTMLHeadingElement",
4324      head: "HTMLHeadElement",
4325      hr: "HTMLHRElement",
4326      html: "HTMLHtmlElement",
4327      iframe: "HTMLIFrameElement",
4328      img: "HTMLImageElement",
4329      input: "HTMLInputElement",
4330      keygen: "HTMLKeygenElement",
4331      label: "HTMLLabelElement",
4332      legend: "HTMLLegendElement",
4333      li: "HTMLLIElement",
4334      link: "HTMLLinkElement",
4335      map: "HTMLMapElement",
4336      marquee: "HTMLMarqueeElement",
4337      menu: "HTMLMenuElement",
4338      menuitem: "HTMLMenuItemElement",
4339      meta: "HTMLMetaElement",
4340      meter: "HTMLMeterElement",
4341      object: "HTMLObjectElement",
4342      ol: "HTMLOListElement",
4343      optgroup: "HTMLOptGroupElement",
4344      option: "HTMLOptionElement",
4345      output: "HTMLOutputElement",
4346      p: "HTMLParagraphElement",
4347      param: "HTMLParamElement",
4348      pre: "HTMLPreElement",
4349      progress: "HTMLProgressElement",
4350      q: "HTMLQuoteElement",
4351      script: "HTMLScriptElement",
4352      select: "HTMLSelectElement",
4353      shadow: "HTMLShadowElement",
4354      source: "HTMLSourceElement",
4355      span: "HTMLSpanElement",
4356      style: "HTMLStyleElement",
4357      table: "HTMLTableElement",
4358      tbody: "HTMLTableSectionElement",
4359      template: "HTMLTemplateElement",
4360      textarea: "HTMLTextAreaElement",
4361      thead: "HTMLTableSectionElement",
4362      time: "HTMLTimeElement",
4363      title: "HTMLTitleElement",
4364      tr: "HTMLTableRowElement",
4365      track: "HTMLTrackElement",
4366      ul: "HTMLUListElement",
4367      video: "HTMLVideoElement"
4368    };
4369    function overrideConstructor(tagName) {
4370      var nativeConstructorName = elements[tagName];
4371      var nativeConstructor = window[nativeConstructorName];
4372      if (!nativeConstructor) return;
4373      var element = document.createElement(tagName);
4374      var wrapperConstructor = element.constructor;
4375      window[nativeConstructorName] = wrapperConstructor;
4376    }
4377    Object.keys(elements).forEach(overrideConstructor);
4378    Object.getOwnPropertyNames(scope.wrappers).forEach(function(name) {
4379      window[name] = scope.wrappers[name];
4380    });
4381  })(window.ShadowDOMPolyfill);
4382  (function(scope) {
4383    var ShadowCSS = {
4384      strictStyling: false,
4385      registry: {},
4386      shimStyling: function(root, name, extendsName) {
4387        var scopeStyles = this.prepareRoot(root, name, extendsName);
4388        var typeExtension = this.isTypeExtension(extendsName);
4389        var scopeSelector = this.makeScopeSelector(name, typeExtension);
4390        var cssText = stylesToCssText(scopeStyles, true);
4391        cssText = this.scopeCssText(cssText, scopeSelector);
4392        if (root) {
4393          root.shimmedStyle = cssText;
4394        }
4395        this.addCssToDocument(cssText, name);
4396      },
4397      shimStyle: function(style, selector) {
4398        return this.shimCssText(style.textContent, selector);
4399      },
4400      shimCssText: function(cssText, selector) {
4401        cssText = this.insertDirectives(cssText);
4402        return this.scopeCssText(cssText, selector);
4403      },
4404      makeScopeSelector: function(name, typeExtension) {
4405        if (name) {
4406          return typeExtension ? "[is=" + name + "]" : name;
4407        }
4408        return "";
4409      },
4410      isTypeExtension: function(extendsName) {
4411        return extendsName && extendsName.indexOf("-") < 0;
4412      },
4413      prepareRoot: function(root, name, extendsName) {
4414        var def = this.registerRoot(root, name, extendsName);
4415        this.replaceTextInStyles(def.rootStyles, this.insertDirectives);
4416        this.removeStyles(root, def.rootStyles);
4417        if (this.strictStyling) {
4418          this.applyScopeToContent(root, name);
4419        }
4420        return def.scopeStyles;
4421      },
4422      removeStyles: function(root, styles) {
4423        for (var i = 0, l = styles.length, s; i < l && (s = styles[i]); i++) {
4424          s.parentNode.removeChild(s);
4425        }
4426      },
4427      registerRoot: function(root, name, extendsName) {
4428        var def = this.registry[name] = {
4429          root: root,
4430          name: name,
4431          extendsName: extendsName
4432        };
4433        var styles = this.findStyles(root);
4434        def.rootStyles = styles;
4435        def.scopeStyles = def.rootStyles;
4436        var extendee = this.registry[def.extendsName];
4437        if (extendee) {
4438          def.scopeStyles = extendee.scopeStyles.concat(def.scopeStyles);
4439        }
4440        return def;
4441      },
4442      findStyles: function(root) {
4443        if (!root) {
4444          return [];
4445        }
4446        var styles = root.querySelectorAll("style");
4447        return Array.prototype.filter.call(styles, function(s) {
4448          return !s.hasAttribute(NO_SHIM_ATTRIBUTE);
4449        });
4450      },
4451      applyScopeToContent: function(root, name) {
4452        if (root) {
4453          Array.prototype.forEach.call(root.querySelectorAll("*"), function(node) {
4454            node.setAttribute(name, "");
4455          });
4456          Array.prototype.forEach.call(root.querySelectorAll("template"), function(template) {
4457            this.applyScopeToContent(template.content, name);
4458          }, this);
4459        }
4460      },
4461      insertDirectives: function(cssText) {
4462        cssText = this.insertPolyfillDirectivesInCssText(cssText);
4463        return this.insertPolyfillRulesInCssText(cssText);
4464      },
4465      insertPolyfillDirectivesInCssText: function(cssText) {
4466        cssText = cssText.replace(cssCommentNextSelectorRe, function(match, p1) {
4467          return p1.slice(0, -2) + "{";
4468        });
4469        return cssText.replace(cssContentNextSelectorRe, function(match, p1) {
4470          return p1 + " {";
4471        });
4472      },
4473      insertPolyfillRulesInCssText: function(cssText) {
4474        cssText = cssText.replace(cssCommentRuleRe, function(match, p1) {
4475          return p1.slice(0, -1);
4476        });
4477        return cssText.replace(cssContentRuleRe, function(match, p1, p2, p3) {
4478          var rule = match.replace(p1, "").replace(p2, "");
4479          return p3 + rule;
4480        });
4481      },
4482      scopeCssText: function(cssText, scopeSelector) {
4483        var unscoped = this.extractUnscopedRulesFromCssText(cssText);
4484        cssText = this.insertPolyfillHostInCssText(cssText);
4485        cssText = this.convertColonHost(cssText);
4486        cssText = this.convertColonHostContext(cssText);
4487        cssText = this.convertShadowDOMSelectors(cssText);
4488        if (scopeSelector) {
4489          var self = this, cssText;
4490          withCssRules(cssText, function(rules) {
4491            cssText = self.scopeRules(rules, scopeSelector);
4492          });
4493        }
4494        cssText = cssText + "\n" + unscoped;
4495        return cssText.trim();
4496      },
4497      extractUnscopedRulesFromCssText: function(cssText) {
4498        var r = "", m;
4499        while (m = cssCommentUnscopedRuleRe.exec(cssText)) {
4500          r += m[1].slice(0, -1) + "\n\n";
4501        }
4502        while (m = cssContentUnscopedRuleRe.exec(cssText)) {
4503          r += m[0].replace(m[2], "").replace(m[1], m[3]) + "\n\n";
4504        }
4505        return r;
4506      },
4507      convertColonHost: function(cssText) {
4508        return this.convertColonRule(cssText, cssColonHostRe, this.colonHostPartReplacer);
4509      },
4510      convertColonHostContext: function(cssText) {
4511        return this.convertColonRule(cssText, cssColonHostContextRe, this.colonHostContextPartReplacer);
4512      },
4513      convertColonRule: function(cssText, regExp, partReplacer) {
4514        return cssText.replace(regExp, function(m, p1, p2, p3) {
4515          p1 = polyfillHostNoCombinator;
4516          if (p2) {
4517            var parts = p2.split(","), r = [];
4518            for (var i = 0, l = parts.length, p; i < l && (p = parts[i]); i++) {
4519              p = p.trim();
4520              r.push(partReplacer(p1, p, p3));
4521            }
4522            return r.join(",");
4523          } else {
4524            return p1 + p3;
4525          }
4526        });
4527      },
4528      colonHostContextPartReplacer: function(host, part, suffix) {
4529        if (part.match(polyfillHost)) {
4530          return this.colonHostPartReplacer(host, part, suffix);
4531        } else {
4532          return host + part + suffix + ", " + part + " " + host + suffix;
4533        }
4534      },
4535      colonHostPartReplacer: function(host, part, suffix) {
4536        return host + part.replace(polyfillHost, "") + suffix;
4537      },
4538      convertShadowDOMSelectors: function(cssText) {
4539        for (var i = 0; i < shadowDOMSelectorsRe.length; i++) {
4540          cssText = cssText.replace(shadowDOMSelectorsRe[i], " ");
4541        }
4542        return cssText;
4543      },
4544      scopeRules: function(cssRules, scopeSelector) {
4545        var cssText = "";
4546        if (cssRules) {
4547          Array.prototype.forEach.call(cssRules, function(rule) {
4548            if (rule.selectorText && (rule.style && rule.style.cssText !== undefined)) {
4549              cssText += this.scopeSelector(rule.selectorText, scopeSelector, this.strictStyling) + " {\n	";
4550              cssText += this.propertiesFromRule(rule) + "\n}\n\n";
4551            } else if (rule.type === CSSRule.MEDIA_RULE) {
4552              cssText += "@media " + rule.media.mediaText + " {\n";
4553              cssText += this.scopeRules(rule.cssRules, scopeSelector);
4554              cssText += "\n}\n\n";
4555            } else {
4556              try {
4557                if (rule.cssText) {
4558                  cssText += rule.cssText + "\n\n";
4559                }
4560              } catch (x) {
4561                if (rule.type === CSSRule.KEYFRAMES_RULE && rule.cssRules) {
4562                  cssText += this.ieSafeCssTextFromKeyFrameRule(rule);
4563                }
4564              }
4565            }
4566          }, this);
4567        }
4568        return cssText;
4569      },
4570      ieSafeCssTextFromKeyFrameRule: function(rule) {
4571        var cssText = "@keyframes " + rule.name + " {";
4572        Array.prototype.forEach.call(rule.cssRules, function(rule) {
4573          cssText += " " + rule.keyText + " {" + rule.style.cssText + "}";
4574        });
4575        cssText += " }";
4576        return cssText;
4577      },
4578      scopeSelector: function(selector, scopeSelector, strict) {
4579        var r = [], parts = selector.split(",");
4580        parts.forEach(function(p) {
4581          p = p.trim();
4582          if (this.selectorNeedsScoping(p, scopeSelector)) {
4583            p = strict && !p.match(polyfillHostNoCombinator) ? this.applyStrictSelectorScope(p, scopeSelector) : this.applySelectorScope(p, scopeSelector);
4584          }
4585          r.push(p);
4586        }, this);
4587        return r.join(", ");
4588      },
4589      selectorNeedsScoping: function(selector, scopeSelector) {
4590        if (Array.isArray(scopeSelector)) {
4591          return true;
4592        }
4593        var re = this.makeScopeMatcher(scopeSelector);
4594        return !selector.match(re);
4595      },
4596      makeScopeMatcher: function(scopeSelector) {
4597        scopeSelector = scopeSelector.replace(/\[/g, "\\[").replace(/\]/g, "\\]");
4598        return new RegExp("^(" + scopeSelector + ")" + selectorReSuffix, "m");
4599      },
4600      applySelectorScope: function(selector, selectorScope) {
4601        return Array.isArray(selectorScope) ? this.applySelectorScopeList(selector, selectorScope) : this.applySimpleSelectorScope(selector, selectorScope);
4602      },
4603      applySelectorScopeList: function(selector, scopeSelectorList) {
4604        var r = [];
4605        for (var i = 0, s; s = scopeSelectorList[i]; i++) {
4606          r.push(this.applySimpleSelectorScope(selector, s));
4607        }
4608        return r.join(", ");
4609      },
4610      applySimpleSelectorScope: function(selector, scopeSelector) {
4611        if (selector.match(polyfillHostRe)) {
4612          selector = selector.replace(polyfillHostNoCombinator, scopeSelector);
4613          return selector.replace(polyfillHostRe, scopeSelector + " ");
4614        } else {
4615          return scopeSelector + " " + selector;
4616        }
4617      },
4618      applyStrictSelectorScope: function(selector, scopeSelector) {
4619        scopeSelector = scopeSelector.replace(/\[is=([^\]]*)\]/g, "$1");
4620        var splits = [ " ", ">", "+", "~" ], scoped = selector, attrName = "[" + scopeSelector + "]";
4621        splits.forEach(function(sep) {
4622          var parts = scoped.split(sep);
4623          scoped = parts.map(function(p) {
4624            var t = p.trim().replace(polyfillHostRe, "");
4625            if (t && splits.indexOf(t) < 0 && t.indexOf(attrName) < 0) {
4626              p = t.replace(/([^:]*)(:*)(.*)/, "$1" + attrName + "$2$3");
4627            }
4628            return p;
4629          }).join(sep);
4630        });
4631        return scoped;
4632      },
4633      insertPolyfillHostInCssText: function(selector) {
4634        return selector.replace(colonHostContextRe, polyfillHostContext).replace(colonHostRe, polyfillHost);
4635      },
4636      propertiesFromRule: function(rule) {
4637        var cssText = rule.style.cssText;
4638        if (rule.style.content && !rule.style.content.match(/['"]+|attr/)) {
4639          cssText = cssText.replace(/content:[^;]*;/g, "content: '" + rule.style.content + "';");
4640        }
4641        var style = rule.style;
4642        for (var i in style) {
4643          if (style[i] === "initial") {
4644            cssText += i + ": initial; ";
4645          }
4646        }
4647        return cssText;
4648      },
4649      replaceTextInStyles: function(styles, action) {
4650        if (styles && action) {
4651          if (!(styles instanceof Array)) {
4652            styles = [ styles ];
4653          }
4654          Array.prototype.forEach.call(styles, function(s) {
4655            s.textContent = action.call(this, s.textContent);
4656          }, this);
4657        }
4658      },
4659      addCssToDocument: function(cssText, name) {
4660        if (cssText.match("@import")) {
4661          addOwnSheet(cssText, name);
4662        } else {
4663          addCssToDocument(cssText);
4664        }
4665      }
4666    };
4667    var selectorRe = /([^{]*)({[\s\S]*?})/gim, cssCommentRe = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//gim, cssCommentNextSelectorRe = /\/\*\s*@polyfill ([^*]*\*+([^/*][^*]*\*+)*\/)([^{]*?){/gim, cssContentNextSelectorRe = /polyfill-next-selector[^}]*content\:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim, cssCommentRuleRe = /\/\*\s@polyfill-rule([^*]*\*+([^/*][^*]*\*+)*)\//gim, cssContentRuleRe = /(polyfill-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim, cssCommentUnscopedRuleRe = /\/\*\s@polyfill-unscoped-rule([^*]*\*+([^/*][^*]*\*+)*)\//gim, cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content\:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim, cssPseudoRe = /::(x-[^\s{,(]*)/gim, cssPartRe = /::part\(([^)]*)\)/gim, polyfillHost = "-shadowcsshost", polyfillHostContext = "-shadowcsscontext", parenSuffix = ")(?:\\((" + "(?:\\([^)(]*\\)|[^)(]*)+?" + ")\\))?([^,{]*)";
4668    var cssColonHostRe = new RegExp("(" + polyfillHost + parenSuffix, "gim"), cssColonHostContextRe = new RegExp("(" + polyfillHostContext + parenSuffix, "gim"), selectorReSuffix = "([>\\s~+[.,{:][\\s\\S]*)?$", colonHostRe = /\:host/gim, colonHostContextRe = /\:host-context/gim, polyfillHostNoCombinator = polyfillHost + "-no-combinator", polyfillHostRe = new RegExp(polyfillHost, "gim"), polyfillHostContextRe = new RegExp(polyfillHostContext, "gim"), shadowDOMSelectorsRe = [ />>>/g, /::shadow/g, /::content/g, /\/deep\//g, /\/shadow\//g, /\/shadow-deep\//g, /\^\^/g, /\^/g ];
4669    function stylesToCssText(styles, preserveComments) {
4670      var cssText = "";
4671      Array.prototype.forEach.call(styles, function(s) {
4672        cssText += s.textContent + "\n\n";
4673      });
4674      if (!preserveComments) {
4675        cssText = cssText.replace(cssCommentRe, "");
4676      }
4677      return cssText;
4678    }
4679    function cssTextToStyle(cssText) {
4680      var style = document.createElement("style");
4681      style.textContent = cssText;
4682      return style;
4683    }
4684    function cssToRules(cssText) {
4685      var style = cssTextToStyle(cssText);
4686      document.head.appendChild(style);
4687      var rules = [];
4688      if (style.sheet) {
4689        try {
4690          rules = style.sheet.cssRules;
4691        } catch (e) {}
4692      } else {
4693        console.warn("sheet not found", style);
4694      }
4695      style.parentNode.removeChild(style);
4696      return rules;
4697    }
4698    var frame = document.createElement("iframe");
4699    frame.style.display = "none";
4700    function initFrame() {
4701      frame.initialized = true;
4702      document.body.appendChild(frame);
4703      var doc = frame.contentDocument;
4704      var base = doc.createElement("base");
4705      base.href = document.baseURI;
4706      doc.head.appendChild(base);
4707    }
4708    function inFrame(fn) {
4709      if (!frame.initialized) {
4710        initFrame();
4711      }
4712      document.body.appendChild(frame);
4713      fn(frame.contentDocument);
4714      document.body.removeChild(frame);
4715    }
4716    var isChrome = navigator.userAgent.match("Chrome");
4717    function withCssRules(cssText, callback) {
4718      if (!callback) {
4719        return;
4720      }
4721      var rules;
4722      if (cssText.match("@import") && isChrome) {
4723        var style = cssTextToStyle(cssText);
4724        inFrame(function(doc) {
4725          doc.head.appendChild(style.impl);
4726          rules = Array.prototype.slice.call(style.sheet.cssRules, 0);
4727          callback(rules);
4728        });
4729      } else {
4730        rules = cssToRules(cssText);
4731        callback(rules);
4732      }
4733    }
4734    function rulesToCss(cssRules) {
4735      for (var i = 0, css = []; i < cssRules.length; i++) {
4736        css.push(cssRules[i].cssText);
4737      }
4738      return css.join("\n\n");
4739    }
4740    function addCssToDocument(cssText) {
4741      if (cssText) {
4742        getSheet().appendChild(document.createTextNode(cssText));
4743      }
4744    }
4745    function addOwnSheet(cssText, name) {
4746      var style = cssTextToStyle(cssText);
4747      style.setAttribute(name, "");
4748      style.setAttribute(SHIMMED_ATTRIBUTE, "");
4749      document.head.appendChild(style);
4750    }
4751    var SHIM_ATTRIBUTE = "shim-shadowdom";
4752    var SHIMMED_ATTRIBUTE = "shim-shadowdom-css";
4753    var NO_SHIM_ATTRIBUTE = "no-shim";
4754    var sheet;
4755    function getSheet() {
4756      if (!sheet) {
4757        sheet = document.createElement("style");
4758        sheet.setAttribute(SHIMMED_ATTRIBUTE, "");
4759        sheet[SHIMMED_ATTRIBUTE] = true;
4760      }
4761      return sheet;
4762    }
4763    if (window.ShadowDOMPolyfill) {
4764      addCssToDocument("style { display: none !important; }\n");
4765      var doc = ShadowDOMPolyfill.wrap(document);
4766      var head = doc.querySelector("head");
4767      head.insertBefore(getSheet(), head.childNodes[0]);
4768      document.addEventListener("DOMContentLoaded", function() {
4769        var urlResolver = scope.urlResolver;
4770        if (window.HTMLImports && !HTMLImports.useNative) {
4771          var SHIM_SHEET_SELECTOR = "link[rel=stylesheet]" + "[" + SHIM_ATTRIBUTE + "]";
4772          var SHIM_STYLE_SELECTOR = "style[" + SHIM_ATTRIBUTE + "]";
4773          HTMLImports.importer.documentPreloadSelectors += "," + SHIM_SHEET_SELECTOR;
4774          HTMLImports.importer.importsPreloadSelectors += "," + SHIM_SHEET_SELECTOR;
4775          HTMLImports.parser.documentSelectors = [ HTMLImports.parser.documentSelectors, SHIM_SHEET_SELECTOR, SHIM_STYLE_SELECTOR ].join(",");
4776          var originalParseGeneric = HTMLImports.parser.parseGeneric;
4777          HTMLImports.parser.parseGeneric = function(elt) {
4778            if (elt[SHIMMED_ATTRIBUTE]) {
4779              return;
4780            }
4781            var style = elt.__importElement || elt;
4782            if (!style.hasAttribute(SHIM_ATTRIBUTE)) {
4783              originalParseGeneric.call(this, elt);
4784              return;
4785            }
4786            if (elt.__resource) {
4787              style = elt.ownerDocument.createElement("style");
4788              style.textContent = elt.__resource;
4789            }
4790            HTMLImports.path.resolveUrlsInStyle(style, elt.href);
4791            style.textContent = ShadowCSS.shimStyle(style);
4792            style.removeAttribute(SHIM_ATTRIBUTE, "");
4793            style.setAttribute(SHIMMED_ATTRIBUTE, "");
4794            style[SHIMMED_ATTRIBUTE] = true;
4795            if (style.parentNode !== head) {
4796              if (elt.parentNode === head) {
4797                head.replaceChild(style, elt);
4798              } else {
4799                this.addElementToDocument(style);
4800              }
4801            }
4802            style.__importParsed = true;
4803            this.markParsingComplete(elt);
4804            this.parseNext();
4805          };
4806          var hasResource = HTMLImports.parser.hasResource;
4807          HTMLImports.parser.hasResource = function(node) {
4808            if (node.localName === "link" && node.rel === "stylesheet" && node.hasAttribute(SHIM_ATTRIBUTE)) {
4809              return node.__resource;
4810            } else {
4811              return hasResource.call(this, node);
4812            }
4813          };
4814        }
4815      });
4816    }
4817    scope.ShadowCSS = ShadowCSS;
4818  })(window.WebComponents);
4819}
4820
4821(function(scope) {
4822  if (window.ShadowDOMPolyfill) {
4823    window.wrap = ShadowDOMPolyfill.wrapIfNeeded;
4824    window.unwrap = ShadowDOMPolyfill.unwrapIfNeeded;
4825  } else {
4826    window.wrap = window.unwrap = function(n) {
4827      return n;
4828    };
4829  }
4830})(window.WebComponents);
4831
4832(function(scope) {
4833  "use strict";
4834  var hasWorkingUrl = false;
4835  if (!scope.forceJURL) {
4836    try {
4837      var u = new URL("b", "http://a");
4838      u.pathname = "c%20d";
4839      hasWorkingUrl = u.href === "http://a/c%20d";
4840    } catch (e) {}
4841  }
4842  if (hasWorkingUrl) return;
4843  var relative = Object.create(null);
4844  relative["ftp"] = 21;
4845  relative["file"] = 0;
4846  relative["gopher"] = 70;
4847  relative["http"] = 80;
4848  relative["https"] = 443;
4849  relative["ws"] = 80;
4850  relative["wss"] = 443;
4851  var relativePathDotMapping = Object.create(null);
4852  relativePathDotMapping["%2e"] = ".";
4853  relativePathDotMapping[".%2e"] = "..";
4854  relativePathDotMapping["%2e."] = "..";
4855  relativePathDotMapping["%2e%2e"] = "..";
4856  function isRelativeScheme(scheme) {
4857    return relative[scheme] !== undefined;
4858  }
4859  function invalid() {
4860    clear.call(this);
4861    this._isInvalid = true;
4862  }
4863  function IDNAToASCII(h) {
4864    if ("" == h) {
4865      invalid.call(this);
4866    }
4867    return h.toLowerCase();
4868  }
4869  function percentEscape(c) {
4870    var unicode = c.charCodeAt(0);
4871    if (unicode > 32 && unicode < 127 && [ 34, 35, 60, 62, 63, 96 ].indexOf(unicode) == -1) {
4872      return c;
4873    }
4874    return encodeURIComponent(c);
4875  }
4876  function percentEscapeQuery(c) {
4877    var unicode = c.charCodeAt(0);
4878    if (unicode > 32 && unicode < 127 && [ 34, 35, 60, 62, 96 ].indexOf(unicode) == -1) {
4879      return c;
4880    }
4881    return encodeURIComponent(c);
4882  }
4883  var EOF = undefined, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
4884  function parse(input, stateOverride, base) {
4885    function err(message) {
4886      errors.push(message);
4887    }
4888    var state = stateOverride || "scheme start", cursor = 0, buffer = "", seenAt = false, seenBracket = false, errors = [];
4889    loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) {
4890      var c = input[cursor];
4891      switch (state) {
4892       case "scheme start":
4893        if (c && ALPHA.test(c)) {
4894          buffer += c.toLowerCase();
4895          state = "scheme";
4896        } else if (!stateOverride) {
4897          buffer = "";
4898          state = "no scheme";
4899          continue;
4900        } else {
4901          err("Invalid scheme.");
4902          break loop;
4903        }
4904        break;
4905
4906       case "scheme":
4907        if (c && ALPHANUMERIC.test(c)) {
4908          buffer += c.toLowerCase();
4909        } else if (":" == c) {
4910          this._scheme = buffer;
4911          buffer = "";
4912          if (stateOverride) {
4913            break loop;
4914          }
4915          if (isRelativeScheme(this._scheme)) {
4916            this._isRelative = true;
4917          }
4918          if ("file" == this._scheme) {
4919            state = "relative";
4920          } else if (this._isRelative && base && base._scheme == this._scheme) {
4921            state = "relative or authority";
4922          } else if (this._isRelative) {
4923            state = "authority first slash";
4924          } else {
4925            state = "scheme data";
4926          }
4927        } else if (!stateOverride) {
4928          buffer = "";
4929          cursor = 0;
4930          state = "no scheme";
4931          continue;
4932        } else if (EOF == c) {
4933          break loop;
4934        } else {
4935          err("Code point not allowed in scheme: " + c);
4936          break loop;
4937        }
4938        break;
4939
4940       case "scheme data":
4941        if ("?" == c) {
4942          query = "?";
4943          state = "query";
4944        } else if ("#" == c) {
4945          this._fragment = "#";
4946          state = "fragment";
4947        } else {
4948          if (EOF != c && "	" != c && "\n" != c && "\r" != c) {
4949            this._schemeData += percentEscape(c);
4950          }
4951        }
4952        break;
4953
4954       case "no scheme":
4955        if (!base || !isRelativeScheme(base._scheme)) {
4956          err("Missing scheme.");
4957          invalid.call(this);
4958        } else {
4959          state = "relative";
4960          continue;
4961        }
4962        break;
4963
4964       case "relative or authority":
4965        if ("/" == c && "/" == input[cursor + 1]) {
4966          state = "authority ignore slashes";
4967        } else {
4968          err("Expected /, got: " + c);
4969          state = "relative";
4970          continue;
4971        }
4972        break;
4973
4974       case "relative":
4975        this._isRelative = true;
4976        if ("file" != this._scheme) this._scheme = base._scheme;
4977        if (EOF == c) {
4978          this._host = base._host;
4979          this._port = base._port;
4980          this._path = base._path.slice();
4981          this._query = base._query;
4982          break loop;
4983        } else if ("/" == c || "\\" == c) {
4984          if ("\\" == c) err("\\ is an invalid code point.");
4985          state = "relative slash";
4986        } else if ("?" == c) {
4987          this._host = base._host;
4988          this._port = base._port;
4989          this._path = base._path.slice();
4990          this._query = "?";
4991          state = "query";
4992        } else if ("#" == c) {
4993          this._host = base._host;
4994          this._port = base._port;
4995          this._path = base._path.slice();
4996          this._query = base._query;
4997          this._fragment = "#";
4998          state = "fragment";
4999        } else {
5000          var nextC = input[cursor + 1];
5001          var nextNextC = input[cursor + 2];
5002          if ("file" != this._scheme || !ALPHA.test(c) || nextC != ":" && nextC != "|" || EOF != nextNextC && "/" != nextNextC && "\\" != nextNextC && "?" != nextNextC && "#" != nextNextC) {
5003            this._host = base._host;
5004            this._port = base._port;
5005            this._path = base._path.slice();
5006            this._path.pop();
5007          }
5008          state = "relative path";
5009          continue;
5010        }
5011        break;
5012
5013       case "relative slash":
5014        if ("/" == c || "\\" == c) {
5015          if ("\\" == c) {
5016            err("\\ is an invalid code point.");
5017          }
5018          if ("file" == this._scheme) {
5019            state = "file host";
5020          } else {
5021            state = "authority ignore slashes";
5022          }
5023        } else {
5024          if ("file" != this._scheme) {
5025            this._host = base._host;
5026            this._port = base._port;
5027          }
5028          state = "relative path";
5029          continue;
5030        }
5031        break;
5032
5033       case "authority first slash":
5034        if ("/" == c) {
5035          state = "authority second slash";
5036        } else {
5037          err("Expected '/', got: " + c);
5038          state = "authority ignore slashes";
5039          continue;
5040        }
5041        break;
5042
5043       case "authority second slash":
5044        state = "authority ignore slashes";
5045        if ("/" != c) {
5046          err("Expected '/', got: " + c);
5047          continue;
5048        }
5049        break;
5050
5051       case "authority ignore slashes":
5052        if ("/" != c && "\\" != c) {
5053          state = "authority";
5054          continue;
5055        } else {
5056          err("Expected authority, got: " + c);
5057        }
5058        break;
5059
5060       case "authority":
5061        if ("@" == c) {
5062          if (seenAt) {
5063            err("@ already seen.");
5064            buffer += "%40";
5065          }
5066          seenAt = true;
5067          for (var i = 0; i < buffer.length; i++) {
5068            var cp = buffer[i];
5069            if ("	" == cp || "\n" == cp || "\r" == cp) {
5070              err("Invalid whitespace in authority.");
5071              continue;
5072            }
5073            if (":" == cp && null === this._password) {
5074              this._password = "";
5075              continue;
5076            }
5077            var tempC = percentEscape(cp);
5078            null !== this._password ? this._password += tempC : this._username += tempC;
5079          }
5080          buffer = "";
5081        } else if (EOF == c || "/" == c || "\\" == c || "?" == c || "#" == c) {
5082          cursor -= buffer.length;
5083          buffer = "";
5084          state = "host";
5085          continue;
5086        } else {
5087          buffer += c;
5088        }
5089        break;
5090
5091       case "file host":
5092        if (EOF == c || "/" == c || "\\" == c || "?" == c || "#" == c) {
5093          if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ":" || buffer[1] == "|")) {
5094            state = "relative path";
5095          } else if (buffer.length == 0) {
5096            state = "relative path start";
5097          } else {
5098            this._host = IDNAToASCII.call(this, buffer);
5099            buffer = "";
5100            state = "relative path start";
5101          }
5102          continue;
5103        } else if ("	" == c || "\n" == c || "\r" == c) {
5104          err("Invalid whitespace in file host.");
5105        } else {
5106          buffer += c;
5107        }
5108        break;
5109
5110       case "host":
5111       case "hostname":
5112        if (":" == c && !seenBracket) {
5113          this._host = IDNAToASCII.call(this, buffer);
5114          buffer = "";
5115          state = "port";
5116          if ("hostname" == stateOverride) {
5117            break loop;
5118          }
5119        } else if (EOF == c || "/" == c || "\\" == c || "?" == c || "#" == c) {
5120          this._host = IDNAToASCII.call(this, buffer);
5121          buffer = "";
5122          state = "relative path start";
5123          if (stateOverride) {
5124            break loop;
5125          }
5126          continue;
5127        } else if ("	" != c && "\n" != c && "\r" != c) {
5128          if ("[" == c) {
5129            seenBracket = true;
5130          } else if ("]" == c) {
5131            seenBracket = false;
5132          }
5133          buffer += c;
5134        } else {
5135          err("Invalid code point in host/hostname: " + c);
5136        }
5137        break;
5138
5139       case "port":
5140        if (/[0-9]/.test(c)) {
5141          buffer += c;
5142        } else if (EOF == c || "/" == c || "\\" == c || "?" == c || "#" == c || stateOverride) {
5143          if ("" != buffer) {
5144            var temp = parseInt(buffer, 10);
5145            if (temp != relative[this._scheme]) {
5146              this._port = temp + "";
5147            }
5148            buffer = "";
5149          }
5150          if (stateOverride) {
5151            break loop;
5152          }
5153          state = "relative path start";
5154          continue;
5155        } else if ("	" == c || "\n" == c || "\r" == c) {
5156          err("Invalid code point in port: " + c);
5157        } else {
5158          invalid.call(this);
5159        }
5160        break;
5161
5162       case "relative path start":
5163        if ("\\" == c) err("'\\' not allowed in path.");
5164        state = "relative path";
5165        if ("/" != c && "\\" != c) {
5166          continue;
5167        }
5168        break;
5169
5170       case "relative path":
5171        if (EOF == c || "/" == c || "\\" == c || !stateOverride && ("?" == c || "#" == c)) {
5172          if ("\\" == c) {
5173            err("\\ not allowed in relative path.");
5174          }
5175          var tmp;
5176          if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
5177            buffer = tmp;
5178          }
5179          if (".." == buffer) {
5180            this._path.pop();
5181            if ("/" != c && "\\" != c) {
5182              this._path.push("");
5183            }
5184          } else if ("." == buffer && "/" != c && "\\" != c) {
5185            this._path.push("");
5186          } else if ("." != buffer) {
5187            if ("file" == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == "|") {
5188              buffer = buffer[0] + ":";
5189            }
5190            this._path.push(buffer);
5191          }
5192          buffer = "";
5193          if ("?" == c) {
5194            this._query = "?";
5195            state = "query";
5196          } else if ("#" == c) {
5197            this._fragment = "#";
5198            state = "fragment";
5199          }
5200        } else if ("	" != c && "\n" != c && "\r" != c) {
5201          buffer += percentEscape(c);
5202        }
5203        break;
5204
5205       case "query":
5206        if (!stateOverride && "#" == c) {
5207          this._fragment = "#";
5208          state = "fragment";
5209        } else if (EOF != c && "	" != c && "\n" != c && "\r" != c) {
5210          this._query += percentEscapeQuery(c);
5211        }
5212        break;
5213
5214       case "fragment":
5215        if (EOF != c && "	" != c && "\n" != c && "\r" != c) {
5216          this._fragment += c;
5217        }
5218        break;
5219      }
5220      cursor++;
5221    }
5222  }
5223  function clear() {
5224    this._scheme = "";
5225    this._schemeData = "";
5226    this._username = "";
5227    this._password = null;
5228    this._host = "";
5229    this._port = "";
5230    this._path = [];
5231    this._query = "";
5232    this._fragment = "";
5233    this._isInvalid = false;
5234    this._isRelative = false;
5235  }
5236  function jURL(url, base) {
5237    if (base !== undefined && !(base instanceof jURL)) base = new jURL(String(base));
5238    this._url = url;
5239    clear.call(this);
5240    var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, "");
5241    parse.call(this, input, null, base);
5242  }
5243  jURL.prototype = {
5244    toString: function() {
5245      return this.href;
5246    },
5247    get href() {
5248      if (this._isInvalid) return this._url;
5249      var authority = "";
5250      if ("" != this._username || null != this._password) {
5251        authority = this._username + (null != this._password ? ":" + this._password : "") + "@";
5252      }
5253      return this.protocol + (this._isRelative ? "//" + authority + this.host : "") + this.pathname + this._query + this._fragment;
5254    },
5255    set href(href) {
5256      clear.call(this);
5257      parse.call(this, href);
5258    },
5259    get protocol() {
5260      return this._scheme + ":";
5261    },
5262    set protocol(protocol) {
5263      if (this._isInvalid) return;
5264      parse.call(this, protocol + ":", "scheme start");
5265    },
5266    get host() {
5267      return this._isInvalid ? "" : this._port ? this._host + ":" + this._port : this._host;
5268    },
5269    set host(host) {
5270      if (this._isInvalid || !this._isRelative) return;
5271      parse.call(this, host, "host");
5272    },
5273    get hostname() {
5274      return this._host;
5275    },
5276    set hostname(hostname) {
5277      if (this._isInvalid || !this._isRelative) return;
5278      parse.call(this, hostname, "hostname");
5279    },
5280    get port() {
5281      return this._port;
5282    },
5283    set port(port) {
5284      if (this._isInvalid || !this._isRelative) return;
5285      parse.call(this, port, "port");
5286    },
5287    get pathname() {
5288      return this._isInvalid ? "" : this._isRelative ? "/" + this._path.join("/") : this._schemeData;
5289    },
5290    set pathname(pathname) {
5291      if (this._isInvalid || !this._isRelative) return;
5292      this._path = [];
5293      parse.call(this, pathname, "relative path start");
5294    },
5295    get search() {
5296      return this._isInvalid || !this._query || "?" == this._query ? "" : this._query;
5297    },
5298    set search(search) {
5299      if (this._isInvalid || !this._isRelative) return;
5300      this._query = "?";
5301      if ("?" == search[0]) search = search.slice(1);
5302      parse.call(this, search, "query");
5303    },
5304    get hash() {
5305      return this._isInvalid || !this._fragment || "#" == this._fragment ? "" : this._fragment;
5306    },
5307    set hash(hash) {
5308      if (this._isInvalid) return;
5309      this._fragment = "#";
5310      if ("#" == hash[0]) hash = hash.slice(1);
5311      parse.call(this, hash, "fragment");
5312    },
5313    get origin() {
5314      var host;
5315      if (this._isInvalid || !this._scheme) {
5316        return "";
5317      }
5318      switch (this._scheme) {
5319       case "data":
5320       case "file":
5321       case "javascript":
5322       case "mailto":
5323        return "null";
5324      }
5325      host = this.host;
5326      if (!host) {
5327        return "";
5328      }
5329      return this._scheme + "://" + host;
5330    }
5331  };
5332  var OriginalURL = scope.URL;
5333  if (OriginalURL) {
5334    jURL.createObjectURL = function(blob) {
5335      return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
5336    };
5337    jURL.revokeObjectURL = function(url) {
5338      OriginalURL.revokeObjectURL(url);
5339    };
5340  }
5341  scope.URL = jURL;
5342})(this);
5343
5344(function(global) {
5345  var registrationsTable = new WeakMap();
5346  var setImmediate;
5347  if (/Trident|Edge/.test(navigator.userAgent)) {
5348    setImmediate = setTimeout;
5349  } else if (window.setImmediate) {
5350    setImmediate = window.setImmediate;
5351  } else {
5352    var setImmediateQueue = [];
5353    var sentinel = String(Math.random());
5354    window.addEventListener("message", function(e) {
5355      if (e.data === sentinel) {
5356        var queue = setImmediateQueue;
5357        setImmediateQueue = [];
5358        queue.forEach(function(func) {
5359          func();
5360        });
5361      }
5362    });
5363    setImmediate = function(func) {
5364      setImmediateQueue.push(func);
5365      window.postMessage(sentinel, "*");
5366    };
5367  }
5368  var isScheduled = false;
5369  var scheduledObservers = [];
5370  function scheduleCallback(observer) {
5371    scheduledObservers.push(observer);
5372    if (!isScheduled) {
5373      isScheduled = true;
5374      setImmediate(dispatchCallbacks);
5375    }
5376  }
5377  function wrapIfNeeded(node) {
5378    return window.ShadowDOMPolyfill && window.ShadowDOMPolyfill.wrapIfNeeded(node) || node;
5379  }
5380  function dispatchCallbacks() {
5381    isScheduled = false;
5382    var observers = scheduledObservers;
5383    scheduledObservers = [];
5384    observers.sort(function(o1, o2) {
5385      return o1.uid_ - o2.uid_;
5386    });
5387    var anyNonEmpty = false;
5388    observers.forEach(function(observer) {
5389      var queue = observer.takeRecords();
5390      removeTransientObserversFor(observer);
5391      if (queue.length) {
5392        observer.callback_(queue, observer);
5393        anyNonEmpty = true;
5394      }
5395    });
5396    if (anyNonEmpty) dispatchCallbacks();
5397  }
5398  function removeTransientObserversFor(observer) {
5399    observer.nodes_.forEach(function(node) {
5400      var registrations = registrationsTable.get(node);
5401      if (!registrations) return;
5402      registrations.forEach(function(registration) {
5403        if (registration.observer === observer) registration.removeTransientObservers();
5404      });
5405    });
5406  }
5407  function forEachAncestorAndObserverEnqueueRecord(target, callback) {
5408    for (var node = target; node; node = node.parentNode) {
5409      var registrations = registrationsTable.get(node);
5410      if (registrations) {
5411        for (var j = 0; j < registrations.length; j++) {
5412          var registration = registrations[j];
5413          var options = registration.options;
5414          if (node !== target && !options.subtree) continue;
5415          var record = callback(options);
5416          if (record) registration.enqueue(record);
5417        }
5418      }
5419    }
5420  }
5421  var uidCounter = 0;
5422  function JsMutationObserver(callback) {
5423    this.callback_ = callback;
5424    this.nodes_ = [];
5425    this.records_ = [];
5426    this.uid_ = ++uidCounter;
5427  }
5428  JsMutationObserver.prototype = {
5429    observe: function(target, options) {
5430      target = wrapIfNeeded(target);
5431      if (!options.childList && !options.attributes && !options.characterData || options.attributeOldValue && !options.attributes || options.attributeFilter && options.attributeFilter.length && !options.attributes || options.characterDataOldValue && !options.characterData) {
5432        throw new SyntaxError();
5433      }
5434      var registrations = registrationsTable.get(target);
5435      if (!registrations) registrationsTable.set(target, registrations = []);
5436      var registration;
5437      for (var i = 0; i < registrations.length; i++) {
5438        if (registrations[i].observer === this) {
5439          registration = registrations[i];
5440          registration.removeListeners();
5441          registration.options = options;
5442          break;
5443        }
5444      }
5445      if (!registration) {
5446        registration = new Registration(this, target, options);
5447        registrations.push(registration);
5448        this.nodes_.push(target);
5449      }
5450      registration.addListeners();
5451    },
5452    disconnect: function() {
5453      this.nodes_.forEach(function(node) {
5454        var registrations = registrationsTable.get(node);
5455        for (var i = 0; i < registrations.length; i++) {
5456          var registration = registrations[i];
5457          if (registration.observer === this) {
5458            registration.removeListeners();
5459            registrations.splice(i, 1);
5460            break;
5461          }
5462        }
5463      }, this);
5464      this.records_ = [];
5465    },
5466    takeRecords: function() {
5467      var copyOfRecords = this.records_;
5468      this.records_ = [];
5469      return copyOfRecords;
5470    }
5471  };
5472  function MutationRecord(type, target) {
5473    this.type = type;
5474    this.target = target;
5475    this.addedNodes = [];
5476    this.removedNodes = [];
5477    this.previousSibling = null;
5478    this.nextSibling = null;
5479    this.attributeName = null;
5480    this.attributeNamespace = null;
5481    this.oldValue = null;
5482  }
5483  function copyMutationRecord(original) {
5484    var record = new MutationRecord(original.type, original.target);
5485    record.addedNodes = original.addedNodes.slice();
5486    record.removedNodes = original.removedNodes.slice();
5487    record.previousSibling = original.previousSibling;
5488    record.nextSibling = original.nextSibling;
5489    record.attributeName = original.attributeName;
5490    record.attributeNamespace = original.attributeNamespace;
5491    record.oldValue = original.oldValue;
5492    return record;
5493  }
5494  var currentRecord, recordWithOldValue;
5495  function getRecord(type, target) {
5496    return currentRecord = new MutationRecord(type, target);
5497  }
5498  function getRecordWithOldValue(oldValue) {
5499    if (recordWithOldValue) return recordWithOldValue;
5500    recordWithOldValue = copyMutationRecord(currentRecord);
5501    recordWithOldValue.oldValue = oldValue;
5502    return recordWithOldValue;
5503  }
5504  function clearRecords() {
5505    currentRecord = recordWithOldValue = undefined;
5506  }
5507  function recordRepresentsCurrentMutation(record) {
5508    return record === recordWithOldValue || record === currentRecord;
5509  }
5510  function selectRecord(lastRecord, newRecord) {
5511    if (lastRecord === newRecord) return lastRecord;
5512    if (recordWithOldValue && recordRepresentsCurrentMutation(lastRecord)) return recordWithOldValue;
5513    return null;
5514  }
5515  function Registration(observer, target, options) {
5516    this.observer = observer;
5517    this.target = target;
5518    this.options = options;
5519    this.transientObservedNodes = [];
5520  }
5521  Registration.prototype = {
5522    enqueue: function(record) {
5523      var records = this.observer.records_;
5524      var length = records.length;
5525      if (records.length > 0) {
5526        var lastRecord = records[length - 1];
5527        var recordToReplaceLast = selectRecord(lastRecord, record);
5528        if (recordToReplaceLast) {
5529          records[length - 1] = recordToReplaceLast;
5530          return;
5531        }
5532      } else {
5533        scheduleCallback(this.observer);
5534      }
5535      records[length] = record;
5536    },
5537    addListeners: function() {
5538      this.addListeners_(this.target);
5539    },
5540    addListeners_: function(node) {
5541      var options = this.options;
5542      if (options.attributes) node.addEventListener("DOMAttrModified", this, true);
5543      if (options.characterData) node.addEventListener("DOMCharacterDataModified", this, true);
5544      if (options.childList) node.addEventListener("DOMNodeInserted", this, true);
5545      if (options.childList || options.subtree) node.addEventListener("DOMNodeRemoved", this, true);
5546    },
5547    removeListeners: function() {
5548      this.removeListeners_(this.target);
5549    },
5550    removeListeners_: function(node) {
5551      var options = this.options;
5552      if (options.attributes) node.removeEventListener("DOMAttrModified", this, true);
5553      if (options.characterData) node.removeEventListener("DOMCharacterDataModified", this, true);
5554      if (options.childList) node.removeEventListener("DOMNodeInserted", this, true);
5555      if (options.childList || options.subtree) node.removeEventListener("DOMNodeRemoved", this, true);
5556    },
5557    addTransientObserver: function(node) {
5558      if (node === this.target) return;
5559      this.addListeners_(node);
5560      this.transientObservedNodes.push(node);
5561      var registrations = registrationsTable.get(node);
5562      if (!registrations) registrationsTable.set(node, registrations = []);
5563      registrations.push(this);
5564    },
5565    removeTransientObservers: function() {
5566      var transientObservedNodes = this.transientObservedNodes;
5567      this.transientObservedNodes = [];
5568      transientObservedNodes.forEach(function(node) {
5569        this.removeListeners_(node);
5570        var registrations = registrationsTable.get(node);
5571        for (var i = 0; i < registrations.length; i++) {
5572          if (registrations[i] === this) {
5573            registrations.splice(i, 1);
5574            break;
5575          }
5576        }
5577      }, this);
5578    },
5579    handleEvent: function(e) {
5580      e.stopImmediatePropagation();
5581      switch (e.type) {
5582       case "DOMAttrModified":
5583        var name = e.attrName;
5584        var namespace = e.relatedNode.namespaceURI;
5585        var target = e.target;
5586        var record = new getRecord("attributes", target);
5587        record.attributeName = name;
5588        record.attributeNamespace = namespace;
5589        var oldValue = e.attrChange === MutationEvent.ADDITION ? null : e.prevValue;
5590        forEachAncestorAndObserverEnqueueRecord(target, function(options) {
5591          if (!options.attributes) return;
5592          if (options.attributeFilter && options.attributeFilter.length && options.attributeFilter.indexOf(name) === -1 && options.attributeFilter.indexOf(namespace) === -1) {
5593            return;
5594          }
5595          if (options.attributeOldValue) return getRecordWithOldValue(oldValue);
5596          return record;
5597        });
5598        break;
5599
5600       case "DOMCharacterDataModified":
5601        var target = e.target;
5602        var record = getRecord("characterData", target);
5603        var oldValue = e.prevValue;
5604        forEachAncestorAndObserverEnqueueRecord(target, function(options) {
5605          if (!options.characterData) return;
5606          if (options.characterDataOldValue) return getRecordWithOldValue(oldValue);
5607          return record;
5608        });
5609        break;
5610
5611       case "DOMNodeRemoved":
5612        this.addTransientObserver(e.target);
5613
5614       case "DOMNodeInserted":
5615        var changedNode = e.target;
5616        var addedNodes, removedNodes;
5617        if (e.type === "DOMNodeInserted") {
5618          addedNodes = [ changedNode ];
5619          removedNodes = [];
5620        } else {
5621          addedNodes = [];
5622          removedNodes = [ changedNode ];
5623        }
5624        var previousSibling = changedNode.previousSibling;
5625        var nextSibling = changedNode.nextSibling;
5626        var record = getRecord("childList", e.target.parentNode);
5627        record.addedNodes = addedNodes;
5628        record.removedNodes = removedNodes;
5629        record.previousSibling = previousSibling;
5630        record.nextSibling = nextSibling;
5631        forEachAncestorAndObserverEnqueueRecord(e.relatedNode, function(options) {
5632          if (!options.childList) return;
5633          return record;
5634        });
5635      }
5636      clearRecords();
5637    }
5638  };
5639  global.JsMutationObserver = JsMutationObserver;
5640  if (!global.MutationObserver) global.MutationObserver = JsMutationObserver;
5641})(this);
5642
5643window.HTMLImports = window.HTMLImports || {
5644  flags: {}
5645};
5646
5647(function(scope) {
5648  var IMPORT_LINK_TYPE = "import";
5649  var useNative = Boolean(IMPORT_LINK_TYPE in document.createElement("link"));
5650  var hasShadowDOMPolyfill = Boolean(window.ShadowDOMPolyfill);
5651  var wrap = function(node) {
5652    return hasShadowDOMPolyfill ? ShadowDOMPolyfill.wrapIfNeeded(node) : node;
5653  };
5654  var rootDocument = wrap(document);
5655  var currentScriptDescriptor = {
5656    get: function() {
5657      var script = HTMLImports.currentScript || document.currentScript || (document.readyState !== "complete" ? document.scripts[document.scripts.length - 1] : null);
5658      return wrap(script);
5659    },
5660    configurable: true
5661  };
5662  Object.defineProperty(document, "_currentScript", currentScriptDescriptor);
5663  Object.defineProperty(rootDocument, "_currentScript", currentScriptDescriptor);
5664  var isIE = /Trident|Edge/.test(navigator.userAgent);
5665  function whenReady(callback, doc) {
5666    doc = doc || rootDocument;
5667    whenDocumentReady(function() {
5668      watchImportsLoad(callback, doc);
5669    }, doc);
5670  }
5671  var requiredReadyState = isIE ? "complete" : "interactive";
5672  var READY_EVENT = "readystatechange";
5673  function isDocumentReady(doc) {
5674    return doc.readyState === "complete" || doc.readyState === requiredReadyState;
5675  }
5676  function whenDocumentReady(callback, doc) {
5677    if (!isDocumentReady(doc)) {
5678      var checkReady = function() {
5679        if (doc.readyState === "complete" || doc.readyState === requiredReadyState) {
5680          doc.removeEventListener(READY_EVENT, checkReady);
5681          whenDocumentReady(callback, doc);
5682        }
5683      };
5684      doc.addEventListener(READY_EVENT, checkReady);
5685    } else if (callback) {
5686      callback();
5687    }
5688  }
5689  function markTargetLoaded(event) {
5690    event.target.__loaded = true;
5691  }
5692  function watchImportsLoad(callback, doc) {
5693    var imports = doc.querySelectorAll("link[rel=import]");
5694    var parsedCount = 0, importCount = imports.length, newImports = [], errorImports = [];
5695    function checkDone() {
5696      if (parsedCount == importCount && callback) {
5697        callback({
5698          allImports: imports,
5699          loadedImports: newImports,
5700          errorImports: errorImports
5701        });
5702      }
5703    }
5704    function loadedImport(e) {
5705      markTargetLoaded(e);
5706      newImports.push(this);
5707      parsedCount++;
5708      checkDone();
5709    }
5710    function errorLoadingImport(e) {
5711      errorImports.push(this);
5712      parsedCount++;
5713      checkDone();
5714    }
5715    if (importCount) {
5716      for (var i = 0, imp; i < importCount && (imp = imports[i]); i++) {
5717        if (isImportLoaded(imp)) {
5718          parsedCount++;
5719          checkDone();
5720        } else {
5721          imp.addEventListener("load", loadedImport);
5722          imp.addEventListener("error", errorLoadingImport);
5723        }
5724      }
5725    } else {
5726      checkDone();
5727    }
5728  }
5729  function isImportLoaded(link) {
5730    return useNative ? link.__loaded || link.import && link.import.readyState !== "loading" : link.__importParsed;
5731  }
5732  if (useNative) {
5733    new MutationObserver(function(mxns) {
5734      for (var i = 0, l = mxns.length, m; i < l && (m = mxns[i]); i++) {
5735        if (m.addedNodes) {
5736          handleImports(m.addedNodes);
5737        }
5738      }
5739    }).observe(document.head, {
5740      childList: true
5741    });
5742    function handleImports(nodes) {
5743      for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) {
5744        if (isImport(n)) {
5745          handleImport(n);
5746        }
5747      }
5748    }
5749    function isImport(element) {
5750      return element.localName === "link" && element.rel === "import";
5751    }
5752    function handleImport(element) {
5753      var loaded = element.import;
5754      if (loaded) {
5755        markTargetLoaded({
5756          target: element
5757        });
5758      } else {
5759        element.addEventListener("load", markTargetLoaded);
5760        element.addEventListener("error", markTargetLoaded);
5761      }
5762    }
5763    (function() {
5764      if (document.readyState === "loading") {
5765        var imports = document.querySelectorAll("link[rel=import]");
5766        for (var i = 0, l = imports.length, imp; i < l && (imp = imports[i]); i++) {
5767          handleImport(imp);
5768        }
5769      }
5770    })();
5771  }
5772  whenReady(function(detail) {
5773    HTMLImports.ready = true;
5774    HTMLImports.readyTime = new Date().getTime();
5775    var evt = rootDocument.createEvent("CustomEvent");
5776    evt.initCustomEvent("HTMLImportsLoaded", true, true, detail);
5777    rootDocument.dispatchEvent(evt);
5778  });
5779  scope.IMPORT_LINK_TYPE = IMPORT_LINK_TYPE;
5780  scope.useNative = useNative;
5781  scope.rootDocument = rootDocument;
5782  scope.whenReady = whenReady;
5783  scope.isIE = isIE;
5784})(HTMLImports);
5785
5786(function(scope) {
5787  var modules = [];
5788  var addModule = function(module) {
5789    modules.push(module);
5790  };
5791  var initializeModules = function() {
5792    modules.forEach(function(module) {
5793      module(scope);
5794    });
5795  };
5796  scope.addModule = addModule;
5797  scope.initializeModules = initializeModules;
5798})(HTMLImports);
5799
5800HTMLImports.addModule(function(scope) {
5801  var CSS_URL_REGEXP = /(url\()([^)]*)(\))/g;
5802  var CSS_IMPORT_REGEXP = /(@import[\s]+(?!url\())([^;]*)(;)/g;
5803  var path = {
5804    resolveUrlsInStyle: function(style, linkUrl) {
5805      var doc = style.ownerDocument;
5806      var resolver = doc.createElement("a");
5807      style.textContent = this.resolveUrlsInCssText(style.textContent, linkUrl, resolver);
5808      return style;
5809    },
5810    resolveUrlsInCssText: function(cssText, linkUrl, urlObj) {
5811      var r = this.replaceUrls(cssText, urlObj, linkUrl, CSS_URL_REGEXP);
5812      r = this.replaceUrls(r, urlObj, linkUrl, CSS_IMPORT_REGEXP);
5813      return r;
5814    },
5815    replaceUrls: function(text, urlObj, linkUrl, regexp) {
5816      return text.replace(regexp, function(m, pre, url, post) {
5817        var urlPath = url.replace(/["']/g, "");
5818        if (linkUrl) {
5819          urlPath = new URL(urlPath, linkUrl).href;
5820        }
5821        urlObj.href = urlPath;
5822        urlPath = urlObj.href;
5823        return pre + "'" + urlPath + "'" + post;
5824      });
5825    }
5826  };
5827  scope.path = path;
5828});
5829
5830HTMLImports.addModule(function(scope) {
5831  var xhr = {
5832    async: true,
5833    ok: function(request) {
5834      return request.status >= 200 && request.status < 300 || request.status === 304 || request.status === 0;
5835    },
5836    load: function(url, next, nextContext) {
5837      var request = new XMLHttpRequest();
5838      if (scope.flags.debug || scope.flags.bust) {
5839        url += "?" + Math.random();
5840      }
5841      request.open("GET", url, xhr.async);
5842      request.addEventListener("readystatechange", function(e) {
5843        if (request.readyState === 4) {
5844          var locationHeader = request.getResponseHeader("Location");
5845          var redirectedUrl = null;
5846          if (locationHeader) {
5847            var redirectedUrl = locationHeader.substr(0, 1) === "/" ? location.origin + locationHeader : locationHeader;
5848          }
5849          next.call(nextContext, !xhr.ok(request) && request, request.response || request.responseText, redirectedUrl);
5850        }
5851      });
5852      request.send();
5853      return request;
5854    },
5855    loadDocument: function(url, next, nextContext) {
5856      this.load(url, next, nextContext).responseType = "document";
5857    }
5858  };
5859  scope.xhr = xhr;
5860});
5861
5862HTMLImports.addModule(function(scope) {
5863  var xhr = scope.xhr;
5864  var flags = scope.flags;
5865  var Loader = function(onLoad, onComplete) {
5866    this.cache = {};
5867    this.onload = onLoad;
5868    this.oncomplete = onComplete;
5869    this.inflight = 0;
5870    this.pending = {};
5871  };
5872  Loader.prototype = {
5873    addNodes: function(nodes) {
5874      this.inflight += nodes.length;
5875      for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) {
5876        this.require(n);
5877      }
5878      this.checkDone();
5879    },
5880    addNode: function(node) {
5881      this.inflight++;
5882      this.require(node);
5883      this.checkDone();
5884    },
5885    require: function(elt) {
5886      var url = elt.src || elt.href;
5887      elt.__nodeUrl = url;
5888      if (!this.dedupe(url, elt)) {
5889        this.fetch(url, elt);
5890      }
5891    },
5892    dedupe: function(url, elt) {
5893      if (this.pending[url]) {
5894        this.pending[url].push(elt);
5895        return true;
5896      }
5897      var resource;
5898      if (this.cache[url]) {
5899        this.onload(url, elt, this.cache[url]);
5900        this.tail();
5901        return true;
5902      }
5903      this.pending[url] = [ elt ];
5904      return false;
5905    },
5906    fetch: function(url, elt) {
5907      flags.load && console.log("fetch", url, elt);
5908      if (!url) {
5909        setTimeout(function() {
5910          this.receive(url, elt, {
5911            error: "href must be specified"
5912          }, null);
5913        }.bind(this), 0);
5914      } else if (url.match(/^data:/)) {
5915        var pieces = url.split(",");
5916        var header = pieces[0];
5917        var body = pieces[1];
5918        if (header.indexOf(";base64") > -1) {
5919          body = atob(body);
5920        } else {
5921          body = decodeURIComponent(body);
5922        }
5923        setTimeout(function() {
5924          this.receive(url, elt, null, body);
5925        }.bind(this), 0);
5926      } else {
5927        var receiveXhr = function(err, resource, redirectedUrl) {
5928          this.receive(url, elt, err, resource, redirectedUrl);
5929        }.bind(this);
5930        xhr.load(url, receiveXhr);
5931      }
5932    },
5933    receive: function(url, elt, err, resource, redirectedUrl) {
5934      this.cache[url] = resource;
5935      var $p = this.pending[url];
5936      for (var i = 0, l = $p.length, p; i < l && (p = $p[i]); i++) {
5937        this.onload(url, p, resource, err, redirectedUrl);
5938        this.tail();
5939      }
5940      this.pending[url] = null;
5941    },
5942    tail: function() {
5943      --this.inflight;
5944      this.checkDone();
5945    },
5946    checkDone: function() {
5947      if (!this.inflight) {
5948        this.oncomplete();
5949      }
5950    }
5951  };
5952  scope.Loader = Loader;
5953});
5954
5955HTMLImports.addModule(function(scope) {
5956  var Observer = function(addCallback) {
5957    this.addCallback = addCallback;
5958    this.mo = new MutationObserver(this.handler.bind(this));
5959  };
5960  Observer.prototype = {
5961    handler: function(mutations) {
5962      for (var i = 0, l = mutations.length, m; i < l && (m = mutations[i]); i++) {
5963        if (m.type === "childList" && m.addedNodes.length) {
5964          this.addedNodes(m.addedNodes);
5965        }
5966      }
5967    },
5968    addedNodes: function(nodes) {
5969      if (this.addCallback) {
5970        this.addCallback(nodes);
5971      }
5972      for (var i = 0, l = nodes.length, n, loading; i < l && (n = nodes[i]); i++) {
5973        if (n.children && n.children.length) {
5974          this.addedNodes(n.children);
5975        }
5976      }
5977    },
5978    observe: function(root) {
5979      this.mo.observe(root, {
5980        childList: true,
5981        subtree: true
5982      });
5983    }
5984  };
5985  scope.Observer = Observer;
5986});
5987
5988HTMLImports.addModule(function(scope) {
5989  var path = scope.path;
5990  var rootDocument = scope.rootDocument;
5991  var flags = scope.flags;
5992  var isIE = scope.isIE;
5993  var IMPORT_LINK_TYPE = scope.IMPORT_LINK_TYPE;
5994  var IMPORT_SELECTOR = "link[rel=" + IMPORT_LINK_TYPE + "]";
5995  var importParser = {
5996    documentSelectors: IMPORT_SELECTOR,
5997    importsSelectors: [ IMPORT_SELECTOR, "link[rel=stylesheet]", "style", "script:not([type])", 'script[type="text/javascript"]' ].join(","),
5998    map: {
5999      link: "parseLink",
6000      script: "parseScript",
6001      style: "parseStyle"
6002    },
6003    dynamicElements: [],
6004    parseNext: function() {
6005      var next = this.nextToParse();
6006      if (next) {
6007        this.parse(next);
6008      }
6009    },
6010    parse: function(elt) {
6011      if (this.isParsed(elt)) {
6012        flags.parse && console.log("[%s] is already parsed", elt.localName);
6013        return;
6014      }
6015      var fn = this[this.map[elt.localName]];
6016      if (fn) {
6017        this.markParsing(elt);
6018        fn.call(this, elt);
6019      }
6020    },
6021    parseDynamic: function(elt, quiet) {
6022      this.dynamicElements.push(elt);
6023      if (!quiet) {
6024        this.parseNext();
6025      }
6026    },
6027    markParsing: function(elt) {
6028      flags.parse && console.log("parsing", elt);
6029      this.parsingElement = elt;
6030    },
6031    markParsingComplete: function(elt) {
6032      elt.__importParsed = true;
6033      this.markDynamicParsingComplete(elt);
6034      if (elt.__importElement) {
6035        elt.__importElement.__importParsed = true;
6036        this.markDynamicParsingComplete(elt.__importElement);
6037      }
6038      this.parsingElement = null;
6039      flags.parse && console.log("completed", elt);
6040    },
6041    markDynamicParsingComplete: function(elt) {
6042      var i = this.dynamicElements.indexOf(elt);
6043      if (i >= 0) {
6044        this.dynamicElements.splice(i, 1);
6045      }
6046    },
6047    parseImport: function(elt) {
6048      if (HTMLImports.__importsParsingHook) {
6049        HTMLImports.__importsParsingHook(elt);
6050      }
6051      if (elt.import) {
6052        elt.import.__importParsed = true;
6053      }
6054      this.markParsingComplete(elt);
6055      if (elt.__resource && !elt.__error) {
6056        elt.dispatchEvent(new CustomEvent("load", {
6057          bubbles: false
6058        }));
6059      } else {
6060        elt.dispatchEvent(new CustomEvent("error", {
6061          bubbles: false
6062        }));
6063      }
6064      if (elt.__pending) {
6065        var fn;
6066        while (elt.__pending.length) {
6067          fn = elt.__pending.shift();
6068          if (fn) {
6069            fn({
6070              target: elt
6071            });
6072          }
6073        }
6074      }
6075      this.parseNext();
6076    },
6077    parseLink: function(linkElt) {
6078      if (nodeIsImport(linkElt)) {
6079        this.parseImport(linkElt);
6080      } else {
6081        linkElt.href = linkElt.href;
6082        this.parseGeneric(linkElt);
6083      }
6084    },
6085    parseStyle: function(elt) {
6086      var src = elt;
6087      elt = cloneStyle(elt);
6088      src.__appliedElement = elt;
6089      elt.__importElement = src;
6090      this.parseGeneric(elt);
6091    },
6092    parseGeneric: function(elt) {
6093      this.trackElement(elt);
6094      this.addElementToDocument(elt);
6095    },
6096    rootImportForElement: function(elt) {
6097      var n = elt;
6098      while (n.ownerDocument.__importLink) {
6099        n = n.ownerDocument.__importLink;
6100      }
6101      return n;
6102    },
6103    addElementToDocument: function(elt) {
6104      var port = this.rootImportForElement(elt.__importElement || elt);
6105      port.parentNode.insertBefore(elt, port);
6106    },
6107    trackElement: function(elt, callback) {
6108      var self = this;
6109      var done = function(e) {
6110        if (callback) {
6111          callback(e);
6112        }
6113        self.markParsingComplete(elt);
6114        self.parseNext();
6115      };
6116      elt.addEventListener("load", done);
6117      elt.addEventListener("error", done);
6118      if (isIE && elt.localName === "style") {
6119        var fakeLoad = false;
6120        if (elt.textContent.indexOf("@import") == -1) {
6121          fakeLoad = true;
6122        } else if (elt.sheet) {
6123          fakeLoad = true;
6124          var csr = elt.sheet.cssRules;
6125          var len = csr ? csr.length : 0;
6126          for (var i = 0, r; i < len && (r = csr[i]); i++) {
6127            if (r.type === CSSRule.IMPORT_RULE) {
6128              fakeLoad = fakeLoad && Boolean(r.styleSheet);
6129            }
6130          }
6131        }
6132        if (fakeLoad) {
6133          elt.dispatchEvent(new CustomEvent("load", {
6134            bubbles: false
6135          }));
6136        }
6137      }
6138    },
6139    parseScript: function(scriptElt) {
6140      var script = document.createElement("script");
6141      script.__importElement = scriptElt;
6142      script.src = scriptElt.src ? scriptElt.src : generateScriptDataUrl(scriptElt);
6143      scope.currentScript = scriptElt;
6144      this.trackElement(script, function(e) {
6145        script.parentNode.removeChild(script);
6146        scope.currentScript = null;
6147      });
6148      this.addElementToDocument(script);
6149    },
6150    nextToParse: function() {
6151      this._mayParse = [];
6152      return !this.parsingElement && (this.nextToParseInDoc(rootDocument) || this.nextToParseDynamic());
6153    },
6154    nextToParseInDoc: function(doc, link) {
6155      if (doc && this._mayParse.indexOf(doc) < 0) {
6156        this._mayParse.push(doc);
6157        var nodes = doc.querySelectorAll(this.parseSelectorsForNode(doc));
6158        for (var i = 0, l = nodes.length, p = 0, n; i < l && (n = nodes[i]); i++) {
6159          if (!this.isParsed(n)) {
6160            if (this.hasResource(n)) {
6161              return nodeIsImport(n) ? this.nextToParseInDoc(n.import, n) : n;
6162            } else {
6163              return;
6164            }
6165          }
6166        }
6167      }
6168      return link;
6169    },
6170    nextToParseDynamic: function() {
6171      return this.dynamicElements[0];
6172    },
6173    parseSelectorsForNode: function(node) {
6174      var doc = node.ownerDocument || node;
6175      return doc === rootDocument ? this.documentSelectors : this.importsSelectors;
6176    },
6177    isParsed: function(node) {
6178      return node.__importParsed;
6179    },
6180    needsDynamicParsing: function(elt) {
6181      return this.dynamicElements.indexOf(elt) >= 0;
6182    },
6183    hasResource: function(node) {
6184      if (nodeIsImport(node) && node.import === undefined) {
6185        return false;
6186      }
6187      return true;
6188    }
6189  };
6190  function nodeIsImport(elt) {
6191    return elt.localName === "link" && elt.rel === IMPORT_LINK_TYPE;
6192  }
6193  function generateScriptDataUrl(script) {
6194    var scriptContent = generateScriptContent(script);
6195    return "data:text/javascript;charset=utf-8," + encodeURIComponent(scriptContent);
6196  }
6197  function generateScriptContent(script) {
6198    return script.textContent + generateSourceMapHint(script);
6199  }
6200  function generateSourceMapHint(script) {
6201    var owner = script.ownerDocument;
6202    owner.__importedScripts = owner.__importedScripts || 0;
6203    var moniker = script.ownerDocument.baseURI;
6204    var num = owner.__importedScripts ? "-" + owner.__importedScripts : "";
6205    owner.__importedScripts++;
6206    return "\n//# sourceURL=" + moniker + num + ".js\n";
6207  }
6208  function cloneStyle(style) {
6209    var clone = style.ownerDocument.createElement("style");
6210    clone.textContent = style.textContent;
6211    path.resolveUrlsInStyle(clone);
6212    return clone;
6213  }
6214  scope.parser = importParser;
6215  scope.IMPORT_SELECTOR = IMPORT_SELECTOR;
6216});
6217
6218HTMLImports.addModule(function(scope) {
6219  var flags = scope.flags;
6220  var IMPORT_LINK_TYPE = scope.IMPORT_LINK_TYPE;
6221  var IMPORT_SELECTOR = scope.IMPORT_SELECTOR;
6222  var rootDocument = scope.rootDocument;
6223  var Loader = scope.Loader;
6224  var Observer = scope.Observer;
6225  var parser = scope.parser;
6226  var importer = {
6227    documents: {},
6228    documentPreloadSelectors: IMPORT_SELECTOR,
6229    importsPreloadSelectors: [ IMPORT_SELECTOR ].join(","),
6230    loadNode: function(node) {
6231      importLoader.addNode(node);
6232    },
6233    loadSubtree: function(parent) {
6234      var nodes = this.marshalNodes(parent);
6235      importLoader.addNodes(nodes);
6236    },
6237    marshalNodes: function(parent) {
6238      return parent.querySelectorAll(this.loadSelectorsForNode(parent));
6239    },
6240    loadSelectorsForNode: function(node) {
6241      var doc = node.ownerDocument || node;
6242      return doc === rootDocument ? this.documentPreloadSelectors : this.importsPreloadSelectors;
6243    },
6244    loaded: function(url, elt, resource, err, redirectedUrl) {
6245      flags.load && console.log("loaded", url, elt);
6246      elt.__resource = resource;
6247      elt.__error = err;
6248      if (isImportLink(elt)) {
6249        var doc = this.documents[url];
6250        if (doc === undefined) {
6251          doc = err ? null : makeDocument(resource, redirectedUrl || url);
6252          if (doc) {
6253            doc.__importLink = elt;
6254            this.bootDocument(doc);
6255          }
6256          this.documents[url] = doc;
6257        }
6258        elt.import = doc;
6259      }
6260      parser.parseNext();
6261    },
6262    bootDocument: function(doc) {
6263      this.loadSubtree(doc);
6264      this.observer.observe(doc);
6265      parser.parseNext();
6266    },
6267    loadedAll: function() {
6268      parser.parseNext();
6269    }
6270  };
6271  var importLoader = new Loader(importer.loaded.bind(importer), importer.loadedAll.bind(importer));
6272  importer.observer = new Observer();
6273  function isImportLink(elt) {
6274    return isLinkRel(elt, IMPORT_LINK_TYPE);
6275  }
6276  function isLinkRel(elt, rel) {
6277    return elt.localName === "link" && elt.getAttribute("rel") === rel;
6278  }
6279  function hasBaseURIAccessor(doc) {
6280    return !!Object.getOwnPropertyDescriptor(doc, "baseURI");
6281  }
6282  function makeDocument(resource, url) {
6283    var doc = document.implementation.createHTMLDocument(IMPORT_LINK_TYPE);
6284    doc._URL = url;
6285    var base = doc.createElement("base");
6286    base.setAttribute("href", url);
6287    if (!doc.baseURI && !hasBaseURIAccessor(doc)) {
6288      Object.defineProperty(doc, "baseURI", {
6289        value: url
6290      });
6291    }
6292    var meta = doc.createElement("meta");
6293    meta.setAttribute("charset", "utf-8");
6294    doc.head.appendChild(meta);
6295    doc.head.appendChild(base);
6296    doc.body.innerHTML = resource;
6297    if (window.HTMLTemplateElement && HTMLTemplateElement.bootstrap) {
6298      HTMLTemplateElement.bootstrap(doc);
6299    }
6300    return doc;
6301  }
6302  if (!document.baseURI) {
6303    var baseURIDescriptor = {
6304      get: function() {
6305        var base = document.querySelector("base");
6306        return base ? base.href : window.location.href;
6307      },
6308      configurable: true
6309    };
6310    Object.defineProperty(document, "baseURI", baseURIDescriptor);
6311    Object.defineProperty(rootDocument, "baseURI", baseURIDescriptor);
6312  }
6313  scope.importer = importer;
6314  scope.importLoader = importLoader;
6315});
6316
6317HTMLImports.addModule(function(scope) {
6318  var parser = scope.parser;
6319  var importer = scope.importer;
6320  var dynamic = {
6321    added: function(nodes) {
6322      var owner, parsed, loading;
6323      for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) {
6324        if (!owner) {
6325          owner = n.ownerDocument;
6326          parsed = parser.isParsed(owner);
6327        }
6328        loading = this.shouldLoadNode(n);
6329        if (loading) {
6330          importer.loadNode(n);
6331        }
6332        if (this.shouldParseNode(n) && parsed) {
6333          parser.parseDynamic(n, loading);
6334        }
6335      }
6336    },
6337    shouldLoadNode: function(node) {
6338      return node.nodeType === 1 && matches.call(node, importer.loadSelectorsForNode(node));
6339    },
6340    shouldParseNode: function(node) {
6341      return node.nodeType === 1 && matches.call(node, parser.parseSelectorsForNode(node));
6342    }
6343  };
6344  importer.observer.addCallback = dynamic.added.bind(dynamic);
6345  var matches = HTMLElement.prototype.matches || HTMLElement.prototype.matchesSelector || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector || HTMLElement.prototype.msMatchesSelector;
6346});
6347
6348(function(scope) {
6349  var initializeModules = scope.initializeModules;
6350  var isIE = scope.isIE;
6351  if (scope.useNative) {
6352    return;
6353  }
6354  if (isIE && typeof window.CustomEvent !== "function") {
6355    window.CustomEvent = function(inType, params) {
6356      params = params || {};
6357      var e = document.createEvent("CustomEvent");
6358      e.initCustomEvent(inType, Boolean(params.bubbles), Boolean(params.cancelable), params.detail);
6359      return e;
6360    };
6361    window.CustomEvent.prototype = window.Event.prototype;
6362  }
6363  initializeModules();
6364  var rootDocument = scope.rootDocument;
6365  function bootstrap() {
6366    HTMLImports.importer.bootDocument(rootDocument);
6367  }
6368  if (document.readyState === "complete" || document.readyState === "interactive" && !window.attachEvent) {
6369    bootstrap();
6370  } else {
6371    document.addEventListener("DOMContentLoaded", bootstrap);
6372  }
6373})(HTMLImports);
6374
6375window.CustomElements = window.CustomElements || {
6376  flags: {}
6377};
6378
6379(function(scope) {
6380  var flags = scope.flags;
6381  var modules = [];
6382  var addModule = function(module) {
6383    modules.push(module);
6384  };
6385  var initializeModules = function() {
6386    modules.forEach(function(module) {
6387      module(scope);
6388    });
6389  };
6390  scope.addModule = addModule;
6391  scope.initializeModules = initializeModules;
6392  scope.hasNative = Boolean(document.registerElement);
6393  scope.useNative = !flags.register && scope.hasNative && !window.ShadowDOMPolyfill && (!window.HTMLImports || HTMLImports.useNative);
6394})(CustomElements);
6395
6396CustomElements.addModule(function(scope) {
6397  var IMPORT_LINK_TYPE = window.HTMLImports ? HTMLImports.IMPORT_LINK_TYPE : "none";
6398  function forSubtree(node, cb) {
6399    findAllElements(node, function(e) {
6400      if (cb(e)) {
6401        return true;
6402      }
6403      forRoots(e, cb);
6404    });
6405    forRoots(node, cb);
6406  }
6407  function findAllElements(node, find, data) {
6408    var e = node.firstElementChild;
6409    if (!e) {
6410      e = node.firstChild;
6411      while (e && e.nodeType !== Node.ELEMENT_NODE) {
6412        e = e.nextSibling;
6413      }
6414    }
6415    while (e) {
6416      if (find(e, data) !== true) {
6417        findAllElements(e, find, data);
6418      }
6419      e = e.nextElementSibling;
6420    }
6421    return null;
6422  }
6423  function forRoots(node, cb) {
6424    var root = node.shadowRoot;
6425    while (root) {
6426      forSubtree(root, cb);
6427      root = root.olderShadowRoot;
6428    }
6429  }
6430  function forDocumentTree(doc, cb) {
6431    _forDocumentTree(doc, cb, []);
6432  }
6433  function _forDocumentTree(doc, cb, processingDocuments) {
6434    doc = wrap(doc);
6435    if (processingDocuments.indexOf(doc) >= 0) {
6436      return;
6437    }
6438    processingDocuments.push(doc);
6439    var imports = doc.querySelectorAll("link[rel=" + IMPORT_LINK_TYPE + "]");
6440    for (var i = 0, l = imports.length, n; i < l && (n = imports[i]); i++) {
6441      if (n.import) {
6442        _forDocumentTree(n.import, cb, processingDocuments);
6443      }
6444    }
6445    cb(doc);
6446  }
6447  scope.forDocumentTree = forDocumentTree;
6448  scope.forSubtree = forSubtree;
6449});
6450
6451CustomElements.addModule(function(scope) {
6452  var flags = scope.flags;
6453  var forSubtree = scope.forSubtree;
6454  var forDocumentTree = scope.forDocumentTree;
6455  function addedNode(node) {
6456    return added(node) || addedSubtree(node);
6457  }
6458  function added(node) {
6459    if (scope.upgrade(node)) {
6460      return true;
6461    }
6462    attached(node);
6463  }
6464  function addedSubtree(node) {
6465    forSubtree(node, function(e) {
6466      if (added(e)) {
6467        return true;
6468      }
6469    });
6470  }
6471  function attachedNode(node) {
6472    attached(node);
6473    if (inDocument(node)) {
6474      forSubtree(node, function(e) {
6475        attached(e);
6476      });
6477    }
6478  }
6479  var hasPolyfillMutations = !window.MutationObserver || window.MutationObserver === window.JsMutationObserver;
6480  scope.hasPolyfillMutations = hasPolyfillMutations;
6481  var isPendingMutations = false;
6482  var pendingMutations = [];
6483  function deferMutation(fn) {
6484    pendingMutations.push(fn);
6485    if (!isPendingMutations) {
6486      isPendingMutations = true;
6487      setTimeout(takeMutations);
6488    }
6489  }
6490  function takeMutations() {
6491    isPendingMutations = false;
6492    var $p = pendingMutations;
6493    for (var i = 0, l = $p.length, p; i < l && (p = $p[i]); i++) {
6494      p();
6495    }
6496    pendingMutations = [];
6497  }
6498  function attached(element) {
6499    if (hasPolyfillMutations) {
6500      deferMutation(function() {
6501        _attached(element);
6502      });
6503    } else {
6504      _attached(element);
6505    }
6506  }
6507  function _attached(element) {
6508    if (element.__upgraded__ && (element.attachedCallback || element.detachedCallback)) {
6509      if (!element.__attached && inDocument(element)) {
6510        element.__attached = true;
6511        if (element.attachedCallback) {
6512          element.attachedCallback();
6513        }
6514      }
6515    }
6516  }
6517  function detachedNode(node) {
6518    detached(node);
6519    forSubtree(node, function(e) {
6520      detached(e);
6521    });
6522  }
6523  function detached(element) {
6524    if (hasPolyfillMutations) {
6525      deferMutation(function() {
6526        _detached(element);
6527      });
6528    } else {
6529      _detached(element);
6530    }
6531  }
6532  function _detached(element) {
6533    if (element.__upgraded__ && (element.attachedCallback || element.detachedCallback)) {
6534      if (element.__attached && !inDocument(element)) {
6535        element.__attached = false;
6536        if (element.detachedCallback) {
6537          element.detachedCallback();
6538        }
6539      }
6540    }
6541  }
6542  function inDocument(element) {
6543    var p = element;
6544    var doc = wrap(document);
6545    while (p) {
6546      if (p == doc) {
6547        return true;
6548      }
6549      p = p.parentNode || p.nodeType === Node.DOCUMENT_FRAGMENT_NODE && p.host;
6550    }
6551  }
6552  function watchShadow(node) {
6553    if (node.shadowRoot && !node.shadowRoot.__watched) {
6554      flags.dom && console.log("watching shadow-root for: ", node.localName);
6555      var root = node.shadowRoot;
6556      while (root) {
6557        observe(root);
6558        root = root.olderShadowRoot;
6559      }
6560    }
6561  }
6562  function handler(mutations) {
6563    if (flags.dom) {
6564      var mx = mutations[0];
6565      if (mx && mx.type === "childList" && mx.addedNodes) {
6566        if (mx.addedNodes) {
6567          var d = mx.addedNodes[0];
6568          while (d && d !== document && !d.host) {
6569            d = d.parentNode;
6570          }
6571          var u = d && (d.URL || d._URL || d.host && d.host.localName) || "";
6572          u = u.split("/?").shift().split("/").pop();
6573        }
6574      }
6575      console.group("mutations (%d) [%s]", mutations.length, u || "");
6576    }
6577    mutations.forEach(function(mx) {
6578      if (mx.type === "childList") {
6579        forEach(mx.addedNodes, function(n) {
6580          if (!n.localName) {
6581            return;
6582          }
6583          addedNode(n);
6584        });
6585        forEach(mx.removedNodes, function(n) {
6586          if (!n.localName) {
6587            return;
6588          }
6589          detachedNode(n);
6590        });
6591      }
6592    });
6593    flags.dom && console.groupEnd();
6594  }
6595  function takeRecords(node) {
6596    node = wrap(node);
6597    if (!node) {
6598      node = wrap(document);
6599    }
6600    while (node.parentNode) {
6601      node = node.parentNode;
6602    }
6603    var observer = node.__observer;
6604    if (observer) {
6605      handler(observer.takeRecords());
6606      takeMutations();
6607    }
6608  }
6609  var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
6610  function observe(inRoot) {
6611    if (inRoot.__observer) {
6612      return;
6613    }
6614    var observer = new MutationObserver(handler);
6615    observer.observe(inRoot, {
6616      childList: true,
6617      subtree: true
6618    });
6619    inRoot.__observer = observer;
6620  }
6621  function upgradeDocument(doc) {
6622    doc = wrap(doc);
6623    flags.dom && console.group("upgradeDocument: ", doc.baseURI.split("/").pop());
6624    addedNode(doc);
6625    observe(doc);
6626    flags.dom && console.groupEnd();
6627  }
6628  function upgradeDocumentTree(doc) {
6629    forDocumentTree(doc, upgradeDocument);
6630  }
6631  var originalCreateShadowRoot = Element.prototype.createShadowRoot;
6632  if (originalCreateShadowRoot) {
6633    Element.prototype.createShadowRoot = function() {
6634      var root = originalCreateShadowRoot.call(this);
6635      CustomElements.watchShadow(this);
6636      return root;
6637    };
6638  }
6639  scope.watchShadow = watchShadow;
6640  scope.upgradeDocumentTree = upgradeDocumentTree;
6641  scope.upgradeSubtree = addedSubtree;
6642  scope.upgradeAll = addedNode;
6643  scope.attachedNode = attachedNode;
6644  scope.takeRecords = takeRecords;
6645});
6646
6647CustomElements.addModule(function(scope) {
6648  var flags = scope.flags;
6649  function upgrade(node) {
6650    if (!node.__upgraded__ && node.nodeType === Node.ELEMENT_NODE) {
6651      var is = node.getAttribute("is");
6652      var definition = scope.getRegisteredDefinition(is || node.localName);
6653      if (definition) {
6654        if (is && definition.tag == node.localName) {
6655          return upgradeWithDefinition(node, definition);
6656        } else if (!is && !definition.extends) {
6657          return upgradeWithDefinition(node, definition);
6658        }
6659      }
6660    }
6661  }
6662  function upgradeWithDefinition(element, definition) {
6663    flags.upgrade && console.group("upgrade:", element.localName);
6664    if (definition.is) {
6665      element.setAttribute("is", definition.is);
6666    }
6667    implementPrototype(element, definition);
6668    element.__upgraded__ = true;
6669    created(element);
6670    scope.attachedNode(element);
6671    scope.upgradeSubtree(element);
6672    flags.upgrade && console.groupEnd();
6673    return element;
6674  }
6675  function implementPrototype(element, definition) {
6676    if (Object.__proto__) {
6677      element.__proto__ = definition.prototype;
6678    } else {
6679      customMixin(element, definition.prototype, definition.native);
6680      element.__proto__ = definition.prototype;
6681    }
6682  }
6683  function customMixin(inTarget, inSrc, inNative) {
6684    var used = {};
6685    var p = inSrc;
6686    while (p !== inNative && p !== HTMLElement.prototype) {
6687      var keys = Object.getOwnPropertyNames(p);
6688      for (var i = 0, k; k = keys[i]; i++) {
6689        if (!used[k]) {
6690          Object.defineProperty(inTarget, k, Object.getOwnPropertyDescriptor(p, k));
6691          used[k] = 1;
6692        }
6693      }
6694      p = Object.getPrototypeOf(p);
6695    }
6696  }
6697  function created(element) {
6698    if (element.createdCallback) {
6699      element.createdCallback();
6700    }
6701  }
6702  scope.upgrade = upgrade;
6703  scope.upgradeWithDefinition = upgradeWithDefinition;
6704  scope.implementPrototype = implementPrototype;
6705});
6706
6707CustomElements.addModule(function(scope) {
6708  var isIE11OrOlder = scope.isIE11OrOlder;
6709  var upgradeDocumentTree = scope.upgradeDocumentTree;
6710  var upgradeAll = scope.upgradeAll;
6711  var upgradeWithDefinition = scope.upgradeWithDefinition;
6712  var implementPrototype = scope.implementPrototype;
6713  var useNative = scope.useNative;
6714  function register(name, options) {
6715    var definition = options || {};
6716    if (!name) {
6717      throw new Error("document.registerElement: first argument `name` must not be empty");
6718    }
6719    if (name.indexOf("-") < 0) {
6720      throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '" + String(name) + "'.");
6721    }
6722    if (isReservedTag(name)) {
6723      throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '" + String(name) + "'. The type name is invalid.");
6724    }
6725    if (getRegisteredDefinition(name)) {
6726      throw new Error("DuplicateDefinitionError: a type with name '" + String(name) + "' is already registered");
6727    }
6728    if (!definition.prototype) {
6729      definition.prototype = Object.create(HTMLElement.prototype);
6730    }
6731    definition.__name = name.toLowerCase();
6732    definition.lifecycle = definition.lifecycle || {};
6733    definition.ancestry = ancestry(definition.extends);
6734    resolveTagName(definition);
6735    resolvePrototypeChain(definition);
6736    overrideAttributeApi(definition.prototype);
6737    registerDefinition(definition.__name, definition);
6738    definition.ctor = generateConstructor(definition);
6739    definition.ctor.prototype = definition.prototype;
6740    definition.prototype.constructor = definition.ctor;
6741    if (scope.ready) {
6742      upgradeDocumentTree(document);
6743    }
6744    return definition.ctor;
6745  }
6746  function overrideAttributeApi(prototype) {
6747    if (prototype.setAttribute._polyfilled) {
6748      return;
6749    }
6750    var setAttribute = prototype.setAttribute;
6751    prototype.setAttribute = function(name, value) {
6752      changeAttribute.call(this, name, value, setAttribute);
6753    };
6754    var removeAttribute = prototype.removeAttribute;
6755    prototype.removeAttribute = function(name) {
6756      changeAttribute.call(this, name, null, removeAttribute);
6757    };
6758    prototype.setAttribute._polyfilled = true;
6759  }
6760  function changeAttribute(name, value, operation) {
6761    name = name.toLowerCase();
6762    var oldValue = this.getAttribute(name);
6763    operation.apply(this, arguments);
6764    var newValue = this.getAttribute(name);
6765    if (this.attributeChangedCallback && newValue !== oldValue) {
6766      this.attributeChangedCallback(name, oldValue, newValue);
6767    }
6768  }
6769  function isReservedTag(name) {
6770    for (var i = 0; i < reservedTagList.length; i++) {
6771      if (name === reservedTagList[i]) {
6772        return true;
6773      }
6774    }
6775  }
6776  var reservedTagList = [ "annotation-xml", "color-profile", "font-face", "font-face-src", "font-face-uri", "font-face-format", "font-face-name", "missing-glyph" ];
6777  function ancestry(extnds) {
6778    var extendee = getRegisteredDefinition(extnds);
6779    if (extendee) {
6780      return ancestry(extendee.extends).concat([ extendee ]);
6781    }
6782    return [];
6783  }
6784  function resolveTagName(definition) {
6785    var baseTag = definition.extends;
6786    for (var i = 0, a; a = definition.ancestry[i]; i++) {
6787      baseTag = a.is && a.tag;
6788    }
6789    definition.tag = baseTag || definition.__name;
6790    if (baseTag) {
6791      definition.is = definition.__name;
6792    }
6793  }
6794  function resolvePrototypeChain(definition) {
6795    if (!Object.__proto__) {
6796      var nativePrototype = HTMLElement.prototype;
6797      if (definition.is) {
6798        var inst = document.createElement(definition.tag);
6799        var expectedPrototype = Object.getPrototypeOf(inst);
6800        if (expectedPrototype === definition.prototype) {
6801          nativePrototype = expectedPrototype;
6802        }
6803      }
6804      var proto = definition.prototype, ancestor;
6805      while (proto && proto !== nativePrototype) {
6806        ancestor = Object.getPrototypeOf(proto);
6807        proto.__proto__ = ancestor;
6808        proto = ancestor;
6809      }
6810      definition.native = nativePrototype;
6811    }
6812  }
6813  function instantiate(definition) {
6814    return upgradeWithDefinition(domCreateElement(definition.tag), definition);
6815  }
6816  var registry = {};
6817  function getRegisteredDefinition(name) {
6818    if (name) {
6819      return registry[name.toLowerCase()];
6820    }
6821  }
6822  function registerDefinition(name, definition) {
6823    registry[name] = definition;
6824  }
6825  function generateConstructor(definition) {
6826    return function() {
6827      return instantiate(definition);
6828    };
6829  }
6830  var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
6831  function createElementNS(namespace, tag, typeExtension) {
6832    if (namespace === HTML_NAMESPACE) {
6833      return createElement(tag, typeExtension);
6834    } else {
6835      return domCreateElementNS(namespace, tag);
6836    }
6837  }
6838  function createElement(tag, typeExtension) {
6839    var definition = getRegisteredDefinition(typeExtension || tag);
6840    if (definition) {
6841      if (tag == definition.tag && typeExtension == definition.is) {
6842        return new definition.ctor();
6843      }
6844      if (!typeExtension && !definition.is) {
6845        return new definition.ctor();
6846      }
6847    }
6848    var element;
6849    if (typeExtension) {
6850      element = createElement(tag);
6851      element.setAttribute("is", typeExtension);
6852      return element;
6853    }
6854    element = domCreateElement(tag);
6855    if (tag.indexOf("-") >= 0) {
6856      implementPrototype(element, HTMLElement);
6857    }
6858    return element;
6859  }
6860  var domCreateElement = document.createElement.bind(document);
6861  var domCreateElementNS = document.createElementNS.bind(document);
6862  var isInstance;
6863  if (!Object.__proto__ && !useNative) {
6864    isInstance = function(obj, ctor) {
6865      var p = obj;
6866      while (p) {
6867        if (p === ctor.prototype) {
6868          return true;
6869        }
6870        p = p.__proto__;
6871      }
6872      return false;
6873    };
6874  } else {
6875    isInstance = function(obj, base) {
6876      return obj instanceof base;
6877    };
6878  }
6879  function wrapDomMethodToForceUpgrade(obj, methodName) {
6880    var orig = obj[methodName];
6881    obj[methodName] = function() {
6882      var n = orig.apply(this, arguments);
6883      upgradeAll(n);
6884      return n;
6885    };
6886  }
6887  wrapDomMethodToForceUpgrade(Node.prototype, "cloneNode");
6888  wrapDomMethodToForceUpgrade(document, "importNode");
6889  if (isIE11OrOlder) {
6890    (function() {
6891      var importNode = document.importNode;
6892      document.importNode = function() {
6893        var n = importNode.apply(document, arguments);
6894        if (n.nodeType == n.DOCUMENT_FRAGMENT_NODE) {
6895          var f = document.createDocumentFragment();
6896          f.appendChild(n);
6897          return f;
6898        } else {
6899          return n;
6900        }
6901      };
6902    })();
6903  }
6904  document.registerElement = register;
6905  document.createElement = createElement;
6906  document.createElementNS = createElementNS;
6907  scope.registry = registry;
6908  scope.instanceof = isInstance;
6909  scope.reservedTagList = reservedTagList;
6910  scope.getRegisteredDefinition = getRegisteredDefinition;
6911  document.register = document.registerElement;
6912});
6913
6914(function(scope) {
6915  var useNative = scope.useNative;
6916  var initializeModules = scope.initializeModules;
6917  var isIE11OrOlder = /Trident/.test(navigator.userAgent);
6918  if (useNative) {
6919    var nop = function() {};
6920    scope.watchShadow = nop;
6921    scope.upgrade = nop;
6922    scope.upgradeAll = nop;
6923    scope.upgradeDocumentTree = nop;
6924    scope.upgradeSubtree = nop;
6925    scope.takeRecords = nop;
6926    scope.instanceof = function(obj, base) {
6927      return obj instanceof base;
6928    };
6929  } else {
6930    initializeModules();
6931  }
6932  var upgradeDocumentTree = scope.upgradeDocumentTree;
6933  if (!window.wrap) {
6934    if (window.ShadowDOMPolyfill) {
6935      window.wrap = ShadowDOMPolyfill.wrapIfNeeded;
6936      window.unwrap = ShadowDOMPolyfill.unwrapIfNeeded;
6937    } else {
6938      window.wrap = window.unwrap = function(node) {
6939        return node;
6940      };
6941    }
6942  }
6943  function bootstrap() {
6944    upgradeDocumentTree(wrap(document));
6945    if (window.HTMLImports) {
6946      HTMLImports.__importsParsingHook = function(elt) {
6947        upgradeDocumentTree(wrap(elt.import));
6948      };
6949    }
6950    CustomElements.ready = true;
6951    setTimeout(function() {
6952      CustomElements.readyTime = Date.now();
6953      if (window.HTMLImports) {
6954        CustomElements.elapsed = CustomElements.readyTime - HTMLImports.readyTime;
6955      }
6956      document.dispatchEvent(new CustomEvent("WebComponentsReady", {
6957        bubbles: true
6958      }));
6959    });
6960  }
6961  if (isIE11OrOlder && typeof window.CustomEvent !== "function") {
6962    window.CustomEvent = function(inType, params) {
6963      params = params || {};
6964      var e = document.createEvent("CustomEvent");
6965      e.initCustomEvent(inType, Boolean(params.bubbles), Boolean(params.cancelable), params.detail);
6966      return e;
6967    };
6968    window.CustomEvent.prototype = window.Event.prototype;
6969  }
6970  if (document.readyState === "complete" || scope.flags.eager) {
6971    bootstrap();
6972  } else if (document.readyState === "interactive" && !window.attachEvent && (!window.HTMLImports || window.HTMLImports.ready)) {
6973    bootstrap();
6974  } else {
6975    var loadEvent = window.HTMLImports && !HTMLImports.ready ? "HTMLImportsLoaded" : "DOMContentLoaded";
6976    window.addEventListener(loadEvent, bootstrap);
6977  }
6978  scope.isIE11OrOlder = isIE11OrOlder;
6979})(window.CustomElements);
6980
6981(function(scope) {
6982  if (!Function.prototype.bind) {
6983    Function.prototype.bind = function(scope) {
6984      var self = this;
6985      var args = Array.prototype.slice.call(arguments, 1);
6986      return function() {
6987        var args2 = args.slice();
6988        args2.push.apply(args2, arguments);
6989        return self.apply(scope, args2);
6990      };
6991    };
6992  }
6993})(window.WebComponents);
6994
6995(function(scope) {
6996  "use strict";
6997  if (!window.performance) {
6998    var start = Date.now();
6999    window.performance = {
7000      now: function() {
7001        return Date.now() - start;
7002      }
7003    };
7004  }
7005  if (!window.requestAnimationFrame) {
7006    window.requestAnimationFrame = function() {
7007      var nativeRaf = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
7008      return nativeRaf ? function(callback) {
7009        return nativeRaf(function() {
7010          callback(performance.now());
7011        });
7012      } : function(callback) {
7013        return window.setTimeout(callback, 1e3 / 60);
7014      };
7015    }();
7016  }
7017  if (!window.cancelAnimationFrame) {
7018    window.cancelAnimationFrame = function() {
7019      return window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || function(id) {
7020        clearTimeout(id);
7021      };
7022    }();
7023  }
7024  var elementDeclarations = [];
7025  var polymerStub = function(name, dictionary) {
7026    if (typeof name !== "string" && arguments.length === 1) {
7027      Array.prototype.push.call(arguments, document._currentScript);
7028    }
7029    elementDeclarations.push(arguments);
7030  };
7031  window.Polymer = polymerStub;
7032  scope.consumeDeclarations = function(callback) {
7033    scope.consumeDeclarations = function() {
7034      throw "Possible attempt to load Polymer twice";
7035    };
7036    if (callback) {
7037      callback(elementDeclarations);
7038    }
7039    elementDeclarations = null;
7040  };
7041  function installPolymerWarning() {
7042    if (window.Polymer === polymerStub) {
7043      window.Polymer = function() {
7044        throw new Error("You tried to use polymer without loading it first. To " + 'load polymer, <link rel="import" href="' + 'components/polymer/polymer.html">');
7045      };
7046    }
7047  }
7048  if (HTMLImports.useNative) {
7049    installPolymerWarning();
7050  } else {
7051    addEventListener("DOMContentLoaded", installPolymerWarning);
7052  }
7053})(window.WebComponents);
7054
7055(function(scope) {
7056  var style = document.createElement("style");
7057  style.textContent = "" + "body {" + "transition: opacity ease-in 0.2s;" + " } \n" + "body[unresolved] {" + "opacity: 0; display: block; overflow: hidden; position: relative;" + " } \n";
7058  var head = document.querySelector("head");
7059  head.insertBefore(style, head.firstChild);
7060})(window.WebComponents);
7061
7062(function(scope) {
7063  window.Platform = scope;
7064})(window.WebComponents);