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