PageSourceSearch

https://equitablegrowth.org/wp-content/themes/equitable-growth/dist/scripts/main.js?ver=20220001

js equitablegrowth.org collected 2026-09-24 08:38:04 UTC 1,807,767 bytes, 42,386 lines download raw bytes

1/*
2     _ _      _       _
3 ___| (_) ___| | __  (_)___
4/ __| | |/ __| |/ /  | / __|
5\__ \ | | (__|   < _ | \__ \
6|___/_|_|\___|_|\_(_)/ |___/
7                   |__/
8
9 Version: 1.8.0
10  Author: Ken Wheeler
11 Website: http://kenwheeler.github.io
12    Docs: http://kenwheeler.github.io/slick
13    Repo: http://github.com/kenwheeler/slick
14  Issues: http://github.com/kenwheeler/slick/issues
15
16 */
17/* global window, document, define, jQuery, setInterval, clearInterval */
18;(function(factory) {
19    'use strict';
20    if (typeof define === 'function' && define.amd) {
21        define(['jquery'], factory);
22    } else if (typeof exports !== 'undefined') {
23        module.exports = factory(require('jquery'));
24    } else {
25        factory(jQuery);
26    }
27
28}(function($) {
29    'use strict';
30    var Slick = window.Slick || {};
31
32    Slick = (function() {
33
34        var instanceUid = 0;
35
36        function Slick(element, settings) {
37
38            var _ = this, dataSettings;
39
40            _.defaults = {
41                accessibility: true,
42                adaptiveHeight: false,
43                appendArrows: $(element),
44                appendDots: $(element),
45                arrows: true,
46                asNavFor: null,
47                prevArrow: '<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',
48                nextArrow: '<button class="slick-next" aria-label="Next" type="button">Next</button>',
49                autoplay: false,
50                autoplaySpeed: 3000,
51                centerMode: false,
52                centerPadding: '50px',
53                cssEase: 'ease',
54                customPaging: function(slider, i) {
55                    return $('<button type="button" />').text(i + 1);
56                },
57                dots: false,
58                dotsClass: 'slick-dots',
59                draggable: true,
60                easing: 'linear',
61                edgeFriction: 0.35,
62                fade: false,
63                focusOnSelect: false,
64                focusOnChange: false,
65                infinite: true,
66                initialSlide: 0,
67                lazyLoad: 'ondemand',
68                mobileFirst: false,
69                pauseOnHover: true,
70                pauseOnFocus: true,
71                pauseOnDotsHover: false,
72                respondTo: 'window',
73                responsive: null,
74                rows: 1,
75                rtl: false,
76                slide: '',
77                slidesPerRow: 1,
78                slidesToShow: 1,
79                slidesToScroll: 1,
80                speed: 500,
81                swipe: true,
82                swipeToSlide: false,
83                touchMove: true,
84                touchThreshold: 5,
85                useCSS: true,
86                useTransform: true,
87                variableWidth: false,
88                vertical: false,
89                verticalSwiping: false,
90                waitForAnimate: true,
91                zIndex: 1000
92            };
93
94            _.initials = {
95                animating: false,
96                dragging: false,
97                autoPlayTimer: null,
98                currentDirection: 0,
99                currentLeft: null,
100                currentSlide: 0,
101                direction: 1,
102                $dots: null,
103                listWidth: null,
104                listHeight: null,
105                loadIndex: 0,
106                $nextArrow: null,
107                $prevArrow: null,
108                scrolling: false,
109                slideCount: null,
110                slideWidth: null,
111                $slideTrack: null,
112                $slides: null,
113                sliding: false,
114                slideOffset: 0,
115                swipeLeft: null,
116                swiping: false,
117                $list: null,
118                touchObject: {},
119                transformsEnabled: false,
120                unslicked: false
121            };
122
123            $.extend(_, _.initials);
124
125            _.activeBreakpoint = null;
126            _.animType = null;
127            _.animProp = null;
128            _.breakpoints = [];
129            _.breakpointSettings = [];
130            _.cssTransitions = false;
131            _.focussed = false;
132            _.interrupted = false;
133            _.hidden = 'hidden';
134            _.paused = true;
135            _.positionProp = null;
136            _.respondTo = null;
137            _.rowCount = 1;
138            _.shouldClick = true;
139            _.$slider = $(element);
140            _.$slidesCache = null;
141            _.transformType = null;
142            _.transitionType = null;
143            _.visibilityChange = 'visibilitychange';
144            _.windowWidth = 0;
145            _.windowTimer = null;
146
147            dataSettings = $(element).data('slick') || {};
148
149            _.options = $.extend({}, _.defaults, settings, dataSettings);
150
151            _.currentSlide = _.options.initialSlide;
152
153            _.originalSettings = _.options;
154
155            if (typeof document.mozHidden !== 'undefined') {
156                _.hidden = 'mozHidden';
157                _.visibilityChange = 'mozvisibilitychange';
158            } else if (typeof document.webkitHidden !== 'undefined') {
159                _.hidden = 'webkitHidden';
160                _.visibilityChange = 'webkitvisibilitychange';
161            }
162
163            _.autoPlay = $.proxy(_.autoPlay, _);
164            _.autoPlayClear = $.proxy(_.autoPlayClear, _);
165            _.autoPlayIterator = $.proxy(_.autoPlayIterator, _);
166            _.changeSlide = $.proxy(_.changeSlide, _);
167            _.clickHandler = $.proxy(_.clickHandler, _);
168            _.selectHandler = $.proxy(_.selectHandler, _);
169            _.setPosition = $.proxy(_.setPosition, _);
170            _.swipeHandler = $.proxy(_.swipeHandler, _);
171            _.dragHandler = $.proxy(_.dragHandler, _);
172            _.keyHandler = $.proxy(_.keyHandler, _);
173
174            _.instanceUid = instanceUid++;
175
176            // A simple way to check for HTML strings
177            // Strict HTML recognition (must start with <)
178            // Extracted from jQuery v1.11 source
179            _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;
180
181
182            _.registerBreakpoints();
183            _.init(true);
184
185        }
186
187        return Slick;
188
189    }());
190
191    Slick.prototype.activateADA = function() {
192        var _ = this;
193
194        _.$slideTrack.find('.slick-active').attr({
195            'aria-hidden': 'false'
196        }).find('a, input, button, select').attr({
197            'tabindex': '0'
198        });
199
200    };
201
202    Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) {
203
204        var _ = this;
205
206        if (typeof(index) === 'boolean') {
207            addBefore = index;
208            index = null;
209        } else if (index < 0 || (index >= _.slideCount)) {
210            return false;
211        }
212
213        _.unload();
214
215        if (typeof(index) === 'number') {
216            if (index === 0 && _.$slides.length === 0) {
217                $(markup).appendTo(_.$slideTrack);
218            } else if (addBefore) {
219                $(markup).insertBefore(_.$slides.eq(index));
220            } else {
221                $(markup).insertAfter(_.$slides.eq(index));
222            }
223        } else {
224            if (addBefore === true) {
225                $(markup).prependTo(_.$slideTrack);
226            } else {
227                $(markup).appendTo(_.$slideTrack);
228            }
229        }
230
231        _.$slides = _.$slideTrack.children(this.options.slide);
232
233        _.$slideTrack.children(this.options.slide).detach();
234
235        _.$slideTrack.append(_.$slides);
236
237        _.$slides.each(function(index, element) {
238            $(element).attr('data-slick-index', index);
239        });
240
241        _.$slidesCache = _.$slides;
242
243        _.reinit();
244
245    };
246
247    Slick.prototype.animateHeight = function() {
248        var _ = this;
249        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
250            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
251            _.$list.animate({
252                height: targetHeight
253            }, _.options.speed);
254        }
255    };
256
257    Slick.prototype.animateSlide = function(targetLeft, callback) {
258
259        var animProps = {},
260            _ = this;
261
262        _.animateHeight();
263
264        if (_.options.rtl === true && _.options.vertical === false) {
265            targetLeft = -targetLeft;
266        }
267        if (_.transformsEnabled === false) {
268            if (_.options.vertical === false) {
269                _.$slideTrack.animate({
270                    left: targetLeft
271                }, _.options.speed, _.options.easing, callback);
272            } else {
273                _.$slideTrack.animate({
274                    top: targetLeft
275                }, _.options.speed, _.options.easing, callback);
276            }
277
278        } else {
279
280            if (_.cssTransitions === false) {
281                if (_.options.rtl === true) {
282                    _.currentLeft = -(_.currentLeft);
283                }
284                $({
285                    animStart: _.currentLeft
286                }).animate({
287                    animStart: targetLeft
288                }, {
289                    duration: _.options.speed,
290                    easing: _.options.easing,
291                    step: function(now) {
292                        now = Math.ceil(now);
293                        if (_.options.vertical === false) {
294                            animProps[_.animType] = 'translate(' +
295                                now + 'px, 0px)';
296                            _.$slideTrack.css(animProps);
297                        } else {
298                            animProps[_.animType] = 'translate(0px,' +
299                                now + 'px)';
300                            _.$slideTrack.css(animProps);
301                        }
302                    },
303                    complete: function() {
304                        if (callback) {
305                            callback.call();
306                        }
307                    }
308                });
309
310            } else {
311
312                _.applyTransition();
313                targetLeft = Math.ceil(targetLeft);
314
315                if (_.options.vertical === false) {
316                    animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)';
317                } else {
318                    animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)';
319                }
320                _.$slideTrack.css(animProps);
321
322                if (callback) {
323                    setTimeout(function() {
324
325                        _.disableTransition();
326
327                        callback.call();
328                    }, _.options.speed);
329                }
330
331            }
332
333        }
334
335    };
336
337    Slick.prototype.getNavTarget = function() {
338
339        var _ = this,
340            asNavFor = _.options.asNavFor;
341
342        if ( asNavFor && asNavFor !== null ) {
343            asNavFor = $(asNavFor).not(_.$slider);
344        }
345
346        return asNavFor;
347
348    };
349
350    Slick.prototype.asNavFor = function(index) {
351
352        var _ = this,
353            asNavFor = _.getNavTarget();
354
355        if ( asNavFor !== null && typeof asNavFor === 'object' ) {
356            asNavFor.each(function() {
357                var target = $(this).slick('getSlick');
358                if(!target.unslicked) {
359                    target.slideHandler(index, true);
360                }
361            });
362        }
363
364    };
365
366    Slick.prototype.applyTransition = function(slide) {
367
368        var _ = this,
369            transition = {};
370
371        if (_.options.fade === false) {
372            transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase;
373        } else {
374            transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase;
375        }
376
377        if (_.options.fade === false) {
378            _.$slideTrack.css(transition);
379        } else {
380            _.$slides.eq(slide).css(transition);
381        }
382
383    };
384
385    Slick.prototype.autoPlay = function() {
386
387        var _ = this;
388
389        _.autoPlayClear();
390
391        if ( _.slideCount > _.options.slidesToShow ) {
392            _.autoPlayTimer = setInterval( _.autoPlayIterator, _.options.autoplaySpeed );
393        }
394
395    };
396
397    Slick.prototype.autoPlayClear = function() {
398
399        var _ = this;
400
401        if (_.autoPlayTimer) {
402            clearInterval(_.autoPlayTimer);
403        }
404
405    };
406
407    Slick.prototype.autoPlayIterator = function() {
408
409        var _ = this,
410            slideTo = _.currentSlide + _.options.slidesToScroll;
411
412        if ( !_.paused && !_.interrupted && !_.focussed ) {
413
414            if ( _.options.infinite === false ) {
415
416                if ( _.direction === 1 && ( _.currentSlide + 1 ) === ( _.slideCount - 1 )) {
417                    _.direction = 0;
418                }
419
420                else if ( _.direction === 0 ) {
421
422                    slideTo = _.currentSlide - _.options.slidesToScroll;
423
424                    if ( _.currentSlide - 1 === 0 ) {
425                        _.direction = 1;
426                    }
427
428                }
429
430            }
431
432            _.slideHandler( slideTo );
433
434        }
435
436    };
437
438    Slick.prototype.buildArrows = function() {
439
440        var _ = this;
441
442        if (_.options.arrows === true ) {
443
444            _.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow');
445            _.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow');
446
447            if( _.slideCount > _.options.slidesToShow ) {
448
449                _.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
450                _.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
451
452                if (_.htmlExpr.test(_.options.prevArrow)) {
453                    _.$prevArrow.prependTo(_.options.appendArrows);
454                }
455
456                if (_.htmlExpr.test(_.options.nextArrow)) {
457                    _.$nextArrow.appendTo(_.options.appendArrows);
458                }
459
460                if (_.options.infinite !== true) {
461                    _.$prevArrow
462                        .addClass('slick-disabled')
463                        .attr('aria-disabled', 'true');
464                }
465
466            } else {
467
468                _.$prevArrow.add( _.$nextArrow )
469
470                    .addClass('slick-hidden')
471                    .attr({
472                        'aria-disabled': 'true',
473                        'tabindex': '-1'
474                    });
475
476            }
477
478        }
479
480    };
481
482    Slick.prototype.buildDots = function() {
483
484        var _ = this,
485            i, dot;
486
487        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
488
489            _.$slider.addClass('slick-dotted');
490
491            dot = $('<ul />').addClass(_.options.dotsClass);
492
493            for (i = 0; i <= _.getDotCount(); i += 1) {
494                dot.append($('<li />').append(_.options.customPaging.call(this, _, i)));
495            }
496
497            _.$dots = dot.appendTo(_.options.appendDots);
498
499            _.$dots.find('li').first().addClass('slick-active');
500
501        }
502
503    };
504
505    Slick.prototype.buildOut = function() {
506
507        var _ = this;
508
509        _.$slides =
510            _.$slider
511                .children( _.options.slide + ':not(.slick-cloned)')
512                .addClass('slick-slide');
513
514        _.slideCount = _.$slides.length;
515
516        _.$slides.each(function(index, element) {
517            $(element)
518                .attr('data-slick-index', index)
519                .data('originalStyling', $(element).attr('style') || '');
520        });
521
522        _.$slider.addClass('slick-slider');
523
524        _.$slideTrack = (_.slideCount === 0) ?
525            $('<div class="slick-track"/>').appendTo(_.$slider) :
526            _.$slides.wrapAll('<div class="slick-track"/>').parent();
527
528        _.$list = _.$slideTrack.wrap(
529            '<div class="slick-list"/>').parent();
530        _.$slideTrack.css('opacity', 0);
531
532        if (_.options.centerMode === true || _.options.swipeToSlide === true) {
533            _.options.slidesToScroll = 1;
534        }
535
536        $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading');
537
538        _.setupInfinite();
539
540        _.buildArrows();
541
542        _.buildDots();
543
544        _.updateDots();
545
546
547        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);
548
549        if (_.options.draggable === true) {
550            _.$list.addClass('draggable');
551        }
552
553    };
554
555    Slick.prototype.buildRows = function() {
556
557        var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection;
558
559        newSlides = document.createDocumentFragment();
560        originalSlides = _.$slider.children();
561
562        if(_.options.rows > 0) {
563
564            slidesPerSection = _.options.slidesPerRow * _.options.rows;
565            numOfSlides = Math.ceil(
566                originalSlides.length / slidesPerSection
567            );
568
569            for(a = 0; a < numOfSlides; a++){
570                var slide = document.createElement('div');
571                for(b = 0; b < _.options.rows; b++) {
572                    var row = document.createElement('div');
573                    for(c = 0; c < _.options.slidesPerRow; c++) {
574                        var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c));
575                        if (originalSlides.get(target)) {
576                            row.appendChild(originalSlides.get(target));
577                        }
578                    }
579                    slide.appendChild(row);
580                }
581                newSlides.appendChild(slide);
582            }
583
584            _.$slider.empty().append(newSlides);
585            _.$slider.children().children().children()
586                .css({
587                    'width':(100 / _.options.slidesPerRow) + '%',
588                    'display': 'inline-block'
589                });
590
591        }
592
593    };
594
595    Slick.prototype.checkResponsive = function(initial, forceUpdate) {
596
597        var _ = this,
598            breakpoint, targetBreakpoint, respondToWidth, triggerBreakpoint = false;
599        var sliderWidth = _.$slider.width();
600        var windowWidth = window.innerWidth || $(window).width();
601
602        if (_.respondTo === 'window') {
603            respondToWidth = windowWidth;
604        } else if (_.respondTo === 'slider') {
605            respondToWidth = sliderWidth;
606        } else if (_.respondTo === 'min') {
607            respondToWidth = Math.min(windowWidth, sliderWidth);
608        }
609
610        if ( _.options.responsive &&
611            _.options.responsive.length &&
612            _.options.responsive !== null) {
613
614            targetBreakpoint = null;
615
616            for (breakpoint in _.breakpoints) {
617                if (_.breakpoints.hasOwnProperty(breakpoint)) {
618                    if (_.originalSettings.mobileFirst === false) {
619                        if (respondToWidth < _.breakpoints[breakpoint]) {
620                            targetBreakpoint = _.breakpoints[breakpoint];
621                        }
622                    } else {
623                        if (respondToWidth > _.breakpoints[breakpoint]) {
624                            targetBreakpoint = _.breakpoints[breakpoint];
625                        }
626                    }
627                }
628            }
629
630            if (targetBreakpoint !== null) {
631                if (_.activeBreakpoint !== null) {
632                    if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) {
633                        _.activeBreakpoint =
634                            targetBreakpoint;
635                        if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
636                            _.unslick(targetBreakpoint);
637                        } else {
638                            _.options = $.extend({}, _.originalSettings,
639                                _.breakpointSettings[
640                                    targetBreakpoint]);
641                            if (initial === true) {
642                                _.currentSlide = _.options.initialSlide;
643                            }
644                            _.refresh(initial);
645                        }
646                        triggerBreakpoint = targetBreakpoint;
647                    }
648                } else {
649                    _.activeBreakpoint = targetBreakpoint;
650                    if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
651                        _.unslick(targetBreakpoint);
652                    } else {
653                        _.options = $.extend({}, _.originalSettings,
654                            _.breakpointSettings[
655                                targetBreakpoint]);
656                        if (initial === true) {
657                            _.currentSlide = _.options.initialSlide;
658                        }
659                        _.refresh(initial);
660                    }
661                    triggerBreakpoint = targetBreakpoint;
662                }
663            } else {
664                if (_.activeBreakpoint !== null) {
665                    _.activeBreakpoint = null;
666                    _.options = _.originalSettings;
667                    if (initial === true) {
668                        _.currentSlide = _.options.initialSlide;
669                    }
670                    _.refresh(initial);
671                    triggerBreakpoint = targetBreakpoint;
672                }
673            }
674
675            // only trigger breakpoints during an actual break. not on initialize.
676            if( !initial && triggerBreakpoint !== false ) {
677                _.$slider.trigger('breakpoint', [_, triggerBreakpoint]);
678            }
679        }
680
681    };
682
683    Slick.prototype.changeSlide = function(event, dontAnimate) {
684
685        var _ = this,
686            $target = $(event.currentTarget),
687            indexOffset, slideOffset, unevenOffset;
688
689        // If target is a link, prevent default action.
690        if($target.is('a')) {
691            event.preventDefault();
692        }
693
694        // If target is not the <li> element (ie: a child), find the <li>.
695        if(!$target.is('li')) {
696            $target = $target.closest('li');
697        }
698
699        unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0);
700        indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll;
701
702        switch (event.data.message) {
703
704            case 'previous':
705                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset;
706                if (_.slideCount > _.options.slidesToShow) {
707                    _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate);
708                }
709                break;
710
711            case 'next':
712                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset;
713                if (_.slideCount > _.options.slidesToShow) {
714                    _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate);
715                }
716                break;
717
718            case 'index':
719                var index = event.data.index === 0 ? 0 :
720                    event.data.index || $target.index() * _.options.slidesToScroll;
721
722                _.slideHandler(_.checkNavigable(index), false, dontAnimate);
723                $target.children().trigger('focus');
724                break;
725
726            default:
727                return;
728        }
729
730    };
731
732    Slick.prototype.checkNavigable = function(index) {
733
734        var _ = this,
735            navigables, prevNavigable;
736
737        navigables = _.getNavigableIndexes();
738        prevNavigable = 0;
739        if (index > navigables[navigables.length - 1]) {
740            index = navigables[navigables.length - 1];
741        } else {
742            for (var n in navigables) {
743                if (index < navigables[n]) {
744                    index = prevNavigable;
745                    break;
746                }
747                prevNavigable = navigables[n];
748            }
749        }
750
751        return index;
752    };
753
754    Slick.prototype.cleanUpEvents = function() {
755
756        var _ = this;
757
758        if (_.options.dots && _.$dots !== null) {
759
760            $('li', _.$dots)
761                .off('click.slick', _.changeSlide)
762                .off('mouseenter.slick', $.proxy(_.interrupt, _, true))
763                .off('mouseleave.slick', $.proxy(_.interrupt, _, false));
764
765            if (_.options.accessibility === true) {
766                _.$dots.off('keydown.slick', _.keyHandler);
767            }
768        }
769
770        _.$slider.off('focus.slick blur.slick');
771
772        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
773            _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide);
774            _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide);
775
776            if (_.options.accessibility === true) {
777                _.$prevArrow && _.$prevArrow.off('keydown.slick', _.keyHandler);
778                _.$nextArrow && _.$nextArrow.off('keydown.slick', _.keyHandler);
779            }
780        }
781
782        _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler);
783        _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler);
784        _.$list.off('touchend.slick mouseup.slick', _.swipeHandler);
785        _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler);
786
787        _.$list.off('click.slick', _.clickHandler);
788
789        $(document).off(_.visibilityChange, _.visibility);
790
791        _.cleanUpSlideEvents();
792
793        if (_.options.accessibility === true) {
794            _.$list.off('keydown.slick', _.keyHandler);
795        }
796
797        if (_.options.focusOnSelect === true) {
798            $(_.$slideTrack).children().off('click.slick', _.selectHandler);
799        }
800
801        $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange);
802
803        $(window).off('resize.slick.slick-' + _.instanceUid, _.resize);
804
805        $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault);
806
807        $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition);
808
809    };
810
811    Slick.prototype.cleanUpSlideEvents = function() {
812
813        var _ = this;
814
815        _.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true));
816        _.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false));
817
818    };
819
820    Slick.prototype.cleanUpRows = function() {
821
822        var _ = this, originalSlides;
823
824        if(_.options.rows > 0) {
825            originalSlides = _.$slides.children().children();
826            originalSlides.removeAttr('style');
827            _.$slider.empty().append(originalSlides);
828        }
829
830    };
831
832    Slick.prototype.clickHandler = function(event) {
833
834        var _ = this;
835
836        if (_.shouldClick === false) {
837            event.stopImmediatePropagation();
838            event.stopPropagation();
839            event.preventDefault();
840        }
841
842    };
843
844    Slick.prototype.destroy = function(refresh) {
845
846        var _ = this;
847
848        _.autoPlayClear();
849
850        _.touchObject = {};
851
852        _.cleanUpEvents();
853
854        $('.slick-cloned', _.$slider).detach();
855
856        if (_.$dots) {
857            _.$dots.remove();
858        }
859
860        if ( _.$prevArrow && _.$prevArrow.length ) {
861
862            _.$prevArrow
863                .removeClass('slick-disabled slick-arrow slick-hidden')
864                .removeAttr('aria-hidden aria-disabled tabindex')
865                .css('display','');
866
867            if ( _.htmlExpr.test( _.options.prevArrow )) {
868                _.$prevArrow.remove();
869            }
870        }
871
872        if ( _.$nextArrow && _.$nextArrow.length ) {
873
874            _.$nextArrow
875                .removeClass('slick-disabled slick-arrow slick-hidden')
876                .removeAttr('aria-hidden aria-disabled tabindex')
877                .css('display','');
878
879            if ( _.htmlExpr.test( _.options.nextArrow )) {
880                _.$nextArrow.remove();
881            }
882        }
883
884
885        if (_.$slides) {
886
887            _.$slides
888                .removeClass('slick-slide slick-active slick-center slick-visible slick-current')
889                .removeAttr('aria-hidden')
890                .removeAttr('data-slick-index')
891                .each(function(){
892                    $(this).attr('style', $(this).data('originalStyling'));
893                });
894
895            _.$slideTrack.children(this.options.slide).detach();
896
897            _.$slideTrack.detach();
898
899            _.$list.detach();
900
901            _.$slider.append(_.$slides);
902        }
903
904        _.cleanUpRows();
905
906        _.$slider.removeClass('slick-slider');
907        _.$slider.removeClass('slick-initialized');
908        _.$slider.removeClass('slick-dotted');
909
910        _.unslicked = true;
911
912        if(!refresh) {
913            _.$slider.trigger('destroy', [_]);
914        }
915
916    };
917
918    Slick.prototype.disableTransition = function(slide) {
919
920        var _ = this,
921            transition = {};
922
923        transition[_.transitionType] = '';
924
925        if (_.options.fade === false) {
926            _.$slideTrack.css(transition);
927        } else {
928            _.$slides.eq(slide).css(transition);
929        }
930
931    };
932
933    Slick.prototype.fadeSlide = function(slideIndex, callback) {
934
935        var _ = this;
936
937        if (_.cssTransitions === false) {
938
939            _.$slides.eq(slideIndex).css({
940                zIndex: _.options.zIndex
941            });
942
943            _.$slides.eq(slideIndex).animate({
944                opacity: 1
945            }, _.options.speed, _.options.easing, callback);
946
947        } else {
948
949            _.applyTransition(slideIndex);
950
951            _.$slides.eq(slideIndex).css({
952                opacity: 1,
953                zIndex: _.options.zIndex
954            });
955
956            if (callback) {
957                setTimeout(function() {
958
959                    _.disableTransition(slideIndex);
960
961                    callback.call();
962                }, _.options.speed);
963            }
964
965        }
966
967    };
968
969    Slick.prototype.fadeSlideOut = function(slideIndex) {
970
971        var _ = this;
972
973        if (_.cssTransitions === false) {
974
975            _.$slides.eq(slideIndex).animate({
976                opacity: 0,
977                zIndex: _.options.zIndex - 2
978            }, _.options.speed, _.options.easing);
979
980        } else {
981
982            _.applyTransition(slideIndex);
983
984            _.$slides.eq(slideIndex).css({
985                opacity: 0,
986                zIndex: _.options.zIndex - 2
987            });
988
989        }
990
991    };
992
993    Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) {
994
995        var _ = this;
996
997        if (filter !== null) {
998
999            _.$slidesCache = _.$slides;
1000
1001            _.unload();
1002
1003            _.$slideTrack.children(this.options.slide).detach();
1004
1005            _.$slidesCache.filter(filter).appendTo(_.$slideTrack);
1006
1007            _.reinit();
1008
1009        }
1010
1011    };
1012
1013    Slick.prototype.focusHandler = function() {
1014
1015        var _ = this;
1016
1017        _.$slider
1018            .off('focus.slick blur.slick')
1019            .on('focus.slick blur.slick', '*', function(event) {
1020
1021            event.stopImmediatePropagation();
1022            var $sf = $(this);
1023
1024            setTimeout(function() {
1025
1026                if( _.options.pauseOnFocus ) {
1027                    _.focussed = $sf.is(':focus');
1028                    _.autoPlay();
1029                }
1030
1031            }, 0);
1032
1033        });
1034    };
1035
1036    Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() {
1037
1038        var _ = this;
1039        return _.currentSlide;
1040
1041    };
1042
1043    Slick.prototype.getDotCount = function() {
1044
1045        var _ = this;
1046
1047        var breakPoint = 0;
1048        var counter = 0;
1049        var pagerQty = 0;
1050
1051        if (_.options.infinite === true) {
1052            if (_.slideCount <= _.options.slidesToShow) {
1053                 ++pagerQty;
1054            } else {
1055                while (breakPoint < _.slideCount) {
1056                    ++pagerQty;
1057                    breakPoint = counter + _.options.slidesToScroll;
1058                    counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
1059                }
1060            }
1061        } else if (_.options.centerMode === true) {
1062            pagerQty = _.slideCount;
1063        } else if(!_.options.asNavFor) {
1064            pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll);
1065        }else {
1066            while (breakPoint < _.slideCount) {
1067                ++pagerQty;
1068                breakPoint = counter + _.options.slidesToScroll;
1069                counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
1070            }
1071        }
1072
1073        return pagerQty - 1;
1074
1075    };
1076
1077    Slick.prototype.getLeft = function(slideIndex) {
1078
1079        var _ = this,
1080            targetLeft,
1081            verticalHeight,
1082            verticalOffset = 0,
1083            targetSlide,
1084            coef;
1085
1086        _.slideOffset = 0;
1087        verticalHeight = _.$slides.first().outerHeight(true);
1088
1089        if (_.options.infinite === true) {
1090            if (_.slideCount > _.options.slidesToShow) {
1091                _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1;
1092                coef = -1
1093
1094                if (_.options.vertical === true && _.options.centerMode === true) {
1095                    if (_.options.slidesToShow === 2) {
1096                        coef = -1.5;
1097                    } else if (_.options.slidesToShow === 1) {
1098                        coef = -2
1099                    }
1100                }
1101                verticalOffset = (verticalHeight * _.options.slidesToShow) * coef;
1102            }
1103            if (_.slideCount % _.options.slidesToScroll !== 0) {
1104                if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) {
1105                    if (slideIndex > _.slideCount) {
1106                        _.slideOffset = ((_.options.slidesToShow - (sl
1106ideIndex - _.slideCount)) * _.slideWidth) * -1;
1107                        verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1;
1108                    } else {
1109                        _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1;
1110                        verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1;
1111                    }
1112                }
1113            }
1114        } else {
1115            if (slideIndex + _.options.slidesToShow > _.slideCount) {
1116                _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth;
1117                verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight;
1118            }
1119        }
1120
1121        if (_.slideCount <= _.options.slidesToShow) {
1122            _.slideOffset = 0;
1123            verticalOffset = 0;
1124        }
1125
1126        if (_.options.centerMode === true && _.slideCount <= _.options.slidesToShow) {
1127            _.slideOffset = ((_.slideWidth * Math.floor(_.options.slidesToShow)) / 2) - ((_.slideWidth * _.slideCount) / 2);
1128        } else if (_.options.centerMode === true && _.options.infinite === true) {
1129            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth;
1130        } else if (_.options.centerMode === true) {
1131            _.slideOffset = 0;
1132            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2);
1133        }
1134
1135        if (_.options.vertical === false) {
1136            targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset;
1137        } else {
1138            targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset;
1139        }
1140
1141        if (_.options.variableWidth === true) {
1142
1143            if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
1144                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
1145            } else {
1146                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow);
1147            }
1148
1149            if (_.options.rtl === true) {
1150                if (targetSlide[0]) {
1151                    targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
1152                } else {
1153                    targetLeft =  0;
1154                }
1155            } else {
1156                targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
1157            }
1158
1159            if (_.options.centerMode === true) {
1160                if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
1161                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
1162                } else {
1163                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1);
1164                }
1165
1166                if (_.options.rtl === true) {
1167                    if (targetSlide[0]) {
1168                        targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
1169                    } else {
1170                        targetLeft =  0;
1171                    }
1172                } else {
1173                    targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
1174                }
1175
1176                targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2;
1177            }
1178        }
1179
1180        return targetLeft;
1181
1182    };
1183
1184    Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) {
1185
1186        var _ = this;
1187
1188        return _.options[option];
1189
1190    };
1191
1192    Slick.prototype.getNavigableIndexes = function() {
1193
1194        var _ = this,
1195            breakPoint = 0,
1196            counter = 0,
1197            indexes = [],
1198            max;
1199
1200        if (_.options.infinite === false) {
1201            max = _.slideCount;
1202        } else {
1203            breakPoint = _.options.slidesToScroll * -1;
1204            counter = _.options.slidesToScroll * -1;
1205            max = _.slideCount * 2;
1206        }
1207
1208        while (breakPoint < max) {
1209            indexes.push(breakPoint);
1210            breakPoint = counter + _.options.slidesToScroll;
1211            counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
1212        }
1213
1214        return indexes;
1215
1216    };
1217
1218    Slick.prototype.getSlick = function() {
1219
1220        return this;
1221
1222    };
1223
1224    Slick.prototype.getSlideCount = function() {
1225
1226        var _ = this,
1227            slidesTraversed, swipedSlide, centerOffset;
1228
1229        centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0;
1230
1231        if (_.options.swipeToSlide === true) {
1232            _.$slideTrack.find('.slick-slide').each(function(index, slide) {
1233                if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) {
1234                    swipedSlide = slide;
1235                    return false;
1236                }
1237            });
1238
1239            slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1;
1240
1241            return slidesTraversed;
1242
1243        } else {
1244            return _.options.slidesToScroll;
1245        }
1246
1247    };
1248
1249    Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) {
1250
1251        var _ = this;
1252
1253        _.changeSlide({
1254            data: {
1255                message: 'index',
1256                index: parseInt(slide)
1257            }
1258        }, dontAnimate);
1259
1260    };
1261
1262    Slick.prototype.init = function(creation) {
1263
1264        var _ = this;
1265
1266        if (!$(_.$slider).hasClass('slick-initialized')) {
1267
1268            $(_.$slider).addClass('slick-initialized');
1269
1270            _.buildRows();
1271            _.buildOut();
1272            _.setProps();
1273            _.startLoad();
1274            _.loadSlider();
1275            _.initializeEvents();
1276            _.updateArrows();
1277            _.updateDots();
1278            _.checkResponsive(true);
1279            _.focusHandler();
1280
1281        }
1282
1283        if (creation) {
1284            _.$slider.trigger('init', [_]);
1285        }
1286
1287        if (_.options.accessibility === true) {
1288            _.initADA();
1289        }
1290
1291        if ( _.options.autoplay ) {
1292
1293            _.paused = false;
1294            _.autoPlay();
1295
1296        }
1297
1298    };
1299
1300    Slick.prototype.initADA = function() {
1301        var _ = this,
1302                numDotGroups = Math.ceil(_.slideCount / _.options.slidesToShow),
1303                tabControlIndexes = _.getNavigableIndexes().filter(function(val) {
1304                    return (val >= 0) && (val < _.slideCount);
1305                });
1306
1307        _.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({
1308            'aria-hidden': 'true',
1309            'tabindex': '-1'
1310        }).find('a, input, button, select').attr({
1311            'tabindex': '-1'
1312        });
1313
1314        if (_.$dots !== null) {
1315            _.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function(i) {
1316                var slideControlIndex = tabControlIndexes.indexOf(i);
1317
1318                $(this).attr({
1319                    'role': 'tabpanel',
1320                    'id': 'slick-slide' + _.instanceUid + i,
1321                    'tabindex': -1
1322                });
1323
1324                if (slideControlIndex !== -1) {
1325                   var ariaButtonControl = 'slick-slide-control' + _.instanceUid + slideControlIndex
1326                   if ($('#' + ariaButtonControl).length) {
1327                     $(this).attr({
1328                         'aria-describedby': ariaButtonControl
1329                     });
1330                   }
1331                }
1332            });
1333
1334            _.$dots.attr('role', 'tablist').find('li').each(function(i) {
1335                var mappedSlideIndex = tabControlIndexes[i];
1336
1337                $(this).attr({
1338                    'role': 'presentation'
1339                });
1340
1341                $(this).find('button').first().attr({
1342                    'role': 'tab',
1343                    'id': 'slick-slide-control' + _.instanceUid + i,
1344                    'aria-controls': 'slick-slide' + _.instanceUid + mappedSlideIndex,
1345                    'aria-label': (i + 1) + ' of ' + numDotGroups,
1346                    'aria-selected': null,
1347                    'tabindex': '-1'
1348                });
1349
1350            }).eq(_.currentSlide).find('button').attr({
1351                'aria-selected': 'true',
1352                'tabindex': '0'
1353            }).end();
1354        }
1355
1356        for (var i=_.currentSlide, max=i+_.options.slidesToShow; i < max; i++) {
1357          if (_.options.focusOnChange) {
1358            _.$slides.eq(i).attr({'tabindex': '0'});
1359          } else {
1360            _.$slides.eq(i).removeAttr('tabindex');
1361          }
1362        }
1363
1364        _.activateADA();
1365
1366    };
1367
1368    Slick.prototype.initArrowEvents = function() {
1369
1370        var _ = this;
1371
1372        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
1373            _.$prevArrow
1374               .off('click.slick')
1375               .on('click.slick', {
1376                    message: 'previous'
1377               }, _.changeSlide);
1378            _.$nextArrow
1379               .off('click.slick')
1380               .on('click.slick', {
1381                    message: 'next'
1382               }, _.changeSlide);
1383
1384            if (_.options.accessibility === true) {
1385                _.$prevArrow.on('keydown.slick', _.keyHandler);
1386                _.$nextArrow.on('keydown.slick', _.keyHandler);
1387            }
1388        }
1389
1390    };
1391
1392    Slick.prototype.initDotEvents = function() {
1393
1394        var _ = this;
1395
1396        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
1397            $('li', _.$dots).on('click.slick', {
1398                message: 'index'
1399            }, _.changeSlide);
1400
1401            if (_.options.accessibility === true) {
1402                _.$dots.on('keydown.slick', _.keyHandler);
1403            }
1404        }
1405
1406        if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.slideCount > _.options.slidesToShow) {
1407
1408            $('li', _.$dots)
1409                .on('mouseenter.slick', $.proxy(_.interrupt, _, true))
1410                .on('mouseleave.slick', $.proxy(_.interrupt, _, false));
1411
1412        }
1413
1414    };
1415
1416    Slick.prototype.initSlideEvents = function() {
1417
1418        var _ = this;
1419
1420        if ( _.options.pauseOnHover ) {
1421
1422            _.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true));
1423            _.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false));
1424
1425        }
1426
1427    };
1428
1429    Slick.prototype.initializeEvents = function() {
1430
1431        var _ = this;
1432
1433        _.initArrowEvents();
1434
1435        _.initDotEvents();
1436        _.initSlideEvents();
1437
1438        _.$list.on('touchstart.slick mousedown.slick', {
1439            action: 'start'
1440        }, _.swipeHandler);
1441        _.$list.on('touchmove.slick mousemove.slick', {
1442            action: 'move'
1443        }, _.swipeHandler);
1444        _.$list.on('touchend.slick mouseup.slick', {
1445            action: 'end'
1446        }, _.swipeHandler);
1447        _.$list.on('touchcancel.slick mouseleave.slick', {
1448            action: 'end'
1449        }, _.swipeHandler);
1450
1451        _.$list.on('click.slick', _.clickHandler);
1452
1453        $(document).on(_.visibilityChange, $.proxy(_.visibility, _));
1454
1455        if (_.options.accessibility === true) {
1456            _.$list.on('keydown.slick', _.keyHandler);
1457        }
1458
1459        if (_.options.focusOnSelect === true) {
1460            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
1461        }
1462
1463        $(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _));
1464
1465        $(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _));
1466
1467        $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault);
1468
1469        $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition);
1470        $(_.setPosition);
1471
1472    };
1473
1474    Slick.prototype.initUI = function() {
1475
1476        var _ = this;
1477
1478        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
1479
1480            _.$prevArrow.show();
1481            _.$nextArrow.show();
1482
1483        }
1484
1485        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
1486
1487            _.$dots.show();
1488
1489        }
1490
1491    };
1492
1493    Slick.prototype.keyHandler = function(event) {
1494
1495        var _ = this;
1496         //Dont slide if the cursor is inside the form fields and arrow keys are pressed
1497        if(!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
1498            if (event.keyCode === 37 && _.options.accessibility === true) {
1499                _.changeSlide({
1500                    data: {
1501                        message: _.options.rtl === true ? 'next' :  'previous'
1502                    }
1503                });
1504            } else if (event.keyCode === 39 && _.options.accessibility === true) {
1505                _.changeSlide({
1506                    data: {
1507                        message: _.options.rtl === true ? 'previous' : 'next'
1508                    }
1509                });
1510            }
1511        }
1512
1513    };
1514
1515    Slick.prototype.lazyLoad = function() {
1516
1517        var _ = this,
1518            loadRange, cloneRange, rangeStart, rangeEnd;
1519
1520        function loadImages(imagesScope) {
1521
1522            $('img[data-lazy]', imagesScope).each(function() {
1523
1524                var image = $(this),
1525                    imageSource = $(this).attr('data-lazy'),
1526                    imageSrcSet = $(this).attr('data-srcset'),
1527                    imageSizes  = $(this).attr('data-sizes') || _.$slider.attr('data-sizes'),
1528                    imageToLoad = document.createElement('img');
1529
1530                imageToLoad.onload = function() {
1531
1532                    image
1533                        .animate({ opacity: 0 }, 100, function() {
1534
1535                            if (imageSrcSet) {
1536                                image
1537                                    .attr('srcset', imageSrcSet );
1538
1539                                if (imageSizes) {
1540                                    image
1541                                        .attr('sizes', imageSizes );
1542                                }
1543                            }
1544
1545                            image
1546                                .attr('src', imageSource)
1547                                .animate({ opacity: 1 }, 200, function() {
1548                                    image
1549                                        .removeAttr('data-lazy data-srcset data-sizes')
1550                                        .removeClass('slick-loading');
1551                                });
1552                            _.$slider.trigger('lazyLoaded', [_, image, imageSource]);
1553                        });
1554
1555                };
1556
1557                imageToLoad.onerror = function() {
1558
1559                    image
1560                        .removeAttr( 'data-lazy' )
1561                        .removeClass( 'slick-loading' )
1562                        .addClass( 'slick-lazyload-error' );
1563
1564                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);
1565
1566                };
1567
1568                imageToLoad.src = imageSource;
1569
1570            });
1571
1572        }
1573
1574        if (_.options.centerMode === true) {
1575            if (_.options.infinite === true) {
1576                rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1);
1577                rangeEnd = rangeStart + _.options.slidesToShow + 2;
1578            } else {
1579                rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1));
1580                rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide;
1581            }
1582        } else {
1583            rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide;
1584            rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow);
1585            if (_.options.fade === true) {
1586                if (rangeStart > 0) rangeStart--;
1587                if (rangeEnd <= _.slideCount) rangeEnd++;
1588            }
1589        }
1590
1591        loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd);
1592
1593        if (_.options.lazyLoad === 'anticipated') {
1594            var prevSlide = rangeStart - 1,
1595                nextSlide = rangeEnd,
1596                $slides = _.$slider.find('.slick-slide');
1597
1598            for (var i = 0; i < _.options.slidesToScroll; i++) {
1599                if (prevSlide < 0) prevSlide = _.slideCount - 1;
1600                loadRange = loadRange.add($slides.eq(prevSlide));
1601                loadRange = loadRange.add($slides.eq(nextSlide));
1602                prevSlide--;
1603                nextSlide++;
1604            }
1605        }
1606
1607        loadImages(loadRange);
1608
1609        if (_.slideCount <= _.options.slidesToShow) {
1610            cloneRange = _.$slider.find('.slick-slide');
1611            loadImages(cloneRange);
1612        } else
1613        if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
1614            cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow);
1615            loadImages(cloneRange);
1616        } else if (_.currentSlide === 0) {
1617            cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1);
1618            loadImages(cloneRange);
1619        }
1620
1621    };
1622
1623    Slick.prototype.loadSlider = function() {
1624
1625        var _ = this;
1626
1627        _.setPosition();
1628
1629        _.$slideTrack.css({
1630            opacity: 1
1631        });
1632
1633        _.$slider.removeClass('slick-loading');
1634
1635        _.initUI();
1636
1637        if (_.options.lazyLoad === 'progressive') {
1638            _.progressiveLazyLoad();
1639        }
1640
1641    };
1642
1643    Slick.prototype.next = Slick.prototype.slickNext = function() {
1644
1645        var _ = this;
1646
1647        _.changeSlide({
1648            data: {
1649                message: 'next'
1650            }
1651        });
1652
1653    };
1654
1655    Slick.prototype.orientationChange = function() {
1656
1657        var _ = this;
1658
1659        _.checkResponsive();
1660        _.setPosition();
1661
1662    };
1663
1664    Slick.prototype.pause = Slick.prototype.slickPause = function() {
1665
1666        var _ = this;
1667
1668        _.autoPlayClear();
1669        _.paused = true;
1670
1671    };
1672
1673    Slick.prototype.play = Slick.prototype.slickPlay = function() {
1674
1675        var _ = this;
1676
1677        _.autoPlay();
1678        _.options.autoplay = true;
1679        _.paused = false;
1680        _.focussed = false;
1681        _.interrupted = false;
1682
1683    };
1684
1685    Slick.prototype.postSlide = function(index) {
1686
1687        var _ = this;
1688
1689        if( !_.unslicked ) {
1690
1691            _.$slider.trigger('afterChange', [_, index]);
1692
1693            _.animating = false;
1694
1695            if (_.slideCount > _.options.slidesToShow) {
1696                _.setPosition();
1697            }
1698
1699            _.swipeLeft = null;
1700
1701            if ( _.options.autoplay ) {
1702                _.autoPlay();
1703            }
1704
1705            if (_.options.accessibility === true) {
1706                _.initADA();
1707
1708                if (_.options.focusOnChange) {
1709                    var $currentSlide = $(_.$slides.get(_.currentSlide));
1710                    $currentSlide.attr('tabindex', 0).focus();
1711                }
1712            }
1713
1714        }
1715
1716    };
1717
1718    Slick.prototype.prev = Slick.prototype.slickPrev = function() {
1719
1720        var _ = this;
1721
1722        _.changeSlide({
1723            data: {
1724                message: 'previous'
1725            }
1726        });
1727
1728    };
1729
1730    Slick.prototype.preventDefault = function(event) {
1731
1732        event.preventDefault();
1733
1734    };
1735
1736    Slick.prototype.progressiveLazyLoad = function( tryCount ) {
1737
1738        tryCount = tryCount || 1;
1739
1740        var _ = this,
1741            $imgsToLoad = $( 'img[data-lazy]', _.$slider ),
1742            image,
1743            imageSource,
1744            imageSrcSet,
1745            imageSizes,
1746            imageToLoad;
1747
1748        if ( $imgsToLoad.length ) {
1749
1750            image = $imgsToLoad.first();
1751            imageSource = image.attr('data-lazy');
1752            imageSrcSet = image.attr('data-srcset');
1753            imageSizes  = image.attr('data-sizes') || _.$slider.attr('data-sizes');
1754            imageToLoad = document.createElement('img');
1755
1756            imageToLoad.onload = function() {
1757
1758                if (imageSrcSet) {
1759                    image
1760                        .attr('srcset', imageSrcSet );
1761
1762                    if (imageSizes) {
1763                        image
1764                            .attr('sizes', imageSizes );
1765                    }
1766                }
1767
1768                image
1769                    .attr( 'src', imageSource )
1770                    .removeAttr('data-lazy data-srcset data-sizes')
1771                    .removeClass('slick-loading');
1772
1773                if ( _.options.adaptiveHeight === true ) {
1774                    _.setPosition();
1775                }
1776
1777                _.$slider.trigger('lazyLoaded', [ _, image, imageSource ]);
1778                _.progressiveLazyLoad();
1779
1780            };
1781
1782            imageToLoad.onerror = function() {
1783
1784                if ( tryCount < 3 ) {
1785
1786                    /**
1787                     * try to load the image 3 times,
1788                     * leave a slight delay so we don't get
1789                     * servers blocking the request.
1790                     */
1791                    setTimeout( function() {
1792                        _.progressiveLazyLoad( tryCount + 1 );
1793                    }, 500 );
1794
1795                } else {
1796
1797                    image
1798                        .removeAttr( 'data-lazy' )
1799                        .removeClass( 'slick-loading' )
1800                        .addClass( 'slick-lazyload-error' );
1801
1802                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);
1803
1804                    _.progressiveLazyLoad();
1805
1806                }
1807
1808            };
1809
1810            imageToLoad.src = imageSource;
1811
1812        } else {
1813
1814            _.$slider.trigger('allImagesLoaded', [ _ ]);
1815
1816        }
1817
1818    };
1819
1820    Slick.prototype.refresh = function( initializing ) {
1821
1822        var _ = this, currentSlide, lastVisibleIndex;
1823
1824        lastVisibleIndex = _.slideCount - _.options.slidesToShow;
1825
1826        // in non-infinite sliders, we don't want to go past the
1827        // last visible index.
1828        if( !_.options.infinite && ( _.currentSlide > lastVisibleIndex )) {
1829            _.currentSlide = lastVisibleIndex;
1830        }
1831
1832        // if less slides than to show, go to start.
1833        if ( _.slideCount <= _.options.slidesToShow ) {
1834            _.currentSlide = 0;
1835
1836        }
1837
1838        currentSlide = _.currentSlide;
1839
1840        _.destroy(true);
1841
1842        $.extend(_, _.initials, { currentSlide: currentSlide });
1843
1844        _.init();
1845
1846        if( !initializing ) {
1847
1848            _.changeSlide({
1849                data: {
1850                    message: 'index',
1851                    index: currentSlide
1852                }
1853            }, false);
1854
1855        }
1856
1857    };
1858
1859    Slick.prototype.registerBreakpoints = function() {
1860
1861        var _ = this, breakpoint, currentBreakpoint, l,
1862            responsiveSettings = _.options.responsive || null;
1863
1864        if ( $.type(responsiveSettings) === 'array' && responsiveSettings.length ) {
1865
1866            _.respondTo = _.options.respondTo || 'window';
1867
1868            for ( breakpoint in responsiveSettings ) {
1869
1870                l = _.breakpoints.length-1;
1871
1872                if (responsiveSettings.hasOwnProperty(breakpoint)) {
1873                    currentBreakpoint = responsiveSettings[breakpoint].breakpoint;
1874
1875                    // loop through the breakpoints and cut out any existing
1876                    // ones with the same breakpoint number, we don't want dupes.
1877                    while( l >= 0 ) {
1878                        if( _.breakpoints[l] && _.breakpoints[l] === currentBreakpoint ) {
1879                            _.breakpoints.splice(l,1);
1880                        }
1881                        l--;
1882                    }
1883
1884                    _.breakpoints.push(currentBreakpoint);
1885                    _.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings;
1886
1887                }
1888
1889            }
1890
1891            _.breakpoints.sort(function(a, b) {
1892                return ( _.options.mobileFirst ) ? a-b : b-a;
1893            });
1894
1895        }
1896
1897    };
1898
1899    Slick.prototype.reinit = function() {
1900
1901        var _ = this;
1902
1903        _.$slides =
1904            _.$slideTrack
1905                .children(_.options.slide)
1906                .addClass('slick-slide');
1907
1908        _.slideCount = _.$slides.length;
1909
1910        if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) {
1911            _.currentSlide = _.currentSlide - _.options.slidesToScroll;
1912        }
1913
1914        if (_.slideCount <= _.options.slidesToShow) {
1915            _.currentSlide = 0;
1916        }
1917
1918        _.registerBreakpoints();
1919
1920        _.setProps();
1921        _.setupInfinite();
1922        _.buildArrows();
1923        _.updateArrows();
1924        _.initArrowEvents();
1925        _.buildDots();
1926        _.updateDots();
1927        _.initDotEvents();
1928        _.cleanUpSlideEvents();
1929        _.initSlideEvents();
1930
1931        _.checkResponsive(false, true);
1932
1933        if (_.options.focusOnSelect === true) {
1934            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
1935        }
1936
1937        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);
1938
1939        _.setPosition();
1940        _.focusHandler();
1941
1942        _.paused = !_.options.autoplay;
1943        _.autoPlay();
1944
1945        _.$slider.trigger('reInit', [_]);
1946
1947    };
1948
1949    Slick.prototype.resize = function() {
1950
1951        var _ = this;
1952
1953        if ($(window).width() !== _.windowWidth) {
1954            clearTimeout(_.windowDelay);
1955            _.windowDelay = window.setTimeout(function() {
1956                _.windowWidth = $(window).width();
1957                _.checkResponsive();
1958                if( !_.unslicked ) { _.setPosition(); }
1959            }, 50);
1960        }
1961    };
1962
1963    Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) {
1964
1965        var _ = this;
1966
1967        if (typeof(index) === 'boolean') {
1968            removeBefore = index;
1969            index = removeBefore === true ? 0 : _.slideCount - 1;
1970        } else {
1971            index = removeBefore === true ? --index : index;
1972        }
1973
1974        if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) {
1975            return false;
1976        }
1977
1978        _.unload();
1979
1980        if (removeAll === true) {
1981            _.$slideTrack.children().remove();
1982        } else {
1983            _.$slideTrack.children(this.options.slide).eq(index).remove();
1984        }
1985
1986        _.$slides = _.$slideTrack.children(this.options.slide);
1987
1988        _.$slideTrack.children(this.options.slide).detach();
1989
1990        _.$slideTrack.append(_.$slides);
1991
1992        _.$slidesCache = _.$slides;
1993
1994        _.reinit();
1995
1996    };
1997
1998    Slick.prototype.setCSS = function(position) {
1999
2000        var _ = this,
2001            positionProps = {},
2002            x, y;
2003
2004        if (_.options.rtl === true) {
2005            position = -position;
2006        }
2007        x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px';
2008        y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px';
2009
2010        positionProps[_.positionProp] = position;
2011
2012        if (_.transformsEnabled === false) {
2013            _.$slideTrack.css(positionProps);
2014        } else {
2015            positionProps = {};
2016            if (_.cssTransitions === false) {
2017                positionProps[_.animType] = 'translate(' + x + ', ' + y + ')';
2018                _.$slideTrack.css(positionProps);
2019            } else {
2020                positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)';
2021                _.$slideTrack.css(positionProps);
2022            }
2023        }
2024
2025    };
2026
2027    Slick.prototype.setDimensions = function() {
2028
2029        var _ = this;
2030
2031        if (_.options.vertical === false) {
2032            if (_.options.centerMode === true) {
2033                _.$list.css({
2034                    padding: ('0px ' + _.options.centerPadding)
2035                });
2036            }
2037        } else {
2038            _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow);
2039            if (_.options.centerMode === true) {
2040                _.$list.css({
2041                    padding: (_.options.centerPadding + ' 0px')
2042                });
2043            }
2044        }
2045
2046        _.listWidth = _.$list.width();
2047        _.listHeight = _.$list.height();
2048
2049
2050        if (_.options.vertical === false && _.options.variableWidth === false) {
2051            _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
2052            _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length)));
2053
2054        } else if (_.options.variableWidth === true) {
2055            _.$slideTrack.width(5000 * _.slideCount);
2056        } else {
2057            _.slideWidth = Math.ceil(_.listWidth);
2058            _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length)));
2059        }
2060
2061        var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
2062        if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset);
2063
2064    };
2065
2066    Slick.prototype.setFade = function() {
2067
2068        var _ = this,
2069            targetLeft;
2070
2071        _.$slides.each(function(index, element) {
2072            targetLeft = (_.slideWidth * index) * -1;
2073            if (_.options.rtl === true) {
2074                $(element).css({
2075                    position: 'relative',
2076                    right: targetLeft,
2077                    top: 0,
2078                    zIndex: _.options.zIndex - 2,
2079                    opacity: 0
2080                });
2081            } else {
2082                $(element).css({
2083                    position: 'relative',
2084                    left: targetLeft,
2085                    top: 0,
2086                    zIndex: _.options.zIndex - 2,
2087                    opacity: 0
2088                });
2089            }
2090        });
2091
2092        _.$slides.eq(_.currentSlide).css({
2093            zIndex: _.options.zIndex - 1,
2094            opacity: 1
2095        });
2096
2097    };
2098
2099    Slick.prototype.setHeight = function() {
2100
2101        var _ = this;
2102
2103        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
2104            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
2105            _.$list.css('height', targetHeight);
2106        }
2107
2108    };
2109
2110    Slick.prototype.setOption =
2111    Slick.prototype.slickSetOption = function() {
2112
2113        /**
2114         * accepts arguments in format of:
2115         *
2116         *  - for changing a single option's value:
2117         *     .slick("setOption", option, value, refresh )
2118         *
2119         *  - for changing a set of responsive options:
2120         *     .slick("setOption", 'responsive', [{}, ...], refresh )
2121         *
2122         *  - for updating multiple values at once (not responsive)
2123         *     .slick("setOption", { 'option': value, ... }, refresh )
2124         */
2125
2126        var _ = this, l, item, option, value, refresh = false, t
2126ype;
2127
2128        if( $.type( arguments[0] ) === 'object' ) {
2129
2130            option =  arguments[0];
2131            refresh = arguments[1];
2132            type = 'multiple';
2133
2134        } else if ( $.type( arguments[0] ) === 'string' ) {
2135
2136            option =  arguments[0];
2137            value = arguments[1];
2138            refresh = arguments[2];
2139
2140            if ( arguments[0] === 'responsive' && $.type( arguments[1] ) === 'array' ) {
2141
2142                type = 'responsive';
2143
2144            } else if ( typeof arguments[1] !== 'undefined' ) {
2145
2146                type = 'single';
2147
2148            }
2149
2150        }
2151
2152        if ( type === 'single' ) {
2153
2154            _.options[option] = value;
2155
2156
2157        } else if ( type === 'multiple' ) {
2158
2159            $.each( option , function( opt, val ) {
2160
2161                _.options[opt] = val;
2162
2163            });
2164
2165
2166        } else if ( type === 'responsive' ) {
2167
2168            for ( item in value ) {
2169
2170                if( $.type( _.options.responsive ) !== 'array' ) {
2171
2172                    _.options.responsive = [ value[item] ];
2173
2174                } else {
2175
2176                    l = _.options.responsive.length-1;
2177
2178                    // loop through the responsive object and splice out duplicates.
2179                    while( l >= 0 ) {
2180
2181                        if( _.options.responsive[l].breakpoint === value[item].breakpoint ) {
2182
2183                            _.options.responsive.splice(l,1);
2184
2185                        }
2186
2187                        l--;
2188
2189                    }
2190
2191                    _.options.responsive.push( value[item] );
2192
2193                }
2194
2195            }
2196
2197        }
2198
2199        if ( refresh ) {
2200
2201            _.unload();
2202            _.reinit();
2203
2204        }
2205
2206    };
2207
2208    Slick.prototype.setPosition = function() {
2209
2210        var _ = this;
2211
2212        _.setDimensions();
2213
2214        _.setHeight();
2215
2216        if (_.options.fade === false) {
2217            _.setCSS(_.getLeft(_.currentSlide));
2218        } else {
2219            _.setFade();
2220        }
2221
2222        _.$slider.trigger('setPosition', [_]);
2223
2224    };
2225
2226    Slick.prototype.setProps = function() {
2227
2228        var _ = this,
2229            bodyStyle = document.body.style;
2230
2231        _.positionProp = _.options.vertical === true ? 'top' : 'left';
2232
2233        if (_.positionProp === 'top') {
2234            _.$slider.addClass('slick-vertical');
2235        } else {
2236            _.$slider.removeClass('slick-vertical');
2237        }
2238
2239        if (bodyStyle.WebkitTransition !== undefined ||
2240            bodyStyle.MozTransition !== undefined ||
2241            bodyStyle.msTransition !== undefined) {
2242            if (_.options.useCSS === true) {
2243                _.cssTransitions = true;
2244            }
2245        }
2246
2247        if ( _.options.fade ) {
2248            if ( typeof _.options.zIndex === 'number' ) {
2249                if( _.options.zIndex < 3 ) {
2250                    _.options.zIndex = 3;
2251                }
2252            } else {
2253                _.options.zIndex = _.defaults.zIndex;
2254            }
2255        }
2256
2257        if (bodyStyle.OTransform !== undefined) {
2258            _.animType = 'OTransform';
2259            _.transformType = '-o-transform';
2260            _.transitionType = 'OTransition';
2261            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
2262        }
2263        if (bodyStyle.MozTransform !== undefined) {
2264            _.animType = 'MozTransform';
2265            _.transformType = '-moz-transform';
2266            _.transitionType = 'MozTransition';
2267            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false;
2268        }
2269        if (bodyStyle.webkitTransform !== undefined) {
2270            _.animType = 'webkitTransform';
2271            _.transformType = '-webkit-transform';
2272            _.transitionType = 'webkitTransition';
2273            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
2274        }
2275        if (bodyStyle.msTransform !== undefined) {
2276            _.animType = 'msTransform';
2277            _.transformType = '-ms-transform';
2278            _.transitionType = 'msTransition';
2279            if (bodyStyle.msTransform === undefined) _.animType = false;
2280        }
2281        if (bodyStyle.transform !== undefined && _.animType !== false) {
2282            _.animType = 'transform';
2283            _.transformType = 'transform';
2284            _.transitionType = 'transition';
2285        }
2286        _.transformsEnabled = _.options.useTransform && (_.animType !== null && _.animType !== false);
2287    };
2288
2289
2290    Slick.prototype.setSlideClasses = function(index) {
2291
2292        var _ = this,
2293            centerOffset, allSlides, indexOffset, remainder;
2294
2295        allSlides = _.$slider
2296            .find('.slick-slide')
2297            .removeClass('slick-active slick-center slick-current')
2298            .attr('aria-hidden', 'true');
2299
2300        _.$slides
2301            .eq(index)
2302            .addClass('slick-current');
2303
2304        if (_.options.centerMode === true) {
2305
2306            var evenCoef = _.options.slidesToShow % 2 === 0 ? 1 : 0;
2307
2308            centerOffset = Math.floor(_.options.slidesToShow / 2);
2309
2310            if (_.options.infinite === true) {
2311
2312                if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) {
2313                    _.$slides
2314                        .slice(index - centerOffset + evenCoef, index + centerOffset + 1)
2315                        .addClass('slick-active')
2316                        .attr('aria-hidden', 'false');
2317
2318                } else {
2319
2320                    indexOffset = _.options.slidesToShow + index;
2321                    allSlides
2322                        .slice(indexOffset - centerOffset + 1 + evenCoef, indexOffset + centerOffset + 2)
2323                        .addClass('slick-active')
2324                        .attr('aria-hidden', 'false');
2325
2326                }
2327
2328                if (index === 0) {
2329
2330                    allSlides
2331                        .eq(allSlides.length - 1 - _.options.slidesToShow)
2332                        .addClass('slick-center');
2333
2334                } else if (index === _.slideCount - 1) {
2335
2336                    allSlides
2337                        .eq(_.options.slidesToShow)
2338                        .addClass('slick-center');
2339
2340                }
2341
2342            }
2343
2344            _.$slides
2345                .eq(index)
2346                .addClass('slick-center');
2347
2348        } else {
2349
2350            if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) {
2351
2352                _.$slides
2353                    .slice(index, index + _.options.slidesToShow)
2354                    .addClass('slick-active')
2355                    .attr('aria-hidden', 'false');
2356
2357            } else if (allSlides.length <= _.options.slidesToShow) {
2358
2359                allSlides
2360                    .addClass('slick-active')
2361                    .attr('aria-hidden', 'false');
2362
2363            } else {
2364
2365                remainder = _.slideCount % _.options.slidesToShow;
2366                indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index;
2367
2368                if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) {
2369
2370                    allSlides
2371                        .slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder)
2372                        .addClass('slick-active')
2373                        .attr('aria-hidden', 'false');
2374
2375                } else {
2376
2377                    allSlides
2378                        .slice(indexOffset, indexOffset + _.options.slidesToShow)
2379                        .addClass('slick-active')
2380                        .attr('aria-hidden', 'false');
2381
2382                }
2383
2384            }
2385
2386        }
2387
2388        if (_.options.lazyLoad === 'ondemand' || _.options.lazyLoad === 'anticipated') {
2389            _.lazyLoad();
2390        }
2391    };
2392
2393    Slick.prototype.setupInfinite = function() {
2394
2395        var _ = this,
2396            i, slideIndex, infiniteCount;
2397
2398        if (_.options.fade === true) {
2399            _.options.centerMode = false;
2400        }
2401
2402        if (_.options.infinite === true && _.options.fade === false) {
2403
2404            slideIndex = null;
2405
2406            if (_.slideCount > _.options.slidesToShow) {
2407
2408                if (_.options.centerMode === true) {
2409                    infiniteCount = _.options.slidesToShow + 1;
2410                } else {
2411                    infiniteCount = _.options.slidesToShow;
2412                }
2413
2414                for (i = _.slideCount; i > (_.slideCount -
2415                        infiniteCount); i -= 1) {
2416                    slideIndex = i - 1;
2417                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
2418                        .attr('data-slick-index', slideIndex - _.slideCount)
2419                        .prependTo(_.$slideTrack).addClass('slick-cloned');
2420                }
2421                for (i = 0; i < infiniteCount  + _.slideCount; i += 1) {
2422                    slideIndex = i;
2423                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
2424                        .attr('data-slick-index', slideIndex + _.slideCount)
2425                        .appendTo(_.$slideTrack).addClass('slick-cloned');
2426                }
2427                _.$slideTrack.find('.slick-cloned').find('[id]').each(function() {
2428                    $(this).attr('id', '');
2429                });
2430
2431            }
2432
2433        }
2434
2435    };
2436
2437    Slick.prototype.interrupt = function( toggle ) {
2438
2439        var _ = this;
2440
2441        if( !toggle ) {
2442            _.autoPlay();
2443        }
2444        _.interrupted = toggle;
2445
2446    };
2447
2448    Slick.prototype.selectHandler = function(event) {
2449
2450        var _ = this;
2451
2452        var targetElement =
2453            $(event.target).is('.slick-slide') ?
2454                $(event.target) :
2455                $(event.target).parents('.slick-slide');
2456
2457        var index = parseInt(targetElement.attr('data-slick-index'));
2458
2459        if (!index) index = 0;
2460
2461        if (_.slideCount <= _.options.slidesToShow) {
2462
2463            _.slideHandler(index, false, true);
2464            return;
2465
2466        }
2467
2468        _.slideHandler(index);
2469
2470    };
2471
2472    Slick.prototype.slideHandler = function(index, sync, dontAnimate) {
2473
2474        var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null,
2475            _ = this, navTarget;
2476
2477        sync = sync || false;
2478
2479        if (_.animating === true && _.options.waitForAnimate === true) {
2480            return;
2481        }
2482
2483        if (_.options.fade === true && _.currentSlide === index) {
2484            return;
2485        }
2486
2487        if (sync === false) {
2488            _.asNavFor(index);
2489        }
2490
2491        targetSlide = index;
2492        targetLeft = _.getLeft(targetSlide);
2493        slideLeft = _.getLeft(_.currentSlide);
2494
2495        _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft;
2496
2497        if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) {
2498            if (_.options.fade === false) {
2499                targetSlide = _.currentSlide;
2500                if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
2501                    _.animateSlide(slideLeft, function() {
2502                        _.postSlide(targetSlide);
2503                    });
2504                } else {
2505                    _.postSlide(targetSlide);
2506                }
2507            }
2508            return;
2509        } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) {
2510            if (_.options.fade === false) {
2511                targetSlide = _.currentSlide;
2512                if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
2513                    _.animateSlide(slideLeft, function() {
2514                        _.postSlide(targetSlide);
2515                    });
2516                } else {
2517                    _.postSlide(targetSlide);
2518                }
2519            }
2520            return;
2521        }
2522
2523        if ( _.options.autoplay ) {
2524            clearInterval(_.autoPlayTimer);
2525        }
2526
2527        if (targetSlide < 0) {
2528            if (_.slideCount % _.options.slidesToScroll !== 0) {
2529                animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll);
2530            } else {
2531                animSlide = _.slideCount + targetSlide;
2532            }
2533        }
2533 else if (targetSlide >= _.slideCount) {
2534            if (_.slideCount % _.options.slidesToScroll !== 0) {
2535                animSlide = 0;
2536            } else {
2537                animSlide = targetSlide - _.slideCount;
2538            }
2539        } else {
2540            animSlide = targetSlide;
2541        }
2542
2543        _.animating = true;
2544
2545        _.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]);
2546
2547        oldSlide = _.currentSlide;
2548        _.currentSlide = animSlide;
2549
2550        _.setSlideClasses(_.currentSlide);
2551
2552        if ( _.options.asNavFor ) {
2553
2554            navTarget = _.getNavTarget();
2555            navTarget = navTarget.slick('getSlick');
2556
2557            if ( navTarget.slideCount <= navTarget.options.slidesToShow ) {
2558                navTarget.setSlideClasses(_.currentSlide);
2559            }
2560
2561        }
2562
2563        _.updateDots();
2564        _.updateArrows();
2565
2566        if (_.options.fade === true) {
2567            if (dontAnimate !== true) {
2568
2569                _.fadeSlideOut(oldSlide);
2570
2571                _.fadeSlide(animSlide, function() {
2572                    _.postSlide(animSlide);
2573                });
2574
2575            } else {
2576                _.postSlide(animSlide);
2577            }
2578            _.animateHeight();
2579            return;
2580        }
2581
2582        if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
2583            _.animateSlide(targetLeft, function() {
2584                _.postSlide(animSlide);
2585            });
2586        } else {
2587            _.postSlide(animSlide);
2588        }
2589
2590    };
2591
2592    Slick.prototype.startLoad = function() {
2593
2594        var _ = this;
2595
2596        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
2597
2598            _.$prevArrow.hide();
2599            _.$nextArrow.hide();
2600
2601        }
2602
2603        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
2604
2605            _.$dots.hide();
2606
2607        }
2608
2609        _.$slider.addClass('slick-loading');
2610
2611    };
2612
2613    Slick.prototype.swipeDirection = function() {
2614
2615        var xDist, yDist, r, swipeAngle, _ = this;
2616
2617        xDist = _.touchObject.startX - _.touchObject.curX;
2618        yDist = _.touchObject.startY - _.touchObject.curY;
2619        r = Math.atan2(yDist, xDist);
2620
2621        swipeAngle = Math.round(r * 180 / Math.PI);
2622        if (swipeAngle < 0) {
2623            swipeAngle = 360 - Math.abs(swipeAngle);
2624        }
2625
2626        if ((swipeAngle <= 45) && (swipeAngle >= 0)) {
2627            return (_.options.rtl === false ? 'left' : 'right');
2628        }
2629        if ((swipeAngle <= 360) && (swipeAngle >= 315)) {
2630            return (_.options.rtl === false ? 'left' : 'right');
2631        }
2632        if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
2633            return (_.options.rtl === false ? 'right' : 'left');
2634        }
2635        if (_.options.verticalSwiping === true) {
2636            if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
2637                return 'down';
2638            } else {
2639                return 'up';
2640            }
2641        }
2642
2643        return 'vertical';
2644
2645    };
2646
2647    Slick.prototype.swipeEnd = function(event) {
2648
2649        var _ = this,
2650            slideCount,
2651            direction;
2652
2653        _.dragging = false;
2654        _.swiping = false;
2655
2656        if (_.scrolling) {
2657            _.scrolling = false;
2658            return false;
2659        }
2660
2661        _.interrupted = false;
2662        _.shouldClick = ( _.touchObject.swipeLength > 10 ) ? false : true;
2663
2664        if ( _.touchObject.curX === undefined ) {
2665            return false;
2666        }
2667
2668        if ( _.touchObject.edgeHit === true ) {
2669            _.$slider.trigger('edge', [_, _.swipeDirection() ]);
2670        }
2671
2672        if ( _.touchObject.swipeLength >= _.touchObject.minSwipe ) {
2673
2674            direction = _.swipeDirection();
2675
2676            switch ( direction ) {
2677
2678                case 'left':
2679                case 'down':
2680
2681                    slideCount =
2682                        _.options.swipeToSlide ?
2683                            _.checkNavigable( _.currentSlide + _.getSlideCount() ) :
2684                            _.currentSlide + _.getSlideCount();
2685
2686                    _.currentDirection = 0;
2687
2688                    break;
2689
2690                case 'right':
2691                case 'up':
2692
2693                    slideCount =
2694                        _.options.swipeToSlide ?
2695                            _.checkNavigable( _.currentSlide - _.getSlideCount() ) :
2696                            _.currentSlide - _.getSlideCount();
2697
2698                    _.currentDirection = 1;
2699
2700                    break;
2701
2702                default:
2703
2704
2705            }
2706
2707            if( direction != 'vertical' ) {
2708
2709                _.slideHandler( slideCount );
2710                _.touchObject = {};
2711                _.$slider.trigger('swipe', [_, direction ]);
2712
2713            }
2714
2715        } else {
2716
2717            if ( _.touchObject.startX !== _.touchObject.curX ) {
2718
2719                _.slideHandler( _.currentSlide );
2720                _.touchObject = {};
2721
2722            }
2723
2724        }
2725
2726    };
2727
2728    Slick.prototype.swipeHandler = function(event) {
2729
2730        var _ = this;
2731
2732        if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) {
2733            return;
2734        } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) {
2735            return;
2736        }
2737
2738        _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ?
2739            event.originalEvent.touches.length : 1;
2740
2741        _.touchObject.minSwipe = _.listWidth / _.options
2742            .touchThreshold;
2743
2744        if (_.options.verticalSwiping === true) {
2745            _.touchObject.minSwipe = _.listHeight / _.options
2746                .touchThreshold;
2747        }
2748
2749        switch (event.data.action) {
2750
2751            case 'start':
2752                _.swipeStart(event);
2753                break;
2754
2755            case 'move':
2756                _.swipeMove(event);
2757                break;
2758
2759            case 'end':
2760                _.swipeEnd(event);
2761                break;
2762
2763        }
2764
2765    };
2766
2767    Slick.prototype.swipeMove = function(event) {
2768
2769        var _ = this,
2770            edgeWasHit = false,
2771            curLeft, swipeDirection, swipeLength, positionOffset, touches, verticalSwipeLength;
2772
2773        touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;
2774
2775        if (!_.dragging || _.scrolling || touches && touches.length !== 1) {
2776            return false;
2777        }
2778
2779        curLeft = _.getLeft(_.currentSlide);
2780
2781        _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
2782        _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;
2783
2784        _.touchObject.swipeLength = Math.round(Math.sqrt(
2785            Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));
2786
2787        verticalSwipeLength = Math.round(Math.sqrt(
2788            Math.pow(_.touchObject.curY - _.touchObject.startY, 2)));
2789
2790        if (!_.options.verticalSwiping && !_.swiping && verticalSwipeLength > 4) {
2791            _.scrolling = true;
2792            return false;
2793        }
2794
2795        if (_.options.verticalSwiping === true) {
2796            _.touchObject.swipeLength = verticalSwipeLength;
2797        }
2798
2799        swipeDirection = _.swipeDirection();
2800
2801        if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) {
2802            _.swiping = true;
2803            event.preventDefault();
2804        }
2805
2806        positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1);
2807        if (_.options.verticalSwiping === true) {
2808            positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1;
2809        }
2810
2811
2812        swipeLength = _.touchObject.swipeLength;
2813
2814        _.touchObject.edgeHit = false;
2815
2816        if (_.options.infinite === false) {
2817            if ((_.currentSlide === 0 && swipeDirection === 'right') || (_.currentSlide >= _.getDotCount() && swipeDirection === 'left')) {
2818                swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
2819                _.touchObject.edgeHit = true;
2820            }
2821        }
2822
2823        if (_.options.vertical === false) {
2824            _.swipeLeft = curLeft + swipeLength * positionOffset;
2825        } else {
2826            _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset;
2827        }
2828        if (_.options.verticalSwiping === true) {
2829            _.swipeLeft = curLeft + swipeLength * positionOffset;
2830        }
2831
2832        if (_.options.fade === true || _.options.touchMove === false) {
2833            return false;
2834        }
2835
2836        if (_.animating === true) {
2837            _.swipeLeft = null;
2838            return false;
2839        }
2840
2841        _.setCSS(_.swipeLeft);
2842
2843    };
2844
2845    Slick.prototype.swipeStart = function(event) {
2846
2847        var _ = this,
2848            touches;
2849
2850        _.interrupted = true;
2851
2852        if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) {
2853            _.touchObject = {};
2854            return false;
2855        }
2856
2857        if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
2858            touches = event.originalEvent.touches[0];
2859        }
2860
2861        _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
2862        _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;
2863
2864        _.dragging = true;
2865
2866    };
2867
2868    Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() {
2869
2870        var _ = this;
2871
2872        if (_.$slidesCache !== null) {
2873
2874            _.unload();
2875
2876            _.$slideTrack.children(this.options.slide).detach();
2877
2878            _.$slidesCache.appendTo(_.$slideTrack);
2879
2880            _.reinit();
2881
2882        }
2883
2884    };
2885
2886    Slick.prototype.unload = function() {
2887
2888        var _ = this;
2889
2890        $('.slick-cloned', _.$slider).remove();
2891
2892        if (_.$dots) {
2893            _.$dots.remove();
2894        }
2895
2896        if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) {
2897            _.$prevArrow.remove();
2898        }
2899
2900        if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) {
2901            _.$nextArrow.remove();
2902        }
2903
2904        _.$slides
2905            .removeClass('slick-slide slick-active slick-visible slick-current')
2906            .attr('aria-hidden', 'true')
2907            .css('width', '');
2908
2909    };
2910
2911    Slick.prototype.unslick = function(fromBreakpoint) {
2912
2913        var _ = this;
2914        _.$slider.trigger('unslick', [_, fromBreakpoint]);
2915        _.destroy();
2916
2917    };
2918
2919    Slick.prototype.updateArrows = function() {
2920
2921        var _ = this,
2922            centerOffset;
2923
2924        centerOffset = Math.floor(_.options.slidesToShow / 2);
2925
2926        if ( _.options.arrows === true &&
2927            _.slideCount > _.options.slidesToShow &&
2928            !_.options.infinite ) {
2929
2930            _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
2931            _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
2932
2933            if (_.currentSlide === 0) {
2934
2935                _.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
2936                _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
2937
2938            } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) {
2939
2940                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
2941                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
2942
2943            } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) {
2944
2945                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
2946                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
2947
2948            }
2949
2950        }
2951
2952    };
2953
2954    Slick.prototype.updateDots = function() {
2955
2956        var _ = this;
2957
2958        if (_.$dots !== null) {
2959
2960            _.$dots
2961                .find('li')
2962                    .removeClass('slick-active')
2963                    .end();
2964
2965            _.$dots
2966                .find('li')
2967                .eq(Math.floor(_.currentSlide / _.options.slidesToScroll))
2968                .addClass('slick-active');
2969
2970        }
2971
2972    };
2973
2974    Slick.prototype.visibility = function() {
2975
2976        var _ = this;
2977
2978        if ( _.options.autoplay ) {
2979
2980            if ( document[_.hidden] ) {
2981
2982                _.interrupted = true;
2983
2984            } else {
2985
2986                _.interrupted = false;
2987
2988            }
2989
2990        }
2991
2992    };
2993
2994    $.fn.slick = function() {
2995        var _ = this,
2996            opt = arguments[0],
2997            args = Array.prototype.slice.call(arguments, 1),
2998            l = _.length,
2999            i,
3000            ret;
3001        for (i = 0; i < l; i++) {
3002            if (typeof opt == 'object' || typeof opt == 'undefined')
3003                _[i].slick = new Slick(_[i], opt);
3004            else
3005                ret = _[i].slick[opt].apply(_[i].slick, args);
3006            if (typeof ret != 'undefined') return ret;
3007        }
3008        return _;
3009    };
3010
3011}));
3012
vendor: 44,287 bytes, lines 3013-4844
3013/*!
3014 * fancyBox - jQuery Plugin
3015 * version: 2.1.5 (Fri, 14 Jun 2013)
3016 * requires jQuery v1.6 or later
3017 *
3018 * Examples at http://fancyapps.com/fancybox/
3019 * License: www.fancyapps.com/fancybox/#license
3020 *
3021 * Copyright 2012 Janis Skarnelis - [email protected]
3022 *
3023 */
3024
3025;(function (window, document, $, undefined) {
3026	"use strict";
3027
3028	var H = $("html"),
3029		W = $(window),
3030		D = $(document),
3031		F = $.fancybox = function () {
3032			F.open.apply( this, arguments );
3033		},
3034		IE =  navigator.userAgent.match(/msie/i),
3035		didUpdate	= null,
3036		isTouch		= document.createTouch !== undefined,
3037
3038		isQuery	= function(obj) {
3039			return obj && obj.hasOwnProperty && obj instanceof $;
3040		},
3041		isString = function(str) {
3042			return str && $.type(str) === "string";
3043		},
3044		isPercentage = function(str) {
3045			return isString(str) && str.indexOf('%') > 0;
3046		},
3047		isScrollable = function(el) {
3048			return (el && !(el.style.overflow && el.style.overflow === 'hidden') && ((el.clientWidth && el.scrollWidth > el.clientWidth) || (el.clientHeight && el.scrollHeight > el.clientHeight)));
3049		},
3050		getScalar = function(orig, dim) {
3051			var value = parseInt(orig, 10) || 0;
3052
3053			if (dim && isPercentage(orig)) {
3054				value = F.getViewport()[ dim ] / 100 * value;
3055			}
3056
3057			return Math.ceil(value);
3058		},
3059		getValue = function(value, dim) {
3060			return getScalar(value, dim) + 'px';
3061		};
3062
3063	$.extend(F, {
3064		// The current version of fancyBox
3065		version: '2.1.5',
3066
3067		defaults: {
3068			padding : 15,
3069			margin  : 20,
3070
3071			width     : 800,
3072			height    : 600,
3073			minWidth  : 100,
3074			minHeight : 100,
3075			maxWidth  : 9999,
3076			maxHeight : 9999,
3077			pixelRatio: 1, // Set to 2 for retina display support
3078
3079			autoSize   : true,
3080			autoHeight : false,
3081			autoWidth  : false,
3082
3083			autoResize  : true,
3084			autoCenter  : !isTouch,
3085			fitToView   : true,
3086			aspectRatio : false,
3087			topRatio    : 0.5,
3088			leftRatio   : 0.5,
3089
3090			scrolling : 'auto', // 'auto', 'yes' or 'no'
3091			wrapCSS   : '',
3092
3093			arrows     : true,
3094			closeBtn   : true,
3095			closeClick : false,
3096			nextClick  : false,
3097			mouseWheel : true,
3098			autoPlay   : false,
3099			playSpeed  : 3000,
3100			preload    : 3,
3101			modal      : false,
3102			loop       : true,
3103
3104			ajax  : {
3105				dataType : 'html',
3106				headers  : { 'X-fancyBox': true }
3107			},
3108			iframe : {
3109				scrolling : 'auto',
3110				preload   : true
3111			},
3112			swf : {
3113				wmode: 'transparent',
3114				allowfullscreen   : 'true',
3115				allowscriptaccess : 'always'
3116			},
3117
3118			keys  : {
3119				next : {
3120					13 : 'left', // enter
3121					34 : 'up',   // page down
3122					39 : 'left', // right arrow
3123					40 : 'up'    // down arrow
3124				},
3125				prev : {
3126					8  : 'right',  // backspace
3127					33 : 'down',   // page up
3128					37 : 'right',  // left arrow
3129					38 : 'down'    // up arrow
3130				},
3131				close  : [27], // escape key
3132				play   : [32], // space - start/stop slideshow
3133				toggle : [70]  // letter "f" - toggle fullscreen
3134			},
3135
3136			direction : {
3137				next : 'left',
3138				prev : 'right'
3139			},
3140
3141			scrollOutside  : true,
3142
3143			// Override some properties
3144			index   : 0,
3145			type    : null,
3146			href    : null,
3147			content : null,
3148			title   : null,
3149
3150			// HTML templates
3151			tpl: {
3152				wrap     : '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',
3153				image    : '<img class="fancybox-image" src="{href}" alt="" />',
3154				iframe   : '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen' + (IE ? ' allowtransparency="true"' : '') + '></iframe>',
3155				error    : '<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>',
3156				closeBtn : '<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>',
3157				next     : '<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',
3158				prev     : '<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>',
3159				loading  : '<div id="fancybox-loading"><div></div></div>'
3160			},
3161
3162			// Properties for each animation type
3163			// Opening fancyBox
3164			openEffect  : 'fade', // 'elastic', 'fade' or 'none'
3165			openSpeed   : 250,
3166			openEasing  : 'swing',
3167			openOpacity : true,
3168			openMethod  : 'zoomIn',
3169
3170			// Closing fancyBox
3171			closeEffect  : 'fade', // 'elastic', 'fade' or 'none'
3172			closeSpeed   : 250,
3173			closeEasing  : 'swing',
3174			closeOpacity : true,
3175			closeMethod  : 'zoomOut',
3176
3177			// Changing next gallery item
3178			nextEffect : 'elastic', // 'elastic', 'fade' or 'none'
3179			nextSpeed  : 250,
3180			nextEasing : 'swing',
3181			nextMethod : 'changeIn',
3182
3183			// Changing previous gallery item
3184			prevEffect : 'elastic', // 'elastic', 'fade' or 'none'
3185			prevSpeed  : 250,
3186			prevEasing : 'swing',
3187			prevMethod : 'changeOut',
3188
3189			// Enable default helpers
3190			helpers : {
3191				overlay : true,
3192				title   : true
3193			},
3194
3195			// Callbacks
3196			onCancel     : $.noop, // If canceling
3197			beforeLoad   : $.noop, // Before loading
3198			afterLoad    : $.noop, // After loading
3199			beforeShow   : $.noop, // Before changing in current item
3200			afterShow    : $.noop, // After opening
3201			beforeChange : $.noop, // Before changing gallery item
3202			beforeClose  : $.noop, // Before closing
3203			afterClose   : $.noop  // After closing
3204		},
3205
3206		//Current state
3207		group    : {}, // Selected group
3208		opts     : {}, // Group options
3209		previous : null,  // Previous element
3210		coming   : null,  // Element being loaded
3211		current  : null,  // Currently loaded element
3212		isActive : false, // Is activated
3213		isOpen   : false, // Is currently open
3214		isOpened : false, // Have been fully opened at least once
3215
3216		wrap  : null,
3217		skin  : null,
3218		outer : null,
3219		inner : null,
3220
3221		player : {
3222			timer    : null,
3223			isActive : false
3224		},
3225
3226		// Loaders
3227		ajaxLoad   : null,
3228		imgPreload : null,
3229
3230		// Some collections
3231		transitions : {},
3232		helpers     : {},
3233
3234		/*
3235		 *	Static methods
3236		 */
3237
3238		open: function (group, opts) {
3239			if (!group) {
3240				return;
3241			}
3242
3243			if (!$.isPlainObject(opts)) {
3244				opts = {};
3245			}
3246
3247			// Close if already active
3248			if (false === F.close(true)) {
3249				return;
3250			}
3251
3252			// Normalize group
3253			if (!$.isArray(group)) {
3254				group = isQuery(group) ? $(group).get() : [group];
3255			}
3256
3257			// Recheck if the type of each element is `object` and set content type (image, ajax, etc)
3258			$.each(group, function(i, element) {
3259				var obj = {},
3260					href,
3261					title,
3262					content,
3263					type,
3264					rez,
3265					hrefParts,
3266					selector;
3267
3268				if ($.type(element) === "object") {
3269					// Check if is DOM element
3270					if (element.nodeType) {
3271						element = $(element);
3272					}
3273
3274					if (isQuery(element)) {
3275						obj = {
3276							href    : element.data('fancybox-href') || element.attr('href'),
3277							title   : $('<div/>').text( element.data('fancybox-title') || element.attr('title') || '' ).html(),
3278							isDom   : true,
3279							element : element
3280						};
3281
3282						if ($.metadata) {
3283							$.extend(true, obj, element.metadata());
3284						}
3285
3286					} else {
3287						obj = element;
3288					}
3289				}
3290
3291				href  = opts.href  || obj.href || (isString(element) ? element : null);
3292				title = opts.title !== undefined ? opts.title : obj.title || '';
3293
3294				content = opts.content || obj.content;
3295				type    = content ? 'html' : (opts.type  || obj.type);
3296
3297				if (!type && obj.isDom) {
3298					type = element.data('fancybox-type');
3299
3300					if (!type) {
3301						rez  = element.prop('class').match(/fancybox\.(\w+)/);
3302						type = rez ? rez[1] : null;
3303					}
3304				}
3305
3306				if (isString(href)) {
3307					// Try to guess the content type
3308					if (!type) {
3309						if (F.isImage(href)) {
3310							type = 'image';
3311
3312						} else if (F.isSWF(href)) {
3313							type = 'swf';
3314
3315						} else if (href.charAt(0) === '#') {
3316							type = 'inline';
3317
3318						} else if (isString(element)) {
3319							type    = 'html';
3320							content = element;
3321						}
3322					}
3323
3324					// Split url into two pieces with source url and content selector, e.g,
3325					// "/mypage.html #my_id" will load "/mypage.html" and display element having id "my_id"
3326					if (type === 'ajax') {
3327						hrefParts = href.split(/\s+/, 2);
3328						href      = hrefParts.shift();
3329						selector  = hrefParts.shift();
3330					}
3331				}
3332
3333				if (!content) {
3334					if (type === 'inline') {
3335						if (href) {
3336							content = $( isString(href) ? href.replace(/.*(?=#[^\s]+$)/, '') : href ); //strip for ie7
3337
3338						} else if (obj.isDom) {
3339							content = element;
3340						}
3341
3342					} else if (type === 'html') {
3343						content = href;
3344
3345					} else if (!type && !href && obj.isDom) {
3346						type    = 'inline';
3347						content = element;
3348					}
3349				}
3350
3351				$.extend(obj, {
3352					href     : href,
3353					type     : type,
3354					content  : content,
3355					title    : title,
3356					selector : selector
3357				});
3358
3359				group[ i ] = obj;
3360			});
3361
3362			// Extend the defaults
3363			F.opts = $.extend(true, {}, F.defaults, opts);
3364
3365			// All options are merged recursive except keys
3366			if (opts.keys !== undefined) {
3367				F.opts.keys = opts.keys ? $.extend({}, F.defaults.keys, opts.keys) : false;
3368			}
3369
3370			F.group = group;
3371
3372			return F._start(F.opts.index);
3373		},
3374
3375		// Cancel image loading or abort ajax request
3376		cancel: function () {
3377			var coming = F.coming;
3378
3379			if (coming && false === F.trigger('onCancel')) {
3380				return;
3381			}
3382
3383			F.hideLoading();
3384
3385			if (!coming) {
3386				return;
3387			}
3388
3389			if (F.ajaxLoad) {
3390				F.ajaxLoad.abort();
3391			}
3392
3393			F.ajaxLoad = null;
3394
3395			if (F.imgPreload) {
3396				F.imgPreload.onload = F.imgPreload.onerror = null;
3397			}
3398
3399			if (coming.wrap) {
3400				coming.wrap.stop(true, true).trigger('onReset').remove();
3401			}
3402
3403			F.coming = null;
3404
3405			// If the first item has been canceled, then clear everything
3406			if (!F.current) {
3407				F._afterZoomOut( coming );
3408			}
3409		},
3410
3411		// Start closing animation if is open; remove immediately if opening/closing
3412		close: function (event) {
3413			F.cancel();
3414
3415			if (false === F.trigger('beforeClose')) {
3416				return;
3417			}
3418
3419			F.unbindEvents();
3420
3421			if (!F.isActive) {
3422				return;
3423			}
3424
3425			if (!F.isOpen || event === true) {
3426				$('.fancybox-wrap').stop(true).trigger('onReset').remove();
3427
3428				F._afterZoomOut();
3429
3430			} else {
3431				F.isOpen = F.isOpened = false;
3432				F.isClosing = true;
3433
3434				$('.fancybox-item, .fancybox-nav').remove();
3435
3436				F.wrap.stop(true, true).removeClass('fancybox-opened');
3437
3438				F.transitions[ F.current.closeMethod ]();
3439			}
3440		},
3441
3442		// Manage slideshow:
3443		//   $.fancybox.play(); - toggle slideshow
3444		//   $.fancybox.play( true ); - start
3445		//   $.fancybox.play( false ); - stop
3446		play: function ( action ) {
3447			var clear = function () {
3448					clearTimeout(F.player.timer);
3449				},
3450				set = function () {
3451					clear();
3452
3453					if (F.current && F.player.isActive) {
3454						F.player.timer = setTimeout(F.next, F.current.playSpeed);
3455					}
3456				},
3457				stop = function () {
3458					clear();
3459
3460					D.unbind('.player');
3461
3462					F.player.isActive = false;
3463
3464					F.trigger('onPlayEnd');
3465				},
3466				start = function () {
3467					if (F.current && (F.current.loop || F.current.index < F.group.length - 1)) {
3468						F.player.isActive = true;
3469
3470						D.bind({
3471							'onCancel.player beforeClose.player' : stop,
3472							'onUpdate.player'   : set,
3473							'beforeLoad.player' : clear
3474						});
3475
3476						set();
3477
3478						F.trigger('onPlayStart');
3479					}
3480				};
3481
3482			if (action === true || (!F.player.isActive && action !== false)) {
3483				start();
3484			} else {
3485				stop();
3486			}
3487		},
3488
3489		// Navigate to next gallery item
3490		next: function ( direction ) {
3491			var current = F.current;
3492
3493			if (current) {
3494				if (!isString(direction)) {
3495					direction = current.direction.next;
3496				}
3497
3498				F.jumpto(current.index + 1, direction, 'next');
3499			}
3500		},
3501
3502		// Navigate to previous gallery item
3503		prev: function ( direction ) {
3504			var current = F.current;
3505
3506			if (current) {
3507				if (!isString(direction)) {
3508					direction = current.direction.prev;
3509				}
3510
3511				F.jumpto(current.index - 1, direction, 'prev');
3512			}
3513		},
3514
3515		// Navigate to gallery item by index
3516		jumpto: function ( index, direction, router ) {
3517			var current = F.current;
3518
3519			if (!current) {
3520				return;
3521			}
3522
3523			index = getScalar(index);
3524
3525			F.direction = direction || current.direction[ (index >= current.index ? 'next' : 'prev') ];
3526			F.router    = router || 'jumpto';
3527
3528			if (current.loop) {
3529				if (index < 0) {
3530					index = current.group.length + (index % current.group.length);
3531				}
3532
3533				index = index % current.group.length;
3534			}
3535
3536			if (current.group[ index ] !== undefined) {
3537				F.cancel();
3538
3539				F._start(index);
3540			}
3541		},
3542
3543		// Center inside viewport and toggle position type to fixed or absolute if needed
3544		reposition: function (e, onlyAbsolute) {
3545			var current = F.current,
3546				wrap    = current ? current.wrap : null,
3547				pos;
3548
3549			if (wrap) {
3550				pos = F._getPosition(onlyAbsolute);
3551
3552				if (e && e.type === 'scroll') {
3553					delete pos.position;
3554
3555					wrap.stop(true, true).animate(pos, 200);
3556
3557				} else {
3558					wrap.css(pos);
3559
3560					current.pos = $.extend({}, current.dim, pos);
3561				}
3562			}
3563		},
3564
3565		update: function (e) {
3566			var type = (e && e.originalEvent && e.originalEvent.type),
3567				anyway = !type || type === 'orientationchange';
3568
3569			if (anyway) {
3570				clearTimeout(didUpdate);
3571
3572				didUpdate = null;
3573			}
3574
3575			if (!F.isOpen || didUpdate) {
3576				return;
3577			}
3578
3579			didUpdate = setTimeout(function() {
3580				var current = F.current;
3581
3582				if (!current || F.isClosing) {
3583					return;
3584				}
3585
3586				F.wrap.removeClass('fancybox-tmp');
3587
3588				if (anyway || type === 'load' || (type === 'resize' && current.autoResize)) {
3589					F._setDimension();
3590				}
3591
3592				if (!(type === 'scroll' && current.canShrink)) {
3593					F.reposition(e);
3594				}
3595
3596				F.trigger('onUpdate');
3597
3598				didUpdate = null;
3599
3600			}, (anyway && !isTouch ? 0 : 300));
3601		},
3602
3603		// Shrink content to fit inside viewport or restore if resized
3604		toggle: function ( action ) {
3605			if (F.isOpen) {
3606				F.current.fitToView = $.type(action) === "boolean" ? action : !F.current.fitToView;
3607
3608				// Help browser to restore document dimensions
3609				if (isTouch) {
3610					F.wrap.removeAttr('style').addClass('fancybox-tmp');
3611
3612					F.trigger('onUpdate');
3613				}
3614
3615				F.update();
3616			}
3617		},
3618
3619		hideLoading: function () {
3620			D.unbind('.loading');
3621
3622			$('#fancybox-loading').remove();
3623		},
3624
3625		showLoading: function () {
3626			var el, viewport;
3627
3628			F.hideLoading();
3629
3630			el = $(F.opts.tpl.loading).click(F.cancel).appendTo('body');
3631
3632			// If user will press the escape-button, the request will be canceled
3633			D.bind('keydown.loading', function(e) {
3634				if ((e.which || e.keyCode) === 27) {
3635					e.preventDefault();
3636
3637					F.cancel();
3638				}
3639			});
3640
3641			if (!F.defaults.fixed) {
3642				viewport = F.getViewport();
3643
3644				el.css({
3645					position : 'absolute',
3646					top  : (viewport.h * 0.5) + viewport.y,
3647					left : (viewport.w * 0.5) + viewport.x
3648				});
3649			}
3650
3651			F.trigger('onLoading');
3652		},
3653
3654		getViewport: function () {
3655			var locked = (F.current && F.current.locked) || false,
3656				rez    = {
3657					x: W.scrollLeft(),
3658					y: W.scrollTop()
3659				};
3660
3661			if (locked && locked.length) {
3662				rez.w = locked[0].clientWidth;
3663				rez.h = locked[0].clientHeight;
3664
3665			} else {
3666				// See http://bugs.jquery.com/ticket/6724
3667				rez.w = isTouch && window.innerWidth  ? window.innerWidth  : W.width();
3668				rez.h = isTouch && window.innerHeight ? window.innerHeight : W.height();
3669			}
3670
3671			return rez;
3672		},
3673
3674		// Unbind the keyboard / clicking actions
3675		unbindEvents: function () {
3676			if (F.wrap && isQuery(F.wrap)) {
3677				F.wrap.unbind('.fb');
3678			}
3679
3680			D.unbind('.fb');
3681			W.unbind('.fb');
3682		},
3683
3684		bindEvents: function () {
3685			var current = F.current,
3686				keys;
3687
3688			if (!current) {
3689				return;
3690			}
3691
3692			// Changing document height on iOS devices triggers a 'resize' event,
3693			// that can change document height... repeating infinitely
3694			W.bind('orientationchange.fb' + (isTouch ? '' : ' resize.fb') + (current.autoCenter && !current.locked ? ' scroll.fb' : ''), F.update);
3695
3696			keys = current.keys;
3697
3698			if (keys) {
3699				D.bind('keydown.fb', function (e) {
3700					var code   = e.which || e.keyCode,
3701						target = e.target || e.srcElement;
3702
3703					// Skip esc key if loading, because showLoading will cancel preloading
3704					if (code === 27 && F.coming) {
3705						return false;
3706					}
3707
3708					// Ignore key combinations and key events within form elements
3709					if (!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey && !(target && (target.type || $(target).is('[contenteditable]')))) {
3710						$.each(keys, function(i, val) {
3711							if (current.group.length > 1 && val[ code ] !== undefined) {
3712								F[ i ]( val[ code ] );
3713
3714								e.preventDefault();
3715								return false;
3716							}
3717
3718							if ($.inArray(code, val) > -1) {
3719								F[ i ] ();
3720
3721								e.preventDefault();
3722								return false;
3723							}
3724						});
3725					}
3726				});
3727			}
3728
3729			if ($.fn.mousewheel && current.mouseWheel) {
3730				F.wrap.bind('mousewheel.fb', function (e, delta, deltaX, deltaY) {
3731					var target = e.target || null,
3732						parent = $(target),
3733						canScroll = false;
3734
3735					while (parent.length) {
3736						if (canScroll || parent.is('.fancybox-skin') || parent.is('.fancybox-wrap')) {
3737							break;
3738						}
3739
3740						canScroll = isScrollable( parent[0] );
3741						parent    = $(parent).parent();
3742					}
3743
3744					if (delta !== 0 && !canScroll) {
3745						if (F.group.length > 1 && !current.canShrink) {
3746							if (deltaY > 0 || deltaX > 0) {
3747								F.prev( deltaY > 0 ? 'down' : 'left' );
3748
3749							} else if (deltaY < 0 || deltaX < 0) {
3750								F.next( deltaY < 0 ? 'up' : 'right' );
3751							}
3752
3753							e.preventDefault();
3754						}
3755					}
3756				});
3757			}
3758		},
3759
3760		trigger: function (event, o) {
3761			var ret, obj = o || F.coming || F.current;
3762
3763			if (obj) {
3764				if ($.isFunction( obj[event] )) {
3765					ret = obj[event].apply(obj, Array.prototype.slice.call(arguments, 1));
3766				}
3767
3768				if (ret === false) {
3769					return false;
3770				}
3771
3772				if (obj.helpers) {
3773					$.each(obj.helpers, function (helper, opts) {
3774						if (opts && F.helpers[helper] && $.isFunction(F.helpers[helper][event])) {
3775							F.helpers[helper][event]($.extend(true, {}, F.helpers[helper].defaults, opts), obj);
3776						}
3777					});
3778				}
3779			}
3780
3781			D.trigger(event);
3782		},
3783
3784		isImage: function (str) {
3785			return isString(str) && str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i);
3786		},
3787
3788		isSWF: function (str) {
3789			return isString(str) && str.match(/\.(swf)((\?|#).*)?$/i);
3790		},
3791
3792		_start: function (index) {
3793			var coming = {},
3794				obj,
3795				href,
3796				type,
3797				margin,
3798				padding;
3799
3800			index = getScalar( index );
3801			obj   = F.group[ index ] || null;
3802
3803			if (!obj) {
3804				return false;
3805			}
3806
3807			coming = $.extend(true, {}, F.opts, obj);
3808
3809			// Convert margin and padding properties to array - top, right, bottom, left
3810			margin  = coming.margin;
3811			padding = coming.padding;
3812
3813			if ($.type(margin) === 'number') {
3814				coming.margin = [margin, margin, margin, margin];
3815			}
3816
3817			if ($.type(padding) === 'number') {
3818				coming.padding = [padding, padding, padding, padding];
3819			}
3820
3821			// 'modal' propery is just a shortcut
3822			if (coming.modal) {
3823				$.extend(true, coming, {
3824					closeBtn   : false,
3825					closeClick : false,
3826					nextClick  : false,
3827					arrows     : false,
3828					mouseWheel : false,
3829					keys       : null,
3830					helpers: {
3831						overlay : {
3832							closeClick : false
3833						}
3834					}
3835				});
3836			}
3837
3838			// 'autoSize' property is a shortcut, too
3839			if (coming.autoSize) {
3840				coming.autoWidth = coming.autoHeight = true;
3841			}
3842
3843			if (coming.width === 'auto') {
3844				coming.autoWidth = true;
3845			}
3846
3847			if (coming.height === 'auto') {
3848				coming.autoHeight = true;
3849			}
3850
3851			/*
3852			 * Add reference to the group, so it`s possible to access from callbacks, example:
3853			 * afterLoad : function() {
3854			 *     this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : '');
3855			 * }
3856			 */
3857
3858			coming.group  = F.group;
3859			coming.index  = index;
3860
3861			// Give a chance for callback or helpers to update coming item (type, title, etc)
3862			F.coming = coming;
3863
3864			if (false === F.trigger('beforeLoad')) {
3865				F.coming = null;
3866
3867				return;
3868			}
3869
3870			type = coming.type;
3871			href = coming.href;
3872
3873			if (!type) {
3874				F.coming = null;
3875
3876				//If we can not determine content type then drop silently or display next/prev item if looping through gallery
3877				if (F.current && F.router && F.router !== 'jumpto') {
3878					F.current.index = index;
3879
3880					return F[ F.router ]( F.direction );
3881				}
3882
3883				return false;
3884			}
3885
3886			F.isActive = true;
3887
3888			if (type === 'image' || type === 'swf') {
3889				coming.autoHeight = coming.autoWidth = false;
3890				coming.scrolling  = 'visible';
3891			}
3892
3893			if (type === 'image') {
3894				coming.aspectRatio = true;
3895			}
3896
3897			if (type === 'iframe' && isTouch) {
3898				coming.scrolling = 'scroll';
3899			}
3900
3901			// Build the neccessary markup
3902			coming.wrap = $(coming.tpl.wrap).addClass('fancybox-' + (isTouch ? 'mobile' : 'desktop') + ' fancybox-type-' + type + ' fancybox-tmp ' + coming.wrapCSS).appendTo( coming.parent || 'body' );
3903
3904			$.extend(coming, {
3905				skin  : $('.fancybox-skin',  coming.wrap),
3906				outer : $('.fancybox-outer', coming.wrap),
3907				inner : $('.fancybox-inner', coming.wrap)
3908			});
3909
3910			$.each(["Top", "Right", "Bottom", "Left"], function(i, v) {
3911				coming.skin.css('padding' + v, getValue(coming.padding[ i ]));
3912			});
3913
3914			F.trigger('onReady');
3915
3916			// Check before try to load; 'inline' and 'html' types need content, others - href
3917			if (type === 'inline' || type === 'html') {
3918				if (!coming.content || !coming.content.length) {
3919					return F._error( 'content' );
3920				}
3921
3922			} else if (!href) {
3923				return F._error( 'href' );
3924			}
3925
3926			if (type === 'image') {
3927				F._loadImage();
3928
3929			} else if (type === 'ajax') {
3930				F._loadAjax();
3931
3932			} else if (type === 'iframe') {
3933				F._loadIframe();
3934
3935			} else {
3936				F._afterLoad();
3937			}
3938		},
3939
3940		_error: function ( type ) {
3941			$.extend(F.coming, {
3942				type       : 'html',
3943				autoWidth  : true,
3944				autoHeight : true,
3945				minWidth   : 0,
3946				minHeight  : 0,
3947				scrolling  : 'no',
3948				hasError   : type,
3949				content    : F.coming.tpl.error
3950			});
3951
3952			F._afterLoad();
3953		},
3954
3955		_loadImage: function () {
3956			// Reset preload image so it is later possible to check "complete" property
3957			var img = F.imgPreload = new Image();
3958
3959			img.onload = function () {
3960				this.onload = this.onerror = null;
3961
3962				F.coming.width  = this.width / F.opts.pixelRatio;
3963				F.coming.height = this.height / F.opts.pixelRatio;
3964
3965				F._afterLoad();
3966			};
3967
3968			img.onerror = function () {
3969				this.onload = this.onerror = null;
3970
3971				F._error( 'image' );
3972			};
3973
3974			img.src = F.coming.href;
3975
3976			if (img.complete !== true) {
3977				F.showLoading();
3978			}
3979		},
3980
3981		_loadAjax: function () {
3982			var coming = F.coming;
3983
3984			F.showLoading();
3985
3986			F.ajaxLoad = $.ajax($.extend({}, coming.ajax, {
3987				url: coming.href,
3988				error: function (jqXHR, textStatus) {
3989					if (F.coming && textStatus !== 'abort') {
3990						F._error( 'ajax', jqXHR );
3991
3992					} else {
3993						F.hideLoading();
3994					}
3995				},
3996				success: function (data, textStatus) {
3997					if (textStatus === 'success') {
3998						coming.content = data;
3999
4000						F._afterLoad();
4001					}
4002				}
4003			}));
4004		},
4005
4006		_loadIframe: function() {
4007			var coming = F.coming,
4008				iframe = $(coming.tpl.iframe.replace(/\{rnd\}/g, new Date().getTime()))
4009					.attr('scrolling', isTouch ? 'auto' : coming.iframe.scrolling)
4010					.attr('src', coming.href);
4011
4012			// This helps IE
4013			$(coming.wrap).bind('onReset', function () {
4014				try {
4015					$(this).find('iframe').hide().attr('src', '//about:blank').end().empty();
4016				} catch (e) {}
4017			});
4018
4019			if (coming.iframe.preload) {
4020				F.showLoading();
4021
4022				iframe.one('load', function() {
4023					$(this).data('ready', 1);
4024
4025					// iOS will lose scrolling if we resize
4026					if (!isTouch) {
4027						$(this).bind('load.fb', F.update);
4028					}
4029
4030					// Without this trick:
4031					//   - iframe won't scroll on iOS devices
4032					//   - IE7 sometimes displays empty iframe
4033					$(this).parents('.fancybox-wrap').width('100%').removeClass('fancybox-tmp').show();
4034
4035					F._afterLoad();
4036				});
4037			}
4038
4039			coming.content = iframe.appendTo( coming.inner );
4040
4041			if (!coming.iframe.preload) {
4042				F._afterLoad();
4043			}
4044		},
4045
4046		_preloadImages: function() {
4047			var group   = F.group,
4048				current = F.current,
4049				len     = group.length,
4050				cnt     = current.preload ? Math.min(current.preload, len - 1) : 0,
4051				item,
4052				i;
4053
4054			for (i = 1; i <= cnt; i += 1) {
4055				item = group[ (current.index + i ) % len ];
4056
4057				if (item.type === 'image' && item.href) {
4058					new Image().src = item.href;
4059				}
4060			}
4061		},
4062
4063		_afterLoad: function () {
4064			var coming   = F.coming,
4065				previous = F.current,
4066				placeholder = 'fancybox-placeholder',
4067				current,
4068				content,
4069				type,
4070				scrolling,
4071				href,
4072				embed;
4073
4074			F.hideLoading();
4075
4076			if (!coming || F.isActive === false) {
4077				return;
4078			}
4079
4080			if (false === F.trigger('afterLoad', coming, previous)) {
4081				coming.wrap.stop(true).trigger('onReset').remove();
4082
4083				F.coming = null;
4084
4085				return;
4086			}
4087
4088			if (previous) {
4089				F.trigger('beforeChange', previous);
4090
4091				previous.wrap.stop(true).removeClass('fancybox-opened')
4092					.find('.fancybox-item, .fancybox-nav')
4093					.remove();
4094			}
4095
4096			F.unbindEvents();
4097
4098			current   = coming;
4099			content   = coming.content;
4100			type      = coming.type;
4101			scrolling = coming.scrolling;
4102
4103			$.extend(F, {
4104				wrap  : current.wrap,
4105				skin  : current.skin,
4106				outer : current.outer,
4107				inner : current.inner,
4108				current  : current,
4109				previous : previous
4110			});
4111
4112			href = current.href;
4113
4114			switch (type) {
4115				case 'inline':
4116				case 'ajax':
4117				case 'html':
4118					if (current.selector) {
4119						content = $('<div>').html(content).find(current.selector);
4120
4121					} else if (isQuery(content)) {
4122						if (!content.data(placeholder)) {
4123							content.data(placeholder, $('<div class="' + placeholder + '"></div>').insertAfter( content ).hide() );
4124						}
4125
4126						content = content.show().detach();
4127
4128						current.wrap.bind('onReset', function () {
4129							if ($(this).find(content).length) {
4130								content.hide().replaceAll( content.data(placeholder) ).data(placeholder, false);
4131							}
4132						});
4133					}
4134				break;
4135
4136				case 'image':
4137					content = current.tpl.image.replace(/\{href\}/g, href);
4138				break;
4139
4140				case 'swf':
4141					content = '<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="' + href + '"></param>';
4142					embed   = '';
4143
4144					$.each(current.swf, function(name, val) {
4145						content += '<param name="' + name + '" value="' + val + '"></param>';
4146						embed   += ' ' + name + '="' + val + '"';
4147					});
4148
4149					content += '<embed src="' + href + '" type="application/x-shockwave-flash" width="100%" height="100%"' + embed + '></embed></object>';
4150				break;
4151			}
4152
4153			if (!(isQuery(content) && content.parent().is(current.inner))) {
4154				current.inner.append( content );
4155			}
4156
4157			// Give a chance for helpers or callbacks to update elements
4158			F.trigger('beforeShow');
4159
4160			// Set scrolling before calculating dimensions
4161			current.inner.css('overflow', scrolling === 'yes' ? 'scroll' : (scrolling === 'no' ? 'hidden' : scrolling));
4162
4163			// Set initial dimensions and start position
4164			F._setDimension();
4165
4166			F.reposition();
4167
4168			F.isOpen = false;
4169			F.coming = null;
4170
4171			F.bindEvents();
4172
4173			if (!F.isOpened) {
4174				$('.fancybox-wrap').not( current.wrap ).stop(true).trigger('onReset').remove();
4175
4176			} else if (previous.prevMethod) {
4177				F.transitions[ previous.prevMethod ]();
4178			}
4179
4180			F.transitions[ F.isOpened ? current.nextMethod : current.openMethod ]();
4181
4182			F._preloadImages();
4183		},
4184
4185		_setDimension: function () {
4186			var viewport   = F.getViewport(),
4187				steps      = 0,
4188				canShrink  = false,
4189				canExpand  = false,
4190				wrap       = F.wrap,
4191				skin       = F.skin,
4192				inner      = F.inner,
4193				current    = F.current,
4194				width      = current.width,
4195				height     = current.height,
4196				minWidth   = current.minWidth,
4197				minHeight  = current.minHeight,
4198				maxWidth   = current.maxWidth,
4199				maxHeight  = current.maxHeight,
4200				scrolling  = current.scrolling,
4201				scrollOut  = current.scrollOutside ? current.scrollbarWidth : 0,
4202				margin     = current.margin,
4203				wMargin    = getScalar(margin[1] + margin[3]),
4204				hMargin    = getScalar(margin[0] + margin[2]),
4205				wPadding,
4206				hPadding,
4207				wSpace,
4208				hSpace,
4209				origWidth,
4210				origHeight,
4211				origMaxWidth,
4212				origMaxHeight,
4213				ratio,
4214				width_,
4215				height_,
4216				maxWidth_,
4217				maxHeight_,
4218				iframe,
4219				body;
4220
4221			// Reset dimensions so we could re-check actual size
4222			wrap.add(skin).add(inner).width('auto').height('auto').removeClass('fancybox-tmp');
4223
4224			wPadding = getScalar(skin.outerWidth(true)  - skin.width());
4225			hPadding = getScalar(skin.outerHeight(true) - skin.height());
4226
4227			// Any space between content and viewport (margin, padding, border, title)
4228			wSpace = wMargin + wPadding;
4229			hSpace = hMargin + hPadding;
4230
4231			origWidth  = isPercentage(width)  ? (viewport.w - wSpace) * getScalar(width)  / 100 : width;
4232			origHeight = isPercentage(height) ? (viewport.h - hSpace) * getScalar(height) / 100 : height;
4233
4234			if (current.type === 'iframe') {
4235				iframe = current.content;
4236
4237				if (current.autoHeight && iframe && iframe.data('ready') === 1) {
4238					try {
4239						if (iframe[0].contentWindow.document.location) {
4240							inner.width( origWidth ).height(9999);
4241
4242							body = iframe.contents().find('body');
4243
4244							if (scrollOut) {
4245								body.css('overflow-x', 'hidden');
4246							}
4247
4248							origHeight = body.outerHeight(true);
4249						}
4250
4251					} catch (e) {}
4252				}
4253
4254			} else if (current.autoWidth || current.autoHeight) {
4255				inner.addClass( 'fancybox-tmp' );
4256
4257				// Set width or height in case we need to calculate only one dimension
4258				if (!current.autoWidth) {
4259					inner.width( origWidth );
4260				}
4261
4262				if (!current.autoHeight) {
4263					inner.height( origHeight );
4264				}
4265
4266				if (current.autoWidth) {
4267					origWidth = inner.width();
4268				}
4269
4270				if (current.autoHeight) {
4271					origHeight = inner.height();
4272				}
4273
4274				inner.removeClass( 'fancybox-tmp' );
4275			}
4276
4277			width  = getScalar( origWidth );
4278			height = getScalar( origHeight );
4279
4280			ratio  = origWidth / origHeight;
4281
4282			// Calculations for the content
4283			minWidth  = getScalar(isPercentage(minWidth) ? getScalar(minWidth, 'w') - wSpace : minWidth);
4284			maxWidth  = getScalar(isPercentage(maxWidth) ? getScalar(maxWidth, 'w') - wSpace : maxWidth);
4285
4286			minHeight = getScalar(isPercentage(minHeight) ? getScalar(minHeight, 'h') - hSpace : minHeight);
4287			maxHeight = getScalar(isPercentage(maxHeight) ? getScalar(maxHeight, 'h') - hSpace : maxHeight);
4288
4289			// These will be used to determine if wrap can fit in the viewport
4290			origMaxWidth  = maxWidth;
4291			origMaxHeight = maxHeight;
4292
4293			if (current.fitToView) {
4294				maxWidth  = Math.min(viewport.w - wSpace, maxWidth);
4295				maxHeight = Math.min(viewport.h - hSpace, maxHeight);
4296			}
4297
4298			maxWidth_  = viewport.w - wMargin;
4299			maxHeight_ = viewport.h - hMargin;
4300
4301			if (current.aspectRatio) {
4302				if (width > maxWidth) {
4303					width  = maxWidth;
4304					height = getScalar(width / ratio);
4305				}
4306
4307				if (height > maxHeight) {
4308					height = maxHeight;
4309					width  = getScalar(height * ratio);
4310				}
4311
4312				if (width < minWidth) {
4313					width  = minWidth;
4314					height = getScalar(width / ratio);
4315				}
4316
4317				if (height < minHeight) {
4318					height = minHeight;
4319					width  = getScalar(height * ratio);
4320				}
4321
4322			} else {
4323				width = Math.max(minWidth, Math.min(width, maxWidth));
4324
4325				if (current.autoHeight && current.type !== 'iframe') {
4326					inner.width( width );
4327
4328					height = inner.height();
4329				}
4330
4331				height = Math.max(minHeight, Math.min(height, maxHeight));
4332			}
4333
4334			// Try to fit inside viewport (including the title)
4335			if (current.fitToView) {
4336				inner.width( width ).height( height );
4337
4338				wrap.width( width + wPadding );
4339
4340				// Real wrap dimensions
4341				width_  = wrap.width();
4342				height_ = wrap.height();
4343
4344				if (current.aspectRatio) {
4345					while ((width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight) {
4346						if (steps++ > 19) {
4347							break;
4348						}
4349
4350						height = Math.max(minHeight, Math.min(maxHeight, height - 10));
4351						width  = getScalar(height * ratio);
4352
4353						if (width < minWidth) {
4354							width  = minWidth;
4355							height = getScalar(width / ratio);
4356						}
4357
4358						if (width > maxWidth) {
4359							width  = maxWidth;
4360							height = getScalar(width / ratio);
4361						}
4362
4363						inner.width( width ).height( height );
4364
4365						wrap.width( width + wPadding );
4366
4367						width_  = wrap.width();
4368						height_ = wrap.height();
4369					}
4370
4371				} else {
4372					width  = Math.max(minWidth,  Math.min(width,  width  - (width_  - maxWidth_)));
4373					height = Math.max(minHeight, Math.min(height, height - (height_ - maxHeight_)));
4374				}
4375			}
4376
4377			if (scrollOut && scrolling === 'auto' && height < origHeight && (width + wPadding + scrollOut) < maxWidth_) {
4378				width += scrollOut;
4379			}
4380
4381			inner.width( width ).height( height );
4382
4383			wrap.width( width + wPadding );
4384
4385			width_  = wrap.width();
4386			height_ = wrap.height();
4387
4388			canShrink = (width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight;
4389			canExpand = current.aspectRatio ? (width < origMaxWidth && height < origMaxHeight && width < origWidth && height < origHeight) : ((width < origMaxWidth || height < origMaxHeight) && (width < origWidth || height < origHeight));
4390
4391			$.extend(current, {
4392				dim : {
4393					width	: getValue( width_ ),
4394					height	: getValue( height_ )
4395				},
4396				origWidth  : origWidth,
4397				origHeight : origHeight,
4398				canShrink  : canShrink,
4399				canExpand  : canExpand,
4400				wPadding   : wPadding,
4401				hPadding   : hPadding,
4402				wrapSpace  : height_ - skin.outerHeight(true),
4403				skinSpace  : skin.height() - height
4404			});
4405
4406			if (!iframe && current.autoHeight && height > minHeight && height < maxHeight && !canExpand) {
4407				inner.height('auto');
4408			}
4409		},
4410
4411		_getPosition: function (onlyAbsolute) {
4412			var current  = F.current,
4413				viewport = F.getViewport(),
4414				margin   = current.margin,
4415				width    = F.wrap.width()  + margin[1] + margin[3],
4416				height   = F.wrap.height() + margin[0] + margin[2],
4417				rez      = {
4418					position: 'absolute',
4419					top  : margin[0],
4420					left : margin[3]
4421				};
4422
4423			if (current.autoCenter && current.fixed && !onlyAbsolute && height <= viewport.h && width <= viewport.w) {
4424				rez.position = 'fixed';
4425
4426			} else if (!current.locked) {
4427				rez.top  += viewport.y;
4428				rez.left += viewport.x;
4429			}
4430
4431			rez.top  = getValue(Math.max(rez.top,  rez.top  + ((viewport.h - height) * current.topRatio)));
4432			rez.left = getValue(Math.max(rez.left, rez.left + ((viewport.w - width)  * current.leftRatio)));
4433
4434			return rez;
4435		},
4436
4437		_afterZoomIn: function () {
4438			var current = F.current;
4439
4440			if (!current) {
4441				return;
4442			}
4443
4444			F.isOpen = F.isOpened = true;
4445
4446			F.wrap.css('overflow', 'visible').addClass('fancybox-opened').hide().show(0);
4447
4448			F.update();
4449
4450			// Assign a click event
4451			if ( current.closeClick || (current.nextClick && F.group.length > 1) ) {
4452				F.inner.css('cursor', 'pointer').bind('click.fb', function(e) {
4453					if (!$(e.target).is('a') && !$(e.target).parent().is('a')) {
4454						e.preventDefault();
4455
4456						F[ current.closeClick ? 'close' : 'next' ]();
4457					}
4458				});
4459			}
4460
4461			// Create a close button
4462			if (current.closeBtn) {
4463				$(current.tpl.closeBtn).appendTo(F.skin).bind('click.fb', function(e) {
4464					e.preventDefault();
4465
4466					F.close();
4467				});
4468			}
4469
4470			// Create navigation arrows
4471			if (current.arrows && F.group.length > 1) {
4472				if (current.loop || current.index > 0) {
4473					$(current.tpl.prev).appendTo(F.outer).bind('click.fb', F.prev);
4474				}
4475
4476				if (current.loop || current.index < F.group.length - 1) {
4477					$(current.tpl.next).appendTo(F.outer).bind('click.fb', F.next);
4478				}
4479			}
4480
4481			F.trigger('afterShow');
4482
4483			// Stop the slideshow if this is the last item
4484			if (!current.loop && current.index === current.group.length - 1) {
4485
4486				F.play( false );
4487
4488			} else if (F.opts.autoPlay && !F.player.isActive) {
4489				F.opts.autoPlay = false;
4490
4491				F.play(true);
4492			}
4493		},
4494
4495		_afterZoomOut: function ( obj ) {
4496			obj = obj || F.current;
4497
4498			$('.fancybox-wrap').trigger('onReset').remove();
4499
4500			$.extend(F, {
4501				group  : {},
4502				opts   : {},
4503				router : false,
4504				current   : null,
4505				isActive  : false,
4506				isOpened  : false,
4507				isOpen    : false,
4508				isClosing : false,
4509				wrap   : null,
4510				skin   : null,
4511				outer  : null,
4512				inner  : null
4513			});
4514
4515			F.trigger('afterClose', obj);
4516		}
4517	});
4518
4519	/*
4520	 *	Default transitions
4521	 */
4522
4523	F.transitions = {
4524		getOrigPosition: function () {
4525			var current  = F.current,
4526				element  = current.element,
4527				orig     = current.orig,
4528				pos      = {},
4529				width    = 50,
4530				height   = 50,
4531				hPadding = current.hPadding,
4532				wPadding = current.wPadding,
4533				viewport = F.getViewport();
4534
4535			if (!orig && current.isDom && element.is(':visible')) {
4536				orig = element.find('img:first');
4537
4538				if (!orig.length) {
4539					orig = element;
4540				}
4541			}
4542
4543			if (isQuery(orig)) {
4544				pos = orig.offset();
4545
4546				if (orig.is('img')) {
4547					width  = orig.outerWidth();
4548					height = orig.outerHeight();
4549				}
4550
4551			} else {
4552				pos.top  = viewport.y + (viewport.h - height) * current.topRatio;
4553				pos.left = viewport.x + (viewport.w - width)  * current.leftRatio;
4554			}
4555
4556			if (F.wrap.css('position') === 'fixed' || current.locked) {
4557				pos.top  -= viewport.y;
4558				pos.left -= viewport.x;
4559			}
4560
4561			pos = {
4562				top     : getValue(pos.top  - hPadding * current.topRatio),
4563				left    : getValue(pos.left - wPadding * current.leftRatio),
4564				width   : getValue(width  + wPadding),
4565				height  : getValue(height + hPadding)
4566			};
4567
4568			return pos;
4569		},
4570
4571		step: function (now, fx) {
4572			var ratio,
4573				padding,
4574				value,
4575				prop       = fx.prop,
4576				current    = F.current,
4577				wrapSpace  = current.wrapSpace,
4578				skinSpace  = current.skinSpace;
4579
4580			if (prop === 'width' || prop === 'height') {
4581				ratio = fx.end === fx.start ? 1 : (now - fx.start) / (fx.end - fx.start);
4582
4583				if (F.isClosing) {
4584					ratio = 1 - ratio;
4585				}
4586
4587				padding = prop === 'width' ? current.wPadding : current.hPadding;
4588				value   = now - padding;
4589
4590				F.skin[ prop ](  getScalar( prop === 'width' ?  value : value - (wrapSpace * ratio) ) );
4591				F.inner[ prop ]( getScalar( prop === 'width' ?  value : value - (wrapSpace * ratio) - (skinSpace * ratio) ) );
4592			}
4593		},
4594
4595		zoomIn: function () {
4596			var current  = F.current,
4597				startPos = current.pos,
4598				effect   = current.openEffect,
4599				elastic  = effect === 'elastic',
4600				endPos   = $.extend({opacity : 1}, startPos);
4601
4602			// Remove "position" property that breaks older IE
4603			delete endPos.position;
4604
4605			if (elastic) {
4606				startPos = this.getOrigPosition();
4607
4608				if (current.openOpacity) {
4609					startPos.opacity = 0.1;
4610				}
4611
4612			} else if (effect === 'fade') {
4613				startPos.opacity = 0.1;
4614			}
4615
4616			F.wrap.css(startPos).animate(endPos, {
4617				duration : effect === 'none' ? 0 : current.openSpeed,
4618				easing   : current.openEasing,
4619				step     : elastic ? this.step : null,
4620				complete : F._afterZoomIn
4621			});
4622		},
4623
4624		zoomOut: function () {
4625			var current  = F.current,
4626				effect   = current.closeEffect,
4627				elastic  = effect === 'elastic',
4628				endPos   = {opacity : 0.1};
4629
4630			if (elastic) {
4631				endPos = this.getOrigPosition();
4632
4633				if (current.closeOpacity) {
4634					endPos.opacity = 0.1;
4635				}
4636			}
4637
4638			F.wrap.animate(endPos, {
4639				duration : effect === 'none' ? 0 : current.closeSpeed,
4640				easing   : current.closeEasing,
4641				step     : elastic ? this.step : null,
4642				complete : F._afterZoomOut
4643			});
4644		},
4645
4646		changeIn: function () {
4647			var current   = F.current,
4648				effect    = current.nextEffect,
4649				startPos  = current.pos,
4650				endPos    = { opacity : 1 },
4651				direction = F.direction,
4652				distance  = 200,
4653				field;
4654
4655			startPos.opacity = 0.1;
4656
4657			if (effect === 'elastic') {
4658				field = direction === 'down' || direction === 'up' ? 'top' : 'left';
4659
4660				if (direction === 'down' || direction === 'right') {
4661					startPos[ field ] = getValue(getScalar(startPos[ field ]) - distance);
4662					endPos[ field ]   = '+=' + distance + 'px';
4663
4664				} else {
4665					startPos[ field ] = getValue(getScalar(startPos[ field ]) + distance);
4666					endPos[ field ]   = '-=' + distance + 'px';
4667				}
4668			}
4669
4670			// Workaround for http://bugs.jquery.com/ticket/12273
4671			if (effect === 'none') {
4672				F._afterZoomIn();
4673
4674			} else {
4675				F.wrap.css(startPos).animate(endPos, {
4676					duration : current.nextSpeed,
4677					easing   : current.nextEasing,
4678					complete : F._afterZoomIn
4679				});
4680			}
4681		},
4682
4683		changeOut: function () {
4684			var previous  = F.previous,
4685				effect    = previous.prevEffect,
4686				endPos    = { opacity : 0.1 },
4687				direction = F.direction,
4688				distance  = 200;
4689
4690			if (effect === 'elastic') {
4691				endPos[ direction === 'down' || direction === 'up' ? 'top' : 'left' ] = ( direction === 'up' || direction === 'left' ? '-' : '+' ) + '=' + distance + 'px';
4692			}
4693
4694			previous.wrap.animate(endPos, {
4695				duration : effect === 'none' ? 0 : previous.prevSpeed,
4696				easing   : previous.prevEasing,
4697				complete : function () {
4698					$(this).trigger('onReset').remove();
4699				}
4700			});
4701		}
4702	};
4703
4704	/*
4705	 *	Overlay helper
4706	 */
4707
4708	F.helpers.overlay = {
4709		defaults : {
4710			closeClick : true,      // if true, fancyBox will be closed when user clicks on the overlay
4711			speedOut   : 200,       // duration of fadeOut animation
4712			showEarly  : true,      // indicates if should be opened immediately or wait until the content is ready
4713			css        : {},        // custom CSS properties
4714			locked     : !isTouch,  // if true, the content will be locked into overlay
4715			fixed      : true       // if false, the overlay CSS position property will not be set to "fixed"
4716		},
4717
4718		overlay : null,      // current handle
4719		fixed   : false,     // indicates if the overlay has position "fixed"
4720		el      : $('html'), // element that contains "the lock"
4721
4722		// Public methods
4723		create : function(opts) {
4724			var parent;
4725
4726			opts = $.extend({}, this.defaults, opts);
4727
4728			if (this.overlay) {
4729				this.close();
4730			}
4731
4732			parent = F.coming ? F.coming.parent : opts.parent;
4733
4734			this.overlay = $('<div class="fancybox-overlay"></div>').appendTo( parent && parent.length ? parent : 'body' );
4735			this.fixed   = false;
4736
4737			if (opts.fixed && F.defaults.fixed) {
4738				this.overlay.addClass('fancybox-overlay-fixed');
4739
4740				this.fixed = true;
4741			}
4742		},
4743
4744		open : function(opts) {
4745			var that = this;
4746
4747			opts = $.extend({}, this.defaults, opts);
4748
4749			if (this.overlay) {
4750				this.overlay.unbind('.overlay').width('auto').height('auto');
4751
4752			} else {
4753				this.create(opts);
4754			}
4755
4756			if (!this.fixed) {
4757				W.bind('resize.overlay', $.proxy( this.update, this) );
4758
4759				this.update();
4760			}
4761
4762			if (opts.closeClick) {
4763				this.overlay.bind('click.overlay', function(e) {
4764					if ($(e.target).hasClass('fancybox-overlay')) {
4765						if (F.isActive) {
4766							F.close();
4767						} else {
4768							that.close();
4769						}
4770
4771						return false;
4772					}
4773				});
4774			}
4775
4776			this.overlay.css( opts.css ).show();
4777		},
4778
4779		close : function() {
4780			W.unbind('resize.overlay');
4781
4782			if (this.el.hasClass('fancybox-lock')) {
4783				$('.fancybox-margin').removeClass('fancybox-margin');
4784
4785				this.el.removeClass('fancybox-lock');
4786
4787				W.scrollTop( this.scrollV ).scrollLeft( this.scrollH );
4788			}
4789
4790			$('.fancybox-overlay').remove().hide();
4791
4792			$.extend(this, {
4793				overlay : null,
4794				fixed   : false
4795			});
4796		},
4797
4798		// Private, callbacks
4799
4800		update : function () {
4801			var width = '100%', offsetWidth;
4802
4803			// Reset width/height so it will not mess
4804			this.overlay.width(width).height('100%');
4805
4806			// jQuery does not return reliable result for IE
4807			if (IE) {
4808				offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth);
4809
4810				if (D.width() > offsetWidth) {
4811					width = D.width();
4812				}
4813
4814			} else if (D.width() > W.width()) {
4815				width = D.width();
4816			}
4817
4818			this.overlay.width(width).height(D.height());
4819		},
4820
4821		// This is where we can manipulate DOM, because later it would cause iframes to reload
4822		onReady : function (opts, obj) {
4823			var overlay = this.overlay;
4824
4825			$('.fancybox-overlay').stop(true, true);
4826
4827			if (!overlay) {
4828				this.create(opts);
4829			}
4830
4831			if (opts.locked && this.fixed && obj.fixed) {
4832				obj.locked = this.overlay.append( obj.wrap );
4833				obj.fixed  = false;
4834			}
4835
4836			if (opts.showEarly === true) {
4837				this.beforeShow.apply(this, arguments);
4838			}
4839		},
4840
4841		beforeShow : function(opts, obj) {
4842			if (obj.locked && !this.el.hasClass('fancybox-lock')) {
4843				if (this.fixPosition !== false) {
4844					$('*
vendor: 1,346 bytes, lines 4844-4902
4844:not(object)').filter(function(){
4845						return ($(this).css('position') === 'fixed' && !$(this).hasClass("fancybox-overlay") && !$(this).hasClass("fancybox-wrap") );
4846					}).addClass('fancybox-margin');
4847				}
4848
4849				this.el.addClass('fancybox-margin');
4850
4851				this.scrollV = W.scrollTop();
4852				this.scrollH = W.scrollLeft();
4853
4854				this.el.addClass('fancybox-lock');
4855
4856				W.scrollTop( this.scrollV ).scrollLeft( this.scrollH );
4857			}
4858
4859			this.open(opts);
4860		},
4861
4862		onUpdate : function() {
4863			if (!this.fixed) {
4864				this.update();
4865			}
4866		},
4867
4868		afterClose: function (opts) {
4869			// Remove overlay if exists and fancyBox is not opening
4870			// (e.g., it is not being open using afterClose callback)
4871			if (this.overlay && !F.coming) {
4872				this.overlay.fadeOut(opts.speedOut, $.proxy( this.close, this ));
4873			}
4874		}
4875	};
4876
4877	/*
4878	 *	Title helper
4879	 */
4880
4881	F.helpers.title = {
4882		defaults : {
4883			type     : 'float', // 'float', 'inside', 'outside' or 'over',
4884			position : 'bottom' // 'top' or 'bottom'
4885		},
4886
4887		beforeShow: function (opts) {
4888			var current = F.current,
4889				text    = current.title,
4890				type    = opts.type,
4891				title,
4892				target;
4893
4894			if ($.isFunction(text)) {
4895				text = text.call(current.element, current);
4896			}
4897
4898			if (!isString(text) || $.trim(text) === '') {
4899				return;
4900			}
4901
4902			title = $('<div class="fancybox-title fancybox-title-' + type + '-wrap">
vendor: 3,163 bytes, lines 4902-5031
4902' + text + '</div>');
4903
4904			switch (type) {
4905				case 'inside':
4906					target = F.skin;
4907				break;
4908
4909				case 'outside':
4910					target = F.wrap;
4911				break;
4912
4913				case 'over':
4914					target = F.inner;
4915				break;
4916
4917				default: // 'float'
4918					target = F.skin;
4919
4920					title.appendTo('body');
4921
4922					if (IE) {
4923						title.width( title.width() );
4924					}
4925
4926					title.wrapInner('<span class="child"></span>');
4927
4928					//Increase bottom margin so this title will also fit into viewport
4929					F.current.margin[2] += Math.abs( getScalar(title.css('margin-bottom')) );
4930				break;
4931			}
4932
4933			title[ (opts.position === 'top' ? 'prependTo'  : 'appendTo') ](target);
4934		}
4935	};
4936
4937	// jQuery plugin initialization
4938	$.fn.fancybox = function (options) {
4939		var index,
4940			that     = $(this),
4941			selector = this.selector || '',
4942			run      = function(e) {
4943				var what = $(this).blur(), idx = index, relType, relVal;
4944
4945				if (!(e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) && !what.is('.fancybox-wrap')) {
4946					relType = options.groupAttr || 'data-fancybox-group';
4947					relVal  = what.attr(relType);
4948
4949					if (!relVal) {
4950						relType = 'rel';
4951						relVal  = what.get(0)[ relType ];
4952					}
4953
4954					if (relVal && relVal !== '' && relVal !== 'nofollow') {
4955						what = selector.length ? $(selector) : that;
4956						what = what.filter('[' + relType + '="' + relVal + '"]');
4957						idx  = what.index(this);
4958					}
4959
4960					options.index = idx;
4961
4962					// Stop an event from bubbling if everything is fine
4963					if (F.open(what, options) !== false) {
4964						e.preventDefault();
4965					}
4966				}
4967			};
4968
4969		options = options || {};
4970		index   = options.index || 0;
4971
4972		if (!selector || options.live === false) {
4973			that.unbind('click.fb-start').bind('click.fb-start', run);
4974
4975		} else {
4976			D.undelegate(selector, 'click.fb-start').delegate(selector + ":not('.fancybox-item, .fancybox-nav')", 'click.fb-start', run);
4977		}
4978
4979		this.filter('[data-fancybox-start=1]').trigger('click');
4980
4981		return this;
4982	};
4983
4984	// Tests that need a body at doc ready
4985	D.ready(function() {
4986		var w1, w2;
4987
4988		if ( $.scrollbarWidth === undefined ) {
4989			// http://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth
4990			$.scrollbarWidth = function() {
4991				var parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body'),
4992					child  = parent.children(),
4993					width  = child.innerWidth() - child.height( 99 ).innerWidth();
4994
4995				parent.remove();
4996
4997				return width;
4998			};
4999		}
5000
5001		if ( $.support.fixedPosition === undefined ) {
5002			$.support.fixedPosition = (function() {
5003				var elem  = $('<div style="position:fixed;top:20px;"></div>').appendTo('body'),
5004					fixed = ( elem[0].offsetTop === 20 || elem[0].offsetTop === 15 );
5005
5006				elem.remove();
5007
5008				return fixed;
5009			}());
5010		}
5011
5012		$.extend(F.defaults, {
5013			scrollbarWidth : $.scrollbarWidth(),
5014			fixed  : $.support.fixedPosition,
5015			parent : $('body')
5016		});
5017
5018		//Get real width of page scroll-bar
5019		w1 = $(window).width();
5020
5021		H.addClass('fancybox-lock-test');
5022
5023		w2 = $(window).width();
5024
5025		H.removeClass('fancybox-lock-test');
5026
5027		$("<style type='text/css'>.fancybox-margin{margin-right:" + (w2 - w1) + "px;}</style>").appendTo("head");
5028	});
5029
5030}(window, document, jQuery));
5031
vendor: 23,187 bytes, lines 5032-5077
5032/*! fancyBox v2.1.5 fancyapps.com | fancyapps.com/fancybox/#license */
5033(function(s,H,f,w){var K=f("html"),q=f(s),p=f(H),b=f.fancybox=function(){b.open.apply(this,arguments)},J=navigator.userAgent.match(/msie/i),C=null,t=H.createTouch!==w,u=function(a){return a&&a.hasOwnProperty&&a instanceof f},r=function(a){return a&&"string"===f.type(a)},F=function(a){return r(a)&&0<a.indexOf("%")},m=function(a,d){var e=parseInt(a,10)||0;d&&F(a)&&(e*=b.getViewport()[d]/100);return Math.ceil(e)},x=function(a,b){return m(a,b)+"px"};f.extend(b,{version:"2.1.5",defaults:{padding:15,margin:20,
5034width:800,height:600,minWidth:100,minHeight:100,maxWidth:9999,maxHeight:9999,pixelRatio:1,autoSize:!0,autoHeight:!1,autoWidth:!1,autoResize:!0,autoCenter:!t,fitToView:!0,aspectRatio:!1,topRatio:0.5,leftRatio:0.5,scrolling:"auto",wrapCSS:"",arrows:!0,closeBtn:!0,closeClick:!1,nextClick:!1,mouseWheel:!0,autoPlay:!1,playSpeed:3E3,preload:3,modal:!1,loop:!0,ajax:{dataType:"html",headers:{"X-fancyBox":!0}},iframe:{scrolling:"auto",preload:!0},swf:{wmode:"transparent",allowfullscreen:"true",allowscriptaccess:"always"},
5035keys:{next:{13:"left",34:"up",39:"left",40:"up"},prev:{8:"right",33:"down",37:"right",38:"down"},close:[27],play:[32],toggle:[70]},direction:{next:"left",prev:"right"},scrollOutside:!0,index:0,type:null,href:null,content:null,title:null,tpl:{wrap:'<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',image:'<img class="fancybox-image" src="{href}" alt="" />',iframe:'<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen'+
5036(J?' allowtransparency="true"':"")+"></iframe>",error:'<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>',closeBtn:'<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>',next:'<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',prev:'<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>'},openEffect:"fade",openSpeed:250,openEasing:"swing",openOpacity:!0,
5037openMethod:"zoomIn",closeEffect:"fade",closeSpeed:250,closeEasing:"swing",closeOpacity:!0,closeMethod:"zoomOut",nextEffect:"elastic",nextSpeed:250,nextEasing:"swing",nextMethod:"changeIn",prevEffect:"elastic",prevSpeed:250,prevEasing:"swing",prevMethod:"changeOut",helpers:{overlay:!0,title:!0},onCancel:f.noop,beforeLoad:f.noop,afterLoad:f.noop,beforeShow:f.noop,afterShow:f.noop,beforeChange:f.noop,beforeClose:f.noop,afterClose:f.noop},group:{},opts:{},previous:null,coming:null,current:null,isActive:!1,
5038isOpen:!1,isOpened:!1,wrap:null,skin:null,outer:null,inner:null,player:{timer:null,isActive:!1},ajaxLoad:null,imgPreload:null,transitions:{},helpers:{},open:function(a,d){if(a&&(f.isPlainObject(d)||(d={}),!1!==b.close(!0)))return f.isArray(a)||(a=u(a)?f(a).get():[a]),f.each(a,function(e,c){var l={},g,h,k,n,m;"object"===f.type(c)&&(c.nodeType&&(c=f(c)),u(c)?(l={href:c.data("fancybox-href")||c.attr("href"),title:f("<div/>").text(c.data("fancybox-title")||c.attr("title")).html(),isDom:!0,element:c},
5039f.metadata&&f.extend(!0,l,c.metadata())):l=c);g=d.href||l.href||(r(c)?c:null);h=d.title!==w?d.title:l.title||"";n=(k=d.content||l.content)?"html":d.type||l.type;!n&&l.isDom&&(n=c.data("fancybox-type"),n||(n=(n=c.prop("class").match(/fancybox\.(\w+)/))?n[1]:null));r(g)&&(n||(b.isImage(g)?n="image":b.isSWF(g)?n="swf":"#"===g.charAt(0)?n="inline":r(c)&&(n="html",k=c)),"ajax"===n&&(m=g.split(/\s+/,2),g=m.shift(),m=m.shift()));k||("inline"===n?g?k=f(r(g)?g.replace(/.*(?=#[^\s]+$)/,""):g):l.isDom&&(k=c):
5040"html"===n?k=g:n||g||!l.isDom||(n="inline",k=c));f.extend(l,{href:g,type:n,content:k,title:h,selector:m});a[e]=l}),b.opts=f.extend(!0,{},b.defaults,d),d.keys!==w&&(b.opts.keys=d.keys?f.extend({},b.defaults.keys,d.keys):!1),b.group=a,b._start(b.opts.index)},cancel:function(){var a=b.coming;a&&!1===b.trigger("onCancel")||(b.hideLoading(),a&&(b.ajaxLoad&&b.ajaxLoad.abort(),b.ajaxLoad=null,b.imgPreload&&(b.imgPreload.onload=b.imgPreload.onerror=null),a.wrap&&a.wrap.stop(!0,!0).trigger("onReset").remove(),
5041b.coming=null,b.current||b._afterZoomOut(a)))},close:function(a){b.cancel();!1!==b.trigger("beforeClose")&&(b.unbindEvents(),b.isActive&&(b.isOpen&&!0!==a?(b.isOpen=b.isOpened=!1,b.isClosing=!0,f(".fancybox-item, .fancybox-nav").remove(),b.wrap.stop(!0,!0).removeClass("fancybox-opened"),b.transitions[b.current.closeMethod]()):(f(".fancybox-wrap").stop(!0).trigger("onReset").remove(),b._afterZoomOut())))},play:function(a){var d=function(){clearTimeout(b.player.timer)},e=function(){d();b.current&&b.player.isActive&&
5042(b.player.timer=setTimeout(b.next,b.current.playSpeed))},c=function(){d();p.unbind(".player");b.player.isActive=!1;b.trigger("onPlayEnd")};!0===a||!b.player.isActive&&!1!==a?b.current&&(b.current.loop||b.current.index<b.group.length-1)&&(b.player.isActive=!0,p.bind({"onCancel.player beforeClose.player":c,"onUpdate.player":e,"beforeLoad.player":d}),e(),b.trigger("onPlayStart")):c()},next:function(a){var d=b.current;d&&(r(a)||(a=d.direction.next),b.jumpto(d.index+1,a,"next"))},prev:function(a){var d=
5043b.current;d&&(r(a)||(a=d.direction.prev),b.jumpto(d.index-1,a,"prev"))},jumpto:function(a,d,e){var c=b.current;c&&(a=m(a),b.direction=d||c.direction[a>=c.index?"next":"prev"],b.router=e||"jumpto",c.loop&&(0>a&&(a=c.group.length+a%c.group.length),a%=c.group.length),c.group[a]!==w&&(b.cancel(),b._start(a)))},reposition:function(a,d){var e=b.current,c=e?e.wrap:null,l;c&&(l=b._getPosition(d),a&&"scroll"===a.type?(delete l.position,c.stop(!0,!0).animate(l,200)):(c.css(l),e.pos=f.extend({},e.dim,l)))},
5044update:function(a){var d=a&&a.originalEvent&&a.originalEvent.type,e=!d||"orientationchange"===d;e&&(clearTimeout(C),C=null);b.isOpen&&!C&&(C=setTimeout(function(){var c=b.current;c&&!b.isClosing&&(b.wrap.removeClass("fancybox-tmp"),(e||"load"===d||"resize"===d&&c.autoResize)&&b._setDimension(),"scroll"===d&&c.canShrink||b.reposition(a),b.trigger("onUpdate"),C=null)},e&&!t?0:300))},toggle:function(a){b.isOpen&&(b.current.fitToView="boolean"===f.type(a)?a:!b.current.fitToView,t&&(b.wrap.removeAttr("style").addClass("fancybox-tmp"),
5045b.trigger("onUpdate")),b.update())},hideLoading:function(){p.unbind(".loading");f("#fancybox-loading").remove()},showLoading:function(){var a,d;b.hideLoading();a=f('<div id="fancybox-loading"><div></div></div>').click(b.cancel).appendTo("body");p.bind("keydown.loading",function(a){27===(a.which||a.keyCode)&&(a.preventDefault(),b.cancel())});b.defaults.fixed||(d=b.getViewport(),a.css({position:"absolute",top:0.5*d.h+d.y,left:0.5*d.w+d.x}));b.trigger("onLoading")},getViewport:function(){var a=b.current&&
5046b.current.locked||!1,d={x:q.scrollLeft(),y:q.scrollTop()};a&&a.length?(d.w=a[0].clientWidth,d.h=a[0].clientHeight):(d.w=t&&s.innerWidth?s.innerWidth:q.width(),d.h=t&&s.innerHeight?s.innerHeight:q.height());return d},unbindEvents:function(){b.wrap&&u(b.wrap)&&b.wrap.unbind(".fb");p.unbind(".fb");q.unbind(".fb")},bindEvents:function(){var a=b.current,d;a&&(q.bind("orientationchange.fb"+(t?"":" resize.fb")+(a.autoCenter&&!a.locked?" scroll.fb":""),b.update),(d=a.keys)&&p.bind("keydown.fb",function(e){var c=
5047e.which||e.keyCode,l=e.target||e.srcElement;if(27===c&&b.coming)return!1;e.ctrlKey||e.altKey||e.shiftKey||e.metaKey||l&&(l.type||f(l).is("[contenteditable]"))||f.each(d,function(d,l){if(1<a.group.length&&l[c]!==w)return b[d](l[c]),e.preventDefault(),!1;if(-1<f.inArray(c,l))return b[d](),e.preventDefault(),!1})}),f.fn.mousewheel&&a.mouseWheel&&b.wrap.bind("mousewheel.fb",function(d,c,l,g){for(var h=f(d.target||null),k=!1;h.length&&!(k||h.is(".fancybox-skin")||h.is(".fancybox-wrap"));)k=h[0]&&!(h[0].style.overflow&&
5048"hidden"===h[0].style.overflow)&&(h[0].clientWidth&&h[0].scrollWidth>h[0].clientWidth||h[0].clientHeight&&h[0].scrollHeight>h[0].clientHeight),h=f(h).parent();0!==c&&!k&&1<b.group.length&&!a.canShrink&&(0<g||0<l?b.prev(0<g?"down":"left"):(0>g||0>l)&&b.next(0>g?"up":"right"),d.preventDefault())}))},trigger:function(a,d){var e,c=d||b.coming||b.current;if(c){f.isFunction(c[a])&&(e=c[a].apply(c,Array.prototype.slice.call(arguments,1)));if(!1===e)return!1;c.helpers&&f.each(c.helpers,function(d,e){if(e&&
5049b.helpers[d]&&f.isFunction(b.helpers[d][a]))b.helpers[d][a](f.extend(!0,{},b.helpers[d].defaults,e),c)})}p.trigger(a)},isImage:function(a){return r(a)&&a.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i)},isSWF:function(a){return r(a)&&a.match(/\.(swf)((\?|#).*)?$/i)},_start:function(a){var d={},e,c;a=m(a);e=b.group[a]||null;if(!e)return!1;d=f.extend(!0,{},b.opts,e);e=d.margin;c=d.padding;"number"===f.type(e)&&(d.margin=[e,e,e,e]);"number"===f.type(c)&&(d.padding=[c,c,
5050c,c]);d.modal&&f.extend(!0,d,{closeBtn:!1,closeClick:!1,nextClick:!1,arrows:!1,mouseWheel:!1,keys:null,helpers:{overlay:{closeClick:!1}}});d.autoSize&&(d.autoWidth=d.autoHeight=!0);"auto"===d.width&&(d.autoWidth=!0);"auto"===d.height&&(d.autoHeight=!0);d.group=b.group;d.index=a;b.coming=d;if(!1===b.trigger("beforeLoad"))b.coming=null;else{c=d.type;e=d.href;if(!c)return b.coming=null,b.current&&b.router&&"jumpto"!==b.router?(b.current.index=a,b[b.router](b.direction)):!1;b.isActive=!0;if("image"===
5051c||"swf"===c)d.autoHeight=d.autoWidth=!1,d.scrolling="visible";"image"===c&&(d.aspectRatio=!0);"iframe"===c&&t&&(d.scrolling="scroll");d.wrap=f(d.tpl.wrap).addClass("fancybox-"+(t?"mobile":"desktop")+" fancybox-type-"+c+" fancybox-tmp "+d.wrapCSS).appendTo(d.parent||"body");f.extend(d,{skin:f(".fancybox-skin",d.wrap),outer:f(".fancybox-outer",d.wrap),inner:f(".fancybox-inner",d.wrap)});f.each(["Top","Right","Bottom","Left"],function(a,b){d.skin.css("padding"+b,x(d.padding[a]))});b.trigger("onReady");
5052if("inline"===c||"html"===c){if(!d.content||!d.content.length)return b._error("content")}else if(!e)return b._error("href");"image"===c?b._loadImage():"ajax"===c?b._loadAjax():"iframe"===c?b._loadIframe():b._afterLoad()}},_error:function(a){f.extend(b.coming,{type:"html",autoWidth:!0,autoHeight:!0,minWidth:0,minHeight:0,scrolling:"no",hasError:a,content:b.coming.tpl.error});b._afterLoad()},_loadImage:function(){var a=b.imgPreload=new Image;a.onload=function(){this.onload=this.onerror=null;b.coming.width=
5053this.width/b.opts.pixelRatio;b.coming.height=this.height/b.opts.pixelRatio;b._afterLoad()};a.onerror=function(){this.onload=this.onerror=null;b._error("image")};a.src=b.coming.href;!0!==a.complete&&b.showLoading()},_loadAjax:function(){var a=b.coming;b.showLoading();b.ajaxLoad=f.ajax(f.extend({},a.ajax,{url:a.href,error:function(a,e){b.coming&&"abort"!==e?b._error("ajax",a):b.hideLoading()},success:function(d,e){"success"===e&&(a.content=d,b._afterLoad())}}))},_loadIframe:function(){var a=b.coming,
5054d=f(a.tpl.iframe.replace(/\{rnd\}/g,(new Date).getTime())).attr("scrolling",t?"auto":a.iframe.scrolling).attr("src",a.href);f(a.wrap).bind("onReset",function(){try{f(this).find("iframe").hide().attr("src","//about:blank").end().empty()}catch(a){}});a.iframe.preload&&(b.showLoading(),d.one("load",function(){f(this).data("ready",1);t||f(this).bind("load.fb",b.update);f(this).parents(".fancybox-wrap").width("100%").removeClass("fancybox-tmp").show();b._afterLoad()}));a.content=d.appendTo(a.inner);a.iframe.preload||
5055b._afterLoad()},_preloadImages:function(){var a=b.group,d=b.current,e=a.length,c=d.preload?Math.min(d.preload,e-1):0,f,g;for(g=1;g<=c;g+=1)f=a[(d.index+g)%e],"image"===f.type&&f.href&&((new Image).src=f.href)},_afterLoad:function(){var a=b.coming,d=b.current,e,c,l,g,h;b.hideLoading();if(a&&!1!==b.isActive)if(!1===b.trigger("afterLoad",a,d))a.wrap.stop(!0).trigger("onReset").remove(),b.coming=null;else{d&&(b.trigger("beforeChange",d),d.wrap.stop(!0).removeClass("fancybox-opened").find(".fancybox-item, .fancybox-nav").remove());
5056b.unbindEvents();e=a.content;c=a.type;l=a.scrolling;f.extend(b,{wrap:a.wrap,skin:a.skin,outer:a.outer,inner:a.inner,current:a,previous:d});g=a.href;switch(c){case "inline":case "ajax":case "html":a.selector?e=f("<div>").html(e).find(a.selector):u(e)&&(e.data("fancybox-placeholder")||e.data("fancybox-placeholder",f('<div class="fancybox-placeholder"></div>').insertAfter(e).hide()),e=e.show().detach(),a.wrap.bind("onReset",function(){f(this).find(e).length&&e.hide().replaceAll(e.data("fancybox-placeholder")).data("fancybox-placeholder",
5057!1)}));break;case "image":e=a.tpl.image.replace(/\{href\}/g,g);break;case "swf":e='<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="'+g+'"></param>',h="",f.each(a.swf,function(a,b){e+='<param name="'+a+'" value="'+b+'"></param>';h+=" "+a+'="'+b+'"'}),e+='<embed src="'+g+'" type="application/x-shockwave-flash" width="100%" height="100%"'+h+"></embed></object>"}u(e)&&e.parent().is(a.inner)||a.inner.append(e);b.trigger("beforeShow");
5058a.inner.css("overflow","yes"===l?"scroll":"no"===l?"hidden":l);b._setDimension();b.reposition();b.isOpen=!1;b.coming=null;b.bindEvents();if(!b.isOpened)f(".fancybox-wrap").not(a.wrap).stop(!0).trigger("onReset").remove();else if(d.prevMethod)b.transitions[d.prevMethod]();b.transitions[b.isOpened?a.nextMethod:a.openMethod]();b._preloadImages()}},_setDimension:function(){var a=b.getViewport(),d=0,e=!1,c=!1,e=b.wrap,l=b.skin,g=b.inner,h=b.current,c=h.width,k=h.height,n=h.minWidth,v=h.minHeight,p=h.maxWidth,
5059q=h.maxHeight,t=h.scrolling,r=h.scrollOutside?h.scrollbarWidth:0,y=h.margin,z=m(y[1]+y[3]),s=m(y[0]+y[2]),w,A,u,D,B,G,C,E,I;e.add(l).add(g).width("auto").height("auto").removeClass("fancybox-tmp");y=m(l.outerWidth(!0)-l.width());w=m(l.outerHeight(!0)-l.height());A=z+y;u=s+w;D=F(c)?(a.w-A)*m(c)/100:c;B=F(k)?(a.h-u)*m(k)/100:k;if("iframe"===h.type){if(I=h.content,h.autoHeight&&1===I.data("ready"))try{I[0].contentWindow.document.location&&(g.width(D).height(9999),G=I.contents().find("body"),r&&G.css("overflow-x",
5060"hidden"),B=G.outerHeight(!0))}catch(H){}}else if(h.autoWidth||h.autoHeight)g.addClass("fancybox-tmp"),h.autoWidth||g.width(D),h.autoHeight||g.height(B),h.autoWidth&&(D=g.width()),h.autoHeight&&(B=g.height()),g.removeClass("fancybox-tmp");c=m(D);k=m(B);E=D/B;n=m(F(n)?m(n,"w")-A:n);p=m(F(p)?m(p,"w")-A:p);v=m(F(v)?m(v,"h")-u:v);q=m(F(q)?m(q,"h")-u:q);G=p;C=q;h.fitToView&&(p=Math.min(a.w-A,p),q=Math.min(a.h-u,q));A=a.w-z;s=a.h-s;h.aspectRatio?(c>p&&(c=p,k=m(c/E)),k>q&&(k=q,c=m(k*E)),c<n&&(c=n,k=m(c/
5061E)),k<v&&(k=v,c=m(k*E))):(c=Math.max(n,Math.min(c,p)),h.autoHeight&&"iframe"!==h.type&&(g.width(c),k=g.height()),k=Math.max(v,Math.min(k,q)));if(h.fitToView)if(g.width(c).height(k),e.width(c+y),a=e.width(),z=e.height(),h.aspectRatio)for(;(a>A||z>s)&&c>n&&k>v&&!(19<d++);)k=Math.max(v,Math.min(q,k-10)),c=m(k*E),c<n&&(c=n,k=m(c/E)),c>p&&(c=p,k=m(c/E)),g.width(c).height(k),e.width(c+y),a=e.width(),z=e.height();else c=Math.max(n,Math.min(c,c-(a-A))),k=Math.max(v,Math.min(k,k-(z-s)));r&&"auto"===t&&k<B&&
5062c+y+r<A&&(c+=r);g.width(c).height(k);e.width(c+y);a=e.width();z=e.height();e=(a>A||z>s)&&c>n&&k>v;c=h.aspectRatio?c<G&&k<C&&c<D&&k<B:(c<G||k<C)&&(c<D||k<B);f.extend(h,{dim:{width:x(a),height:x(z)},origWidth:D,origHeight:B,canShrink:e,canExpand:c,wPadding:y,hPadding:w,wrapSpace:z-l.outerHeight(!0),skinSpace:l.height()-k});!I&&h.autoHeight&&k>v&&k<q&&!c&&g.height("auto")},_getPosition:function(a){var d=b.current,e=b.getViewport(),c=d.margin,f=b.wrap.width()+c[1]+c[3],g=b.wrap.height()+c[0]+c[2],c={position:"absolute",
5063top:c[0],left:c[3]};d.autoCenter&&d.fixed&&!a&&g<=e.h&&f<=e.w?c.position="fixed":d.locked||(c.top+=e.y,c.left+=e.x);c.top=x(Math.max(c.top,c.top+(e.h-g)*d.topRatio));c.left=x(Math.max(c.left,c.left+(e.w-f)*d.leftRatio));return c},_afterZoomIn:function(){var a=b.current;a&&((b.isOpen=b.isOpened=!0,b.wrap.css("overflow","visible").addClass("fancybox-opened"),b.update(),(a.closeClick||a.nextClick&&1<b.group.length)&&b.inner.css("cursor","pointer").bind("click.fb",function(d){f(d.target).is("a")||f(d.target).parent().is("a")||
5064(d.preventDefault(),b[a.closeClick?"close":"next"]())}),a.closeBtn&&f(a.tpl.closeBtn).appendTo(b.skin).bind("click.fb",function(a){a.preventDefault();b.close()}),a.arrows&&1<b.group.length&&((a.loop||0<a.index)&&f(a.tpl.prev).appendTo(b.outer).bind("click.fb",b.prev),(a.loop||a.index<b.group.length-1)&&f(a.tpl.next).appendTo(b.outer).bind("click.fb",b.next)),b.trigger("afterShow"),a.loop||a.index!==a.group.length-1)?b.opts.autoPlay&&!b.player.isActive&&(b.opts.autoPlay=!1,b.play(!0)):b.play(!1))},
5065_afterZoomOut:function(a){a=a||b.current;f(".fancybox-wrap").trigger("onReset").remove();f.extend(b,{group:{},opts:{},router:!1,current:null,isActive:!1,isOpened:!1,isOpen:!1,isClosing:!1,wrap:null,skin:null,outer:null,inner:null});b.trigger("afterClose",a)}});b.transitions={getOrigPosition:function(){var a=b.current,d=a.element,e=a.orig,c={},f=50,g=50,h=a.hPadding,k=a.wPadding,n=b.getViewport();!e&&a.isDom&&d.is(":visible")&&(e=d.find("img:first"),e.length||(e=d));u(e)?(c=e.offset(),e.is("img")&&
5066(f=e.outerWidth(),g=e.outerHeight())):(c.top=n.y+(n.h-g)*a.topRatio,c.left=n.x+(n.w-f)*a.leftRatio);if("fixed"===b.wrap.css("position")||a.locked)c.top-=n.y,c.left-=n.x;return c={top:x(c.top-h*a.topRatio),left:x(c.left-k*a.leftRatio),width:x(f+k),height:x(g+h)}},step:function(a,d){var e,c,f=d.prop;c=b.current;var g=c.wrapSpace,h=c.skinSpace;if("width"===f||"height"===f)e=d.end===d.start?1:(a-d.start)/(d.end-d.start),b.isClosing&&(e=1-e),c="width"===f?c.wPadding:c.hPadding,c=a-c,b.skin[f](m("width"===
5067f?c:c-g*e)),b.inner[f](m("width"===f?c:c-g*e-h*e))},zoomIn:function(){var a=b.current,d=a.pos,e=a.openEffect,c="elastic"===e,l=f.extend({opacity:1},d);delete l.position;c?(d=this.getOrigPosition(),a.openOpacity&&(d.opacity=0.1)):"fade"===e&&(d.opacity=0.1);b.wrap.css(d).animate(l,{duration:"none"===e?0:a.openSpeed,easing:a.openEasing,step:c?this.step:null,complete:b._afterZoomIn})},zoomOut:function(){var a=b.current,d=a.closeEffect,e="elastic"===d,c={opacity:0.1};e&&(c=this.getOrigPosition(),a.closeOpacity&&
5068(c.opacity=0.1));b.wrap.animate(c,{duration:"none"===d?0:a.closeSpeed,easing:a.closeEasing,step:e?this.step:null,complete:b._afterZoomOut})},changeIn:function(){var a=b.current,d=a.nextEffect,e=a.pos,c={opacity:1},f=b.direction,g;e.opacity=0.1;"elastic"===d&&(g="down"===f||"up"===f?"top":"left","down"===f||"right"===f?(e[g]=x(m(e[g])-200),c[g]="+=200px"):(e[g]=x(m(e[g])+200),c[g]="-=200px"));"none"===d?b._afterZoomIn():b.wrap.css(e).animate(c,{duration:a.nextSpeed,easing:a.nextEasing,complete:b._afterZoomIn})},
5069changeOut:function(){var a=b.previous,d=a.prevEffect,e={opacity:0.1},c=b.direction;"elastic"===d&&(e["down"===c||"up"===c?"top":"left"]=("up"===c||"left"===c?"-":"+")+"=200px");a.wrap.animate(e,{duration:"none"===d?0:a.prevSpeed,easing:a.prevEasing,complete:function(){f(this).trigger("onReset").remove()}})}};b.helpers.overlay={defaults:{closeClick:!0,speedOut:200,showEarly:!0,css:{},locked:!t,fixed:!0},overlay:null,fixed:!1,el:f("html"),create:function(a){var d;a=f.extend({},this.defaults,a);this.overlay&&
5070this.close();d=b.coming?b.coming.parent:a.parent;this.overlay=f('<div class="fancybox-overlay"></div>').appendTo(d&&d.lenth?d:"body");this.fixed=!1;a.fixed&&b.defaults.fixed&&(this.overlay.addClass("fancybox-overlay-fixed"),this.fixed=!0)},open:function(a){var d=this;a=f.extend({},this.defaults,a);this.overlay?this.overlay.unbind(".overlay").width("auto").height("auto"):this.create(a);this.fixed||(q.bind("resize.overlay",f.proxy(this.update,this)),this.update());a.closeClick&&this.overlay.bind("click.overlay",
5071function(a){if(f(a.target).hasClass("fancybox-overlay"))return b.isActive?b.close():d.close(),!1});this.overlay.css(a.css).show()},close:function(){q.unbind("resize.overlay");this.el.hasClass("fancybox-lock")&&(f(".fancybox-margin").removeClass("fancybox-margin"),this.el.removeClass("fancybox-lock"),q.scrollTop(this.scrollV).scrollLeft(this.scrollH));f(".fancybox-overlay").remove().hide();f.extend(this,{overlay:null,fixed:!1})},update:function(){var a="100%",b;this.overlay.width(a).height("100%");
5072J?(b=Math.max(H.documentElement.offsetWidth,H.body.offsetWidth),p.width()>b&&(a=p.width())):p.width()>q.width()&&(a=p.width());this.overlay.width(a).height(p.height())},onReady:function(a,b){var e=this.overlay;f(".fancybox-overlay").stop(!0,!0);e||this.create(a);a.locked&&this.fixed&&b.fixed&&(b.locked=this.overlay.append(b.wrap),b.fixed=!1);!0===a.showEarly&&this.beforeShow.apply(this,arguments)},beforeShow:function(a,b){b.locked&&!this.el.hasClass("fancybox-lock")&&(!1!==this.fixPosition&&f("*").filter(function(){return"fixed"===
5073f(this).css("position")&&!f(this).hasClass("fancybox-overlay")&&!f(this).hasClass("fancybox-wrap")}).addClass("fancybox-margin"),this.el.addClass("fancybox-margin"),this.scrollV=q.scrollTop(),this.scrollH=q.scrollLeft(),this.el.addClass("fancybox-lock"),q.scrollTop(this.scrollV).scrollLeft(this.scrollH));this.open(a)},onUpdate:function(){this.fixed||this.update()},afterClose:function(a){this.overlay&&!b.coming&&this.overlay.fadeOut(a.speedOut,f.proxy(this.close,this))}};b.helpers.title={defaults:{type:"float",
5074position:"bottom"},beforeShow:function(a){var d=b.current,e=d.title,c=a.type;f.isFunction(e)&&(e=e.call(d.element,d));if(r(e)&&""!==f.trim(e)){d=f('<div class="fancybox-title fancybox-title-'+c+'-wrap">'+e+"</div>");switch(c){case "inside":c=b.skin;break;case "outside":c=b.wrap;break;case "over":c=b.inner;break;default:c=b.skin,d.appendTo("body"),J&&d.width(d.width()),d.wrapInner('<span class="child"></span>'),b.current.margin[2]+=Math.abs(m(d.css("margin-bottom")))}d["top"===a.position?"prependTo":
5075"appendTo"](c)}}};f.fn.fancybox=function(a){var d,e=f(this),c=this.selector||"",l=function(g){var h=f(this).blur(),k=d,l,m;g.ctrlKey||g.altKey||g.shiftKey||g.metaKey||h.is(".fancybox-wrap")||(l=a.groupAttr||"data-fancybox-group",m=h.attr(l),m||(l="rel",m=h.get(0)[l]),m&&""!==m&&"nofollow"!==m&&(h=c.length?f(c):e,h=h.filter("["+l+'="'+m+'"]'),k=h.index(this)),a.index=k,!1!==b.open(h,a)&&g.preventDefault())};a=a||{};d=a.index||0;c&&!1!==a.live?p.undelegate(c,"click.fb-start").delegate(c+":not('.fancybox-item, .fancybox-nav')",
5076"click.fb-start",l):e.unbind("click.fb-start").bind("click.fb-start",l);this.filter("[data-fancybox-start=1]").trigger("click");return this};p.ready(function(){var a,d;f.scrollbarWidth===w&&(f.scrollbarWidth=function(){var a=f('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo("body"),b=a.children(),b=b.innerWidth()-b.height(99).innerWidth();a.remove();return b});f.support.fixedPosition===w&&(f.support.fixedPosition=function(){var a=f('<div style="position:fixed;top:20px;"></div>').appendTo("body"),
5077b=20===a[0].offsetTop||15===a[0].offsetTop;a.remove();return b}());f.extend(b.defaults,{scrollbarWidth:f.scrollbarWidth(),fixed:f.support.fixedPosition,parent:f("body")});a=f(s).width();K.addClass("fancybox-lock-test");d=f(s).width();K.removeClass("fancybox-lock-test");f("<style type='text/css'>.fancybox-margin{margin-right:"+(d-a)+"px;}</style>").appendTo("head")})})(window,document,jQuery);
vendor: 1,639 bytes, lines 5077-5127
5077
5078// Generated by CoffeeScript 1.9.2
5079
5080/**
5081@license Sticky-kit v1.1.2 | WTFPL | Leaf Corcoran 2015 | http://leafo.net
5082 */
5083
5084(function() {
5085  var $, win;
5086
5087  $ = this.jQuery || window.jQuery;
5088
5089  win = $(window);
5090
5091  $.fn.stick_in_parent = function(opts) {
5092    var doc, elm, enable_bottoming, fn, i, inner_scrolling, len, manual_spacer, offset_top, parent_selector, recalc_every, sticky_class;
5093    if (opts == null) {
5094      opts = {};
5095    }
5096    sticky_class = opts.sticky_class, inner_scrolling = opts.inner_scrolling, recalc_every = opts.recalc_every, parent_selector = opts.parent, offset_top = opts.offset_top, manual_spacer = opts.spacer, enable_bottoming = opts.bottoming;
5097    if (offset_top == null) {
5098      offset_top = 0;
5099    }
5100    if (parent_selector == null) {
5101      parent_selector = void 0;
5102    }
5103    if (inner_scrolling == null) {
5104      inner_scrolling = true;
5105    }
5106    if (sticky_class == null) {
5107      sticky_class = "is_stuck";
5108    }
5109    doc = $(document);
5110    if (enable_bottoming == null) {
5111      enable_bottoming = true;
5112    }
5113    fn = function(elm, padding_bottom, parent_top, parent_height, top, height, el_float, detached) {
5114      var bottomed, detach, fixed, last_pos, last_scroll_height, offset, parent, recalc, recalc_and_tick, recalc_counter, spacer, tick;
5115      if (elm.data("sticky_kit")) {
5116        return;
5117      }
5118      elm.data("sticky_kit", true);
5119      last_scroll_height = doc.height();
5120      parent = elm.parent();
5121      if (parent_selector != null) {
5122        parent = parent.closest(parent_selector);
5123      }
5124      if (!parent.length) {
5125        throw "failed to find stick parent";
5126      }
5127      fixed = false;
5128      bottomed = false;
5129      spacer = manual_spacer != null ? manual_spacer && elm.closest(manual_spacer) : $("<div />");
5130      if (spacer) {
5131        spacer.css('position', elm.css('position'));
5132      }
5133      recalc = function() {
5134        var border_top, padding_top, restore;
5135        if (detached) {
5136          return;
5137        }
5138        last_scroll_height = doc.height();
5139        border_top = parseInt(parent.css("border-top-width"), 10);
5140        padding_top = parseInt(parent.css("padding-top"), 10);
5141        padding_bottom = parseInt(parent.css("padding-bottom"), 10);
5142        parent_top = parent.offset().top + border_top + padding_top;
5143        parent_height = parent.height();
5144        if (fixed) {
5145          fixed = false;
5146          bottomed = false;
5147          if (manual_spacer == null) {
5148            elm.insertAfter(spacer);
5149            spacer.detach();
5150          }
5151          elm.css({
5152            position: "",
5153            top: "",
5154            width: "",
5155            bottom: ""
5156          }).removeClass(sticky_class);
5157          restore = true;
5158        }
5159        top = elm.offset().top - (parseInt(elm.css("margin-top"), 10) || 0) - offset_top;
5160        height = elm.outerHeight(true);
5161        el_float = elm.css("float");
5162        if (spacer) {
5163          spacer.css({
5164            width: elm.outerWidth(true),
5165            height: height,
5166            display: elm.css("display"),
5167            "vertical-align": elm.css("vertical-align"),
5168            "float": el_float
5169          });
5170        }
5171        if (restore) {
5172          return tick();
5173        }
5174      };
5175      recalc();
5176      if (height === parent_height) {
5177        return;
5178      }
5179      last_pos = void 0;
5180      offset = offset_top;
5181      recalc_counter = recalc_every;
5182      tick = function() {
5183        var css, delta, recalced, scroll, will_bottom, win_height;
5184        if (detached) {
5185          return;
5186        }
5187        recalced = false;
5188        if (recalc_counter != null) {
5189          recalc_counter -= 1;
5190          if (recalc_counter <= 0) {
5191            recalc_counter = recalc_every;
5192            recalc();
5193            recalced = true;
5194          }
5195        }
5196        if (!recalced && doc.height() !== last_scroll_height) {
5197          recalc();
5198          recalced = true;
5199        }
5200        scroll = win.scrollTop();
5201        if (last_pos != null) {
5202          delta = scroll - last_pos;
5203        }
5204        last_pos = scroll;
5205        if (fixed) {
5206          if (enable_bottoming) {
5207            will_bottom = scroll + height + offset > parent_height + parent_top;
5208            if (bottomed && !will_bottom) {
5209              bottomed = false;
5210              elm.css({
5211                position: "fixed",
5212                bottom: "",
5213                top: offset
5214              }).trigger("sticky_kit:unbottom");
5215            }
5216          }
5217          if (scroll < top) {
5218            fixed = false;
5219            offset = offset_top;
5220            if (manual_spacer == null) {
5221              if (el_float === "left" || el_float === "right") {
5222                elm.insertAfter(spacer);
5223              }
5224              spacer.detach();
5225            }
5226            css = {
5227              position: "",
5228              width: "",
5229              top: ""
5230            };
5231            elm.css(css).removeClass(sticky_class).trigger("sticky_kit:unstick");
5232          }
5233          if (inner_scrolling) {
5234            win_height = win.height();
5235            if (height + offset_top > win_height) {
5236              if (!bottomed) {
5237                offset -= delta;
5238                offset = Math.max(win_height - height, offset);
5239                offset = Math.min(offset_top, offset);
5240                if (fixed) {
5241                  elm.css({
5242                    top: offset + "px"
5243                  });
5244                }
5245              }
5246            }
5247          }
5248        } else {
5249          if (scroll > top) {
5250            fixed = true;
5251            css = {
5252              position: "fixed",
5253              top: offset
5254            };
5255            css.width = elm.css("box-sizing") === "border-box" ? elm.outerWidth() + "px" : elm.width() + "px";
5256            elm.css(css).addClass(sticky_class);
5257            if (manual_spacer == null) {
5258              elm.after(spacer);
5259              if (el_float === "left" || el_float === "right") {
5260                spacer.append(elm);
5261              }
5262            }
5263            elm.trigger("sticky_kit:stick");
5264          }
5265        }
5266        if (fixed && enable_bottoming) {
5267          if (will_bottom == null) {
5268            will_bottom = scroll + height + offset > parent_height + parent_top;
5269          }
5270          if (!bottomed && will_bottom) {
5271            bottomed = true;
5272            if (parent.css("position") === "static") {
5273              parent.css({
5274                position: "relative"
5275              });
5276            }
5277            return elm.css({
5278              position: "absolute",
5279              bottom: padding_bottom,
5280              top: "auto"
5281            }).trigger("sticky_kit:bottom");
5282          }
5283        }
5284      };
5285      recalc_and_tick = function() {
5286        recalc();
5287        return tick();
5288      };
5289      detach = function() {
5290        detached = true;
5291        win.off("touchmove", tick);
5292        win.off("scroll", tick);
5293        win.off("resize", recalc_and_tick);
5294        $(document.body).off("sticky_kit:recalc", recalc_and_tick);
5295        elm.off("sticky_kit:detach", detach);
5296        elm.removeData("sticky_kit");
5297        elm.css({
5298          position: "",
5299          bottom: "",
5300          top: "",
5301          width: ""
5302        });
5303        parent.position("position", "");
5304        if (fixed) {
5305          if (manual_spacer == null) {
5306            if (el_float === "left" || el_float === "right") {
5307              elm.insertAfter(spacer);
5308            }
5309            spacer.remove();
5310          }
5311          return elm.removeClass(sticky_class);
5312        }
5313      };
5314      win.on("touchmove", tick);
5315      win.on("scroll", tick);
5316      win.on("resize", recalc_and_tick);
5317      $(document.body).on("sticky_kit:recalc", recalc_and_tick);
5318      elm.on("sticky_kit:detach", detach);
5319      return setTimeout(tick, 0);
5320    };
5321    for (i = 0, len = this.length; i < len; i++) {
5322      elm = this[i];
5323      fn($(elm));
5324    }
5325    return this;
5326  };
5327
5328}).call(this);
5329
5330(function (global, factory) {
5331	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
5332	typeof define === 'function' && define.amd ? define(factory) :
5333	(global.jspdf = factory());
5334}(this, (function () { 'use strict';
5335
5336var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
5337  return typeof obj;
5338} : function (obj) {
5339  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
5340};
5341
5342
5343
5344
5345
5346var asyncGenerator = function () {
5347  function AwaitValue(value) {
5348    this.value = value;
5349  }
5350
5351  function AsyncGenerator(gen) {
5352    var front, back;
5353
5354    function send(key, arg) {
5355      return new Promise(function (resolve, reject) {
5356        var request = {
5357          key: key,
5358          arg: arg,
5359          resolve: resolve,
5360          reject: reject,
5361          next: null
5362        };
5363
5364        if (back) {
5365          back = back.next = request;
5366        } else {
5367          front = back = request;
5368          resume(key, arg);
5369        }
5370      });
5371    }
5372
5373    function resume(key, arg) {
vendor: 4,305 bytes, lines 5374-5522
5374      try {
5375        var result = gen[key](arg);
5376        var value = result.value;
5377
5378        if (value instanceof AwaitValue) {
5379          Promise.resolve(value.value).then(function (arg) {
5380            resume("next", arg);
5381          }, function (arg) {
5382            resume("throw", arg);
5383          });
5384        } else {
5385          settle(result.done ? "return" : "normal", result.value);
5386        }
5387      } catch (err) {
5388        settle("throw", err);
5389      }
5390    }
5391
5392    function settle(type, value) {
5393      switch (type) {
5394        case "return":
5395          front.resolve({
5396            value: value,
5397            done: true
5398          });
5399          break;
5400
5401        case "throw":
5402          front.reject(value);
5403          break;
5404
5405        default:
5406          front.resolve({
5407            value: value,
5408            done: false
5409          });
5410          break;
5411      }
5412
5413      front = front.next;
5414
5415      if (front) {
5416        resume(front.key, front.arg);
5417      } else {
5418        back = null;
5419      }
5420    }
5421
5422    this._invoke = send;
5423
5424    if (typeof gen.return !== "function") {
5425      this.return = undefined;
5426    }
5427  }
5428
5429  if (typeof Symbol === "function" && Symbol.asyncIterator) {
5430    AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
5431      return this;
5432    };
5433  }
5434
5435  AsyncGenerator.prototype.next = function (arg) {
5436    return this._invoke("next", arg);
5437  };
5438
5439  AsyncGenerator.prototype.throw = function (arg) {
5440    return this._invoke("throw", arg);
5441  };
5442
5443  AsyncGenerator.prototype.return = function (arg) {
5444    return this._invoke("return", arg);
5445  };
5446
5447  return {
5448    wrap: function (fn) {
5449      return function () {
5450        return new AsyncGenerator(fn.apply(this, arguments));
5451      };
5452    },
5453    await: function (value) {
5454      return new AwaitValue(value);
5455    }
5456  };
5457}();
5458
5459/** @preserve
5460 * jsPDF - PDF Document creation from JavaScript
5461 * Version 1.3.5 Built on 2017-09-14T15:10:09.569Z
5462 *                           CommitID 05dc915baf
5463 *
5464 * Copyright (c) 2010-2016 James Hall <[email protected]>, https://github.com/MrRio/jsPDF
5465 *               2010 Aaron Spike, https://github.com/acspike
5466 *               2012 Willow Systems Corporation, willow-systems.com
5467 *               2012 Pablo Hess, https://github.com/pablohess
5468 *               2012 Florian Jenett, https://github.com/fjenett
5469 *               2013 Warren Weckesser, https://github.com/warrenweckesser
5470 *               2013 Youssef Beddad, https://github.com/lifof
5471 *               2013 Lee Driscoll, https://github.com/lsdriscoll
5472 *               2013 Stefan Slonevskiy, https://github.com/stefslon
5473 *               2013 Jeremy Morel, https://github.com/jmorel
5474 *               2013 Christoph Hartmann, https://github.com/chris-rock
5475 *               2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
5476 *               2014 James Makes, https://github.com/dollaruw
5477 *               2014 Diego Casorran, https://github.com/diegocr
5478 *               2014 Steven Spungin, https://github.com/Flamenco
5479 *               2014 Kenneth Glassey, https://github.com/Gavvers
5480 *
5481 * Licensed under the MIT License
5482 *
5483 * Contributor(s):
5484 *    siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
5485 *    kim3er, mfo, alnorth, Flamenco
5486 */
5487
5488/**
5489 * Creates new jsPDF document object instance.
5490 * @name jsPDF
5491 * @class
5492 * @param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l") <br />
5493 * Can also be an options object.
5494 * @param unit        Measurement unit to be used when coordinates are specified.
5495 *                    One of "pt" (points), "mm" (Default), "cm", "in"
5496 * @param format      One of 'pageFormats' as shown below, default: a4
5497 * @returns {jsPDF}
5498 * @description
5499 * If the first parameter (orientation) is an object, it will be interpreted as an object of named parameters
5500 * ```
5501 * {
5502 *  orientation: 'p',
5503 *  unit: 'mm',
5504 *  format: 'a4',
5505 *  hotfixes: [] // an array of hotfix strings to enable
5506 * }
5507 * ```
5508 */
5509var jsPDF = function (global) {
5510  'use strict';
5511
5512  var pdfVersion = '1.3',
5513      pageFormats = { // Size in pt of various paper formats
5514    'a0': [2383.94, 3370.39],
5515    'a1': [1683.78, 2383.94],
5516    'a2': [1190.55, 1683.78],
5517    'a3': [841.89, 1190.55],
5518    'a4': [595.28, 841.89],
5519    'a5': [419.53, 595.28],
5520    'a6': [297.64, 419.53],
5521    'a7': [209.76, 297.64],
5522    'a8': [147.40, 209.76],
5523    'a9': [104.88, 147.40],
5524    'a10': [73.70, 104.88],
5525    'b0': [2834.65, 4008.19],
5526    'b1': [2004.09, 2834.65],
5527    'b2': [1417.32, 2004.09],
5528    'b3': [1000.63, 1417.32],
5529    'b4': [708.66, 1000.63],
5530    'b5': [498.90, 708.66],
5531    'b6': [354.33, 498.90],
5532    'b7': [249.45, 354.33],
5533    'b8': [175.75, 249.45],
5534    'b9': [124.72, 175.75],
5535    'b10': [87.87, 124.72],
5536    'c0': [2599.37, 3676.54],
5537    'c1': [1836.85, 2599.37],
5538    'c2': [1298.27, 1836.85],
5539    'c3': [918.43, 1298.27],
5540    'c4': [649.13, 918.43],
5541    'c5': [459.21, 649.13],
5542    'c6': [323.15, 459.21],
5543    'c7': [229.61, 323.15],
5544    'c8': [161.57, 229.61],
5545    'c9': [113.39, 161.57],
5546    'c10': [79.37, 113.39],
5547    'dl': [311.81, 623.62],
5548    'letter': [612, 792],
5549    'government-letter': [576, 756],
5550    'legal': [612, 1008],
5551    'junior-legal': [576, 360],
5552    'ledger': [1224, 792],
5553    'tabloid': [792, 1224],
5554    'credit-card': [153, 243]
5555  };
5556
5557  /**
5558   * jsPDF's Internal PubSub Implementation.
5559   * See mrrio.github.io/jsPDF/doc/symbols/PubSub.html
5560   * Backward compatible rewritten on 2014 by
5561   * Diego Casorran, https://github.com/diegocr
5562   *
5563   * @class
5564   * @name PubSub
5565   * @ignore This should not be in the public docs.
5566   */
5567  function PubSub(context) {
5568    var topics = {};
5569
5570    this.subscribe = function (topic, callback, once) {
5571      if (typeof callback !== 'function') {
5572        return false;
5573      }
5574
5575      if (!topics.hasOwnProperty(topic)) {
5576        topics[topic] = {};
5577      }
5578
5579      var id = Math.random().toString(35);
5580      topics[topic][id] = [callback, !!once];
5581
5582      return id;
5583    };
5584
5585    this.unsubscribe = function (token) {
5586      for (var topic in topics) {
5587        if (topics[topic][token]) {
5588          delete topics[topic][token];
5589          return true;
5590        }
5591      }
5592      return false;
5593    };
5594
5595    this.publish = function (topic) {
5596      if (topics.hasOwnProperty(topic)) {
5597        var args = Array.prototype.slice.call(arguments, 1),
5598            idr = [];
5599
5600        for (var id in topics[topic]) {
5601          var sub = topics[topic][id];
5602          try {
5603            sub[0].apply(context, args);
5604          } catch (ex) {
5605            if (global.console) {
5606              console.error('jsPDF PubSub Error', ex.message, ex);
5607            }
5608          }
5609          if (sub[1]) idr.push(id);
5610        }
5611        if (idr.length) idr.forEach(this.unsubscribe);
5612      }
5613    };
5614  }
5615
5616  /**
5617   * @constructor
5618   * @private
5619   */
5620  function jsPDF(orientation, unit, format, compressPdf) {
5621    var options = {};
5622
5623    if ((typeof orientation === 'undefined' ? 'undefined' : _typeof(orientation)) === 'object') {
5624      options = orientation;
5625
5626      orientation = options.orientation;
5627      unit = options.unit || unit;
5628      format = options.format || format;
5629      compressPdf = options.compress || options.compressPdf || compressPdf;
5630    }
5631
5632    // Default options
5633    unit = unit || 'mm';
5634    format = format || 'a4';
5635    orientation = ('' + (orientation || 'P')).toLowerCase();
5636
5637    var format_as_string = ('' + format).toLowerCase(),
5638        compress = !!compressPdf && typeof Uint8Array === 'function',
5639        textColor = options.textColor || '0 g',
5640        drawColor = options.drawColor || '0 G',
5641        activeFontSize = options.fontSize || 16,
5642        lineHeightProportion = options.lineHeight || 1.15,
5643        lineWidth = options.lineWidth || 0.200025,
5644        // 2mm
5645    objectNumber = 2,
5646        // 'n' Current object number
5647    outToPages = !1,
5648        // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
5649    offsets = [],
5650        // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
5651    fonts = {},
5652        // collection of font objects, where key is fontKey - a dynamically created label for a given font.
5653    fontmap = {},
5654        // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
5655    activeFontKey,
5656        // will be string representing the KEY of the font as combination of fontName + fontStyle
5657    k,
5658        // Scale factor
5659    tmp,
5660        page = 0,
5661        currentPage,
5662        pages = [],
5663        pagesContext = [],
5664        // same index as pages and pagedim
5665    pagedim = [],
5666        content = [],
5667        additionalObjects = [],
5668        lineCapID = 0,
5669        lineJoinID = 0,
5670        content_length = 0,
5671        pageWidth,
5672        pageHeight,
5673        pageMode,
5674        zoomMode,
5675        layoutMode,
5676        documentProperties = {
5677      'title': '',
5678      'subject': '',
5679      'author': '',
5680      'keywords': '',
5681      'creator': ''
5682    },
5683        API = {},
5684        events = new PubSub(API),
5685        hotfixes = options.hotfixes || [],
5686
5687
5688    /////////////////////
5689    // Private functions
5690    /////////////////////
5691    f2 = function f2(number) {
5692      return number.toFixed(2); // Ie, %.2f
5693    },
5694        f3 = function f3(number) {
5695      return number.toFixed(3); // Ie, %.3f
5696    },
5697        padd2 = function padd2(number) {
5698      return ('0' + parseInt(number)).slice(-2);
5699    },
5700        out = function out(string) {
5701      if (outToPages) {
5702        /* set by beginPage */
5703        pages[currentPage].push(string);
5704      } else {
5705        // +1 for '\n' that will be used to join 'content'
5706        content_length += string.length + 1;
5707        content.push(string);
5708      }
5709    },
5710        newObject = function newObject() {
5711      // Begin a new object
5712      objectNumber++;
5713      offsets[objectNumber] = content_length;
5714      out(objectNumber + ' 0 obj');
5715      return objectNumber;
5716    },
5717
5718    // Does not output the object until after the pages have been output.
5719    // Returns an object containing the objectId and content.
5720    // All pages have been added so the object ID can be estimated to start right after.
5721    // This does not modify the current objectNumber;  It must be updated after the newObjects are output.
5722    newAdditionalObject = function newAdditionalObject() {
5723      var objId = pages.length * 2 + 1;
5724      objId += additionalObjects.length;
5725      var obj = {
5726        objId: objId,
5727        content: ''
5728      };
5729      additionalObjects.push(obj);
5730      return obj;
5731    },
5732
5733    // Does not output the object.  The caller must call newObjectDeferredBegin(oid) before outputing any data
5734    newObjectDeferred = function newObjectDeferred() {
5735      objectNumber++;
5736      offsets[objectNumber] = function () {
5737        return content_length;
5738      };
5739      return objectNumber;
5740    },
5741        newObjectDeferredBegin = function newObjectDeferredBegin(oid) {
5742      offsets[oid] = content_length;
5743    },
5744        putStream = function putStream(str) {
5745      out('stream');
5746      out(str);
5747      out('endstream');
5748    },
5749        putPages = function putPages() {
5750      var n,
5751          p,
5752          arr,
5753          i,
5754          deflater,
5755          adler32,
5756          adler32cs,
5757          wPt,
5758          hPt,
5759          pageObjectNumbers = [];
5760
5761      adler32cs = global.adler32cs || jsPDF.adler32cs;
5762      if (compress && typeof adler32cs === 'undefined') {
5763        compress = false;
5764      }
5765
5766      // outToPages = false as set in endDocument(). out() writes to content.
5767
5768      for (n = 1; n <= page; n++) {
5769        pageObjectNumbers.push(newObject());
5770        wPt = (pageWidth = pagedim[n].width) * k;
5771        hPt = (pageHeight = pagedim[n].height) * k;
5772        out('<</Type /Page');
5773        out('/Parent 1 0 R');
5774        out('/Resources 2 0 R');
5775        out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
5776        // Added for annotation plugin
5777        events.publish('putPage', {
5778          pageNumber: n,
5779          page: pages[n]
5780        });
5781        out('/Contents ' + (objectNumber + 1) + ' 0 R');
5782        out('>>');
5783        out('endobj');
5784
5785        // Page content
5786        p = pages[n].join('\n');
5787        newObject();
5788        if (compress) {
5789          arr = [];
5790          i = p.length;
5791          while (i--) {
5792            arr[i] = p.charCodeAt(i);
5793          }
5794          adler32 = adler32cs.from(p);
5795          deflater = new Deflater(6);
5796          deflater.append(new Uint8Array(arr));
5797          p = deflater.flush();
5798          arr = new Uint8Array(p.length + 6);
5799          arr.set(new Uint8Array([120, 156])), arr.set(p, 2);
5800          arr.set(new Uint8Array([adler32 & 0xFF, adler32 >> 8 & 0xFF, adler32 >> 16 & 0xFF, adler32 >> 24 & 0xFF]), p.length + 2);
5801          p = String.fromCharCode.apply(null, arr);
5802          out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
5803        } else {
5804          out('<</Length ' + p.length + '>>');
5805        }
5806        putStream(p);
5807        out('endobj');
5808      }
5809      offsets[1] = content_length;
5810      out('1 0 obj');
5811      out('<</Type /Pages');
5812      var kids = '/Kids [';
5813      for (i = 0; i < page; i++) {
5814        kids += pageObjectNumbers[i] + ' 0 R ';
5815      }
5816      out(kids + ']');
5817      out('/Count ' + page);
5818      out('>>');
5819      out('endobj');
5820      events.publish('postPutPages');
5821    },
5822        putFont = function putFont(font) {
5823      font.objectNumber = newObject();
5824      out('<</BaseFont/' + font.PostScriptName + '/Type/Font');
5825      if (typeof font.encoding === 'string') {
5826        out('/Encoding/' + font.encoding);
5827      }
5828      out('/Subtype/Type1>>');
5829      out('endobj');
5830    },
5831        putFonts = function putFonts() {
5832      for (var fontKey in fonts) {
5833        if (fonts.hasOwnProperty(fontKey)) {
5834          putFont(fonts[fontKey]);
5835        }
5836      }
5837    },
5838        putXobjectDict = function putXobjectDict() {
5839      // Loop through images, or other data objects
5840      events.publish('putXobjectDict');
5841    },
5842        putResourceDictionary = function putResourceDictionary() {
5843      out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
5844      out('/Font <<');
5845
5846      // Do this for each font, the '1' bit is the index of the font
5847      for (var fontKey in fonts) {
5848        if (fonts.hasOwnProperty(fontKey)) {
5849          out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
5850        }
5851      }
5852      out('>>');
5853      out('/XObject <<');
5854      putXobjectDict();
5855      out('>>');
5856    },
5857        putResources = function putResources() {
5858      putFonts();
5859      events.publish('putResources');
5860      // Resource dictionary
5861      offsets[2] = content_length;
5862      out('2 0 obj');
5863      out('<<');
5864      putResourceDictionary();
5865      out('>>');
5866      out('endobj');
5867      events.publish('postPutResources');
5868    },
5869        putAdditionalObjects = function putAdditionalObjects() {
5870      events.publish('putAdditionalObjects');
5871      for (var i = 0; i < additionalObjects.length; i++) {
5872        var obj = additionalObjects[i];
5873        offsets[obj.objId] = content_length;
5874        out(obj.objId + ' 0 obj');
5875        out(obj.content);
5876        out('endobj');
5877      }
5878      objectNumber += additionalObjects.length;
5879      events.publish('postPutAdditionalObjects');
5880    },
5881        addToFontDictionary = function addToFontDictionary(fontKey, fontName, fontStyle) {
5882      // this is mapping structure for quick font key lookup.
5883      // returns the KEY of the font (ex: "F1") for a given
5884      // pair of font name and type (ex: "Arial". "Italic")
5885      if (!fontmap.hasOwnProperty(fontName)) {
5886        fontmap[fontName] = {};
5887      }
5888      fontmap[fontName][fontStyle] = fontKey;
5889    },
5890
5891    /**
5892     * FontObject describes a particular font as member of an instnace of jsPDF
5893     *
5894     * It's a collection of properties like 'id' (to be used in PDF stream),
5895     * 'fontName' (font's family name), 'fontStyle' (font's style variant label)
5896     *
5897     * @class
5898     * @public
5899     * @property id {String} PDF-document-instance-specific label assinged to the font.
5900     * @property PostScriptName {String} PDF specification full name for the font
5901     * @property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
5902     * @name FontObject
5903     * @ignore This should not be in the public docs.
5904     */
5905    addFont = function addFont(PostScriptName, fontName, fontStyle, encoding) {
5906      var fontKey = 'F' + (Object.keys(fonts).length + 1).toString(10),
5907
5908      // This is FontObject
5909      font = fonts[fontKey] = {
5910        'id': fontKey,
5911        'PostScriptName': PostScriptName,
5912        'fontName': fontName,
5913        'fontStyle': fontStyle,
5914        'encoding': encoding,
5915        'metadata': {}
5916      };
5917      addToFontDictionary(fontKey, fontName, fontStyle);
5918      events.publish('addFont', font);
5919
5920      return fontKey;
5921    },
5922        addFonts = function addFonts() {
5923
5924      var HELVETICA = "helvetica",
5925          TIMES = "times",
5926          COURIER = "courier",
5927          NORMAL = "normal",
5928          BOLD = "bold",
5929          ITALIC = "italic",
5930          BOLD_ITALIC = "bolditalic",
5931          encoding = 'StandardEncoding',
5932          ZAPF = "zapfdingbats",
5933          standardFonts = [['Helvetica', HELVETICA, NORMAL], ['Helvetica-Bold', HELVETICA, BOLD], ['Helvetica-Oblique', HELVETICA, ITALIC], ['Helvetica-BoldOblique', HELVETICA, BOLD_ITALIC], ['Courier', COURIER, NORMAL], ['Courier-Bold', COURIER, BOLD], ['Courier-Oblique', COURIER, ITALIC], ['Courier-BoldOblique', COURIER, BOLD_ITALIC], ['Times-Roman', TIMES, NORMAL], ['Times-Bold', TIMES, BOLD], ['Times-Italic', TIMES, ITALIC], ['Times-BoldItalic', TIMES, BOLD_ITALIC], ['ZapfDingbats', ZAPF]];
5934
5935      for (var i = 0, l = standardFonts.length; i < l; i++) {
5936        var fontKey = addFont(standardFonts[i][0], standardFonts[i][1], standardFonts[i][2], encoding);
5937
5938        // adding aliases for standard fonts, this time matching the capitalization
5939        var parts = standardFonts[i][0].split('-');
5940        addToFontDictionary(fontKey, parts[0], parts[1] || '');
5941      }
5942      events.publish('addFonts', {
5943        fonts: fonts,
5944        dictionary: fontmap
5945      });
5946    },
5947        SAFE = function __safeCall(fn) {
5948      fn.foo = function __safeCallWrapper() {
5949        try {
5950          return fn.apply(this, arguments);
5951        } catch (e) {
5952          var stack = e.stack || '';
5953          if (~stack.indexOf(' at ')) stack = stack.split(" at ")[1];
5954          var m = "Error in function " + stack.split("\n")[0].split('<')[0] + ": " + e.message;
5955          if (global.console) {
5956            global.console.error(m, e);
5957            if (global.alert) alert(m);
5958          } else {
5959            throw new Error(m);
5960          }
5961        }
5962      };
5963      fn.foo.bar = fn;
5964      return fn.foo;
5965    },
5966        to8bitStream = function to8bitStream(text, flags) {
5967      /**
5968       * PDF 1.3 spec:
5969       * "For text strings encoded in Unicode, the first two bytes must be 254 followed by
5970       * 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
5971       * with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
5972       * to be a meaningful beginning of a word or phrase.) The remainder of the
5973       * string consists of Unicode character codes, according to the UTF-16 encoding
5974       * specified in the Unicode standard, version 2.0. Commonly used Unicode values
5975       * are represented as 2 bytes per character, with the high-order byte appearing first
5976       * in the string."
5977       *
5978       * In other words, if there are chars in a string with char code above 255, we
5979       * recode the string to UCS2 BE - string doubles in length and BOM is prepended.
5980       *
5981       * HOWEVER!
5982       * Actual *content* (body) text (as opposed to strings used in document properties etc)
5983       * does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
5984       *
5985       * Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
5986       * a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
5987       * fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
5988       * code page. There, however, all characters in the stream are treated as GIDs,
5989       * including BOM, which is the reason we need to skip BOM in content text (i.e. that
5990       * that is tied to a font).
5991       *
5992       * To signal this "special" PDFEscape / to8bitStream handling mode,
5993       * API.text() function sets (unless you overwrite it with manual values
5994       * given to API.text(.., flags) )
5995       * flags.autoencode = true
5996       * flags.noBOM = true
5997       *
5998       * ===================================================================================
5999       * `flags` properties relied upon:
6000       *   .sourceEncoding = string with encoding label.
6001       *                     "Unicode" by default. = encoding of the incoming text.
6002       *                     pass some non-existing encoding name
6003       *                     (ex: 'Do not touch my strings! I know what I am doing.')
6004       *                     to make encoding code skip the encoding step.
6005       *   .outputEncoding = Either valid PDF encoding name
6006       *                     (must be supported by jsPDF font metrics, otherwise no encoding)
6007       *                     or a JS object, where key = sourceCharCode, value = outputCharCode
6008       *                     missing keys will be treated as: sourceCharCode === outputCharCode
6009       *   .noBOM
6010       *       See comment higher above for explanation for why this is important
6011       *   .autoencode
6012       *       See comment higher above for explanation for why this is important
6013       */
6014
6015      var i, l, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
6016
6017      flags = flags || {};
6018      sourceEncoding = flags.sourceEncoding || 'Unicode';
6019      outputEncoding = flags.outputEncoding;
6020
6021      // This 'encoding' section relies on font metrics format
6022      // attached to font objects by, among others,
6023      // "Willow Systems' standard_font_metrics plugin"
6024      // see jspdf.plugin.standard_font_metrics.js for format
6025      // of the font.metadata.encoding Object.
6026      // It should be something like
6027      //   .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
6028      //   .widths = {0:width, code:width, ..., 'fof':divisor}
6029      //   .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
6030      if ((flags.autoencode || outputEncoding) && fonts[activeFontKey].metadata && fonts[activeFontKey].metadata[sourceEncoding] && fonts[activeFontKey].metadata[sourceEncoding].encoding) {
6031        encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
6032
6033        // each font has default encoding. Some have it clearly defined.
6034        if (!outputEncoding && fonts[activeFontKey].encoding) {
6035          outputEncoding = fonts[activeFontKey].encoding;
6036        }
6037
6038        // Hmmm, the above did not work? Let's try again, in different place.
6039        if (!outputEncoding && encodingBlock.codePages) {
6040          outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
6041        }
6042
6043        if (typeof outputEncoding === 'string') {
6044          outputEncoding = encodingBlock[outputEncoding];
6045        }
6046        // we want output encoding to be a JS Object, where
6047        // key = sourceEncoding's character code and
6048        // value = outputEncoding's character code.
6049        if (outputEncoding) {
6050          isUnicode = false;
6051          newtext = [];
6052          for (i = 0, l = text.length; i < l; i++) {
6053            ch = outputEncoding[text.charCodeAt(i)];
6054            if (ch) {
6055              newtext.push(String.fromCharCode(ch));
6056            } else {
6057              newtext.push(text[i]);
6058            }
6059
6060            // since we are looping over chars anyway, might as well
6061            // check for residual unicodeness
6062            if (newtext[i].charCodeAt(0) >> 8) {
6063              /* more than 255 */
6064              isUnicode = true;
6065            }
6066          }
6067          text = newtext.join('');
6068        }
6069      }
6070
6071      i = text.length;
6072      // isUnicode may be set to false above. Hence the triple-equal to undefined
6073      while (isUnicode === undefined && i !== 0) {
6074        if (text.charCodeAt(i - 1) >> 8) {
6075          /* more than 255 */
6076          isUnicode = true;
6077        }
6078        i--;
6079      }
6080      if (!isUnicode) {
6081        return text;
6082      }
6083
6084      newtext = flags.noBOM ? [] : [254, 255];
6085      for (i = 0, l = text.length; i < l; i++) {
6086        ch = text.charCodeAt(i);
6087        bch = ch >> 8; // divide by 256
6088        if (bch >> 8) {
6089          /* something left after dividing by 256 second time */
6090          throw new Error("Character at position " + i + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
6091        }
6092        newtext.push(bch);
6093        newtext.push(ch - (bch << 8));
6094      }
6095      return String.fromCharCode.apply(undefined, newtext);
6096    },
6097        pdfEscape = function pdfEscape(text, flags) {
6098      /**
6099       * Replace '/', '(', and ')' with pdf-safe versions
6100       *
6101       * Doing to8bitStream does NOT make this PDF display unicode text. For that
6102       * we also need to reference a unicode font and embed it - royal pain in the rear.
6103       *
6104       * There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
6105       * which JavaScript Strings are happy to provide. So, while we still cannot display
6106       * 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
6107       * 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
6108       * is still parseable.
6109       * This will allow immediate support for unicode in document properties strings.
6110       */
6111      return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
6112    },
6113        putInfo = function putInfo() {
6114      out('/Producer (jsPDF ' + jsPDF.version + ')');
6115      for (var key in documentProperties) {
6116        if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {
6117          out('/' + key.substr(0, 1).toUpperCase() + key.substr(1) + ' (' + pdfEscape(documentProperties[key]) + ')');
6118        }
6119      }
6120      var created = new Date(),
6121          tzoffset = created.getTimezoneOffset(),
6122          tzsign = tzoffset < 0 ? '+' : '-',
6123          tzhour = Math.floor(Math.abs(tzoffset / 60)),
6124          tzmin = Math.abs(tzoffset % 60),
6125          tzstr = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join('');
6126      out(['/CreationDate (D:', created.getFullYear(), padd2(created.getMonth() + 1), padd2(created.getDate()), padd2(created.getHours()), padd2(created.getMinutes()), padd2(created.getSeconds()), tzstr, ')'].join(''));
6127    },
6128        putCatalog = function putCatalog() {
6129      out('/Type /Catalog');
6130      out('/Pages 1 0 R');
6131      // PDF13ref Section 7.2.1
6132      if (!zoomMode) zoomMode = 'fullwidth';
6133      switch (zoomMode) {
6134        case 'fullwidth':
6135          out('/OpenAction [3 0 R /FitH null]');
6136          break;
6137        case 'fullheight':
6138          out('/OpenAction [3 0 R /FitV null]');
6139          break;
6140        case 'fullpage':
6141          out('/OpenAction [3 0 R /Fit]');
6142          break;
6143        case 'original':
6144          out('/OpenAction [3 0 R /XYZ null null 1]');
6145          break;
6146        default:
6147          var pcn = '' + zoomMode;
6148          if (pcn.substr(pcn.length - 1) === '%') zoomMode = parseInt(zoomMode) / 100;
6149          if (typeof zoomMode === 'number') {
6150            out('/OpenAction [3 0 R /XYZ null null ' + f2(zoomMode) + ']');
6151          }
6152      }
6153      if (!layoutMode) layoutMode = 'continuous';
6154      switch (layoutMode) {
6155        case 'continuous':
6156          out('/PageLayout /OneColumn');
6157          break;
6158        case 'single':
6159          out('/PageLayout /SinglePage');
6160          break;
6161        case 'two':
6162        case 'twoleft':
6163          out('/PageLayout /TwoColumnLeft');
6164          break;
6165        case 'tworight':
6166          out('/PageLayout /TwoColumnRight');
6167          break;
6168      }
6169      if (pageMode) {
6170        /**
6171         * A name object specifying how the document should be displayed when opened:
6172         * UseNone      : Neither document outline nor thumbnail images visible -- DEFAULT
6173         * UseOutlines  : Document outline visible
6174         * UseThumbs    : Thumbnail images visible
6175         * FullScreen   : Full-screen mode, with no menu bar, window controls, or any other window visible
6176         */
6177        out('/PageMode /' + pageMode);
6178      }
6179      events.publish('putCatalog');
6180    },
6181        putTrailer = function putTrailer() {
6182      out('/Size ' + (objectNumber + 1));
6183      out('/Root ' + objectNumber + ' 0 R');
6184      out('/Info ' + (objectNumber - 1) + ' 0 R');
6185    },
6186        beginPage = function beginPage(width, height) {
6187      // Dimensions are stored as user units and converted to points on output
6188      var orientation = typeof height === 'string' && height.toLowerCase();
6189      if (typeof width === 'string') {
6190        var format = width.toLowerCase();
6191        if (pageFormats.hasOwnProperty(format)) {
6192          width = pageFormats[format][0] / k;
6193          height = pageFormats[format][1] / k;
6194        }
6195      }
6196      if (Array.isArray(width)) {
6197        height = width[1];
6198        width = width[0];
6199      }
6200      if (orientation) {
6201        switch (orientation.substr(0, 1)) {
6202          case 'l':
6203            if (height > width) orientation = 's';
6204            break;
6205          case 'p':
6206            if (width > height) orientation = 's';
6207            break;
6208        }
6209        if (orientation === 's') {
6210          tmp = width;
6211          width = height;
6212          height = tmp;
6213        }
6214      }
6215      outToPages = true;
6216      pages[++page] = [];
6217      pagedim[page] = {
6218        width: Number(width) || pageWidth,
6219        height: Number(height) || pageHeight
6220      };
6221      pagesContext[page] = {};
6222      _setPage(page);
6223    },
6224        _addPage = function _addPage() {
6225      beginPage.apply(this, arguments);
6226      // Set line width
6227      out(f2(lineWidth * k) + ' w');
6228      // Set draw color
6229      out(drawColor);
6230      // resurrecting non-default line caps, joins
6231      if (lineCapID !== 0) {
6232        out(lineCapID + ' J');
6233      }
6234      if (lineJoinID !== 0) {
6235        out(lineJoinID + ' j');
6236      }
6237      events.publish('addPage', {
6238        pageNumber: page
6239      });
6240    },
6241        _deletePage = function _deletePage(n) {
6242      if (n > 0 && n <= page) {
6243        pages.splice(n, 1);
6244        pagedim.splice(n, 1);
6245        page--;
6246        if (currentPage > page) {
6247          currentPage = page;
6248        }
6249        this.setPage(currentPage);
6250      }
6251    },
6252        _setPage = function _setPage(n) {
6253      if (n > 0 && n <= page) {
6254        currentPage = n;
6255        pageWidth = pagedim[n].width;
6256        pageHeight = pagedim[n].height;
6257      }
6258    },
6259
6260    /**
6261     * Returns a document-specific font key - a label assigned to a
6262     * font name + font type combination at the time the font was added
6263     * to the font inventory.
6264     *
6265     * Font key is used as label for the desired font for a block of text
6266     * to be added to the PDF document stream.
6267     * @private
6268     * @function
6269     * @param fontName {String} can be undefined on "falthy" to indicate "use current"
6270     * @param fontStyle {String} can be undefined on "falthy" to indicate "use current"
6271     * @returns {String} Font key.
6272     */
6273    _getFont = function _getFont(fontName, fontStyle) {
6274      var key;
6275
6276      fontName = fontName !== undefined ? fontName : fonts[activeFontKey].fontName;
6277      fontStyle = fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;
6278
6279      if (fontName !== undefined) {
6280        fontName = fontName.toLowerCase();
6281      }
6282      switch (fontName) {
6283        case 'sans-serif':
6284        case 'verdana':
6285        case 'arial':
6286        case 'helvetica':
6287          fontName = 'helvetica';
6288          break;
6289        case 'fixed':
6290        case 'monospace':
6291        case 'terminal':
6292        case 'courier':
6293          fontName = 'courier';
6294          break;
6295        case 'serif':
6296        case 'cursive':
6297        case 'fantasy':
6298        default:
6299          fontName = 'times';
6300          break;
6301      }
6302
6303      try {
6304        // get a string like 'F3' - the KEY corresponding tot he font + type combination.
6305        key = fontmap[fontName][fontStyle];
6306      } catch (e) {}
6307
6308      if (!key) {
6309        //throw new Error("Unable to look up font label for font '" + fontName + "', '"
6310        //+ fontStyle + "'. Refer to getFontList() for available fonts.");
6311        key = fontmap['times'][fontStyle];
6312        if (key == null) {
6313          key = fontmap['times']['normal'];
6314        }
6315      }
6316      return key;
6317    },
6318        buildDocument = function buildDocument() {
6319      outToPages = false; // switches out() to content
6320
6321      objectNumber = 2;
6322      content_length = 0;
6323      content = [];
6324      offsets = [];
6325      additionalObjects = [];
6326      // Added for AcroForm
6327      events.publish('buildDocument');
6328
6329      // putHeader()
6330      out('%PDF-' + pdfVersion);
6331
6332      putPages();
6333
6334      // Must happen after putPages
6335      // Modifies current object Id
6336      putAdditionalObjects();
6337
6338      putResources();
6339
6340      // Info
6341      newObject();
6342      out('<<');
6343      putInfo();
6344      out('>>');
6345      out('endobj');
6346
6347      // Catalog
6348      newObject();
6349      out('<<');
6350      putCatalog();
6351      out('>>');
6352      out('endobj');
6353
6354      // Cross-ref
6355      var o = content_length,
6356          i,
6357          p = "0000000000";
6358      out('xref');
6359      out('0 ' + (objectNumber + 1));
6360      out(p + ' 65535 f ');
6361      for (i = 1; i <= objectNumber; i++) {
6362        var offset = offsets[i];
6363        if (typeof offset === 'function') {
6364          out((p + offsets[i]()).slice(-10) + ' 00000 n ');
6365        } else {
6366          out((p + offsets[i]).slice(-10) + ' 00000 n ');
6367        }
6368      }
6369      // Trailer
6370      out('trailer');
6371      out('<<');
6372      putTrailer();
6373      out('>>');
6374      out('startxref');
6375      out('' + o);
6376      out('%%EOF');
6377
6378      outToPages = true;
6379
6380      return content.join('\n');
6381    },
6382        getStyle = function getStyle(style) {
6383      // see path-painting operators in PDF spec
6384      var op = 'S'; // stroke
6385      if (style === 'F') {
6386        op = 'f'; // fill
6387      } else if (style === 'FD' || style === 'DF') {
6388        op = 'B'; // both
6389      } else if (style === 'f' || style === 'f*' || style === 'B' || style === 'B*') {
6390        /*
6391         Allow direct use of these PDF path-painting operators:
6392         - f	fill using nonzero winding number rule
6393         - f*	fill using even-odd rule
6394         - B	fill then stroke with fill using non-zero winding number rule
6395         - B*	fill then stroke with fill using even-odd rule
6396         */
6397        op = style;
6398      }
6399      return op;
6400    },
6401        getArrayBuffer = function getArrayBuffer() {
6402      var data = buildDocument(),
6403          len = data.length,
6404          ab = new ArrayBuffer(len),
6405          u8 = new Uint8Array(ab);
6406
6407      while (len--) {
6408        u8[len] = data.charCodeAt(len);
6409      }return ab;
6410    },
6411        getBlob = function getBlob() {
6412      return new Blob([getArrayBuffer()], {
6413        type: "application/pdf"
6414      });
6415    },
6416
6417    /**
6418     * Generates the PDF document.
6419     *
6420     * If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
6421     *
6422     * @param {String} type A string identifying one of the possible output types.
6423     * @param {Object} options An object providing some additional signalling to PDF generator.
6424     * @function
6425     * @returns {jsPDF}
6426     * @methodOf jsPDF#
6427     * @name output
6428     */
6429    _output = SAFE(function (type, options) {
6430      var datauri = ('' + type).substr(0, 6) === 'dataur' ? 'data:application/pdf;base64,' + btoa(buildDocument()) : 0;
6431
6432      switch (type) {
6433        case undefined:
6434          return buildDocument();
6435        case 'save':
6436          if (navigator.getUserMedia) {
6437            if (global.URL === undefined || global.URL.createObjectURL === undefined) {
6438              return API.output('dataurlnewwindow');
6439            }
6440          }
6441          saveAs(getBlob(), options);
6442          if (typeof saveAs.unload === 'function') {
6443            if (global.setTimeout) {
6444              setTimeout(saveAs.unload, 911);
6445            }
6446          }
6447          break;
6448        case 'arraybuffer':
6449          return getArrayBuffer();
6450        case 'blob':
6451          return getBlob();
6452        case 'bloburi':
6453        case 'bloburl':
6454          // User is responsible of calling revokeObjectURL
6455          return global.URL && global.URL.createObjectURL(getBlob()) || void 0;
6456        case 'datauristring':
6457        case 'dataurlstring':
6458          return datauri;
6459        case 'dataurlnewwindow':
6460          var nW = global.open(datauri);
6461          if (nW || typeof safari === "undefined") return nW;
6462        /* pass through */
6463        case 'datauri':
6464        case 'dataurl':
6465          return global.document.location.href = datauri;
6466        default:
6467          throw new Error('Output type "' + type + '" is not supported.');
6468      }
6469      // @TODO: Add different output options
6470    }),
6471
6472
6473    /**
6474     * Used to see if a supplied hotfix was requested when the pdf instance was created.
6475     * @param {String} hotfixName - The name of the hotfix to check.
6476     * @returns {boolean}
6477    */
6478    hasHotfix = function hasHotfix(hotfixName) {
6479      return Array.isArray(hotfixes) === true && hotfixes.indexOf(hotfixName) > -1;
6480    };
6481
6482    switch (unit) {
6483      case 'pt':
6484        k = 1;
6485        break;
6486      case 'mm':
6487        k = 72 / 25.4000508;
6488        break;
6489      case 'cm':
6490        k = 72 / 2.54000508;
6491        break;
6492      case 'in':
6493        k = 72;
6494        break;
6495      case 'px':
6496        if (hasHotfix('px_scaling') == true) {
6497          k = 72 / 96;
6498        } else {
6499          k = 96 / 72;
6500        }
6501        break;
6502      case 'pc':
6503        k = 12;
6504        break;
6505      case 'em':
6506        k = 12;
6507        break;
6508      case 'ex':
6509        k = 6;
6510        break;
6511      default:
6512        throw 'Invalid unit: ' + unit;
6513    }
6514
6515    //---------------------------------------
6516    // Public API
6517
6518    /**
6519     * Object exposing internal API to plugins
6520     * @public
6521     */
6522    API.internal = {
6523      'pdfEscape': pdfEscape,
6524      'getStyle': getStyle,
6525      /**
6526       * Returns {FontObject} describing a particular font.
6527       * @public
6528       * @function
6529       * @param fontName {String} (Optional) Font's family name
6530       * @param fontStyle {String} (Optional) Font's style variation name (Example:"Italic")
6531       * @returns {FontObject}
6532       */
6533      'getFont': function getFont() {
6534        return fonts[_getFont.apply(API, arguments)];
6535      },
6536      'getFontSize': function getFontSize() {
6537        return activeFontSize;
6538      },
6539      'getLineHeight': function getLineHeight() {
6540        return activeFontSize * lineHeightProportion;
6541      },
6542      'write': function write(string1 /*, string2, string3, etc */) {
6543        out(arguments.length === 1 ? string1 : Array.prototype.join.call(arguments, ' '));
6544      },
6545      'getCoordinateString': function getCoordinateString(value) {
6546        return f2(value * k);
6547      },
6548      'getVerticalCoordinateString': function getVerticalCoordinateString(value) {
6549        return f2((pageHeight - value) * k);
6550      },
6551      'collections': {},
6552      'newObject': newObject,
6553      'newAdditionalObject': newAdditionalObject,
6554      'newObjectDeferred': newObjectDeferred,
6555      'newObjectDeferredBegin': newObjectDeferredBegin,
6556      'putStream': putStream,
6557      'events': events,
6558      // ratio that you use in multiplication of a given "size" number to arrive to 'point'
6559      // units of measurement.
6560      // scaleFactor is set at initialization of the document and calculated against the stated
6561      // default measurement units for the document.
6562      // If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
6563      // through multiplication.
6564      'scaleFactor': k,
6565      'pageSize': {
6566        get width() {
6567          return pageWidth;
6568        },
6569        get height() {
6570          return pageHeight;
6571        }
6572      },
6573      'output': function output(type, options) {
6574        return _output(type, options);
6575      },
6576      'getNumberOfPages': function getNumberOfPages() {
6577        return pages.length - 1;
6578      },
6579      'pages': pages,
6580      'out': out,
6581      'f2': f2,
6582      'getPageInfo': function getPageInfo(pageNumberOneBased) {
6583        var objId = (pageNumberOneBased - 1) * 2 + 3;
6584        return {
6585          objId: objId,
6586          pageNumber: pageNumberOneBased,
6587          pageContext: pagesContext[pageNumberOneBased]
6588        };
6589      },
6590      'getCurrentPageInfo': function getCurrentPageInfo() {
6591        var objId = (currentPage - 1) * 2 + 3;
6592        return {
6593          objId: objId,
6594          pageNumber: currentPage,
6595          pageContext: pagesContext[currentPage]
6596        };
6597      },
6598      'getPDFVersion': function getPDFVersion() {
6599        return pdfVersion;
6600      },
6601      'hasHotfix': hasHotfix //Expose the hasHotfix check so plugins can also check them.
6602    };
6603
6604    /**
6605     * Adds (and transfers the focus to) new page to the PDF document.
6606     * @function
6607     * @returns {jsPDF}
6608     *
6609     * @methodOf jsPDF#
6610     * @name addPage
6611     */
6612    API.addPage = function () {
6613      _addPage.apply(this, arguments);
6614      return this;
6615    };
6616    /**
6617     * Adds (and transfers the focus to) new page to the PDF document.
6618     * @function
6619     * @returns {jsPDF}
6620     *
6621     * @methodOf jsPDF#
6622     * @name setPage
6623     * @param {Number} page Switch the active page to the page number specified
6624     * @example
6625     * doc = jsPDF()
6626     * doc.addPage()
6627     * doc.addPage()
6628     * doc.text('I am on page 3', 10, 10)
6629     * doc.setPage(1)
6630     * doc.text('I am on page 1', 10, 10)
6631     */
6632    API.setPage = function () {
6633      _setPage.apply(this, arguments);
6634      return this;
6635    };
6636    API.insertPage = function (beforePage) {
6637      this.addPage();
6638      this.movePage(currentPage, beforePage);
6639      return this;
6640    };
6641    API.movePage = function (targetPage, beforePage) {
6642      if (targetPage > beforePage) {
6643        var tmpPages = pages[targetPage];
6644        var tmpPagedim = pagedim[targetPage];
6645        var tmpPagesContext = pagesContext[targetPage];
6646        for (var i = targetPage; i > beforePage; i--) {
6647          pages[i] = pages[i - 1];
6648          pagedim[i] = pagedim[i - 1];
6649          pagesContext[i] = pagesContext[i - 1];
6650        }
6651        pages[beforePage] = tmpPages;
6652        pagedim[beforePage] = tmpPagedim;
6653        pagesContext[beforePage] = tmpPagesContext;
6654        this.setPage(beforePage);
6655      } else if (targetPage < beforePage) {
6656        var tmpPages = pages[targetPage];
6657        var tmpPagedim = pagedim[targetPage];
6658        var tmpPagesContext = pagesContext[targetPage];
6659        for (var i = targetPage; i < beforePage; i++) {
6660          pages[i] = pages[i + 1];
6661          pagedim[i] = pagedim[i + 1];
6662          pagesContext[i] = pagesContext[i + 1];
6663        }
6664        pages[beforePage] = tmpPages;
6665        pagedim[beforePage] = tmpPagedim;
6666        pagesContext[beforePage] = tmpPagesContext;
6667        this.setPage(beforePage);
6668      }
6669      return this;
6670    };
6671
6672    API.deletePage = function () {
6673      _deletePage.apply(this, arguments);
6674      return this;
6675    };
6676
6677    /**
6678     * Set the display mode options of the page like zoom and layout.
6679     *
6680     * @param {integer|String} zoom   You can pass an integer or percentage as
6681     * a string. 2 will scale the document up 2x, '200%' will scale up by the
6682     * same amount. You can also set it to 'fullwidth', 'fullheight',
6683     * 'fullpage', or 'original'.
6684     *
6685     * Only certain PDF readers support this, such as Adobe Acrobat
6686     *
6687     * @param {String} layout Layout mode can be: 'continuous' - this is the
6688     * default continuous scroll. 'single' - the single page mode only shows one
6689     * page at a time. 'twoleft' - two column left mode, first page starts on
6690     * the left, and 'tworight' - pages are laid out in two columns, with the
6691     * first page on the right. This would be used for books.
6692     * @param {String} pmode 'UseOutlines' - it shows the
6693     * outline of the document on the left. 'UseThumbs' - shows thumbnails along
6694     * the left. 'FullScreen' - prompts the user to enter fullscreen mode.
6695     *
6696     * @function
6697     * @returns {jsPDF}
6698     * @name setDisplayMode
6699     */
6700    API.setDisplayMode = function (zoom, layout, pmode) {
6701      zoomMode = zoom;
6702      layoutMode = layout;
6703      pageMode = pmode;
6704
6705      var validPageModes = [undefined, null, 'UseNone', 'UseOutlines', 'UseThumbs', 'FullScreen'];
6706      if (validPageModes.indexOf(pmode) == -1) {
6707        throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "' + pmode + '" is not recognized.');
6708      }
6709      return this;
6710    },
6711
6712    /**
6713     * Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
6714     *
6715     * @function
6716     * @param {String|Array} text String or array of strings to be added to the page. Each line is shifted one line down per font, spacing settings declared before this call.
6717     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
6718     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
6719     * @param {Object} flags Collection of settings signalling how the text must be encoded. Defaults are sane. If you think you want to pass some flags, you likely can read the source.
6720     * @returns {jsPDF}
6721     * @methodOf jsPDF#
6722     * @name text
6723     */
6724    API.text = function (text, x, y, flags, angle, align) {
6725      /**
6726       * Inserts something like this into PDF
6727       *   BT
6728       *    /F1 16 Tf  % Font name + size
6729       *    16 TL % How many units down for next line in multiline text
6730       *    0 g % color
6731       *    28.35 813.54 Td % position
6732       *    (line one) Tj
6733       *    T* (line two) Tj
6734       *    T* (line three) Tj
6735       *   ET
6736       */
6737      function ESC(s) {
6738        s = s.split("\t").join(Array(options.TabLen || 9).join(" "));
6739        return pdfEscape(s, flags);
6740      }
6741
6742      // Pre-August-2012 the order of arguments was function(x, y, text, flags)
6743      // in effort to make all calls have similar signature like
6744      //   function(data, coordinates... , miscellaneous)
6745      // this method had its args flipped.
6746      // code below allows backward compatibility with old arg order.
6747      if (typeof text === 'number') {
6748        tmp = y;
6749        y = x;
6750        x = text;
6751        text = tmp;
6752      }
6753
6754      // If there are any newlines in text, we assume
6755      // the user wanted to print multiple lines, so break the
6756      // text up into an array.  If the text is already an array,
6757      // we assume the user knows what they are doing.
6758      // Convert text into an array anyway to simplify
6759      // later code.
6760      if (typeof text === 'string') {
6761        if (text.match(/[\n\r]/)) {
6762          text = text.split(/\r\n|\r|\n/g);
6763        } else {
6764          text = [text];
6765        }
6766      }
6767      if (typeof angle === 'string') {
6768        align = angle;
6769        angle = null;
6770      }
6771      if (typeof flags === 'string') {
6772        align = flags;
6773        flags = null;
6774      }
6775      if (typeof flags === 'number') {
6776        angle = flags;
6777        flags = null;
6778      }
6779      var xtra = '',
6780          mode = 'Td',
6781          todo;
6782      if (angle) {
6783        angle *= Math.PI / 180;
6784        var c = Math.cos(angle),
6785            s = Math.sin(angle);
6786        xtra = [f2(c), f2(s), f2(s * -1), f2(c), ''].join(" ");
6787        mode = 'Tm';
6788      }
6789      flags = flags || {};
6790      if (!('noBOM' in flags)) flags.noBOM = true;
6791      if (!('autoencode' in flags)) flags.autoencode = true;
6792
6793      var strokeOption = '';
6794      var pageContext = this.internal.getCurrentPageInfo().pageContext;
6795      if (true === flags.stroke) {
6796        if (pageContext.lastTextWasStroke !== true) {
6797          strokeOption = '1 Tr\n';
6798          pageContext.lastTextWasStroke = true;
6799        }
6800      } else {
6801        if (pageContext.lastTextWasStroke) {
6802          strokeOption = '0 Tr\n';
6803        }
6804        pageContext.lastTextWasStroke = false;
6805      }
6806
6807      if (typeof this._runningPageHeight === 'undefined') {
6808        this._runningPageHeight = 0;
6809      }
6810
6811      if (typeof text === 'string') {
6812        text = ESC(text);
6813      } else if (Object.prototype.toString.call(text) === '[object Array]') {
6814        // we don't want to destroy  original text array, so cloning it
6815        var sa = text.concat(),
6816            da = [],
6817            len = sa.length;
6818        // we do array.join('text that must not be PDFescaped")
6819        // thus, pdfEscape each component separately
6820        while (len--) {
6821          da.push(ESC(sa.shift()));
6822        }
6823        if (align) {
6824          var left,
6825              prevX,
6826              maxLineLength,
6827              leading = activeFontSize * lineHeightProportion,
6828              lineWidths = text.map(function (v) {
6829            return this.getStringUnitWidth(v) * activeFontSize / k;
6830          }, this);
6831          maxLineLength = Math.max.apply(Math, lineWidths);
6832          // The first line uses the "main" Td setting,
6833          // and the subsequent lines are offset by the
6834          // previous line's x coordinate.
6835          if (align === "center") {
6836            // The passed in x coordinate defines
6837            // the center point.
6838            left = x - maxLineLength / 2;
6839            x -= lineWidths[0] / 2;
6840          } else if (align === "right") {
6841            // The passed in x coordinate defines the
6842            // rightmost point of the text.
6843            left = x - maxLineLength;
6844            x -= lineWidths[0];
6845          } else {
6846            throw new Error('Unrecognized alignment option, use "center" or "right".');
6847          }
6848          prevX = x;
6849          text = da[0];
6850          for (var i = 1, len = da.length; i < len; i++) {
6851            var delta = maxLineLength - lineWidths[i];
6852            if (align === "center") delta /= 2;
6853            // T* = x-offset leading Td ( text )
6854            text += ") Tj\n" + (left - prevX + delta) + " -" + leading + " Td (" + da[i];
6855            prevX = left + delta;
6856          }
6857        } else {
6858          text = da.join(") Tj\nT* (");
6859        }
6860      } else {
6861        throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
6862      }
6863      // Using "'" ("go next line and render text" mark) would save space but would complicate our rendering code, templates
6864
6865      // BT .. ET does NOT have default settings for Tf. You must state that explicitely every time for BT .. ET
6866      // if you want text transformation matrix (+ multiline) to work reliably (which reads sizes of things from font declarations)
6867      // Thus, there is NO useful, *reliable* concept of "default" font for a page.
6868      // The fact that "default" (reuse font used before) font worked before in basic cases is an accident
6869      // - readers dealing smartly with brokenness of jsPDF's markup.
6870
6871      var curY;
6872
6873      if (todo) {
6874        //this.addPage();
6875        //this._runningPageHeight += y -  (activeFontSize * 1.7 / k);
6876        //curY = f2(pageHeight - activeFontSize * 1.7 /k);
6877      } else {
6878        curY = f2((pageHeight - y) * k);
6879      }
6880      //curY = f2((pageHeight - (y - this._runningPageHeight)) * k);
6881
6882      //			if (curY < 0){
6883      //				console.log('auto page break');
6884      //				this.addPage();
6885      //				this._runningPageHeight = y -  (activeFontSize * 1.7 / k);
6886      //				curY = f2(pageHeight - activeFontSize * 1.7 /k);
6887      //			}
6888
6889      out('BT\n/' + activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
6890      activeFontSize * lineHeightProportion + ' TL\n' + // line spacing
6891      strokeOption + // stroke option
6892      textColor + '\n' + xtra + f2(x * k) + ' ' + curY + ' ' + mode + '\n(' + text + ') Tj\nET');
6893
6894      if (todo) {
6895        //this.text( todo, x, activeFontSize * 1.7 / k);
6896        //this.text( todo, x, this._runningPageHeight + (activeFontSize * 1.7 / k));
6897        this.text(todo, x, y); // + (activeFontSize * 1.7 / k));
6898      }
6899
6900      return this;
6901    };
6902
6903    /**
6904     * Letter spacing method to print text with gaps
6905     *
6906     * @function
6907     * @param {String|Array} text String to be added to the page.
6908     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
6909     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
6910     * @param {Number} spacing Spacing (in units declared at inception)
6911     * @returns {jsPDF}
6912     * @methodOf jsPDF#
6913     * @name lstext
6914     * @deprecated We'll be removing this function. It doesn't take character width into account.
6915     */
6916    API.lstext = function (text, x, y, spacing) {
6917      console.warn('jsPDF.lstext is deprecated');
6918      for (var i = 0, len = text.length; i < len; i++, x += spacing) {
6919        this.text(text[i], x, y);
6920      }return this;
6921    };
6922
6923    API.line = function (x1, y1, x2, y2) {
6924      return this.lines([[x2 - x1, y2 - y1]], x1, y1);
6925    };
6926
6927    API.clip = function () {
6928      // By patrick-roberts, github.com/MrRio/jsPDF/issues/328
6929      // Call .clip() after calling .rect() with a style argument of null
6930      out('W'); // clip
6931      out('S'); // stroke path; necessary for clip to work
6932    };
6933
6934    /**
6935     * This fixes the previous function clip(). Perhaps the 'stroke path' hack was due to the missing 'n' instruction?
6936     * We introduce the fixed version so as to not break API.
6937     * @param fillRule
6938     */
6939    API.clip_fixed = function (fillRule) {
6940      // Call .clip() after calling drawing ops with a style argument of null
6941      // W is the PDF clipping op
6942      if ('evenodd' === fillRule) {
6943        out('W*');
6944      } else {
6945        out('W');
6946      }
6947      // End the path object without filling or stroking it.
6948      // This operator is a path-painting no-op, used primarily for the side effect of changing the current clipping path
6949      // (see Section 4.4.3, “Clipping Path Operators”)
6950      out('n');
6951    };
6952
6953    /**
6954     * Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
6955     * All data points in `lines` are relative to last line origin.
6956     * `x`, `y` become x1,y1 for first line / curve in the set.
6957     * For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
6958     * For bezier curves you need to specify [x2,y2,x3,y3,x4,y4] - vectors to control points 1, 2, ending point. All vectors are against the start of the curve - x1,y1.
6959     *
6960     * @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, 10) // line, line, bezier curve, line
6961     * @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
6962     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
6963     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
6964     * @param {Number} scale (Defaults to [1.0,1.0]) x,y Scaling factor for all vectors. Elements can be any floating number Sub-one makes drawing smaller. Over-one grows the drawing. Negative flips the direction.
6965     * @param {String} style A string specifying the painting style or null.  Valid styles include: 'S' [default] - stroke, 'F' - fill,  and 'DF' (or 'FD') -  fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
6966     * @param {Boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
6967     * @function
6968     * @returns {jsPDF}
6969     * @methodOf jsPDF#
6970     * @name lines
6971     */
6972    API.lines = function (lines, x, y, scale, style, closed) {
6973      var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4;
6974
6975      // Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
6976      // in effort to make all calls have similar signature like
6977      //   function(content, coordinateX, coordinateY , miscellaneous)
6978      // this method had its args flipped.
6979      // code below allows backward compatibility with old arg order.
6980      if (typeof lines === 'number') {
6981        tmp = y;
6982        y = x;
6983        x = lines;
6984        lines = tmp;
6985      }
6986
6987      scale = scale || [1, 1];
6988
6989      // starting point
6990      out(f3(x * k) + ' ' + f3((pageHeight - y) * k) + ' m ');
6991
6992      scalex = scale[0];
6993      scaley = scale[1];
6994      l = lines.length;
6995      //, x2, y2 // bezier only. In page default measurement "units", *after* scaling
6996      //, x3, y3 // bezier only. In page default measurement "units", *after* scaling
6997      // ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
6998      x4 = x; // last / ending point = starting point for first item.
6999      y4 = y; // last / ending point = starting point for first item.
7000
7001      for (i = 0; i < l; i++) {
7002        leg = lines[i];
7003        if (leg.length === 2) {
7004          // simple line
7005          x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
7006          y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
7007          out(f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' l');
7008        } else {
7009          // bezier curve
7010          x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
7011          y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
7012          x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
7013          y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
7014          x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
7015          y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
7016          out(f3(x2 * k) + ' ' + f3((pageHeight - y2) * k) + ' ' + f3(x3 * k) + ' ' + f3((pageHeight - y3) * k) + ' ' + f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' c');
7017        }
7018      }
7019
7020      if (closed) {
7021        out(' h');
7022      }
7023
7024      // stroking / filling / both the path
7025      if (style !== null) {
7026        out(getStyle(style));
7027      }
7028      return this;
7029    };
7030
7031    /**
7032     * Adds a rectangle to PDF
7033     *
7034     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
7035     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
7036     * @param {Number} w Width (in units declared at inception of PDF document)
7037     * @param {Number} h Height (in units declared at inception of PDF document)
7038     * @param {String} style A string specifying the painting style or null.  Valid styles include: 'S' [default] - stroke, 'F' - fill,  and 'DF' (or 'FD') -  fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
7039     * @function
7040     * @returns {jsPDF}
7041     * @methodOf jsPDF#
7042     * @name rect
7043     */
7044    API.rect = function (x, y, w, h, style) {
7045      var op = getStyle(style);
7046      out([f2(x * k), f2((pageHeight - y) * k), f2(w * k), f2(-h * k), 're'].join(' '));
7047
7048      if (style !== null) {
7049        out(getStyle(style));
7050      }
7051
7052      return this;
7053    };
7054
7055    /**
7056     * Adds a triangle to PDF
7057     *
7058     * @param {Number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page
7059     * @param {Number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page
7060     * @param {Number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page
7061     * @param {Number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page
7062     * @param {Number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page
7063     * @param {Number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page
7064     * @param {String} style A string specifying the painting style or null.  Valid styles include: 'S' [default] - stroke, 'F' - fill,  and 'DF' (or 'FD') -  fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
7065     * @function
7066     * @returns {jsPDF}
7067     * @methodOf jsPDF#
7068     * @name triangle
7069     */
7070    API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
7071      this.lines([[x2 - x1, y2 - y1], // vector to point 2
7072      [x3 - x2, y3 - y2], // vector to point 3
7073      [x1 - x3, y1 - y3] // closing vector back to point 1
7074      ], x1, y1, // start of path
7075      [1, 1], style, true);
7076      return this;
7077    };
7078
7079    /**
7080     * Adds a rectangle with rounded corners to PDF
7081     *
7082     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
7083     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
7084     * @param {Number} w Width (in units declared at inception of PDF document)
7085     * @param {Number} h Height (in units declared at inception of PDF document)
7086     * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
7087     * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
7088     * @param {String} style A string specifying the painting style or null.  Valid styles include: 'S' [default] - stroke, 'F' - fill,  and 'DF' (or 'FD') -  fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
7089     * @function
7090     * @returns {jsPDF}
7091     * @methodOf jsPDF#
7092     * @name roundedRect
7093     */
7094    API.roundedRect = function (x, y, w, h, rx, ry, style) {
7095      var MyArc = 4 / 3 * (Math.SQRT2 - 1);
7096      this.lines([[w - 2 * rx, 0], [rx * MyArc, 0, rx, ry - ry * MyArc, rx, ry], [0, h - 2 * ry], [0, ry * MyArc, -(rx * MyArc), ry, -rx, ry], [-w + 2 * rx, 0], [-(rx * MyArc), 0, -rx, -(ry * MyArc), -rx, -ry], [0, -h + 2 * ry], [0, -(ry * MyArc), rx * MyArc, -ry, rx, -ry]], x + rx, y, // start of path
7097      [1, 1], style);
7098      return this;
7099    };
7100
7101    /**
7102     * Adds an ellipse to PDF
7103     *
7104     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
7105     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
7106     * @param {Number} rx Radius along x axis (in units declared at inception of PDF document)
7107     * @param {Number} rx Radius along y axis (in units declared at inception of PDF document)
7108     * @param {String} style A string specifying the painting style or null.  Valid styles include: 'S' [default] - stroke, 'F' - fill,  and 'DF' (or 'FD') -  fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
7109     * @function
7110     * @returns {jsPDF}
7111     * @methodOf jsPDF#
7112     * @name ellipse
7113     */
7114    API.ellipse = function (x, y, rx, ry, style) {
7115      var lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
7116          ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
7117
7118      out([f2((x + rx) * k), f2((pageHeight - y) * k), 'm', f2((x + rx) * k), f2((pageHeight - (y - ly)) * k), f2((x + lx) * k), f2((pageHeight - (y - ry)) * k), f2(x * k), f2((pageHeight - (y - ry)) * k), 'c'].join(' '));
7119      out([f2((x - lx) * k), f2((pageHeight - (y - ry)) * k), f2((x - rx) * k), f2((pageHeight - (y - ly)) * k), f2((x - rx) * k), f2((pageHeight - y) * k), 'c'].join(' '));
7120      out([f2((x - rx) * k), f2((pageHeight - (y + ly)) * k), f2((x - lx) * k), f2((pageHeight - (y + ry)) * k), f2(x * k), f2((pageHeight - (y + ry)) * k), 'c'].join(' '));
7121      out([f2((x + lx) * k), f2((pageHeight - (y + ry)) * k), f2((x + rx) * k), f2((pageHeight - (y + ly)) * k), f2((x + rx) * k), f2((pageHeight - y) * k), 'c'].join(' '));
7122
7123      if (style !== null) {
7124        out(getStyle(style));
7125      }
7126
7127      return this;
7128    };
7129
7130    /**
7131     * Adds an circle to PDF
7132     *
7133     * @param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
7134     * @param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
7135     * @param {Number} r Radius (in units declared at inception of PDF document)
7136     * @param {String} style A string specifying the painting style or null.  Valid styles include: 'S' [default] - stroke, 'F' - fill,  and 'DF' (or 'FD') -  fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
7137     * @function
7138     * @returns {jsPDF}
7139     * @methodOf jsPDF#
7140     * @name circle
7141     */
7142    API.circle = function (x, y, r, style) {
7143      return this.ellipse(x, y, r, r, style);
7144    };
7145
7146    /**
7147     * Adds a properties to the PDF document
7148     *
7149     * @param {Object} A property_name-to-property_value object structure.
7150     * @function
7151     * @returns {jsPDF}
7152     * @methodOf jsPDF#
7153     * @name setProperties
7154     */
7155    API.setProperties = function (properties) {
7156      // copying only those properties we can render.
7157      for (var property in documentProperties) {
7158        if (documentProperties.hasOwnProperty(property) && properties[property]) {
7159          documentProperties[property] = properties[property];
7160        }
7161      }
7162      return this;
7163    };
7164
7165    /**
7166     * Sets font size for upcoming text elements.
7167     *
7168     * @param {Number} size Font size in points.
7169     * @function
7170     * @returns {jsPDF}
7171     * @methodOf jsPDF#
7172     * @name setFontSize
7173     */
7174    API.setFontSize = function (size) {
7175      activeFontSize = size;
7176      return this;
7177    };
7178
7179    /**
7180     * Sets text font face, variant for upcoming text elements.
7181     * See output of jsPDF.getFontList() for possible font names, styles.
7182     *
7183     * @param {String} fontName Font name or family. Example: "times"
7184     * @param {String} fontStyle Font style or variant. Example: "italic"
7185     * @function
7186     * @returns {jsPDF}
7187     * @methodOf jsPDF#
7188     * @name setFont
7189     */
7190    API.setFont = function (fontName, fontStyle) {
7191      activeFontKey = _getFont(fontName, fontStyle);
7192      // if font is not found, the above line blows up and we never go further
7193      return this;
7194    };
7195
7196    /**
7197     * Switches font style or variant for upcoming text elements,
7198     * while keeping the font face or family same.
7199     * See output of jsPDF.getFontList() for possible font names, styles.
7200     *
7201     * @param {String} style Font style or variant. Example: "italic"
7202     * @function
7203     * @returns {jsPDF}
7204     * @methodOf jsPDF#
7205     * @name setFontStyle
7206     */
7207    API.setFontStyle = API.setFontType = function (style) {
7208      activeFontKey = _getFont(undefined, style);
7209      // if font is not found, the above line blows up and we never go further
7210      return this;
7211    };
7212
7213    /**
7214     * Returns an object - a tree of fontName to fontStyle relationships available to
7215     * active PDF document.
7216     *
7217     * @public
7218     * @function
7219     * @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
7220     * @methodOf jsPDF#
7221     * @name getFontList
7222     */
7223    API.getFontList = function () {
7224      // TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
7225      var list = {},
7226          fontName,
7227          fontStyle,
7228          tmp;
7229
7230      for (fontName in fontmap) {
7231        if (fontmap.hasOwnProperty(fontName)) {
7232          list[fontName] = tmp = [];
7233          for (fontStyle in fontmap[fontName]) {
7234            if (fontmap[fontName].hasOwnProperty(fontStyle)) {
7235              tmp.push(fontStyle);
7236            }
7237          }
7238        }
7239      }
7240
7241      return list;
7242    };
7243
7244    /**
7245     * Add a custom font.
7246     *
7247     * @param {String} Postscript name of the Font.  Example: "Menlo-Regular"
7248     * @param {String} Name of font-family from @font-face definition.  Example: "Menlo Regular"
7249     * @param {String} Font style.  Example: "normal"
7250     * @function
7251     * @returns the {fontKey} (same as the internal method)
7252     * @methodOf jsPDF#
7253     * @name addFont
7254     */
7255    API.addFont = function (postScriptName, fontName, fontStyle) {
7256      addFont(postScriptName, fontName, fontStyle, 'StandardEncoding');
7257    };
7258
7259    /**
7260     * Sets line width for upcoming lines.
7261     *
7262     * @param {Number} width Line width (in units declared at inception of PDF document)
7263     * @function
7264     * @returns {jsPDF}
7265     * @methodOf jsPDF#
7266     * @name setLineWidth
7267     */
7268    API.setLineWidth = function (width) {
7269      out((width * k).toFixed(2) + ' w');
7270      return this;
7271    };
7272
7273    /**
7274     * Sets the stroke color for upcoming elements.
7275     *
7276     * Depending on the number of arguments given, Gray, RGB, or CMYK
7277     * color space is implied.
7278     *
7279     * When only ch1 is given, "Gray" color space is implied and it
7280     * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
7281     * if values are communicated as String types, or in range from 0 (black)
7282     * to 255 (white) if communicated as Number type.
7283     * The RGB-like 0-255 range is provided for backward compatibility.
7284     *
7285     * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
7286     * value must be in the range from 0.00 (minimum intensity) to to 1.00
7287     * (max intensity) if values are communicated as String types, or
7288     * from 0 (min intensity) to to 255 (max intensity) if values are communicated
7289     * as Number types.
7290     * The RGB-like 0-255 range is provided for backward compatibility.
7291     *
7292     * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
7293     * value must be a in the range from 0.00 (0% concentration) to to
7294     * 1.00 (100% concentration)
7295     *
7296     * Because JavaScript treats fixed point numbers badly (rounds to
7297     * floating point nearest to binary representation) it is highly advised to
7298     * communicate the fractional numbers as String types, not JavaScript Number type.
7299     *
7300     * @param {Number|String} ch1 Color channel value
7301     * @param {Number|String} ch2 Color channel value
7302     * @param {Number|String} ch3 Color channel value
7303     * @param {Number|String} ch4 Color channel value
7304     *
7305     * @function
7306     * @returns {jsPDF}
7307     * @methodOf jsPDF#
7308     * @name setDrawColor
7309     */
7310    API.setDrawColor = function (ch1, ch2, ch3, ch4) {
7311      var color;
7312      if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
7313        // Gray color space.
7314        if (typeof ch1 === 'string') {
7315          color = ch1 + ' G';
7316        } else {
7317          color = f2(ch1 / 255) + ' G';
7318        }
7319      } else if (ch4 === undefined) {
7320        // RGB
7321        if (typeof ch1 === 'string') {
7322          color = [ch1, ch2, ch3, 'RG'].join(' ');
7323        } else {
7324          color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'RG'].join(' ');
7325        }
7326      } else {
7327        // CMYK
7328        if (typeof ch1 === 'string') {
7329          color = [ch1, ch2, ch3, ch4, 'K'].join(' ');
7330        } else {
7331          color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'K'].join(' ');
7332        }
7333      }
7334
7335      out(color);
7336      return this;
7337    };
7338
7339    /**
7340     * Sets the fill color for upcoming elements.
7341     *
7342     * Depending on the number of arguments given, Gray, RGB, or CMYK
7343     * color space is implied.
7344     *
7345     * When only ch1 is given, "Gray" color space is implied and it
7346     * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
7347     * if values are communicated as String types, or in range from 0 (black)
7348     * to 255 (white) if communicated as Number type.
7349     * The RGB-like 0-255 range is provided for backward compatibility.
7350     *
7351     * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
7352     * value must be in the range from 0.00 (minimum intensity) to to 1.00
7353     * (max intensity) if values are communicated as String types, or
7354     * from 0 (min intensity) to to 255 (max intensity) if values are communicated
7355     * as Number types.
7356     * The RGB-like 0-255 range is provided for backward compatibility.
7357     *
7358     * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
7359     * value must be a in the range from 0.00 (0% concentration) to to
7360     * 1.00 (100% concentration)
7361     *
7362     * Because JavaScript treats fixed point numbers badly (rounds to
7363     * floating point nearest to binary representation) it is highly advised to
7364     * communicate the fractional numbers as String types, not JavaScript Number type.
7365     *
7366     * @param {Number|String} ch1 Color channel value
7367     * @param {Number|String} ch2 Color channel value
7368     * @param {Number|String} ch3 Color channel value
7369     * @param {Number|String} ch4 Color channel value
7370     *
7371     * @function
7372     * @returns {jsPDF}
7373     * @methodOf jsPDF#
7374     * @name setFillColor
7375     */
7376    API.setFillColor = function (ch1, ch2, ch3, ch4) {
7377      var color;
7378
7379      if (ch2 === undefined || ch4 === undefined && ch1 === ch2 === ch3) {
7380        // Gray color space.
7381        if (typeof ch1 === 'string') {
7382          color = ch1 + ' g';
7383        } else {
7384          color = f2(ch1 / 255) + ' g';
7385        }
7386      } else if (ch4 === undefined || (typeof ch4 === 'undefined' ? 'undefined' : _typeof(ch4)) === 'object') {
7387        // RGB
7388        if (typeof ch1 === 'string') {
7389          color = [ch1, ch2, ch3, 'rg'].join(' ');
7390        } else {
7391          color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'rg'].join(' ');
7392        }
7393        if (ch4 && ch4.a === 0) {
7394          //TODO Implement transparency.
7395          //WORKAROUND use white for now
7396          color = ['255', '255', '255', 'rg'].join(' ');
7397        }
7398      } else {
7399        // CMYK
7400        if (typeof ch1 === 'string') {
7401          color = [ch1, ch2, ch3, ch4, 'k'].join(' ');
7402        } else {
7403          color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'k'].join(' ');
7404        }
7405      }
7406
7407      out(color);
7408      return this;
7409    };
7410
7411    /**
7412     * Sets the text color for upcoming elements.
7413     * If only one, first argument is given,
7414     * treats the value as gray-scale color value.
7415     *
7416     * @param {Number} r Red channel color value in range 0-255 or {String} r color value in hexadecimal, example: '#FFFFFF'
7417     * @param {Number} g Green channel color value in range 0-255
7418     * @param {Number} b Blue channel color value in range 0-255
7419     * @function
7420     * @returns {jsPDF}
7421     * @methodOf jsPDF#
7422     * @name setTextColor
7423     */
7424    API.setTextColor = function (r, g, b) {
7425      if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
7426        var hex = parseInt(r.substr(1), 16);
7427        r = hex >> 16 & 255;
7428        g = hex >> 8 & 255;
7429        b = hex & 255;
7430      }
7431
7432      if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
7433        textColor = f3(r / 255) + ' g';
7434      } else {
7435        textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
7436      }
7437      return this;
7438    };
7439
7440    /**
7441     * Is an Object providing a mapping from human-readable to
7442     * integer flag values designating the varieties of line cap
7443     * and join styles.
7444     *
7445     * @returns {Object}
7446     * @fieldOf jsPDF#
7447     * @name CapJoinStyles
7448     */
7449    API.CapJoinStyles = {
7450      0: 0,
7451      'butt': 0,
7452      'but': 0,
7453      'miter': 0,
7454      1: 1,
7455      'round': 1,
7456      'rounded': 1,
7457      'circle': 1,
7458      2: 2,
7459      'projecting': 2,
7460      'project': 2,
7461      'square': 2,
7462      'bevel': 2
7463    };
7464
7465    /**
7466     * Sets the line cap styles
7467     * See {jsPDF.CapJoinStyles} for variants
7468     *
7469     * @param {String|Number} style A string or number identifying the type of line cap
7470     * @function
7471     * @returns {jsPDF}
7472     * @methodOf jsPDF#
7473     * @name setLineCap
7474     */
7475    API.setLineCap = function (style) {
7476      var id = this.CapJoinStyles[style];
7477      if (id === undefined) {
7478        throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
7479      }
7480      lineCapID = id;
7481      out(id + ' J');
7482
7483      return this;
7484    };
7485
7486    /**
7487     * Sets the line join styles
7488     * See {jsPDF.CapJoinStyles} for variants
7489     *
7490     * @param {String|Number} style A string or number identifying the type of line join
7491     * @function
7492     * @returns {jsPDF}
7493     * @methodOf jsPDF#
7494     * @name setLineJoin
7495     */
7496    API.setLineJoin = function (style) {
7497      var id = this.CapJoinStyles[style];
7498      if (id === undefined) {
7499        throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
7500      }
7501      lineJoinID = id;
7502      out(id + ' j');
7503
7504      return this;
7505    };
7506
7507    // Output is both an internal (for plugins) and external function
7508    API.output = _output;
7509
7510    /**
7511     * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf')
7512     * @param  {String} filename The filename including extension.
7513     *
7514     * @function
7515     * @returns {jsPDF}
7516     * @methodOf jsPDF#
7517     * @name save
7518     */
7519    API.save = function (filename) {
7520      API.output('save', filename);
7521    };
7522
7523    // applying plugins (more methods) ON TOP of built-in API.
7524    // this is intentional as we allow plugins to override
7525    // built-ins
7526    for (var plugin in jsPDF.API) {
7527      if (jsPDF.API.hasOwnProperty(plugin)) {
7528        if (plugin === 'events' && jsPDF.API.events.length) {
7529          (function (events, newEvents) {
7530
7531            // jsPDF.API.events is a JS Array of Arrays
7532            // where each Array is a pair of event name, handler
7533            // Events were added by plugins to the jsPDF instantiator.
7534            // These are always added to the new instance and some ran
7535            // during instantiation.
7536            var eventname, handler_and_args, i;
7537
7538            for (i = newEvents.length - 1; i !== -1; i--) {
7539              // subscribe takes 3 args: 'topic', function, runonce_flag
7540              // if undefined, runonce is false.
7541              // users can attach callback directly,
7542              // or they can attach an array with [callback, runonce_flag]
7543              // that's what the "apply" magic is for below.
7544              eventname = newEvents[i][0];
7545              handler_and_args = newEvents[i][1];
7546              events.subscribe.apply(events, [eventname].concat(typeof handler_and_args === 'function' ? [handler_and_args] : handler_and_args));
7547            }
7548          })(events, jsPDF.API.events);
7549        } else {
7550          API[plugin] = jsPDF.API[plugin];
7551        }
7552      }
7553    }
7554
7555    //////////////////////////////////////////////////////
7556    // continuing initialization of jsPDF Document object
7557    //////////////////////////////////////////////////////
7558    // Add the first page automatically
7559    addFonts();
7560    activeFontKey = 'F1';
7561    _addPage(format, orientation);
7562
7563    events.publish('initialized');
7564    return API;
7565  }
7566
7567  /**
7568   * jsPDF.API is a STATIC property of jsPDF class.
7569   * jsPDF.API is an object you can add methods and properties to.
7570   * The methods / properties you add will show up in new jsPDF objects.
7571   *
7572   * One property is prepopulated. It is the 'events' Object. Plugin authors can add topics,
7573   * callbacks to this object. These will be reassigned to all new instances of jsPDF.
7574   * Examples:
7575   * jsPDF.API.events['initialized'] = function(){ 'this' is API object }
7576   * jsPDF.API.events['addFont'] = function(added_font_object){ 'this' is API object }
7577   *
7578   * @static
7579   * @public
7580   * @memberOf jsPDF
7581   * @name API
7582   *
7583   * @example
7584   * jsPDF.API.mymethod = function(){
7585   *   // 'this' will be ref to internal API object. see jsPDF source
7586   *   // , so you can refer to built-in methods like so:
7587   *   //     this.line(....)
7588   *   //     this.text(....)
7589   * }
7590   * var pdfdoc = new jsPDF()
7591   * pdfdoc.mymethod() // <- !!!!!!
7592   */
7593  jsPDF.API = {
7594    events: []
7595  };
7596  jsPDF.version = "1.x-master";
7597
7598  if (typeof define === 'function' && define.amd) {
7599    define('jsPDF', function () {
7600      return jsPDF;
7601    });
7602  } else if (typeof module !== 'undefined' && module.exports) {
7603    module.exports = jsPDF;
7604  } else {
7605    global.jsPDF = jsPDF;
7606  }
7607  return jsPDF;
7608}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
7609
7610
7611/**
7612 * jsPDF AcroForm Plugin
7613 * Copyright (c) 2016 Alexander Weidt, https://github.com/BiggA94
7614 *
7615 * Licensed under the MIT License.
7616 * http://opensource.org/licenses/mit-license
7617 */
7618
7619(window.AcroForm = function (jsPDFAPI) {
7620    'use strict';
7621
7622    var AcroForm = window.AcroForm;
7623
7624    AcroForm.scale = function (x) {
7625        return x * (acroformPlugin.internal.scaleFactor / 1); // 1 = (96 / 72)
7626    };
7627    AcroForm.antiScale = function (x) {
7628        return 1 / acroformPlugin.internal.scaleFactor * x;
7629    };
7630
7631    var acroformPlugin = {
7632        fields: [],
7633        xForms: [],
7634        /**
7635         * acroFormDictionaryRoot contains information about the AcroForm Dictionary
7636         * 0: The Event-Token, the AcroFormDictionaryCallback has
7637         * 1: The Object ID of the Root
7638         */
7639        acroFormDictionaryRoot: null,
7640        /**
7641         * After the PDF gets evaluated, the reference to the root has to be reset,
7642         * this indicates, whether the root has already been printed out
7643         */
7644        printedOut: false,
7645        internal: null
7646    };
7647
7648    jsPDF.API.acroformPlugin = acroformPlugin;
7649
7650    var annotReferenceCallback = function annotReferenceCallback() {
7651        for (var i in this.acroformPlugin.acroFormDictionaryRoot.Fields) {
7652            var formObject = this.acroformPlugin.acroFormDictionaryRoot.Fields[i];
7653            // add Annot Reference!
7654            if (formObject.hasAnnotation) {
7655                // If theres an Annotation Widget in the Form Object, put the Reference in the /Annot array
7656                createAnnotationReference.call(this, formObject);
7657            }
7658        }
7659    };
7660
7661    var createAcroForm = function createAcroForm() {
7662        if (this.acroformPlugin.acroFormDictionaryRoot) {
7663            //return;
7664            throw new Error("Exception while creating AcroformDictionary");
7665        }
7666
7667        // The Object Number of the AcroForm Dictionary
7668        this.acroformPlugin.acroFormDictionaryRoot = new AcroForm.AcroFormDictionary();
7669
7670        this.acroformPlugin.internal = this.internal;
7671
7672        // add Callback for creating the AcroForm Dictionary
7673        this.acroformPlugin.acroFormDictionaryRoot._eventID = this.internal.events.subscribe('postPutResources', AcroFormDictionaryCallback);
7674
7675        this.internal.events.subscribe('buildDocument', annotReferenceCallback); //buildDocument
7676
7677        // Register event, that is triggered when the DocumentCatalog is written, in order to add /AcroForm
7678        this.internal.events.subscribe('putCatalog', putCatalogCallback);
7679
7680        // Register event, that creates all Fields
7681        this.internal.events.subscribe('postPutPages', createFieldCallback);
7682    };
7683
7684    /**
7685     * Create the Reference to the widgetAnnotation, so that it gets referenced in the Annot[] int the+
7686     * (Requires the Annotation Plugin)
7687     */
7688    var createAnnotationReference = function createAnnotationReference(object) {
7689        var options = {
7690            type: 'reference',
7691            object: object
7692        };
7693        jsPDF.API.annotationPlugin.annotations[this.internal.getPageInfo(object.page).pageNumber].push(options);
7694    };
7695
7696    var putForm = function putForm(formObject) {
7697        if (this.acroformPlugin.printedOut) {
7698            this.acroformPlugin.printedOut = false;
7699            this.acroformPlugin.acroFormDictionaryRoot = null;
7700        }
7701        if (!this.acroformPlugin.acroFormDictionaryRoot) {
7702            createAcroForm.call(this);
7703        }
7704        this.acroformPlugin.acroFormDictionaryRoot.Fields.push(formObject);
7705    };
7706
7707    // Callbacks
7708
7709    var putCatalogCallback = function putCatalogCallback() {
7710        //Put reference to AcroForm to DocumentCatalog
7711        if (typeof this.acroformPlugin.acroFormDictionaryRoot != 'undefined') {
7712            // for safety, shouldn't normally be the case
7713            this.internal.write('/AcroForm ' + this.acroformPlugin.acroFormDictionaryRoot.objId + ' ' + 0 + ' R');
7714        } else {
7715            console.log('Root missing...');
7716        }
7717    };
7718
7719    /**
7720     * Adds /Acroform X 0 R to Document Catalog,
7721     * and creates the AcroForm Dictionary
7722     */
7723    var AcroFormDictionaryCallback = function AcroFormDictionaryCallback() {
7724        // Remove event
7725        this.internal.events.unsubscribe(this.acroformPlugin.acroFormDictionaryRoot._eventID);
7726
7727        delete this.acroformPlugin.acroFormDictionaryRoot._eventID;
7728
7729        this.acroformPlugin.printedOut = true;
7730    };
7731
7732    /**
7733     * Creates the single Fields and writes them into the Document
7734     *
7735     * If fieldArray is set, use the fields that are inside it instead of the fields from the AcroRoot
7736     * (for the FormXObjects...)
7737     */
7738    var createFieldCallback = function createFieldCallback(fieldArray) {
7739        var standardFields = !fieldArray;
7740
7741        if (!fieldArray) {
7742            // in case there is no fieldArray specified, we want to print out the Fields of the AcroForm
7743            // Print out Root
7744            this.internal.newObjectDeferredBegin(this.acroformPlugin.acroFormDictionaryRoot.objId);
7745            this.internal.out(this.acroformPlugin.acroFormDictionaryRoot.getString());
7746        }
7747
7748        var fieldArray = fieldArray || this.acroformPlugin.acroFormDictionaryRoot.Kids;
7749
7750        for (var i in fieldArray) {
7751            var form = fieldArray[i];
7752
7753            var oldRect = form.Rect;
7754
7755            if (form.Rect) {
7756                form.Rect = AcroForm.internal.calculateCoordinates.call(this, form.Rect);
7757            }
7758
7759            // Start Writing the Object
7760            this.internal.newObjectDeferredBegin(form.objId);
7761
7762            var content = "";
7763            content += form.objId + " 0 obj\n";
7764
7765            content += "<<\n" + form.getContent();
7766
7767            form.Rect = oldRect;
7768
7769            if (form.hasAppearanceStream && !form.appearanceStreamContent) {
7770                // Calculate Appearance
7771                var appearance = AcroForm.internal.calculateAppearanceStream.call(this, form);
7772                content += "/AP << /N " + appearance + " >>\n";
7773
7774                this.acroformPlugin.xForms.push(appearance);
7775            }
7776
7777            // Assume AppearanceStreamContent is a Array with N,R,D (at least one of them!)
7778            if (form.appearanceStreamContent) {
7779                content += "/AP << ";
7780                // Iterate over N,R and D
7781                for (var k in form.appearanceStreamContent) {
7782                    var value = form.appearanceStreamContent[k];
7783                    content += "/" + k + " ";
7784                    content += "<< ";
7785                    if (Object.keys(value).length >= 1 || Array.isArray(value)) {
7786                        // appearanceStream is an Array or Object!
7787                        for (var i in value) {
7788                            var obj = value[i];
7789                            if (typeof obj === 'function') {
7790                                // if Function is referenced, call it in order to get the FormXObject
7791                                obj = obj.call(this, form);
7792                            }
7793                            content += "/" + i + " " + obj + " ";
7794
7795                            // In case the XForm is already used, e.g. OffState of CheckBoxes, don't add it
7796                            if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
7797                        }
7798                    } else {
7799                        var obj = value;
7800                        if (typeof obj === 'function') {
7801                            // if Function is referenced, call it in order to get the FormXObject
7802                            obj = obj.call(this, form);
7803                        }
7804                        content += "/" + i + " " + obj + " \n";
7805                        if (!(this.acroformPlugin.xForms.indexOf(obj) >= 0)) this.acroformPlugin.xForms.push(obj);
7806                    }
7807                    content += " >>\n";
7808                }
7809
7810                // appearance stream is a normal Object..
7811                content += ">>\n";
7812            }
7813
7814            content += ">>\nendobj\n";
7815
7816            this.internal.out(content);
7817        }
7818        if (standardFields) {
7819            createXFormObjectCallback.call(this, this.acroformPlugin.xForms);
7820        }
7821    };
7822
7823    var createXFormObjectCallback = function createXFormObjectCallback(fieldArray) {
7824        for (var i in fieldArray) {
7825            var key = i;
7826            var form = fieldArray[i];
7827            // Start Writing the Object
7828            this.internal.newObjectDeferredBegin(form && form.objId);
7829
7830            var content = "";
7831            content += form ? form.getString() : '';
7832            this.internal.out(content);
7833
7834            delete fieldArray[key];
7835        }
7836    };
7837
7838    // Public:
7839
7840    jsPDFAPI.addField = function (fieldObject) {
7841        //var opt = parseOptions(fieldObject);
7842        if (fieldObject instanceof AcroForm.TextField) {
7843            addTextField.call(this, fieldObject);
7844        } else if (fieldObject instanceof AcroForm.ChoiceField) {
7845            addChoiceField.call(this, fieldObject);
7846        } else if (fieldObject instanceof AcroForm.Button) {
7847            addButton.call(this, fieldObject);
7848        } else if (fieldObject instanceof AcroForm.ChildClass) {
7849            putForm.call(this, fieldObject);
7850        } else if (fieldObject) {
7851            // try to put..
7852            putForm.call(this, fieldObject);
7853        }
7854        fieldObject.page = this.acroformPlugin.internal.getCurrentPageInfo().pageNumber;
7855        return this;
7856    };
7857
7858    // ############### sort in:
7859
7860    /**
7861     * Button
7862     * FT = Btn
7863     */
7864    var addButton = function addButton(options) {
7865        var options = options || new AcroForm.Field();
7866
7867        options.FT = '/Btn';
7868
7869        /**
7870         * Calculating the Ff entry:
7871         *
7872         * The Ff entry contains flags, that have to be set bitwise
7873         * In the Following the number in the Comment is the BitPosition
7874         */
7875        var flags = options.Ff || 0;
7876
7877        // 17, Pushbutton
7878        if (options.pushbutton) {
7879            // Options.pushbutton should be 1 or 0
7880            flags = AcroForm.internal.setBitPosition(flags, 17);
7881            delete options.pushbutton;
7882        }
7883
7884        //16, Radio
7885        if (options.radio) {
7886            //flags = options.Ff | options.radio << 15;
7887            flags = AcroForm.internal.setBitPosition(flags, 16);
7888            delete options.radio;
7889        }
7890
7891        // 15, NoToggleToOff (Radio buttons only
7892        if (options.noToggleToOff) {
7893            //flags = options.Ff | options.noToggleToOff << 14;
7894            flags = AcroForm.internal.setBitPosition(flags, 15);
7895            //delete options.noToggleToOff;
7896        }
7897
7898        // In case, there is no Flag set, it is a check-box
7899        options.Ff = flags;
7900
7901        putForm.call(this, options);
7902    };
7903
7904    var addTextField = function addTextField(options) {
7905        var options = options || new AcroForm.Field();
7906
7907        options.FT = '/Tx';
7908
7909        /**
7910         * Calculating the Ff entry:
7911         *
7912         * The Ff entry contains flags, that have to be set bitwise
7913         * In the Following the number in the Comment is the BitPosition
7914         */
7915
7916        var flags = options.Ff || 0;
7917
7918        // 13, multiline
7919        if (options.multiline) {
7920            // Set Flag
7921            flags = flags | 1 << 12;
7922            // Remove multiline from FieldObject
7923            //delete options.multiline;
7924        }
7925
7926        // 14, Password
7927        if (options.password) {
7928            flags = flags | 1 << 13;
7929            //delete options.password;
7930        }
7931
7932        // 21, FileSelect, PDF 1.4...
7933        if (options.fileSelect) {
7934            flags = flags | 1 << 20;
7935            //delete options.fileSelect;
7936        }
7937
7938        // 23, DoNotSpellCheck, PDF 1.4...
7939        if (options.doNotSpellCheck) {
7940            flags = flags | 1 << 22;
7941            //delete options.doNotSpellCheck;
7942        }
7943
7944        // 24, DoNotScroll, PDF 1.4...
7945        if (options.doNotScroll) {
7946            flags = flags | 1 << 23;
7947            //delete options.doNotScroll;
7948        }
7949
7950        options.Ff = options.Ff || flags;
7951
7952        // Add field
7953        putForm.call(this, options);
7954    };
7955
7956    var addChoiceField = function addChoiceField(opt) {
7957        var options = opt || new AcroForm.Field();
7958
7959        options.FT = '/Ch';
7960
7961        /**
7962         * Calculating the Ff entry:
7963         *
7964         * The Ff entry contains flags, that have to be set bitwise
7965         * In the Following the number in the Comment is the BitPosition
7966         */
7967
7968        var flags = options.Ff || 0;
7969
7970        // 18, Combo (If not set, the choiceField is a listBox!!)
7971        if (options.combo) {
7972            // Set Flag
7973            flags = AcroForm.internal.setBitPosition(flags, 18);
7974            // Remove combo from FieldObject
7975            delete options.combo;
7976        }
7977
7978        // 19, Edit
7979        if (options.edit) {
7980            flags = AcroForm.internal.setBitPosition(flags, 19);
7981            delete options.edit;
7982        }
7983
7984        // 20, Sort
7985        if (options.sort) {
7986            flags = AcroForm.internal.setBitPosition(flags, 20);
7987            delete options.sort;
7988        }
7989
7990        // 22, MultiSelect (PDF 1.4)
7991        if (options.multiSelect && this.internal.getPDFVersion() >= 1.4) {
7992            flags = AcroForm.internal.setBitPosition(flags, 22);
7993            delete options.multiSelect;
7994        }
7995
7996        // 23, DoNotSpellCheck (PDF 1.4)
7997        if (options.doNotSpellCheck && this.internal.getPDFVersion() >= 1.4) {
7998            flags = AcroForm.internal.setBitPosition(flags, 23);
7999            delete options.doNotSpellCheck;
8000        }
8001
8002        options.Ff = flags;
8003
8004        //options.hasAnnotation = true;
8005
8006        // Add field
8007        putForm.call(this, options);
8008    };
8009})(jsPDF.API);
8010
8011var AcroForm = window.AcroForm;
8012
8013AcroForm.internal = {};
8014
8015AcroForm.createFormXObject = function (formObject) {
8016    var xobj = new AcroForm.FormXObject();
8017    var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
8018    var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
8019    xobj.BBox = [0, 0, width, height];
8020    return xobj;
8021};
8022
8023// Contains Methods for creating standard appearances
8024AcroForm.Appearance = {
8025    CheckBox: {
8026        createAppearanceStream: function createAppearanceStream() {
8027            var appearance = {
8028                N: {
8029                    On: AcroForm.Appearance.CheckBox.YesNormal
8030                },
8031                D: {
8032                    On: AcroForm.Appearance.CheckBox.YesPushDown,
8033                    Off: AcroForm.Appearance.CheckBox.OffPushDown
8034                }
8035            };
8036
8037            return appearance;
8038        },
8039        /**
8040         * If any other icons are needed, the number between the brackets can be changed
8041         * @returns {string}
8042         */
8043        createMK: function createMK() {
8044            // 3-> Hook
8045            return "<< /CA (3)>>";
8046        },
8047        /**
8048         * Returns the standard On Appearance for a CheckBox
8049         * @returns {AcroForm.FormXObject}
8050         */
8051        YesPushDown: function YesPushDown(formObject) {
8052            var xobj = AcroForm.createFormXObject(formObject);
8053            var stream = "";
8054            // F13 is ZapfDingbats (Symbolic)
8055            formObject.Q = 1; // set text-alignment as centered
8056            var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", 50);
8057            stream += "0.749023 g\n\
8058             0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
8059             f\n\
8060             BMC\n\
8061             q\n\
8062             0 0 1 rg\n\
8063             /F13 " + calcRes.fontSize + " Tf 0 g\n\
8064             BT\n";
8065            stream += calcRes.text;
8066            stream += "ET\n\
8067             Q\n\
8068             EMC\n";
8069            xobj.stream = stream;
8070            return xobj;
8071        },
8072
8073        YesNormal: function YesNormal(formObject) {
8074            var xobj = AcroForm.createFormXObject(formObject);
8075            var stream = "";
8076            formObject.Q = 1; // set text-alignment as centered
8077            var calcRes = AcroForm.internal.calculateX(formObject, "3", "ZapfDingbats", AcroForm.Appearance.internal.getHeight(formOb
8077ject) * 0.9);
8078            stream += "1 g\n\
80790 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
8080f\n\
8081q\n\
80820 0 1 rg\n\
80830 0 " + (AcroForm.Appearance.internal.getWidth(formObject) - 1) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 1) + " re\n\
8084W\n\
8085n\n\
80860 g\n\
8087BT\n\
8088/F13 " + calcRes.fontSize + " Tf 0 g\n";
8089            stream += calcRes.text;
8090            stream += "ET\n\
8091             Q\n";
8092            xobj.stream = stream;
8093            return xobj;
8094        },
8095
8096        /**
8097         * Returns the standard Off Appearance for a CheckBox
8098         * @returns {AcroForm.FormXObject}
8099         */
8100        OffPushDown: function OffPushDown(formObject) {
8101            var xobj = AcroForm.createFormXObject(formObject);
8102            var stream = "";
8103            stream += "0.749023 g\n\
8104            0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
8105            f\n";
8106            xobj.stream = stream;
8107            return xobj;
8108        }
8109    },
8110
8111    RadioButton: {
8112        Circle: {
8113            createAppearanceStream: function createAppearanceStream(name) {
8114                var appearanceStreamContent = {
8115                    D: {
8116                        'Off': AcroForm.Appearance.RadioButton.Circle.OffPushDown
8117                    },
8118                    N: {}
8119                };
8120                appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Circle.YesNormal;
8121                appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Circle.YesPushDown;
8122                return appearanceStreamContent;
8123            },
8124            createMK: function createMK() {
8125                return "<< /CA (l)>>";
8126            },
8127
8128            YesNormal: function YesNormal(formObject) {
8129                var xobj = AcroForm.createFormXObject(formObject);
8130                var stream = "";
8131                // Make the Radius of the Circle relative to min(height, width) of formObject
8132                var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
8133                // The Borderpadding...
8134                DotRadius *= 0.9;
8135                var c = AcroForm.Appearance.internal.Bezier_C;
8136                /*
8137                 The Following is a Circle created with Bezier-Curves.
8138                 */
8139                stream += "q\n\
81401 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
8141" + DotRadius + " 0 m\n\
8142" + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
8143-" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
8144-" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
8145" + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
8146f\n\
8147Q\n";
8148                xobj.stream = stream;
8149                return xobj;
8150            },
8151            YesPushDown: function YesPushDown(formObject) {
8152                var xobj = AcroForm.createFormXObject(formObject);
8153                var stream = "";
8154                var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
8155                // The Borderpadding...
8156                DotRadius *= 0.9;
8157                // Save results for later use; no need to waste processor ticks on doing math
8158                var k = DotRadius * 2;
8159                // var c = AcroForm.Appearance.internal.Bezier_C;
8160                var kc = k * AcroForm.Appearance.internal.Bezier_C;
8161                var dc = DotRadius * AcroForm.Appearance.internal.Bezier_C;
8162                //                 stream += "0.749023 g\n\
8163                //             q\n\
8164                //           1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formOb
8164ject) / 2 + " cm\n\
8165                // " + DotRadius * 2 + " 0 m\n\
8166                // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
8167                // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
8168                // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
8169                // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
8170                //             f\n\
8171                //             Q\n\
8172                //             0 g\n\
8173                //             q\n\
8174                //             1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
8175                // " + DotRadius + " 0 m\n\
8176                // " + DotRadius + " " + DotRadius * c + " " + DotRadius * c + " " + DotRadius + " 0 " + DotRadius + " c\n\
8177                // -" + DotRadius * c + " " + DotRadius + " -" + DotRadius + " " + DotRadius * c + " -" + DotRadius + " 0 c\n\
8178                // -" + DotRadius + " -" + DotRadius * c + " -" + DotRadius * c + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
8179                // " + DotRadius * c + " -" + DotRadius + " " + DotRadius + " -" + DotRadius * c + " " + DotRadius + " 0 c\n\
8180                //             f\n\
8181                //             Q\n";
8182
8183                //  FASTER VERSION with less processor ticks spent on math operations
8184                stream += "0.749023 g\n\
8185            q\n\
8186           1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
8187" + k + " 0 m\n\
8188" + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
8189-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
8190-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
8191" + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
8192            f\n\
8193            Q\n\
8194            0 g\n\
8195            q\n\
8196            1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
8197" + DotRadius + " 0 m\n\
8198" + DotRadius + " " + dc + " " + dc + " " + DotRadius + " 0 " + DotRadius + " c\n\
8199-" + dc + " " + DotRadius + " -" + DotRadius + " " + dc + " -" + DotRadius + " 0 c\n\
8200-" + DotRadius + " -" + dc + " -" + dc + " -" + DotRadius + " 0 -" + DotRadius + " c\n\
8201" + dc + " -" + DotRadius + " " + DotRadius + " -" + dc + " " + DotRadius + " 0 c\n\
8202            f\n\
8203            Q\n";
8204                xobj.stream = stream;
8205                return xobj;
8206            },
8207            OffPushDown: function OffPushDown(formObject) {
8208                var xobj = AcroForm.createFormXObject(formObject);
8209                var stream = "";
8210                var DotRadius = AcroForm.Appearance.internal.getWidth(formObject) <= AcroForm.Appearance.internal.getHeight(formObject) ? AcroForm.Appearance.internal.getWidth(formObject) / 4 : AcroForm.Appearance.internal.getHeight(formObject) / 4;
8211                // The Borderpadding...
8212                DotRadius *= 0.9;
8213                // Save results for later use; no need to waste processor ticks on doing math
8214                var k = DotRadius * 2;
8215                // var c = AcroForm.Appearance.internal.Bezier_C;
8216                var kc = k * AcroForm.Appearance.internal.Bezier_C;
8217                //                 stream += "0.749023 g\n\
8218                //             q\n\
8219                //  1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formObject) / 2 + " cm\n\
8220                // " + DotRadius * 2 + " 0 m\n\
8221                // " + DotRadius * 2 + " " + DotRadius * 2 * c + " " + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 " + DotRadius * 2 + " c\n\
8222                // -" + DotRadius * 2 * c + " " + DotRadius * 2 + " -" + DotRadius * 2 + " " + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 c\n\
8223                // -" + DotRadius * 2 + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 * c + " -" + DotRadius * 2 + " 0 -" + DotRadius * 2 + " c\n\
8224                // " + DotRadius * 2 * c + " -" + DotRadius * 2 + " " + DotRadius * 2 + " -" + DotRadius * 2 * c + " " + DotRadius * 2 + " 0 c\n\
8225                //             f\n\
8226                //             Q\n";
8227
8228                //  FASTER VERSION with less processor ticks spent on math operations
8229                stream += "0.749023 g\n\
8230            q\n\
8231 1 0 0 1 " + AcroForm.Appearance.internal.getWidth(formObject) / 2 + " " + AcroForm.Appearance.internal.getHeight(formOb
8231ject) / 2 + " cm\n\
8232" + k + " 0 m\n\
8233" + k + " " + kc + " " + kc + " " + k + " 0 " + k + " c\n\
8234-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c\n\
8235-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c\n\
8236" + kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c\n\
8237            f\n\
8238            Q\n";
8239                xobj.stream = stream;
8240                return xobj;
8241            }
8242        },
8243
8244        Cross: {
8245            /**
8246             * Creates the Actual AppearanceDictionary-References
8247             * @param name
8248             * @returns
8249             */
8250            createAppearanceStream: function createAppearanceStream(name) {
8251                var appearanceStreamContent = {
8252                    D: {
8253                        'Off': AcroForm.Appearance.RadioButton.Cross.OffPushDown
8254                    },
8255                    N: {}
8256                };
8257                appearanceStreamContent.N[name] = AcroForm.Appearance.RadioButton.Cross.YesNormal;
8258                appearanceStreamContent.D[name] = AcroForm.Appearance.RadioButton.Cross.YesPushDown;
8259                return appearanceStreamContent;
8260            },
8261            createMK: function createMK() {
8262                return "<< /CA (8)>>";
8263            },
8264
8265            YesNormal: function YesNormal(formObject) {
8266                var xobj = AcroForm.createFormXObject(formObject);
8267                var stream = "";
8268                var cross = AcroForm.Appearance.internal.calculateCross(formObject);
8269                stream += "q\n\
8270            1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
8271            W\n\
8272            n\n\
8273            " + cross.x1.x + " " + cross.x1.y + " m\n\
8274            " + cross.x2.x + " " + cross.x2.y + " l\n\
8275            " + cross.x4.x + " " + cross.x4.y + " m\n\
8276            " + cross.x3.x + " " + cross.x3.y + " l\n\
8277            s\n\
8278            Q\n";
8279                xobj.stream = stream;
8280                return xobj;
8281            },
8282            YesPushDown: function YesPushDown(formObject) {
8283                var xobj = AcroForm.createFormXObject(formObject);
8284                var cross = AcroForm.Appearance.internal.calculateCross(formObject);
8285                var stream = "";
8286                stream += "0.749023 g\n\
8287            0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
8288            f\n\
8289            q\n\
8290            1 1 " + (AcroForm.Appearance.internal.getWidth(formObject) - 2) + " " + (AcroForm.Appearance.internal.getHeight(formObject) - 2) + " re\n\
8291            W\n\
8292            n\n\
8293            " + cross.x1.x + " " + cross.x1.y + " m\n\
8294            " + cross.x2.x + " " + cross.x2.y + " l\n\
8295            " + cross.x4.x + " " + cross.x4.y + " m\n\
8296            " + cross.x3.x + " " + cross.x3.y + " l\n\
8297            s\n\
8298            Q\n";
8299                xobj.stream = stream;
8300                return xobj;
8301            },
8302            OffPushDown: function OffPushDown(formObject) {
8303                var xobj = AcroForm.createFormXObject(formObject);
8304                var stream = "";
8305                stream += "0.749023 g\n\
8306            0 0 " + AcroForm.Appearance.internal.getWidth(formObject) + " " + AcroForm.Appearance.internal.getHeight(formObject) + " re\n\
8307            f\n";
8308                xobj.stream = stream;
8309                return xobj;
8310            }
8311        }
8312    },
8313
8314    /**
8315     * Returns the standard Appearance
8316     * @returns {AcroForm.FormXObject}
8317     */
8318    createDefaultAppearanceStream: function createDefaultAppearanceStream(formObject) {
8319        var stream = "";
8320        // Set Helvetica to Standard Font (size: auto)
8321        // Color: Black
8322        stream += "/Helv 0 Tf 0 g";
8323        return stream;
8324    }
8325};
8326
8327AcroForm.Appearance.internal = {
8328    Bezier_C: 0.551915024494,
8329
8330    calculateCross: function calculateCross(formObject) {
8331        var min = function min(x, y) {
8332            return x > y ? y : x;
8333        };
8334
8335        var width = AcroForm.Appearance.internal.getWidth(formObject);
8336        var height = AcroForm.Appearance.internal.getHeight(formOb
8336ject);
8337        var a = min(width, height);
8338        var cross = {
8339            x1: { // upperLeft
8340                x: (width - a) / 2,
8341                y: (height - a) / 2 + a //height - borderPadding
8342            },
8343            x2: { // lowerRight
8344                x: (width - a) / 2 + a,
8345                y: (height - a) / 2 //borderPadding
8346            },
8347            x3: { // lowerLeft
8348                x: (width - a) / 2,
8349                y: (height - a) / 2 //borderPadding
8350            },
8351            x4: { // upperRight
8352                x: (width - a) / 2 + a,
8353                y: (height - a) / 2 + a //height - borderPadding
8354            }
8355        };
8356
8357        return cross;
8358    }
8359};
8360AcroForm.Appearance.internal.getWidth = function (formObject) {
8361    return formObject.Rect[2]; //(formObject.Rect[2] - formObject.Rect[0]) || 0;
8362};
8363AcroForm.Appearance.internal.getHeight = function (formObject) {
8364    return formObject.Rect[3]; //(formObject.Rect[1] - formObject.Rect[3]) || 0;
8365};
8366
8367// ##########################
8368
8369//### For inheritance:
8370AcroForm.internal.inherit = function (child, parent) {
8371    child.prototype = Object.create(parent.prototype);
8372    child.prototype.constructor = child;
8373};
8374
8375// ### Handy Functions:
8376
8377AcroForm.internal.arrayToPdfArray = function (array) {
8378    if (Array.isArray(array)) {
8379        var content = ' [';
8380        for (var i in array) {
8381            var element = array[i].toString();
8382            content += element;
8383            content += i < array.length - 1 ? ' ' : '';
8384        }
8385        content += ']';
8386
8387        return content;
8388    }
8389};
8390
8391AcroForm.internal.toPdfString = function (string) {
8392    string = string || "";
8393
8394    // put Bracket at the Beginning of the String
8395    if (string.indexOf('(') !== 0) {
8396        string = '(' + string;
8397    }
8398
8399    if (string.substring(string.length - 1) != ')') {
8400        string += '(';
8401    }
8402    return string;
8403};
8404
8405// ##########################
8406//          Classes
8407// ##########################
8408
8409
8410AcroForm.PDFObject = function () {
8411    // The Object ID in the PDF Object Model
8412    // todo
8413    var _objId;
8414    Object.defineProperty(this, 'objId', {
8415        get: function get() {
8416            if (!_objId) {
8417                if (this.internal) {
8418                    _objId = this.internal.newObjectDeferred();
8419                } else if (jsPDF.API.acroformPlugin.internal) {
8420                    // todo - find better option, that doesn't rely on a Global Static var
8421                    _objId = jsPDF.API.acroformPlugin.internal.newObjectDeferred();
8422                }
8423            }
8424            if (!_objId) {
8425                console.log("Couldn't create Object ID");
8426            }
8427            return _objId;
8428        },
8429        configurable: false
8430    });
8431};
8432
8433AcroForm.PDFObject.prototype.toString = function () {
8434    return this.objId + " 0 R";
8435};
8436
8437AcroForm.PDFObject.prototype.getString = function () {
8438    var res = this.objId + " 0 obj\n<<";
8439    var content = this.getContent();
8440
8441    res += content + ">>\n";
8442    if (this.stream) {
8443        res += "stream\n";
8444        res += this.stream;
8445        res += "endstream\n";
8446    }
8447    res += "endobj\n";
8448    return res;
8449};
8450
8451AcroForm.PDFObject.prototype.getContent = function () {
8452    /**
8453     * Prints out all enumerable Variables from the Object
8454     * @param fieldObject
8455     * @returns {string}
8456     */
8457    var createContentFromFieldObject = function createContentFromFieldObject(fieldObject) {
8458        var content = '';
8459
8460        var keys = Object.keys(fieldObject).filter(function (key) {
8461            return key != 'content' && key != 'appearanceStreamContent' && key.substring(0, 1) != "_";
8462        });
8463
8464        for (var i in keys) {
8465            var key = keys[i];
8466            var value = fieldObject[key];
8467
8468            /*if (key == 'Rect' && value) {
8469             value = AcroForm.internal.calculateCoordinates.call(jsPDF.API.acroformPlugin.internal, value);
8470             }*/
8471
8472            if (value) {
8473                if (Array.isArray(value)) {
8474                    content += '/' + key + ' ' + AcroForm.internal.arrayToPdfArray(value) + "\n";
8475                } else if (value instanceof AcroForm.PDFObject) {
8476                    // In case it is a reference to another PDFObject, take the referennce number
8477                    content += '/' + key + ' ' + value.objId + " 0 R" + "\n";
8478                } else {
8479                    content += '/' + key + ' ' + value + '\n';
8480                }
8481            }
8482        }
8483        return content;
8484    };
8485
8486    var object = "";
8487
8488    object += createContentFromFieldObject(this);
8489    return object;
8490};
8491
8492AcroForm.FormXObject = function () {
8493    AcroForm.PDFObject.call(this);
8494    this.Type = "/XObject";
8495    this.Subtype = "/Form";
8496    this.FormType = 1;
8497    this.BBox;
8498    this.Matrix;
8499    this.Resources = "2 0 R";
8500    this.PieceInfo;
8501    var _stream;
8502    Object.defineProperty(this, 'Length', {
8503        enumerable: true,
8504        get: function get() {
8505            return _stream !== undefined ? _stream.length : 0;
8506        }
8507    });
8508    Object.defineProperty(this, 'stream', {
8509        enumerable: false,
8510        set: function set(val) {
8511            _stream = val;
8512        },
8513        get: function get() {
8514            if (_stream) {
8515                return _stream;
8516            } else {
8517                return null;
8518            }
8519        }
8520    });
8521};
8522
8523AcroForm.internal.inherit(AcroForm.FormXObject, AcroForm.PDFObject);
8524
8525AcroForm.AcroFormDictionary = function () {
8526    AcroForm.PDFObject.call(this);
8527    var _Kids = [];
8528    Object.defineProperty(this, 'Kids', {
8529        enumerable: false,
8530        configurable: true,
8531        get: function get() {
8532            if (_Kids.length > 0) {
8533                return _Kids;
8534            } else {
8535                return;
8536            }
8537        }
8538    });
8539    Object.defineProperty(this, 'Fields', {
8540        enumerable: true,
8541        configurable: true,
8542        get: function get() {
8543            return _Kids;
8544        }
8545    });
8546    // Default Appearance
8547    this.DA;
8548};
8549
8550AcroForm.internal.inherit(AcroForm.AcroFormDictionary, AcroForm.PDFObject);
8551
8552// ##### The Objects, the User can Create:
8553
8554
8555// The Field Object contains the Variables, that every Field needs
8556// Rectangle for Appearance: lower_left_X, lower_left_Y, width, height
8557AcroForm.Field = function () {
8558    'use strict';
8559
8560    AcroForm.PDFObject.call(this);
8561
8562    var _Rect;
8563    Object.defineProperty(this, 'Rect', {
8564        enumerable: true,
8565        configurable: false,
8566        get: function get() {
8567            if (!_Rect) {
8568                return;
8569            }
8570            var tmp = _Rect;
8571            //var calculatedRes = AcroForm.internal.calculateCoordinates(_Rect); // do later!
8572            return tmp;
8573        },
8574        set: function set(val) {
8575            _Rect = val;
8576        }
8577    });
8578
8579    var _FT = "";
8580    Object.defineProperty(this, 'FT', {
8581        enumerable: true,
8582        set: function set(val) {
8583            _FT = val;
8584        },
8585        get: function get() {
8586            return _FT;
8587        }
8588    });
8589    /**
8590     * The Partial name of the Field Object.
8591     * It has to be unique.
8592     */
8593    var _T;
8594
8595    Object.defineProperty(this, 'T', {
8596        enumerable: true,
8597        configurable: false,
8598        set: function set(val) {
8599            _T = val;
8600        },
8601        get: function get() {
8602            if (!_T || _T.length < 1) {
8603                if (this instanceof AcroForm.ChildClass) {
8604                    // In case of a Child from a Radio´Group, you don't need a FieldName!!!
8605                    return;
8606                }
8607                return "(FieldObject" + AcroForm.Field.FieldNum++ + ")";
8608            }
8609            if (_T.substring(0, 1) == "(" && _T.substring(_T.length - 1)) {
8610                return _T;
8611            }
8612            return "(" + _T + ")";
8613        }
8614    });
8615
8616    var _DA;
8617    // Defines the default appearance (Needed for variable Text)
8618    Object.defineProperty(this, 'DA', {
8619        enumerable: true,
8620        get: function get() {
8621            if (!_DA) {
8622                return;
8623            }
8624            return '(' + _DA + ')';
8625        },
8626        set: function set(val) {
8627            _DA = val;
8628        }
8629    });
8630
8631    var _DV;
8632    // Defines the default value
8633    Object.defineProperty(this, 'DV', {
8634        enumerable: true,
8635        configurable: true,
8636        get: function get() {
8637            if (!_DV) {
8638                return;
8639            }
8640            return _DV;
8641        },
8642        set: function set(val) {
8643            _DV = val;
8644        }
8645    });
8646
8647    //this.Type = "/Annot";
8648    //this.Subtype = "/Widget";
8649    Object.defineProperty(this, 'Type', {
8650        enumerable: true,
8651        get: function get() {
8652            return this.hasAnnotation ? "/Annot" : null;
8653        }
8654    });
8655
8656    Object.defineProperty(this, 'Subtype', {
8657        enumerable: true,
8658        get: function get() {
8659            return this.hasAnnotation ? "/Widget" : null;
8660        }
8661    });
8662
8663    /**
8664     *
8665     * @type {Array}
8666     */
8667    this.BG;
8668
8669    Object.defineProperty(this, 'hasAnnotation', {
8670        enumerable: false,
8671        get: function get() {
8672            if (this.Rect || this.BC || this.BG) {
8673                return true;
8674            }
8675            return false;
8676        }
8677    });
8678
8679    Object.defineProperty(this, 'hasAppearanceStream', {
8680        enumerable: false,
8681        configurable: true,
8682        writable: true
8683    });
8684
8685    Object.defineProperty(this, 'page', {
8686        enumerable: false,
8687        configurable: true,
8688        writable: true
8689    });
8690};
8691AcroForm.Field.FieldNum = 0;
8692
8693AcroForm.internal.inherit(AcroForm.Field, AcroForm.PDFObject);
8694
8695AcroForm.ChoiceField = function () {
8696    AcroForm.Field.call(this);
8697    // Field Type = Choice Field
8698    this.FT = "/Ch";
8699    // options
8700    this.Opt = [];
8701    this.V = '()';
8702    // Top Index
8703    this.TI = 0;
8704    /**
8705     * Defines, whether the
8706     * @type {boolean}
8707     */
8708    this.combo = false;
8709    /**
8710     * Defines, whether the Choice Field is an Edit Field.
8711     * An Edit Field is automatically an Combo Field.
8712     */
8713    Object.defineProperty(this, 'edit', {
8714        enumerable: true,
8715        set: function set(val) {
8716            if (val == true) {
8717                this._edit = true;
8718                // ComboBox has to be true
8719                this.combo = true;
8720            } else {
8721                this._edit = false;
8722            }
8723        },
8724        get: function get() {
8725            if (!this._edit) {
8726                return false;
8727            }
8728            return this._edit;
8729        },
8730        configurable: false
8731    });
8732    this.hasAppearanceStream = true;
8733    Object.defineProperty(this, 'V', {
8734        get: function get() {
8735            AcroForm.internal.toPdfString();
8736        }
8737    });
8738};
8739AcroForm.internal.inherit(AcroForm.ChoiceField, AcroForm.Field);
8740window["ChoiceField"] = AcroForm.ChoiceField;
8741
8742AcroForm.ListBox = function () {
8743    AcroForm.ChoiceField.call(this);
8744    //var combo = true;
8745};
8746AcroForm.internal.inherit(AcroForm.ListBox, AcroForm.ChoiceField);
8747window["ListBox"] = AcroForm.ListBox;
8748
8749AcroForm.ComboBox = function () {
8750    AcroForm.ListBox.call(this);
8751    this.combo = true;
8752};
8753AcroForm.internal.inherit(AcroForm.ComboBox, AcroForm.ListBox);
8754window["ComboBox"] = AcroForm.ComboBox;
8755
8756AcroForm.EditBox = function () {
8757    AcroForm.ComboBox.call(this);
8758    this.edit = true;
8759};
8760AcroForm.internal.inherit(AcroForm.EditBox, AcroForm.ComboBox);
8761window["EditBox"] = AcroForm.EditBox;
8762
8763AcroForm.Button = function () {
8764    AcroForm.Field.call(this);
8765    this.FT = "/Btn";
8766    //this.hasAnnotation = true;
8767};
8768AcroForm.internal.inherit(AcroForm.Button, AcroForm.Field);
8769window["Button"] = AcroForm.Button;
8770
8771AcroForm.PushButton = function () {
8772    AcroForm.Button.call(this);
8773    this.pushbutton = true;
8774};
8775AcroForm.internal.inherit(AcroForm.PushButton, AcroForm.Button);
8776window["PushButton"] = AcroForm.PushButton;
8777
8778AcroForm.RadioButton = function () {
8779    AcroForm.Button.call(this);
8780    this.radio = true;
8781    var _Kids = [];
8782    Object.defineProperty(this, 'Kids', {
8783        enumerable: true,
8784        get: function get() {
8785            if (_Kids.length > 0) {
8786                return _Kids;
8787            }
8788        }
8789    });
8790
8791    Object.defineProperty(this, '__Kids', {
8792        get: function get() {
8793            return _Kids;
8794        }
8795    });
8796
8797    var _noToggleToOff;
8798
8799    Object.defineProperty(this, 'noToggleToOff', {
8800        enumerable: false,
8801        get: function get() {
8802            return _noToggleToOff;
8803        },
8804        set: function set(val) {
8805            _noToggleToOff = val;
8806        }
8807    });
8808
8809    //this.hasAnnotation = false;
8810};
8811AcroForm.internal.inherit(AcroForm.RadioButton, AcroForm.Button);
8812window["RadioButton"] = AcroForm.RadioButton;
8813
8814/*
8815 * The Child classs of a RadioButton (the radioGroup)
8816 * -> The single Buttons
8817 */
8818AcroForm.ChildClass = function (parent, name) {
8819    AcroForm.Field.call(this);
8820    this.Parent = parent;
8821
8822    // todo: set AppearanceType as variable that can be set from the outside...
8823    this._AppearanceType = AcroForm.Appearance.RadioButton.Circle; // The Default appearanceType is the Circle
8824    this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(name);
8825
8826    // Set Print in the Annot Flag
8827    this.F = AcroForm.internal.setBitPosition(this.F, 3, 1);
8828
8829    // Set AppearanceCharacteristicsDictionary with default appearance if field is not interacting with user
8830    this.MK = this._AppearanceType.createMK(); // (8) -> Cross, (1)-> Circle, ()-> nothing
8831
8832    // Default Appearance is Off
8833    this.AS = "/Off"; // + name;
8834
8835    this._Name = name;
8836};
8837AcroForm.internal.inherit(AcroForm.ChildClass, AcroForm.Field);
8838
8839AcroForm.RadioButton.prototype.setAppearance = function (appearance) {
8840    if (!('createAppearanceStream' in appearance && 'createMK' in appearance)) {
8841        console.log("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");
8842        return;
8843    }
8844    for (var i in this.__Kids) {
8845        var child = this.__Kids[i];
8846
8847        child.appearanceStreamContent = appearance.createAppearanceStream(child._Name);
8848        child.MK = appearance.createMK();
8849    }
8850};
8851
8852AcroForm.RadioButton.prototype.createOption = function (name) {
8853    var parent = this;
8854    var child = new AcroForm.ChildClass(parent, name);
8855    // Add to Parent
8856    this.__Kids.push(child);
8857
8858    jsPDF.API.addField(child);
8859
8860    return child;
8861};
8862
8863AcroForm.CheckBox = function () {
8864    Button.call(this);
8865    this.appearanceStreamContent = AcroForm.Appearance.CheckBox.createAppearanceStream();
8866    this.MK = AcroForm.Appearance.CheckBox.createMK();
8867    this.AS = "/On";
8868    this.V = "/On";
8869};
8870AcroForm.internal.inherit(AcroForm.CheckBox, AcroForm.Button);
8871window["CheckBox"] = AcroForm.CheckBox;
8872
8873AcroForm.TextField = function () {
8874    AcroForm.Field.call(this);
8875    this.DA = AcroForm.Appearance.createDefaultAppearanceStream();
8876    this.F = 4;
8877    var _V;
8878    Object.defineProperty(this, 'V', {
8879        get: function get() {
8880            if (_V) {
8881                return "(" + _V + ")";
8882            } else {
8883                return _V;
8884            }
8885        },
8886        enumerable: true,
8887        set: function set(val) {
8888            _V = val;
8889        }
8890    });
8891
8892    var _DV;
8893    Object.defineProperty(this, 'DV', {
8894        get: function get() {
8895            if (_DV) {
8896                return "(" + _DV + ")";
8897            } else {
8898                return _DV;
8899            }
8900        },
8901        enumerable: true,
8902        set: function set(val) {
8903            _DV = val;
8904        }
8905    });
8906
8907    var _multiline = false;
8908    Object.defineProperty(this, 'multiline', {
8909        enumerable: false,
8910        get: function get() {
8911            return _multiline;
8912        },
8913        set: function set(val) {
8914            _multiline = val;
8915        }
8916    });
8917
8918    //this.multiline = false;
8919    //this.password = false;
8920    /**
8921     * For PDF 1.4
8922     * @type {boolean}
8923     */
8924    //this.fileSelect = false;
8925    /**
8926     * For PDF 1.4
8927     * @type {boolean}
8928     */
8929    //this.doNotSpellCheck = false;
8930    /**
8931     * For PDF 1.4
8932     * @type {boolean}
8933     */
8934    //this.doNotScroll = false;
8935
8936    var _MaxLen = false;
8937    Object.defineProperty(this, 'MaxLen', {
8938        enumerable: true,
8939        get: function get() {
8940            return _MaxLen;
8941        },
8942        set: function set(val) {
8943            _MaxLen = val;
8944        }
8945    });
8946
8947    Object.defineProperty(this, 'hasAppearanceStream', {
8948        enumerable: false,
8949        get: function get() {
8950            return this.V || this.DV;
8951        }
8952    });
8953};
8954AcroForm.internal.inherit(AcroForm.TextField, AcroForm.Field);
8955window["TextField"] = AcroForm.TextField;
8956
8957AcroForm.PasswordField = function () {
8958    TextField.call(this);
8959    Object.defineProperty(this, 'password', {
8960        value: true,
8961        enumerable: false,
8962        configurable: false,
8963        writable: false
8964    });
8965};
8966AcroForm.internal.inherit(AcroForm.PasswordField, AcroForm.TextField);
8967window["PasswordField"] = AcroForm.PasswordField;
8968
8969// ############ internal functions
8970
8971/*
8972 * small workaround for calculating the TextMetric approximately
8973 * @param text
8974 * @param fontsize
8975 * @returns {TextMetrics} (Has Height and Width)
8976 */
8977AcroForm.internal.calculateFontSpace = function (text, fontsize, fonttype) {
8978    var fonttype = fonttype || "helvetica";
8979    //re-use canvas object for speed improvements
8980    var canvas = AcroForm.internal.calculateFontSpace.canvas || (AcroForm.internal.calculateFontSpace.canvas = document.createElement('canvas'));
8981
8982    var context = canvas.getContext('2d');
8983    context.save();
8984    var newFont = fontsize + " " + fonttype;
8985    context.font = newFont;
8986    var res = context.measureText(text);
8987    context.fontcolor = 'black';
8988    // Calculate height:
8989    var context = canvas.getContext('2d');
8990    res.height = context.measureText("3").width * 1.5; // 3 because in ZapfDingbats its a Hook and a 3 in normal fonts
8991    context.restore();
8992
8993    return res;
8994};
8995
8996AcroForm.internal.calculateX = function (formObject, text, font, maxFontSize) {
8997    var maxFontSize = maxFontSize || 12;
8998    var font = font || "helvetica";
8999    var returnValue = {
9000        text: "",
9001        fontSize: ""
9002    };
9003    // Remove Brackets
9004    text = text.substr(0, 1) == '(' ? text.substr(1) : text;
9005    text = text.substr(text.length - 1) == ')' ? text.substr(0, text.length - 1) : text;
9006    // split into array of words
9007    var textSplit = text.split(' ');
9008
9009    /**
9010     * the color could be ((alpha)||(r,g,b)||(c,m,y,k))
9011     * @type {string}
9012     */
9013    var fontSize = maxFontSize; // The Starting fontSize (The Maximum)
9014    var lineSpacing = 2;
9015    var borderPadding = 2;
9016
9017    var height = AcroForm.Appearance.internal.getHeight(formObject) || 0;
9018    height = height < 0 ? -height : height;
9019    var width = AcroForm.Appearance.internal.getWidth(formObject) || 0;
9020    width = width < 0 ? -width : width;
9021
9022    var isSmallerThanWidth = function isSmallerThanWidth(i, lastLine, fontSize) {
9023        if (i + 1 < textSplit.length) {
9024            var tmp = lastLine + " " + textSplit[i + 1];
9025            var TextWidth = AcroForm.internal.calculateFontSpace(tmp, fontSize + "px", font).width;
9026            var FieldWidth = width - 2 * borderPadding;
9027            return TextWidth <= FieldWidth;
9028        } else {
9029            return false;
9030        }
9031    };
9032
9033    fontSize++;
9034    FontSize: while (true) {
9035        var text = "";
9036        fontSize--;
9037        var textHeight = AcroForm.internal.calculateFontSpace("3", fontSize + "px", font).height;
9038        var startY = formObject.multiline ? height - fontSize : (height - textHeight) / 2;
9039        startY += lineSpacing;
9040        var startX = -borderPadding;
9041
9042        var lastX = startX,
9043            lastY = startY;
9044        var firstWordInLine = 0,
9045            lastWordInLine = 0;
9046        var lastLength = 0;
9047
9048        if (fontSize == 0) {
9049            // In case, the Text doesn't fit at all
9050            fontSize = 12;
9051            text = "(...) Tj\n";
9052            text += "% Width of Text: " + AcroForm.internal.calculateFontSpace(text, "1px").width + ", FieldWidth:" + width + "\n";
9053            break;
9054        }
9055
9056        lastLength = AcroForm.internal.calculateFontSpace(textSplit[0] + " ", fontSize + "px", font).width;
9057
9058        var lastLine = "";
9059        var lineCount = 0;
9060        Line: for (var i in textSplit) {
9061            lastLine += textSplit[i] + " ";
9062            // Remove last blank
9063            lastLine = lastLine.substr(lastLine.length - 1) == " " ? lastLine.substr(0, lastLine.length - 1) : lastLine;
9064            var key = parseInt(i);
9065            lastLength = AcroForm.internal.calculateFontSpace(lastLine + " ", fontSize + "px", font).width;
9066            var nextLineIsSmaller = isSmallerThanWidth(key, lastLine, fontSize);
9067            var isLastWord = i >= textSplit.length - 1;
9068            if (nextLineIsSmaller && !isLastWord) {
9069                lastLine += " ";
9070                continue; // Line
9071            } else if (!nextLineIsSmaller && !isLastWord) {
9072                if (!formObject.multiline) {
9073                    continue FontSize;
9074                } else {
9075                    if ((textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
9076                        // If the Text is higher than the FieldObject
9077                        continue FontSize;
9078                    }
9079                    lastWordInLine = key;
9080                    // go on
9081                }
9082            } else if (isLastWord) {
9083                lastWordInLine = key;
9084            } else {
9085                if (formObject.multiline && (textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
9086                    // If the Text is higher than the FieldObject
9087                    continue FontSize;
9088                }
9089            }
9090
9091            var line = '';
9092
9093            for (var x = firstWordInLine; x <= lastWordInLine; x++) {
9094                line += textSplit[x] + ' ';
9095            }
9096
9097            // Remove last blank
9098            line = line.substr(line.length - 1) == " " ? line.substr(0, line.length - 1) : line;
9099            //lastLength -= blankSpace.width;
9100            lastLength = AcroForm.internal.calculateFontSpace(line, fontSize + "px", font).width;
9101
9102            // Calculate startX
9103            switch (formObject.Q) {
9104                case 2:
9105                    // Right justified
9106                    startX = width - lastLength - borderPadding;
9107                    break;
9108                case 1:
9109                    // Q = 1 := Text-Alignment: Center
9110                    startX = (width - lastLength) / 2;
9111                    break;
9112                case 0:
9113                default:
9114                    startX = borderPadding;
9115                    break;
9116            }
9117            text += startX + ' ' + lastY + ' Td\n';
9118            text += '(' + line + ') Tj\n';
9119            // reset X in PDF
9120            text += -startX + ' 0 Td\n';
9121
9122            // After a Line, adjust y position
9123            lastY = -(fontSize + lineSpacing);
9124            lastLength = 0;
9125            firstWordInLine = lastWordInLine + 1;
9126            lineCount++;
9127
9128            lastLine = "";
9129            continue Line;
9130        }
9131        break;
9132    }
9133
9134    returnValue.text = text;
9135    returnValue.fontSize = fontSize;
9136
9137    return returnValue;
9138};
9139
9140AcroForm.internal.calculateAppearanceStream = function (formObject) {
9141    if (formObject.appearanceStreamContent) {
9142        // If appearanceStream is already set, use it
9143        return formObject.appearanceStreamContent;
9144    }
9145
9146    if (!formObject.V && !formObject.DV) {
9147        return;
9148    }
9149
9150    // else calculate it
9151
9152    var stream = '';
9153
9154    var text = formObject.V || formObject.DV;
9155
9156    var calcRes = AcroForm.internal.calculateX(formObject, text);
9157
9158    stream += '/Tx BMC\n' + 'q\n' +
9159    //color + '\n' +
9160    '/F1 ' + calcRes.fontSize + ' Tf\n' +
9161    // Text Matrix
9162    '1 0 0 1 0 0 Tm\n';
9163    // Begin Text
9164    stream += 'BT\n';
9165    stream += calcRes.text;
9166    // End Text
9167    stream += 'ET\n';
9168    stream += 'Q\n' + 'EMC\n';
9169
9170    var appearanceStreamContent = new AcroForm.createFormXObject(formObject);
9171
9172    appearanceStreamContent.stream = stream;
9173
9174    return appearanceStreamContent;
9175};
9176
9177/*
9178 * Converts the Parameters from x,y,w,h to lowerLeftX, lowerLeftY, upperRightX, upperRightY
9179 * @param x
9180 * @param y
9181 * @param w
9182 * @param h
9183 * @returns {*[]}
9184 */
9185AcroForm.internal.calculateCoordinates = function (x, y, w, h) {
9186    var coordinates = {};
9187
9188    if (this.internal) {
9189        var mmtopx = function mmtopx(x) {
9190            return x * this.internal.scaleFactor;
9191        };
9192
9193        if (Array.isArray(x)) {
9194            x[0] = AcroForm.scale(x[0]);
9195            x[1] = AcroForm.scale(x[1]);
9196            x[2] = AcroForm.scale(x[2]);
9197            x[3] = AcroForm.scale(x[3]);
9198
9199            coordinates.lowerLeft_X = x[0] || 0;
9200            coordinates.lowerLeft_Y = mmtopx.call(this, this.internal.pageSize.height) - x[3] - x[1] || 0;
9201            coordinates.upperRight_X = x[0] + x[2] || 0;
9202            coordinates.upperRight_Y = mmtopx.call(this, this.internal.pageSize.height) - x[1] || 0;
9203        } else {
9204            x = AcroForm.scale(x);
9205            y = AcroForm.scale(y);
9206            w = AcroForm.scale(w);
9207            h = AcroForm.scale(h);
9208            coordinates.lowerLeft_X = x || 0;
9209            coordinates.lowerLeft_Y = this.internal.pageSize.height - y || 0;
9210            coordinates.upperRight_X = x + w || 0;
9211            coordinates.upperRight_Y = this.internal.pageSize.height - y + h || 0;
9212        }
9213    } else {
9214        // old method, that is fallback, if we can't get the pageheight, the coordinate-system starts from lower left
9215        if (Array.isArray(x)) {
9216            coordinates.lowerLeft_X = x[0] || 0;
9217            coordinates.lowerLeft_Y = x[1] || 0;
9218            coordinates.upperRight_X = x[0] + x[2] || 0;
9219            coordinates.upperRight_Y = x[1] + x[3] || 0;
9220        } else {
9221            coordinates.lowerLeft_X = x || 0;
9222            coordinates.lowerLeft_Y = y || 0;
9223            coordinates.upperRight_X = x + w || 0;
9224            coordinates.upperRight_Y = y + h || 0;
9225        }
9226    }
9227
9228    return [coordinates.lowerLeft_X, coordinates.lowerLeft_Y, coordinates.upperRight_X, coordinates.upperRight_Y];
9229};
9230
9231AcroForm.internal.calculateColor = function (r, g, b) {
9232    var color = new Array(3);
9233    color.r = r | 0;
9234    color.g = g | 0;
9235    color.b = b | 0;
9236    return color;
9237};
9238
9239AcroForm.internal.getBitPosition = function (variable, position) {
9240    variable = variable || 0;
9241    var bitMask = 1;
9242    bitMask = bitMask << position - 1;
9243    return variable | bitMask;
9244};
9245
9246AcroForm.internal.setBitPosition = function (variable, position, value) {
9247    variable = variable || 0;
9248    value = value || 1;
9249
9250    var bitMask = 1;
9251    bitMask = bitMask << position - 1;
9252
9253    if (value == 1) {
9254        // Set the Bit to 1
9255        var variable = variable | bitMask;
9256    } else {
9257        // Set the Bit to 0
9258        var variable = variable & ~bitMask;
9259    }
9260
9261    return variable;
9262};
9263
9264/**
9265 * jsPDF addHTML PlugIn
9266 * Copyright (c) 2014 Diego Casorran
9267 *
9268 * Licensed under the MIT License.
9269 * http://opensource.org/licenses/mit-license
9270 */
9271
9272(function (jsPDFAPI) {
9273	'use strict';
9274
9275	/**
9276  * Renders an HTML element to canvas object which added to the PDF
9277  *
9278  * This feature requires [html2canvas](https://github.com/niklasvh/html2canvas)
9279  * or [rasterizeHTML](https://github.com/cburgmer/rasterizeHTML.js)
9280  *
9281  * @returns {jsPDF}
9282  * @name addHTML
9283  * @param element {Mixed} HTML Element, or anything supported by html2canvas.
9284  * @param x {Number} starting X coordinate in jsPDF instance's declared units.
9285  * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
9286  * @param options {Object} Additional options, check the code below.
9287  * @param callback {Function} to call when the rendering has finished.
9288  * NOTE: Every parameter is optional except 'element' and 'callback', in such
9289  *       case the image is positioned at 0x0 covering the whole PDF document
9290  *       size. Ie, to easily take screenshots of webpages saving them to PDF.
9291  * @deprecated This is being replace with a vector-supporting API. See
9292  * [this link](https://cdn.rawgit.com/MrRio/jsPDF/master/examples/html2pdf/showcase_supported_html.html)
9293  */
9294
9295	jsPDFAPI.addHTML = function (element, x, y, options, callback) {
9296		'use strict';
9297
9298		if (typeof html2canvas === 'undefined' && typeof rasterizeHTML === 'undefined') throw new Error('You need either ' + 'https://github.com/niklasvh/html2canvas' + ' or https://github.com/cburgmer/rasterizeHTML.js');
9299
9300		if (typeof x !== 'number') {
9301			options = x;
9302			callback = y;
9303		}
9304
9305		if (typeof options === 'function') {
9306			callback = options;
9307			options = null;
9308		}
9309
9310		var I = this.internal,
9311		    K = I.scaleFactor,
9312		    W = I.pageSize.width,
9313		    H = I.pageSize.height;
9314
9315		options = options || {};
9316		options.onrendered = function (obj) {
9317			x = parseInt(x) || 0;
9318			y = parseInt(y) || 0;
9319			var dim = options.dim || {};
9320			var h = dim.h || 0;
9321			var w = dim.w || Math.min(W, obj.width / K) - x;
9322
9323			var format = 'JPEG';
9324			if (options.format) format = options.format;
9325
9326			if (obj.height > H && options.pagesplit) {
9327				var crop = function () {
9328					var cy = 0;
9329					while (1) {
9330						var canvas = document.createElement('canvas');
9331						canvas.width = Math.min(W * K, obj.width);
9332						canvas.height = Math.min(H * K, obj.height - cy);
9333						var ctx = canvas.getContext('2d');
9334						ctx.drawImage(obj, 0, cy, obj.width, canvas.height, 0, 0, canvas.width, canvas.height);
9335						var args = [canvas, x, cy ? 0 : y, canvas.width / K, canvas.height / K, format, null, 'SLOW'];
9336						this.addImage.apply(this, args);
9337						cy += canvas.height;
9338						if (cy >= obj.height) break;
9339						this.addPage();
9340					}
9341					callback(w, cy, null, args);
9342				}.bind(this);
9343				if (obj.nodeName === 'CANVAS') {
9344					var img = new Image();
9345					img.onload = crop;
9346					img.src = obj.toDataURL("image/png");
9347					obj = img;
9348				} else {
9349					crop();
9350				}
9351			} else {
9352				var alias = Math.random().toString(35);
9353				var args = [obj, x, y, w, h, format, alias, 'SLOW'];
9354
9355				this.addImage.apply(this, args);
9356
9357				callback(w, h, alias, args);
9358			}
9359		}.bind(this);
9360
9361		if (typeof html2canvas !== 'undefined' && !options.rstz) {
9362			return html2canvas(element, options);
9363		}
9364
9365		if (typeof rasterizeHTML !== 'undefined') {
9366			var meth = 'drawDocument';
9367			if (typeof element === 'string') {
9368				meth = /^http/.test(element) ? 'drawURL' : 'drawHTML';
9369			}
9370			options.width = options.width || W * K;
9371			return rasterizeHTML[meth](element, void 0, options).then(function (r) {
9372				options.onrendered(r.image);
9373			}, function (e) {
9374				callback(null, e);
9375			});
9376		}
9377
9378		return null;
9379	};
9380})(jsPDF.API);
9381
9382/** @preserve
9383 * jsPDF addImage plugin
9384 * Copyright (c) 2012 Jason Siefken, https://github.com/siefkenj/
9385 *               2013 Chris Dowling, https://github.com/gingerchris
9386 *               2013 Trinh Ho, https://github.com/ineedfat
9387 *               2013 Edwin Alejandro Perez, https://github.com/eaparango
9388 *               2013 Norah Smith, https://github.com/burnburnrocket
9389 *               2014 Diego Casorran, https://github.com/diegocr
9390 *               2014 James Robb, https://github.com/jamesbrobb
9391 *
9392 * 
9393 */
9394
9395(function (jsPDFAPI) {
9396	'use strict';
9397
9398	var namespace = 'addImage_',
9399	    supported_image_types = ['jpeg', 'jpg', 'png'];
9400
9401	// Image functionality ported from pdf.js
9402	var putImage = function putImage(img) {
9403
9404		var objectNumber = this.internal.newObject(),
9405		    out = this.internal.write,
9406		    putStream = this.internal.putStream;
9407
9408		img['n'] = objectNumber;
9409
9410		out('<</Type /XObject');
9411		out('/Subtype /Image');
9412		out('/Width ' + img['w']);
9413		out('/Height ' + img['h']);
9414		if (img['cs'] === this.color_spaces.INDEXED) {
9415			out('/ColorSpace [/Indexed /DeviceRGB '
9416			// if an indexed png defines more than one colour with transparency, we've created a smask
9417			+ (img['pal'].length / 3 - 1) + ' ' + ('smask' in img ? objectNumber + 2 : objectNumber + 1) + ' 0 R]');
9418		} else {
9419			out('/ColorSpace /' + img['cs']);
9420			if (img['cs'] === this.color_spaces.DEVICE_CMYK) {
9421				out('/Decode [1 0 1 0 1 0 1 0]');
9422			}
9423		}
9424		out('/BitsPerComponent ' + img['bpc']);
9425		if ('f' in img) {
9426			out('/Filter /' + img['f']);
9427		}
9428		if ('dp' in img) {
9429			out('/DecodeParms <<' + img['dp'] + '>>');
9430		}
9431		if ('trns' in img && img['trns'].constructor == Array) {
9432			var trns = '',
9433			    i = 0,
9434			    len = img['trns'].length;
9435			for (; i < len; i++) {
9436				trns += img['trns'][i] + ' ' + img['trns'][i] + ' ';
9437			}out('/Mask [' + trns + ']');
9438		}
9439		if ('smask' in img) {
9440			out('/SMask ' + (objectNumber + 1) + ' 0 R');
9441		}
9442		out('/Length ' + img['data'].length + '>>');
9443
9444		putStream(img['data']);
9445
9446		out('endobj');
9447
9448		// Soft mask
9449		if ('smask' in img) {
9450			var dp = '/Predictor ' + img['p'] + ' /Colors 1 /BitsPerComponent ' + img['bpc'] + ' /Columns ' + img['w'];
9451			var smask = { 'w': img['w'], 'h': img['h'], 'cs': 'DeviceGray', 'bpc': img['bpc'], 'dp': dp, 'data': img['smask'] };
9452			if ('f' in img) smask.f = img['f'];
9453			putImage.call(this, smask);
9454		}
9455
9456		//Palette
9457		if (img['cs'] === this.color_spaces.INDEXED) {
9458
9459			this.internal.newObject();
9460			//out('<< /Filter / ' + img['f'] +' /Length ' + img['pal'].length + '>>');
9461			//putStream(zlib.compress(img['pal']));
9462			out('<< /Length ' + img['pal'].length + '>>');
9463			putStream(this.arrayBufferToBinaryString(new Uint8Array(img['pal'])));
9464			out('endobj');
9465		}
9466	},
9467	    putResourcesCallback = function putResourcesCallback() {
9468		var images = this.internal.collections[namespace + 'images'];
9469		for (var i in images) {
9470			putImage.call(this, images[i]);
9471		}
9472	},
9473	    putXObjectsDictCallback = function putXObjectsDictCallback() {
9474		var images = this.internal.collections[namespace + 'images'],
9475		    out = this.internal.write,
9476		    image;
9477		for (var i in images) {
9478			image = images[i];
9479			out('/I' + image['i'], image['n'], '0', 'R');
9480		}
9481	},
9482	    checkCompressValue = function checkCompressValue(value) {
9483		if (value && typeof value === 'string') value = value.toUpperCase();
9484		return value in jsPDFAPI.image_compression ? value : jsPDFAPI.image_compression.NONE;
9485	},
9486	    getImages = function getImages() {
9487		var images = this.internal.collections[namespace + 'images'];
9488		//first run, so initialise stuff
9489		if (!images) {
9490			this.internal.collections[namespace + 'images'] = images = {};
9491			this.internal.events.subscribe('putResources', putResourcesCallback);
9492			this.internal.events.subscribe('putXobjectDict', putXObjectsDictCallback);
9493		}
9494
9495		return images;
9496	},
9497	    getImageIndex = function getImageIndex(images) {
9498		var imageIndex = 0;
9499
9500		if (images) {
9501			// this is NOT the first time this method is ran on this instance of jsPDF object.
9502			imageIndex = Object.keys ? Object.keys(images).length : function (o) {
9503				var i = 0;
9504				for (var e in o) {
9505					if (o.hasOwnProperty(e)) {
9506						i++;
9507					}
9508				}
9509				return i;
9510			}(images);
9511		}
9512
9513		return imageIndex;
9514	},
9515	    notDefined = function notDefined(value) {
9516		return typeof value === 'undefined' || value === null;
9517	},
9518	    generateAliasFromData = function generateAliasFromData(data) {
9519		return typeof data === 'string' && jsPDFAPI.sHashCode(data);
9520	},
9521	    doesNotSupportImageType = function doesNotSupportImageType(type) {
9522		return supported_image_types.indexOf(type) === -1;
9523	},
9524	    processMethodNotEnabled = function processMethodNotEnabled(type) {
9525		return typeof jsPDFAPI['process' + type.toUpperCase()] !== 'function';
9526	},
9527	    isDOMElement = function isDOMElement(object) {
9528		return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object.nodeType === 1;
9529	},
9530	    createDataURIFromElement = function createDataURIFromElement(element, format, angle) {
9531
9532		//if element is an image which uses data url definition, just return the dataurl
9533		if (element.nodeName === 'IMG' && element.hasAttribute('src')) {
9534			var src = '' + element.getAttribute('src');
9535			if (!angle && src.indexOf('data:image/') === 0) return src;
9536
9537			// only if the user doesn't care about a format
9538			if (!format && /\.png(?:[?#].*)?$/i.test(src)) format = 'png';
9539		}
9540
9541		if (element.nodeName === 'CANVAS') {
9542			var canvas = element;
9543		} else {
9544			var canvas = document.createElement('canvas');
9545			canvas.width = element.clientWidth || element.width;
9546			canvas.height = element.clientHeight || element.height;
9547
9548			var ctx = canvas.getContext('2d');
9549			if (!ctx) {
9550				throw 'addImage requires canvas to be supported by browser.';
9551			}
9552			if (angle) {
9553				var x,
9554				    y,
9555				    b,
9556				    c,
9557				    s,
9558				    w,
9559				    h,
9560				    to_radians = Math.PI / 180,
9561				    angleInRadians;
9562
9563				if ((typeof angle === 'undefined' ? 'undefined' : _typeof(angle)) === 'object') {
9564					x = angle.x;
9565					y = angle.y;
9566					b = angle.bg;
9567					angle = angle.angle;
9568				}
9569				angleInRadians = angle * to_radians;
9570				c = Math.abs(Math.cos(angleInRadians));
9571				s = Math.abs(Math.sin(angleInRadians));
9572				w = canvas.width;
9573				h = canvas.height;
9574				canvas.width = h * s + w * c;
9575				canvas.height = h * c + w * s;
9576
9577				if (isNaN(x)) x = canvas.width / 2;
9578				if (isNaN(y)) y = canvas.height / 2;
9579
9580				ctx.clearRect(0, 0, canvas.width, canvas.height);
9581				ctx.fillStyle = b || 'white';
9582				ctx.fillRect(0, 0, canvas.width, canvas.height);
9583				ctx.save();
9584				ctx.translate(x, y);
9585				ctx.rotate(angleInRadians);
9586				ctx.drawImage(element, -(w / 2), -(h / 2));
9587				ctx.rotate(-angleInRadians);
9588				ctx.translate(-x, -y);
9589				ctx.restore();
9590			} else {
9591				ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
9592			}
9593		}
9594		return canvas.toDataURL(('' + format).toLowerCase() == 'png' ? 'image/png' : 'image/jpeg');
9595	},
9596	    checkImagesForAlias = function checkImagesForAlias(alias, images) {
9597		var cached_info;
9598		if (images) {
9599			for (var e in images) {
9600				if (alias === images[e].alias) {
9601					cached_info = images[e];
9602					break;
9603				}
9604			}
9605		}
9606		return cached_info;
9607	},
9608	    determineWidthAndHeight = function determineWidthAndHeight(w, h, info) {
9609		if (!w && !h) {
9610			w = -96;
9611			h = -96;
9612		}
9613		if (w < 0) {
9614			w = -1 * info['w'] * 72 / w / this.internal.scaleFactor;
9615		}
9616		if (h < 0) {
9617			h = -1 * info['h'] * 72 / h / this.internal.scaleFactor;
9618		}
9619		if (w === 0) {
9620			w = h * info['w'] / info['h'];
9621		}
9622		if (h === 0) {
9623			h = w * info['h'] / info['w'];
9624		}
9625
9626		return [w, h];
9627	},
9628	    writeImageToPDF = function writeImageToPDF(x, y, w, h, info, index, images) {
9629		var dims = determineWidthAndHeight.call(this, w, h, info),
9630		    coord = this.internal.getCoordinateString,
9631		    vcoord = this.internal.getVerticalCoordinateString;
9632
9633		w = dims[0];
9634		h = dims[1];
9635
9636		images[index] = info;
9637
9638		this.internal.write('q', coord(w), '0 0', coord(h) // TODO: check if this should be shifted by vcoord
9639		, coord(x), vcoord(y + h), 'cm /I' + info['i'], 'Do Q');
9640	};
9641
9642	/**
9643  * COLOR SPACES
9644  */
9645	jsPDFAPI.color_spaces = {
9646		DEVICE_RGB: 'DeviceRGB',
9647		DEVICE_GRAY: 'DeviceGray',
9648		DEVICE_CMYK: 'DeviceCMYK',
9649		CAL_GREY: 'CalGray',
9650		CAL_RGB: 'CalRGB',
9651		LAB: 'Lab',
9652		ICC_BASED: 'ICCBased',
9653		INDEXED: 'Indexed',
9654		PATTERN: 'Pattern',
9655		SEPARATION: 'Separation',
9656		DEVICE_N: 'DeviceN'
9657	};
9658
9659	/**
9660  * DECODE METHODS
9661  */
9662	jsPDFAPI.decode = {
9663		DCT_DECODE: 'DCTDecode',
9664		FLATE_DECODE: 'FlateDecode',
9665		LZW_DECODE: 'LZWDecode',
9666		JPX_DECODE: 'JPXDecode',
9667		JBIG2_DECODE: 'JBIG2Decode',
9668		ASCII85_DECODE: 'ASCII85Decode',
9669		ASCII_HEX_DECODE: 'ASCIIHexDecode',
9670		RUN_LENGTH_DECODE: 'RunLengthDecode',
9671		CCITT_FAX_DECODE: 'CCITTFaxDecode'
9672	};
9673
9674	/**
9675  * IMAGE COMPRESSION TYPES
9676  */
9677	jsPDFAPI.image_compression = {
9678		NONE: 'NONE',
9679		FAST: 'FAST',
9680		MEDIUM: 'MEDIUM',
9681		SLOW: 'SLOW'
9682	};
9683
9684	jsPDFAPI.sHashCode = function (str) {
9685		return Array.prototype.reduce && str.split("").reduce(function (a, b) {
9686			a = (a << 5) - a + b.charCodeAt(0);return a & a;
9687		}, 0);
9688	};
9689
9690	jsPDFAPI.isString = function (object) {
9691		return typeof object === 'string';
9692	};
9693
9694	/**
9695  * Strips out and returns info from a valid base64 data URI
9696  * @param {String[dataURI]} a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
9697  * @returns an Array containing the following
9698  * [0] the complete data URI
9699  * [1] <MIME-type>
9700  * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
9701  * [4] <data>
9702  */
9703	jsPDFAPI.extractInfoFromBase64DataURI = function (dataURI) {
9704		return (/^data:([\w]+?\/([\w]+?));base64,(.+?)$/g.exec(dataURI)
9705		);
9706	};
9707
9708	/**
9709  * Check to see if ArrayBuffer is supported
9710  */
9711	jsPDFAPI.supportsArrayBuffer = function () {
9712		return typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined';
9713	};
9714
9715	/**
9716  * Tests supplied object to determine if ArrayBuffer
9717  * @param {Object[object]}
9718  */
9719	jsPDFAPI.isArrayBuffer = function (object) {
9720		if (!this.supportsArrayBuffer()) return false;
9721		return object instanceof ArrayBuffer;
9722	};
9723
9724	/**
9725  * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
9726  * @param {Object[object]}
9727  */
9728	jsPDFAPI.isArrayBufferView = function (object) {
9729		if (!this.supportsArrayBuffer()) return false;
9730		if (typeof Uint32Array === 'undefined') return false;
9731		return object instanceof Int8Array || object instanceof Uint8Array || typeof Uint8ClampedArray !== 'undefined' && object instanceof Uint8ClampedArray || object instanceof Int16Array || object instanceof Uint16Array || object instanceof Int32Array || object instanceof Uint32Array || object instanceof Float32Array || object instanceof Float64Array;
9732	};
9733
9734	/**
9735  * Exactly what it says on the tin
9736  */
9737	jsPDFAPI.binaryStringToUint8Array = function (binary_string) {
9738		/*
9739   * not sure how efficient this will be will bigger files. Is there a native method?
9740   */
9741		var len = binary_string.length;
9742		var bytes = new Uint8Array(len);
9743		for (var i = 0; i < len; i++) {
9744			bytes[i] = binary_string.charCodeAt(i);
9745		}
9746		return bytes;
9747	};
9748
9749	/**
9750  * Convert the Buffer to a Binary String
9751  */
9752	jsPDFAPI.arrayBufferToBinaryString = function (buffer) {
9753		if (typeof window.atob === "function") {
9754			return atob(this.arrayBufferToBase64(buffer));
9755		} else {
9756			var data = this.isArrayBuffer(buffer) ? buffer : new Uint8Array(buffer);
9757			var chunkSizeForSlice = 0x5000;
9758			var binary_string = '';
9759			var slicesCount = Math.round(data.byteLength / chunkSizeForSlice);
9760			for (var i = 0; i < slicesCount; i++) {
9761				binary_string += String.fromCharCode.apply(null, data.slice(i * chunkSizeForSlice, i * chunkSizeForSlice + chunkSizeForSlice));
9762			}
9763			return binary_string;
9764		}
9765	};
9766
9767	/**
9768  * Converts an ArrayBuffer directly to base64
9769  *
9770  * Taken from here
9771  *
9772  * http://jsperf.com/encoding-xhr-image-data/31
9773  *
9774  * Need to test if this is a better solution for larger files
9775  *
9776  */
9777	jsPDFAPI.arrayBufferToBase64 = function (arrayBuffer) {
9778		var base64 = '';
9779		var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
9780
9781		var bytes = new Uint8Array(arrayBuffer);
9782		var byteLength = bytes.byteLength;
9783		var byteRemainder = byteLength % 3;
9784		var mainLength = byteLength - byteRemainder;
9785
9786		var a, b, c, d;
9787		var chunk;
9788
9789		// Main loop deals with bytes in chunks of 3
9790		for (var i = 0; i < mainLength; i = i + 3) {
9791			// Combine the three bytes into a single integer
9792			chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
9793
9794			// Use bitmasks to extract 6-bit segments from the triplet
9795			a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
9796			b = (chunk & 258048) >> 12; // 258048   = (2^6 - 1) << 12
9797			c = (chunk & 4032) >> 6; // 4032     = (2^6 - 1) << 6
9798			d = chunk & 63; // 63       = 2^6 - 1
9799
9800			// Convert the raw binary segments to the appropriate ASCII encoding
9801			base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
9802		}
9803
9804		// Deal with the remaining bytes and padding
9805		if (byteRemainder == 1) {
9806			chunk = bytes[mainLength];
9807
9808			a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
9809
9810			// Set the 4 least significant bits to zero
9811			b = (chunk & 3) << 4; // 3   = 2^2 - 1
9812
9813			base64 += encodings[a] + encodings[b] + '==';
9814		} else if (byteRemainder == 2) {
9815			chunk = bytes[mainLength] << 8 | bytes[mainLength + 1];
9816
9817			a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
9818			b = (chunk & 1008) >> 4; // 1008  = (2^6 - 1) << 4
9819
9820			// Set the 2 least significant bits to zero
9821			c = (chunk & 15) << 2; // 15    = 2^4 - 1
9822
9823			base64 += encodings[a] + encodings[b] + encodings[c] + '=';
9824		}
9825
9826		return base64;
9827	};
9828
9829	jsPDFAPI.createImageInfo = function (data, wd, ht, cs, bpc, f, imageIndex, alias, dp, trns, pal, smask, p) {
9830		var info = {
9831			alias: alias,
9832			w: wd,
9833			h: ht,
9834			cs: cs,
9835			bpc: bpc,
9836			i: imageIndex,
9837			data: data
9838			// n: objectNumber will be added by putImage code
9839		};
9840
9841		if (f) info.f = f;
9842		if (dp) info.dp = dp;
9843		if (trns) info.trns = trns;
9844		if (pal) info.pal = pal;
9845		if (smask) info.smask = smask;
9846		if (p) info.p = p; // predictor parameter for PNG compression
9847
9848		return info;
9849	};
9850
9851	jsPDFAPI.addImage = function (imageData, format, x, y, w, h, alias, compression, rotation) {
9852		'use strict';
9853
9854		if (typeof format !== 'string') {
9855			var tmp = h;
9856			h = w;
9857			w = y;
9858			y = x;
9859			x = format;
9860			format = tmp;
9861		}
9862
9863		if ((typeof imageData === 'undefined' ? 'undefined' : _typeof(imageData)) === 'object' && !isDOMElement(imageData) && "imageData" in imageData) {
9864			var options = imageData;
9865
9866			imageData = options.imageData;
9867			format = options.format || format;
9868			x = options.x || x || 0;
9869			y = options.y || y || 0;
9870			w = options.w || w;
9871			h = options.h || h;
9872			alias = options.alias || alias;
9873			compression = options.compression || compression;
9874			rotation = options.rotation || options.angle || rotation;
9875		}
9876
9877		if (isNaN(x) || isNaN(y)) {
9878			console.error('jsPDF.addImage: Invalid coordinates', arguments);
9879			throw new Error('Invalid coordinates passed to jsPDF.addImage');
9880		}
9881
9882		var images = getImages.call(this),
9883		    info;
9884
9885		if (!(info = checkImagesForAlias(imageData, images))) {
9886			var dataAsBinaryString;
9887
9888			if (isDOMElement(imageData)) imageData = createDataURIFromElement(imageData, format, rotation);
9889
9890			if (notDefined(alias)) alias = generateAliasFromData(imageData);
9891
9892			if (!(info = checkImagesForAlias(alias, images))) {
9893
9894				if (this.isString(imageData)) {
9895
9896					var base64Info = this.extractInfoFromBase64DataURI(imageData);
9897
9898					if (base64Info) {
9899
9900						format = base64Info[2];
9901						imageData = atob(base64Info[3]); //convert to binary string
9902					} else {
9903
9904						if (imageData.charCodeAt(0) === 0x89 && imageData.charCodeAt(1) === 0x50 && imageData.charCodeAt(2) === 0x4e && imageData.charCodeAt(3) === 0x47) format = 'png';
9905					}
9906				}
9907				format = (format || 'JPEG').toLowerCase();
9908
9909				if (doesNotSupportImageType(format)) throw new Error('addImage currently only supports formats ' + supported_image_types + ', not \'' + format + '\'');
9910
9911				if (processMethodNotEnabled(format)) throw new Error('please ensure that the plugin for \'' + format + '\' support is added');
9912
9913				/**
9914     * need to test if it's more efficient to convert all binary strings
9915     * to TypedArray - or should we just leave and process as string?
9916     */
9917				if (this.supportsArrayBuffer()) {
9918					// no need to convert if imageData is already uint8array
9919					if (!(imageData instanceof Uint8Array)) {
9920						dataAsBinaryString = imageData;
9921						imageData = this.binaryStringToUint8Array(imageData);
9922					}
9923				}
9924
9925				info = this['process' + format.toUpperCase()](imageData, getImageIndex(images), alias, checkCompressValue(compression), dataAsBinaryString);
9926
9927				if (!info) throw new Error('An unkwown error occurred whilst processing the image');
9928			}
9929		}
9930
9931		writeImageToPDF.call(this, x, y, w, h, info, info.i, images);
9932
9933		return this;
9934	};
9935
9936	/**
9937  * JPEG SUPPORT
9938  **/
9939
9940	//takes a string imgData containing the raw bytes of
9941	//a jpeg image and returns [width, height]
9942	//Algorithm from: http://www.64lines.com/jpeg-width-height
9943	var getJpegSize = function getJpegSize(imgData) {
9944		'use strict';
9945
9946		var width, height, numcomponents;
9947		// Verify we have a valid jpeg header 0xff,0xd8,0xff,0xe0,?,?,'J','F','I','F',0x00
9948		if (!imgData.charCodeAt(0) === 0xff || !imgData.charCodeAt(1) === 0xd8 || !imgData.charCodeAt(2) === 0xff || !imgData.charCodeAt(3) === 0xe0 || !imgData.charCodeAt(6) === 'J'.charCodeAt(0) || !imgData.charCodeAt(7) === 'F'.charCodeAt(0) || !imgData.charCodeAt(8) === 'I'.charCodeAt(0) || !imgData.charCodeAt(9) === 'F'.charCodeAt(0) || !imgData.charCodeAt(10) === 0x00) {
9949			throw new Error('getJpegSize requires a binary string jpeg file');
9950		}
9951		var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
9952		var i = 4,
9953		    len = imgData.length;
9954		while (i < len) {
9955			i += blockLength;
9956			if (imgData.charCodeAt(i) !== 0xff) {
9957				throw new Error('getJpegSize could not find the size of the image');
9958			}
9959			if (imgData.charCodeAt(i + 1) === 0xc0 || //(SOF) Huffman  - Baseline DCT
9960			imgData.charCodeAt(i + 1) === 0xc1 || //(SOF) Huffman  - Extended sequential DCT
9961			imgData.charCodeAt(i + 1) === 0xc2 || // Progressive DCT (SOF2)
9962			imgData.charCodeAt(i + 1) === 0xc3 || // Spatial (sequential) lossless (SOF3)
9963			imgData.charCodeAt(i + 1) === 0xc4 || // Differential sequential DCT (SOF5)
9964			imgData.charCodeAt(i + 1) === 0xc5 || // Differential progressive DCT (SOF6)
9965			imgData.charCodeAt(i + 1) === 0xc6 || // Differential spatial (SOF7)
9966			imgData.charCodeAt(i + 1) === 0xc7) {
9967				height = imgData.charCodeAt(i + 5) * 256 + imgData.charCodeAt(i + 6);
9968				width = imgData.charCodeAt(i + 7) * 256 + imgData.charCodeAt(i + 8);
9969				numcomponents = imgData.charCodeAt(i + 9);
9970				return [width, height, numcomponents];
9971			} else {
9972				i += 2;
9973				blockLength = imgData.charCodeAt(i) * 256 + imgData.charCodeAt(i + 1);
9974			}
9975		}
9976	},
9977	    getJpegSizeFromBytes = function getJpegSizeFromBytes(data) {
9978
9979		var hdr = data[0] << 8 | data[1];
9980
9981		if (hdr !== 0xFFD8) throw new Error('Supplied data is not a JPEG');
9982
9983		var len = data.length,
9984		    block = (data[4] << 8) + data[5],
9985		    pos = 4,
9986		    bytes,
9987		    width,
9988		    height,
9989		    numcomponents;
9990
9991		while (pos < len) {
9992			pos += block;
9993			bytes = readBytes(data, pos);
9994			block = (bytes[2] << 8) + bytes[3];
9995			if ((bytes[1] === 0xC0 || bytes[1] === 0xC2) && bytes[0] === 0xFF && block > 7) {
9996				bytes = readBytes(data, pos + 5);
9997				width = (bytes[2] << 8) + bytes[3];
9998				height = (bytes[0] << 8) + bytes[1];
9999				numcomponents = bytes[4];
10000				return { width: width, height: height, numcomponents: numcomponents };
10001			}
10002
10003			pos += 2;
10004		}
10005
10006		throw new Error('getJpegSizeFromBytes could not find the size of the image');
10007	},
10008	    readBytes = function readBytes(data, offset) {
10009		return data.subarray(offset, offset + 5);
10010	};
10011
10012	jsPDFAPI.processJPEG = function (data, index, alias, compression, dataAsBinaryString) {
10013		'use strict';
10014
10015		var colorSpace = this.color_spaces.DEVICE_RGB,
10016		    filter = this.decode.DCT_DECODE,
10017		    bpc = 8,
10018		    dims;
10019
10020		if (this.isString(data)) {
10021			dims = getJpegSize(data);
10022			return this.createImageInfo(data, dims[0], dims[1], dims[3] == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
10023		}
10024
10025		if (this.isArrayBuffer(data)) data = new Uint8Array(data);
10026
10027		if (this.isArrayBufferView(data)) {
10028
10029			dims = getJpegSizeFromBytes(data);
10030
10031			// if we already have a stored binary string rep use that
10032			data = dataAsBinaryString || this.arrayBufferToBinaryString(data);
10033
10034			return this.createImageInfo(data, dims.width, dims.height, dims.numcomponents == 1 ? this.color_spaces.DEVICE_GRAY : colorSpace, bpc, filter, index, alias);
10035		}
10036
10037		return null;
10038	};
10039
10040	jsPDFAPI.processJPG = function () /*data, index, alias, compression, dataAsBinaryString*/{
10041		return this.processJPEG.apply(this, arguments);
10042	};
10043})(jsPDF.API);
10044
10045/**
10046 * jsPDF Annotations PlugIn
10047 * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  [email protected]
10048 *
10049 * Licensed under the MIT License.
10050 * http://opensource.org/licenses/mit-license
10051 */
10052
10053/**
10054 * There are many types of annotations in a PDF document. Annotations are placed
10055 * on a page at a particular location. They are not 'attached' to an object.
10056 * <br />
10057 * This plugin current supports <br />
10058 * <li> Goto Page (set pageNumber and top in options)
10059 * <li> Goto Name (set name and top in options)
10060 * <li> Goto URL (set url in options)
10061 * <p>
10062 * 	The destination magnification factor can also be specified when goto is a page number or a named destination. (see documentation below)
10063 *  (set magFactor in options).  XYZ is the default.
10064 * </p>
10065 * <p>
10066 *  Links, Text, Popup, and FreeText are supported.
10067 * </p>
10068 * <p>
10069 * Options In PDF spec Not Implemented Yet
10070 * <li> link border
10071 * <li> named target
10072 * <li> page coordinates
10073 * <li> destination page scaling and layout
10074 * <li> actions other than URL and GotoPage
10075 * <li> background / hover actions
10076 * </p>
10077 */
10078
10079/*
10080    Destination Magnification Factors
10081    See PDF 1.3 Page 386 for meanings and options
10082
10083    [supported]
10084	XYZ (options; left top zoom)
10085	Fit (no options)
10086	FitH (options: top)
10087	FitV (options: left)
10088
10089	[not supported]
10090	FitR
10091	FitB
10092	FitBH
10093	FitBV
10094 */
10095
10096(function (jsPDFAPI) {
10097	'use strict';
10098
10099	var annotationPlugin = {
10100
10101		/**
10102   * An array of arrays, indexed by <em>pageNumber</em>.
10103   */
10104		annotations: [],
10105
10106		f2: function f2(number) {
10107			return number.toFixed(2);
10108		},
10109
10110		notEmpty: function notEmpty(obj) {
10111			if (typeof obj != 'undefined') {
10112				if (obj != '') {
10113					return true;
10114				}
10115			}
10116		}
10117	};
10118
10119	jsPDF.API.annotationPlugin = annotationPlugin;
10120
10121	jsPDF.API.events.push(['addPage', function (info) {
10122		this.annotationPlugin.annotations[info.pageNumber] = [];
10123	}]);
10124
10125	jsPDFAPI.events.push(['putPage', function (info) {
10126		//TODO store annotations in pageContext so reorder/remove will not affect them.
10127		var pageAnnos = this.annotationPlugin.annotations[info.pageNumber];
10128
10129		var found = false;
10130		for (var a = 0; a < pageAnnos.length && !found; a++) {
10131			var anno = pageAnnos[a];
10132			switch (anno.type) {
10133				case 'link':
10134					if (annotationPlugin.notEmpty(anno.options.url) || annotationPlugin.notEmpty(anno.options.pageNumber)) {
10135						found = true;
10136						break;
10137					}
10138				case 'reference':
10139				case 'text':
10140				case 'freetext':
10141					found = true;
10142					break;
10143			}
10144		}
10145		if (found == false) {
10146			return;
10147		}
10148
10149		this.internal.write("/Annots [");
10150		var f2 = this.annotationPlugin.f2;
10151		var k = this.internal.scaleFactor;
10152		var pageHeight = this.internal.pageSize.height;
10153		var pageInfo = this.internal.getPageInfo(info.pageNumber);
10154		for (var a = 0; a < pageAnnos.length; a++) {
10155			var anno = pageAnnos[a];
10156
10157			switch (anno.type) {
10158				case 'reference':
10159					// References to Widget Anotations (for AcroForm Fields)
10160					this.internal.write(' ' + anno.object.objId + ' 0 R ');
10161					break;
10162				case 'text':
10163					// Create a an object for both the text and the popup
10164					var objText = this.internal.newAdditionalObject();
10165					var objPopup = this.internal.newAdditionalObject();
10166
10167					var title = anno.title || 'Note';
10168					var rect = "/Rect [" + f2(anno.bounds.x * k) + " " + f2(pageHeight - (anno.bounds.y + anno.bounds.h) * k) + " " + f2((anno.bounds.x + anno.bounds.w) * k) + " " + f2((pageHeight - anno.bounds.y) * k) + "] ";
10169					line = '<</Type /Annot /Subtype /' + 'Text' + ' ' + rect + '/Contents (' + anno.contents + ')';
10170					line += ' /Popup ' + objPopup.objId + " 0 R";
10171					line += ' /P ' + pageInfo.objId + " 0 R";
10172					line += ' /T (' + title + ') >>';
10173					objText.content = line;
10174
10175					var parent = objText.objId + ' 0 R';
10176					var popoff = 30;
10177					var rect = "/Rect [" + f2((anno.bounds.x + popoff) * k) + " " + f2(pageHeight - (anno.bounds.y + anno.bounds.h) * k) + " " + f2((anno.bounds.x + anno.bounds.w + popoff) * k) + " " + f2((pageHeight - anno.bounds.y) * k) + "] ";
10178					//var rect2 = "/Rect [" + f2(anno.bounds.x * k) + " " + f2((pageHeight - anno.bounds.y) * k) + " " + f2(anno.bounds.x + anno.bounds.w * k) + " " + f2(pageHeight - (anno.bounds.y + anno.bounds.h) * k) + "] ";
10179					line = '<</Type /Annot /Subtype /' + 'Popup' + ' ' + rect + ' /Parent ' + parent;
10180					if (anno.open) {
10181						line += ' /Open true';
10182					}
10183					line += ' >>';
10184					objPopup.content = line;
10185
10186					this.internal.write(objText.objId, '0 R', objPopup.objId, '0 R');
10187
10188					break;
10189				case 'freetext':
10190					var rect = "/Rect [" + f2(anno.bounds.x * k) + " " + f2((pageHeight - anno.bounds.y) * k) + " " + f2(anno.bounds.x + anno.bounds.w * k) + " " + f2(pageHeight - (anno.bounds.y + anno.bounds.h) * k) + "] ";
10191					var color = anno.color || '#000000';
10192					line = '<</Type /Annot /Subtype /' + 'FreeText' + ' ' + rect + '/Contents (' + anno.contents + ')';
10193					line += ' /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#' + color + ')';
10194					line += ' /Border [0 0 0]';
10195					line += ' >>';
10196					this.internal.write(line);
10197					break;
10198				case 'link':
10199					if (anno.options.name) {
10200						var loc = this.annotations._nameMap[anno.options.name];
10201						anno.options.pageNumber = loc.page;
10202						anno.options.top = loc.y;
10203					} else {
10204						if (!anno.options.top) {
10205							anno.options.top = 0;
10206						}
10207					}
10208
10209					var rect = "/Rect [" + f2(anno.x * k) + " " + f2((pageHeight - anno.y) * k) + " " + f2((anno.x + anno.w) * k) + " " + f2((pageHeight - (anno.y + anno.h)) * k) + "] ";
10210
10211					var line = '';
10212					if (anno.options.url) {
10213						line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /A <</S /URI /URI (' + anno.options.url + ') >>';
10214					} else if (anno.options.pageNumber) {
10215						// first page is 0
10216						var info = this.internal.getPageInfo(anno.options.pageNumber);
10217						line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /Dest [' + info.objId + " 0 R";
10218						anno.options.magFactor = anno.options.magFactor || "XYZ";
10219						switch (anno.options.magFactor) {
10220							case 'Fit':
10221								line += ' /Fit]';
10222								break;
10223							case 'FitH':
10224								//anno.options.top = anno.options.top || f2(pageHeight * k);
10225								line += ' /FitH ' + anno.options.top + ']';
10226								break;
10227							case 'FitV':
10228								anno.options.left = anno.options.left || 0;
10229								line += ' /FitV ' + anno.options.left + ']';
10230								break;
10231							case 'XYZ':
10232							default:
10233								var top = f2((pageHeight - anno.options.top) * k); // || f2(pageHeight * k);
10234								anno.options.left = anno.options.left || 0;
10235								// 0 or null zoom will not change zoom factor
10236								if (typeof anno.options.zoom === 'undefined') {
10237									anno.options.zoom = 0;
10238								}
10239								line += ' /XYZ ' + anno.options.left + ' ' + top + ' ' + anno.options.zoom + ']';
10240								break;
10241						}
10242					} else {
10243						// TODO error - should not be here
10244					}
10245					if (line != '') {
10246						line += " >>";
10247						this.internal.write(line);
10248					}
10249					break;
10250			}
10251		}
10252		this.internal.write("]");
10253	}]);
10254
10255	jsPDFAPI.createAnnotation = function (options) {
10256		switch (options.type) {
10257			case 'link':
10258				this.link(options.bounds.x, options.bounds.y, options.bounds.w, options.bounds.h, options);
10259				break;
10260			case 'text':
10261			case 'freetext':
10262				this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(options);
10263				break;
10264		}
10265	};
10266
10267	/**
10268  * valid options
10269  * <li> pageNumber or url [required]
10270  * <p>If pageNumber is specified, top and zoom may also be specified</p>
10271  */
10272	jsPDFAPI.link = function (x, y, w, h, options) {
10273		'use strict';
10274
10275		this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({
10276			x: x,
10277			y: y,
10278			w: w,
10279			h: h,
10280			options: options,
10281			type: 'link'
10282		});
10283	};
10284
10285	/**
10286  * Currently only supports single line text.
10287  * Returns the width of the text/link
10288  */
10289	jsPDFAPI.textWithLink = function (text, x, y, options) {
10290		'use strict';
10291
10292		var width = this.getTextWidth(text);
10293		var height = this.internal.getLineHeight() / this.internal.scaleFactor;
10294		this.text(text, x, y);
10295		//TODO We really need the text baseline height to do this correctly.
10296		// Or ability to draw text on top, bottom, center, or baseline.
10297		y += height * .2;
10298		this.link(x, y - height, width, height, options);
10299		return width;
10300	};
10301
10302	//TODO move into external library
10303	jsPDFAPI.getTextWidth = function (text) {
10304		'use strict';
10305
10306		var fontSize = this.internal.getFontSize();
10307		var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
10308		return txtWidth;
10309	};
10310
10311	//TODO move into external library
10312	jsPDFAPI.getLineHeight = function () {
10313		return this.internal.getLineHeight();
10314	};
10315
10316	return this;
10317})(jsPDF.API);
10318
10319/**
10320 * jsPDF Autoprint Plugin
10321 *
10322 * Licensed under the MIT License.
10323 * http://opensource.org/licenses/mit-license
10324 */
10325
10326/**
10327* Makes the PDF automatically print. This works in Chrome, Firefox, Acrobat
10328* Reader.
10329*
10330* @returns {jsPDF}
10331* @name autoPrint
10332* @example
10333* var doc = new jsPDF()
10334* doc.text(10, 10, 'This is a test')
10335* doc.autoPrint()
10336* doc.save('autoprint.pdf')
10337*/
10338
10339(function (jsPDFAPI) {
10340  'use strict';
10341
10342  jsPDFAPI.autoPrint = function () {
10343    'use strict';
10344
10345    var refAutoPrintTag;
10346
10347    this.internal.events.subscribe('postPutResources', function () {
10348      refAutoPrintTag = this.internal.newObject();
10349      this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
10350    });
10351
10352    this.internal.events.subscribe("putCatalog", function () {
10353      this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
10354    });
10355    return this;
10356  };
10357})(jsPDF.API);
10358
10359/**
10360 * jsPDF Canvas PlugIn
10361 * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  [email protected]
10362 *
10363 * Licensed under the MIT License.
10364 * http://opensource.org/licenses/mit-license
10365 */
10366
10367/**
10368 * This plugin mimics the HTML5 Canvas
10369 * 
10370 * The goal is to provide a way for current canvas users to print directly to a PDF.
10371 */
10372
10373(function (jsPDFAPI) {
10374	'use strict';
10375
10376	jsPDFAPI.events.push(['initialized', function () {
10377		this.canvas.pdf = this;
10378	}]);
10379
10380	jsPDFAPI.canvas = {
10381		getContext: function getContext(name) {
10382			this.pdf.context2d._canvas = this;
10383			return this.pdf.context2d;
10384		},
10385		style: {}
10386	};
10387
10388	Object.defineProperty(jsPDFAPI.canvas, 'width', {
10389		get: function get() {
10390			return this._width;
10391		},
10392		set: function set(value) {
10393			this._width = value;
10394			this.getContext('2d').pageWrapX = value + 1;
10395		}
10396	});
10397
10398	Object.defineProperty(jsPDFAPI.canvas, 'height', {
10399		get: function get() {
10400			return this._height;
10401		},
10402		set: function set(value) {
10403			this._height = value;
10404			this.getContext('2d').pageWrapY = value + 1;
10405		}
10406	});
10407
10408	return this;
10409})(jsPDF.API);
10410
10411/** ====================================================================
10412 * jsPDF Cell plugin
10413 * Copyright (c) 2013 Youssef Beddad, [email protected]
10414 *               2013 Eduardo Menezes de Morais, [email protected]
10415 *               2013 Lee Driscoll, https://github.com/lsdriscoll
10416 *               2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
10417 *               2014 James Hall, [email protected]
10418 *               2014 Diego Casorran, https://github.com/diegocr
10419 *
10420 * 
10421 * ====================================================================
10422 */
10423
10424(function (jsPDFAPI) {
10425    'use strict';
10426    /*jslint browser:true */
10427    /*global document: false, jsPDF */
10428
10429    var fontName,
10430        fontSize,
10431        fontStyle,
10432        padding = 3,
10433        margin = 13,
10434        headerFunction,
10435        lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
10436        pages = 1,
10437        setLastCellPosition = function setLastCellPosition(x, y, w, h, ln) {
10438        lastCellPos = { 'x': x, 'y': y, 'w': w, 'h': h, 'ln': ln };
10439    },
10440        getLastCellPosition = function getLastCellPosition() {
10441        return lastCellPos;
10442    },
10443        NO_MARGINS = { left: 0, top: 0, bottom: 0 };
10444
10445    jsPDFAPI.setHeaderFunction = function (func) {
10446        headerFunction = func;
10447    };
10448
10449    jsPDFAPI.getTextDimensions = function (txt) {
10450        fontName = this.internal.getFont().fontName;
10451        fontSize = this.table_font_size || this.internal.getFontSize();
10452        fontStyle = this.internal.getFont().fontStyle;
10453        // 1 pixel = 0.264583 mm and 1 mm = 72/25.4 point
10454        var px2pt = 0.264583 * 72 / 25.4,
10455            dimensions,
10456            text;
10457
10458        text = document.createElement('font');
10459        text.id = "jsPDFCell";
10460
10461        try {
10462            text.style.fontStyle = fontStyle;
10463        } catch (e) {
10464            text.style.fontWeight = fontStyle;
10465        }
10466
10467        text.style.fontName = fontName;
10468        text.style.fontSize = fontSize + 'pt';
10469        try {
10470            text.textContent = txt;
10471        } catch (e) {
10472            text.innerText = txt;
10473        }
10474
10475        document.body.appendChild(text);
10476
10477        dimensions = { w: (text.offsetWidth + 1) * px2pt, h: (text.offsetHeight + 1) * px2pt };
10478
10479        document.body.removeChild(text);
10480
10481        return dimensions;
10482    };
10483
10484    jsPDFAPI.cellAddPage = function () {
10485        var margins = this.margins || NO_MARGINS;
10486
10487        this.addPage();
10488
10489        setLastCellPosition(margins.left, margins.top, undefined, undefined);
10490        //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
10491        pages += 1;
10492    };
10493
10494    jsPDFAPI.cellInitialize = function () {
10495        lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined };
10496        pages = 1;
10497    };
10498
10499    jsPDFAPI.cell = function (x, y, w, h, txt, ln, align) {
10500        var curCell = getLastCellPosition();
10501        var pgAdded = false;
10502
10503        // If this is not the first cell, we must change its position
10504        if (curCell.ln !== undefined) {
10505            if (curCell.ln === ln) {
10506                //Same line
10507                x = curCell.x + curCell.w;
10508                y = curCell.y;
10509            } else {
10510                //New line
10511                var margins = this.margins || NO_MARGINS;
10512                if (curCell.y + curCell.h + h + margin >= this.internal.pageSize.height - margins.bottom) {
10513                    this.cellAddPage();
10514                    pgAdded = true;
10515                    if (this.printHeaders && this.tableHeaderRow) {
10516                        this.printHeaderRow(ln, true);
10517                    }
10518                }
10519                //We ignore the passed y: the lines may have different heights
10520                y = getLastCellPosition().y + getLastCellPosition().h;
10521                if (pgAdded) y = margin + 10;
10522            }
10523        }
10524
10525        if (txt[0] !== undefined) {
10526            if (this.printingHeaderRow) {
10527                this.rect(x, y, w, h, 'FD');
10528            } else {
10529                this.rect(x, y, w, h);
10530            }
10531            if (align === 'right') {
10532                if (!(txt instanceof Array)) {
10533                    txt = [txt];
10534                }
10535                for (var i = 0; i < txt.length; i++) {
10536                    var currentLine = txt[i];
10537                    var textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize();
10538                    this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
10539                }
10540            } else {
10541                this.text(txt, x + padding, y + this.internal.getLineHeight());
10542            }
10543        }
10544        setLastCellPosition(x, y, w, h, ln);
10545        return this;
10546    };
10547
10548    /**
10549     * Return the maximum value from an array
10550     * @param array
10551     * @param comparisonFn
10552     * @returns {*}
10553     */
10554    jsPDFAPI.arrayMax = function (array, comparisonFn) {
10555        var max = array[0],
10556            i,
10557            ln,
10558            item;
10559
10560        for (i = 0, ln = array.length; i < ln; i += 1) {
10561            item = array[i];
10562
10563            if (comparisonFn) {
10564                if (comparisonFn(max, item) === -1) {
10565                    max = item;
10566                }
10567            } else {
10568                if (item > max) {
10569                    max = item;
10570                }
10571            }
10572        }
10573
10574        return max;
10575    };
10576
10577    /**
10578     * Create a table from a set of data.
10579     * @param {Integer} [x] : left-position for top-left corner of table
10580     * @param {Integer} [y] top-position for top-left corner of table
10581     * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
10582     * @param {String[]} [headers] Omit or null to auto-generate headers at a performance cost
10583      * @param {Object} [config.printHeaders] True to print column headers at the top of every page
10584     * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
10585     * @param {Object} [config.margins] margin values for left, top, bottom, and width
10586     * @param {Object} [config.fontSize] Integer fontSize to use (optional)
10587     */
10588
10589    jsPDFAPI.table = function (x, y, data, headers, config) {
10590        if (!data) {
10591            throw 'No data for PDF table';
10592        }
10593
10594        var headerNames = [],
10595            headerPrompts = [],
10596            header,
10597            i,
10598            ln,
10599            cln,
10600            columnMatrix = {},
10601            columnWidths = {},
10602            columnData,
10603            column,
10604            columnMinWidths = [],
10605            j,
10606            tableHeaderConfigs = [],
10607            model,
10608            jln,
10609            func,
10610
10611
10612        //set up defaults. If a value is provided in config, defaults will be overwritten:
10613        autoSize = false,
10614            printHeaders = true,
10615            fontSize = 12,
10616            margins = NO_MARGINS;
10617
10618        margins.width = this.internal.pageSize.width;
10619
10620        if (config) {
10621            //override config defaults if the user has specified non-default behavior:
10622            if (config.autoSize === true) {
10623                autoSize = true;
10624            }
10625            if (config.printHeaders === false) {
10626                printHeaders = false;
10627            }
10628            if (config.fontSize) {
10629                fontSize = config.fontSize;
10630            }
10631            if (config.css && typeof config.css['font-size'] !== "undefined") {
10632                fontSize = config.css['font-size'] * 16;
10633            }
10634            if (config.margins) {
10635                margins = config.margins;
10636            }
10637        }
10638
10639        /**
10640         * @property {Number} lnMod
10641         * Keep track of the current line number modifier used when creating cells
10642         */
10643        this.lnMod = 0;
10644        lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined }, pages = 1;
10645
10646        this.printHeaders = printHeaders;
10647        this.margins = margins;
10648        this.setFontSize(fontSize);
10649        this.table_font_size = fontSize;
10650
10651        // Set header values
10652        if (headers === undefined || headers === null) {
10653            // No headers defined so we derive from data
10654            headerNames = Object.keys(data[0]);
10655        } else if (headers[0] && typeof headers[0] !== 'string') {
10656            var px2pt = 0.264583 * 72 / 25.4;
10657
10658            // Split header configs into names and prompts
10659            for (i = 0, ln = headers.length; i < ln; i += 1) {
10660                header = headers[i];
10661                headerNames.push(header.name);
10662                headerPrompts.push(header.prompt);
10663                columnWidths[header.name] = header.width * px2pt;
10664            }
10665        } else {
10666            headerNames = headers;
10667        }
10668
10669        if (autoSize) {
10670            // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
10671            func = function func(rec) {
10672                return rec[header];
10673            };
10674
10675            for (i = 0, ln = headerNames.length; i < ln; i += 1) {
10676                header = headerNames[i];
10677
10678                columnMatrix[header] = data.map(func);
10679
10680                // get header width
10681                columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header).w);
10682                column = columnMatrix[header];
10683
10684                // get cell widths
10685                for (j = 0, cln = column.length; j < cln; j += 1) {
10686                    columnData = column[j];
10687                    columnMinWidths.push(this.getTextDimensions(columnData).w);
10688                }
10689
10690                // get final column width
10691                columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths);
10692
10693                //have to reset
10694                columnMinWidths = [];
10695            }
10696        }
10697
10698        // -- Construct the table
10699
10700        if (printHeaders) {
10701            var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames);
10702
10703            // Construct the header row
10704            for (i = 0, ln = headerNames.length; i < ln; i += 1) {
10705                header = headerNames[i];
10706                tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header)]);
10707            }
10708
10709            // Store the table header config
10710            this.setTableHeaderRow(tableHeaderConfigs);
10711
10712            // Print the header for the start of the table
10713            this.printHeaderRow(1, false);
10714        }
10715
10716        // Construct the data rows
10717        for (i = 0, ln = data.length; i < ln; i += 1) {
10718            var lineHeight;
10719            model = data[i];
10720            lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
10721
10722            for (j = 0, jln = headerNames.length; j < jln; j += 1) {
10723                header = headerNames[j];
10724                this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, header.align);
10725            }
10726        }
10727        this.lastCellPos = lastCellPos;
10728        this.table_x = x;
10729        this.table_y = y;
10730        return this;
10731    };
10732    /**
10733     * Calculate the height for containing the highest column
10734     * @param {String[]} headerNames is the header, used as keys to the data
10735     * @param {Integer[]} columnWidths is size of each column
10736     * @param {Object[]} model is the line of data we want to calculate the height of
10737     */
10738    jsPDFAPI.calculateLineHeight = function (headerNames, columnWidths, model) {
10739        var header,
10740            lineHeight = 0;
10741        for (var j = 0; j < headerNames.length; j++) {
10742            header = headerNames[j];
10743            model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
10744            var h = this.internal.getLineHeight() * model[header].length + padding;
10745            if (h > lineHeight) lineHeight = h;
10746        }
10747        return lineHeight;
10748    };
10749
10750    /**
10751     * Store the config for outputting a table header
10752     * @param {Object[]} config
10753     * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
10754     * except the ln parameter is excluded
10755     */
10756    jsPDFAPI.setTableHeaderRow = function (config) {
10757        this.tableHeaderRow = config;
10758    };
10759
10760    /**
10761     * Output the store header row
10762     * @param lineNumber The line number to output the header at
10763     */
10764    jsPDFAPI.printHeaderRow = function (lineNumber, new_page) {
10765        if (!this.tableHeaderRow) {
10766            throw 'Property tableHeaderRow does not exist.';
10767        }
10768
10769        var tableHeaderCell, tmpArray, i, ln;
10770
10771        this.printingHeaderRow = true;
10772        if (headerFunction !== undefined) {
10773            var position = headerFunction(this, pages);
10774            setLastCellPosition(position[0], position[1], position[2], position[3], -1);
10775        }
10776        this.setFontStyle('bold');
10777        var tempHeaderConf = [];
10778        for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
10779            this.setFillColor(200, 200, 200);
10780
10781            tableHeaderCell = this.tableHeaderRow[i];
10782            if (new_page) {
10783                this.margins.top = margin;
10784                tableHeaderCell[1] = this.margins && this.margins.top || 0;
10785                tempHeaderConf.push(tableHeaderCell);
10786            }
10787            tmpArray = [].concat(tableHeaderCell);
10788            this.cell.apply(this, tmpArray.concat(lineNumber));
10789        }
10790        if (tempHeaderConf.length > 0) {
10791            this.setTableHeaderRow(tempHeaderConf);
10792        }
10793        this.setFontStyle('normal');
10794        this.printingHeaderRow = false;
10795    };
10796})(jsPDF.API);
10797
10798/**
10799 * jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) [email protected]
10800 *
10801 * Licensed under the MIT License. http://opensource.org/licenses/mit-license
10802 */
10803
10804/**
10805 * This plugin mimics the HTML5 Canvas's context2d.
10806 *
10807 * The goal is to provide a way for current canvas implementations to print directly to a PDF.
10808 */
10809
10810/**
10811 * TODO implement stroke opacity (refactor from fill() method )
10812 * TODO transform angle and radii parameters
10813 */
10814
10815/**
10816 * require('jspdf.js'); require('lib/css_colors.js');
10817 */
10818
10819(function (jsPDFAPI) {
10820    'use strict';
10821
10822    jsPDFAPI.events.push(['initialized', function () {
10823        this.context2d.pdf = this;
10824        this.context2d.internal.pdf = this;
10825        this.context2d.ctx = new context();
10826        this.context2d.ctxStack = [];
10827        this.context2d.path = [];
10828    }]);
10829
10830    jsPDFAPI.context2d = {
10831        pageWrapXEnabled: false,
10832        pageWrapYEnabled: false,
10833        pageWrapX: 9999999,
10834        pageWrapY: 9999999,
10835        ctx: new context(),
10836        f2: function f2(number) {
10837            return number.toFixed(2);
10838        },
10839
10840        fillRect: function fillRect(x, y, w, h) {
10841            if (this._isFillTransparent()) {
10842                return;
10843            }
10844            x = this._wrapX(x);
10845            y = this._wrapY(y);
10846
10847            var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
10848            this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
10849        },
10850
10851        strokeRect: function strokeRect(x, y, w, h) {
10852            if (this._isStrokeTransparent()) {
10853                return;
10854            }
10855            x = this._wrapX(x);
10856            y = this._wrapY(y);
10857
10858            var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
10859            this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "s");
10860        },
10861
10862        /**
10863         * We cannot clear PDF commands that were already written to PDF, so we use white instead. <br />
10864         * As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.
10865         * This results in all calls to clearRect() to do nothing, and keep the canvas transparent.
10866         * This flag is stored in the save/restore context and is managed the same way as other drawing states.
10867         * @param x
10868         * @param y
10869         * @param w
10870         * @param h
10871         */
10872        clearRect: function clearRect(x, y, w, h) {
10873            if (this.ctx.ignoreClearRect) {
10874                return;
10875            }
10876
10877            x = this._wrapX(x);
10878            y = this._wrapY(y);
10879
10880            var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
10881            this.save();
10882            this.setFillStyle('#ffffff');
10883            //TODO This is hack to fill with white.
10884            this.pdf.rect(xRect.x, xRect.y, xRect.w, xRect.h, "f");
10885            this.restore();
10886        },
10887
10888        save: function save() {
10889            this.ctx._fontSize = this.pdf.internal.getFontSize();
10890            var ctx = new context();
10891            ctx.copy(this.ctx);
10892            this.ctxStack.push(this.ctx);
10893            this.ctx = ctx;
10894        },
10895
10896        restore: function restore() {
10897            this.ctx = this.ctxStack.pop();
10898            this.setFillStyle(this.ctx.fillStyle);
10899            this.setStrokeStyle(this.ctx.strokeStyle);
10900            this.setFont(this.ctx.font);
10901            this.pdf.setFontSize(this.ctx._fontSize);
10902            this.setLineCap(this.ctx.lineCap);
10903            this.setLineWidth(this.ctx.lineWidth);
10904            this.setLineJoin(this.ctx.lineJoin);
10905        },
10906
10907        rect: function rect(x, y, w, h) {
10908            this.moveTo(x, y);
10909            this.lineTo(x + w, y);
10910            this.lineTo(x + w, y + h);
10911            this.lineTo(x, y + h);
10912            this.lineTo(x, y); //TODO not needed
10913            this.closePath();
10914        },
10915
10916        beginPath: function beginPath() {
10917            this.path = [];
10918        },
10919
10920        closePath: function closePath() {
10921            this.path.push({
10922                type: 'close'
10923            });
10924        },
10925
10926        _getRGBA: function _getRGBA(style) {
10927            // get the decimal values of r, g, and b;
10928            var r, g, b, a;
10929            if (!style) {
10930                return { r: 0, g: 0, b: 0, a: 0, style: style };
10931            }
10932
10933            if (this.internal.rxTransparent.test(style)) {
10934                r = 0;
10935                g = 0;
10936                b = 0;
10937                a = 0;
10938            } else {
10939                var m = this.internal.rxRgb.exec(style);
10940                if (m != null) {
10941                    r = parseInt(m[1]);
10942                    g = parseInt(m[2]);
10943                    b = parseInt(m[3]);
10944                    a = 1;
10945                } else {
10946                    m = this.internal.rxRgba.exec(style);
10947                    if (m != null) {
10948                        r = parseInt(m[1]);
10949                        g = parseInt(m[2]);
10950                        b = parseInt(m[3]);
10951                        a = parseFloat(m[4]);
10952                    } else {
10953                        a = 1;
10954                        if (style.charAt(0) != '#') {
10955                            style = CssColors.colorNameToHex(style);
10956                            if (!style) {
10957                                style = '#000000';
10958                            }
10959                        } else {}
10960
10961                        if (style.length === 4) {
10962                            r = style.substring(1, 2);
10963                            r += r;
10964                            g = style.substring(2, 3);
10965                            g += g;
10966                            b = style.substring(3, 4);
10967                            b += b;
10968                        } else {
10969                            r = style.substring(1, 3);
10970                            g = style.substring(3, 5);
10971                            b = style.substring(5, 7);
10972                        }
10973                        r = parseInt(r, 16);
10974                        g = parseInt(g, 16);
10975                        b = parseInt(b, 16);
10976                    }
10977                }
10978            }
10979            return { r: r, g: g, b: b, a: a, style: style };
10980        },
10981
10982        setFillStyle: function setFillStyle(style) {
10983            var rgba = this._getRGBA(style);
10984
10985            this.ctx.fillStyle = style;
10986            this.ctx._isFillTransparent = rgba.a === 0;
10987            this.ctx._fillOpacity = rgba.a;
10988
10989            this.pdf.setFillColor(rgba.r, rgba.g, rgba.b, {
10990                a: rgba.a
10991            });
10992            this.pdf.setTextColor(rgba.r, rgba.g, rgba.b, {
10993                a: rgba.a
10994            });
10995        },
10996
10997        setStrokeStyle: function setStrokeStyle(style) {
10998            var rgba = this._getRGBA(style);
10999
11000            this.ctx.strokeStyle = rgba.style;
11001            this.ctx._isStrokeTransparent = rgba.a === 0;
11002            this.ctx._strokeOpacity = rgba.a;
11003
11004            //TODO jsPDF to handle rgba
11005            if (rgba.a === 0) {
11006                this.pdf.setDrawColor(255, 255, 255);
11007            } else if (rgba.a === 1) {
11008                this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
11009            } else {
11010                //this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b, {a: rgba.a});
11011                this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
11012            }
11013        },
11014
11015        fillText: function fillText(text, x, y, maxWidth) {
11016            if (this._isFillTransparent()) {
11017                return;
11018            }
11019            x = this._wrapX(x);
11020            y = this._wrapY(y);
11021
11022            var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
11023            x = xpt[0];
11024            y = xpt[1];
11025            var rads = this._matrix_rotation(this.ctx._transform);
11026            var degs = rads * 57.2958;
11027
11028            //TODO only push the clip if it has not been applied to the current PDF context
11029            if (this.ctx._clip_path.length > 0) {
11030                var lines;
11031                if (window.outIntercept) {
11032                    lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
11033                } else {
11034                    lines = this.internal.getCurrentPage();
11035                }
11036                lines.push("q");
11037                var origPath = this.path;
11038                this.path = this.ctx._clip_path;
11039                this.ctx._clip_path = [];
11040                this._fill(null, true);
11041                this.ctx._clip_path = this.path;
11042                this.path = origPath;
11043            }
11044
11045            // We only use X axis as scale hint 
11046            var scale = 1;
11047            try {
11048                scale = this._matrix_decompose(this._getTransform()).scale[0];
11049            } catch (e) {
11050                console.warn(e);
11051            }
11052
11053            // In some cases the transform was very small (5.715760606202283e-17).  Most likely a canvg rounding error.
11054            if (scale < .01) {
11055                this.pdf.text(text, x, this._getBaseline(y), null, degs);
11056            } else {
11057                var oldSize = this.pdf.internal.getFontSize();
11058                this.pdf.setFontSize(oldSize * scale);
11059                this.pdf.text(text, x, this._getBaseline(y), null, degs);
11060                this.pdf.setFontSize(oldSize);
11061            }
11062
11063            if (this.ctx._clip_path.length > 0) {
11064                lines.push('Q');
11065            }
11066        },
11067
11068        strokeText: function strokeText(text, x, y, maxWidth) {
11069            if (this._isStrokeTransparent()) {
11070                return;
11071            }
11072            x = this._wrapX(x);
11073            y = this._wrapY(y);
11074
11075            var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
11076            x = xpt[0];
11077            y = xpt[1];
11078            var rads = this._matrix_rotation(this.ctx._transform);
11079            var degs = rads * 57.2958;
11080
11081            //TODO only push the clip if it has not been applied to the current PDF context
11082            if (this.ctx._clip_path.length > 0) {
11083                var lines;
11084                if (window.outIntercept) {
11085                    lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
11086                } else {
11087                    lines = this.internal.getCurrentPage();
11088                }
11089                lines.push("q");
11090                var origPath = this.path;
11091                this.path = this.ctx._clip_path;
11092                this.ctx._clip_path = [];
11093                this._fill(null, true);
11094                this.ctx._clip_path = this.path;
11095                this.path = origPath;
11096            }
11097
11098            var scale = 1;
11099            // We only use the X axis as scale hint 
11100            try {
11101                scale = this._matrix_decompose(this._getTransform()).scale[0];
11102            } catch (e) {
11103                console.warn(e);
11104            }
11105
11106            if (scale === 1) {
11107                this.pdf.text(text, x, this._getBaseline(y), {
11108                    stroke: true
11109                }, degs);
11110            } else {
11111                var oldSize = this.pdf.internal.getFontSize();
11112                this.pdf.setFontSize(oldSize * scale);
11113                this.pdf.text(text, x, this._getBaseline(y), {
11114                    stroke: true
11115                }, degs);
11116                this.pdf.setFontSize(oldSize);
11117            }
11118
11119            if (this.ctx._clip_path.length > 0) {
11120                lines.push('Q');
11121            }
11122        },
11123
11124        setFont: function setFont(font) {
11125            this.ctx.font = font;
11126
11127            //var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+["']?(\w+)['"]?/;
11128            var rx = /\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+(.*)?/;
11129            m = rx.exec(font);
11130            if (m != null) {
11131                var fontStyle = m[1];
11132                var fontWeight = m[3];
11133                var fontSize = m[4];
11134                var fontSizeUnit = m[5];
11135                var fontFamily = m[6];
11136
11137                if ('px' === fontSizeUnit) {
11138                    fontSize = Math.floor(parseFloat(fontSize));
11139                    // fontSize = fontSize * 1.25;
11140                } else if ('em' === fontSizeUnit) {
11141                    fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
11142                } else {
11143                    fontSize = Math.floor(parseFloat(fontSize));
11144                }
11145
11146                this.pdf.setFontSize(fontSize);
11147
11148                if (fontWeight === 'bold' || fontWeight === '700') {
11149                    this.pdf.setFontStyle('bold');
11150                } else {
11151                    if (fontStyle === 'italic') {
11152                        this.pdf.setFontStyle('italic');
11153                    } else {
11154                        this.pdf.setFontStyle('normal');
11155                    }
11156                }
11157
11158                var name = fontFamily;
11159                var parts = name.toLowerCase().split(/\s*,\s*/);
11160                var jsPdfFontName;
11161
11162                if (parts.indexOf('arial') != -1) {
11163                    jsPdfFontName = 'Arial';
11164                } else if (parts.indexOf('verdana') != -1) {
11165                    jsPdfFontName = 'Verdana';
11166                } else if (parts.indexOf('helvetica') != -1) {
11167                    jsPdfFontName = 'Helvetica';
11168                } else if (parts.indexOf('sans-serif') != -1) {
11169                    jsPdfFontName = 'sans-serif';
11170                } else if (parts.indexOf('fixed') != -1) {
11171                    jsPdfFontName = 'Fixed';
11172                } else if (parts.indexOf('monospace') != -1) {
11173                    jsPdfFontName = 'Monospace';
11174                } else if (parts.indexOf('terminal') != -1) {
11175                    jsPdfFontName = 'Terminal';
11176                } else if (parts.indexOf('courier') != -1) {
11177                    jsPdfFontName = 'Courier';
11178                } else if (parts.indexOf('times') != -1) {
11179                    jsPdfFontName = 'Times';
11180                } else if (parts.indexOf('cursive') != -1) {
11181                    jsPdfFontName = 'Cursive';
11182                } else if (parts.indexOf('fantasy') != -1) {
11183                    jsPdfFontName = 'Fantasy';
11184                } else if (parts.indexOf('serif') != -1) {
11185                    jsPdfFontName = 'Serif';
11186                } else {
11187                    jsPdfFontName = 'Serif';
11188                }
11189
11190                //TODO check more cases
11191                var style;
11192                if ('bold' === fontWeight) {
11193                    style = 'bold';
11194                } else {
11195                    style = 'normal';
11196                }
11197
11198                this.pdf.setFont(jsPdfFontName, style);
11199            } else {
11200                var rx = /\s*(\d+)(pt|px|em)\s+([\w "]+)\s*([\w "]+)?/;
11201                var m = rx.exec(font);
11202                if (m != null) {
11203                    var size = m[1];
11204                    var name = m[3];
11205                    var style = m[4];
11206                    if (!style) {
11207                        style = 'normal';
11208                    }
11209                    if ('em' === fontSizeUnit) {
11210                        size = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
11211                    } else {
11212                        size = Math.floor(parseFloat(size));
11213                    }
11214                    this.pdf.setFontSize(size);
11215                    this.pdf.setFont(name, style);
11216                }
11217            }
11218        },
11219
11220        setTextBaseline: function setTextBaseline(baseline) {
11221            this.ctx.textBaseline = baseline;
11222        },
11223
11224        getTextBaseline: function getTextBaseline() {
11225            return this.ctx.textBaseline;
11226        },
11227
11228        //TODO implement textAlign
11229        setTextAlign: function setTextAlign(align) {
11230            this.ctx.textAlign = align;
11231        },
11232
11233        getTextAlign: function getTextAlign() {
11234            return this.ctx.textAlign;
11235        },
11236
11237        setLineWidth: function setLineWidth(width) {
11238            this.ctx.lineWidth = width;
11239            this.pdf.setLineWidth(width);
11240        },
11241
11242        setLineCap: function setLineCap(style) {
11243            this.ctx.lineCap = style;
11244            this.pdf.setLineCap(style);
11245        },
11246
11247        setLineJoin: function setLineJoin(style) {
11248            this.ctx.lineJoin = style;
11249            this.pdf.setLineJoin(style);
11250        },
11251
11252        moveTo: function moveTo(x, y) {
11253            x = this._wrapX(x);
11254            y = this._wrapY(y);
11255
11256            var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
11257            x = xpt[0];
11258            y = xpt[1];
11259
11260            var obj = {
11261                type: 'mt',
11262                x: x,
11263                y: y
11264            };
11265            this.path.push(obj);
11266        },
11267
11268        _wrapX: function _wrapX(x) {
11269            if (this.pageWrapXEnabled) {
11270                return x % this.pageWrapX;
11271            } else {
11272                return x;
11273            }
11274        },
11275
11276        _wrapY: function _wrapY(y) {
11277            if (this.pageWrapYEnabled) {
11278                this._gotoPage(this._page(y));
11279                return (y - this.lastBreak) % this.pageWrapY;
11280            } else {
11281                return y;
11282            }
11283        },
11284
11285        transform: function transform(a, b, c, d, e, f) {
11286            //TODO apply to current transformation instead of replacing
11287            this.ctx._transform = [a, b, c, d, e, f];
11288        },
11289
11290        setTransform: function setTransform(a, b, c, d, e, f) {
11291            this.ctx._transform = [a, b, c, d, e, f];
11292        },
11293
11294        _getTransform: function _getTransform() {
11295            return this.ctx._transform;
11296        },
11297
11298        lastBreak: 0,
11299        // Y Position of page breaks.
11300        pageBreaks: [],
11301        // returns: One-based Page Number
11302        // Should only be used if pageWrapYEnabled is true
11303        _page: function _page(y) {
11304            if (this.pageWrapYEnabled) {
11305                this.lastBreak = 0;
11306                var manualBreaks = 0;
11307                var autoBreaks = 0;
11308                for (var i = 0; i < this.pageBreaks.length; i++) {
11309                    if (y >= this.pageBreaks[i]) {
11310                        manualBreaks++;
11311                        if (this.lastBreak === 0) {
11312                            autoBreaks++;
11313                        }
11314                        var spaceBetweenLastBreak = this.pageBreaks[i] - this.lastBreak;
11315                        this.lastBreak = this.pageBreaks[i];
11316                        var pagesSinceLastBreak = Math.floor(spaceBetweenLastBreak / this.pageWrapY);
11317                        autoBreaks += pagesSinceLastBreak;
11318                    }
11319                }
11320                if (this.lastBreak === 0) {
11321                    var pagesSinceLastBreak = Math.floor(y / this.pageWrapY) + 1;
11322                    autoBreaks += pagesSinceLastBreak;
11323                }
11324                return autoBreaks + manualBreaks;
11325            } else {
11326                return this.pdf.internal.getCurrentPageInfo().pageNumber;
11327            }
11328        },
11329
11330        _gotoPage: function _gotoPage(pageOneBased) {
11331            // This is a stub to be overriden if needed
11332        },
11333
11334        lineTo: function lineTo(x, y) {
11335            x = this._wrapX(x);
11336            y = this._wrapY(y);
11337
11338            var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
11339            x = xpt[0];
11340            y = xpt[1];
11341
11342            var obj = {
11343                type: 'lt',
11344                x: x,
11345                y: y
11346            };
11347            this.path.push(obj);
11348        },
11349
11350        bezierCurveTo: function bezierCurveTo(x1, y1, x2, y2, x, y) {
11351            x1 = this._wrapX(x1);
11352            y1 = this._wrapY(y1);
11353            x2 = this._wrapX(x2);
11354            y2 = this._wrapY(y2);
11355            x = this._wrapX(x);
11356            y = this._wrapY(y);
11357
11358            var xpt;
11359            xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
11360            x = xpt[0];
11361            y = xpt[1];
11362            xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
11363            x1 = xpt[0];
11364            y1 = xpt[1];
11365            xpt = this._matrix_map_point(this.ctx._transform, [x2, y2]);
11366            x2 = xpt[0];
11367            y2 = xpt[1];
11368
11369            var obj = {
11370                type: 'bct',
11371                x1: x1,
11372                y1: y1,
11373                x2: x2,
11374                y2: y2,
11375                x: x,
11376                y: y
11377            };
11378            this.path.push(obj);
11379        },
11380
11381        quadraticCurveTo: function quadraticCurveTo(x1, y1, x, y) {
11382            x1 = this._wrapX(x1);
11383            y1 = this._wrapY(y1);
11384            x = this._wrapX(x);
11385            y = this._wrapY(y);
11386
11387            var xpt;
11388            xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
11389            x = xpt[0];
11390            y = xpt[1];
11391            xpt = this._matrix_map_point(this.ctx._transform, [x1, y1]);
11392            x1 = xpt[0];
11393            y1 = xpt[1];
11394
11395            var obj = {
11396                type: 'qct',
11397                x1: x1,
11398                y1: y1,
11399                x: x,
11400                y: y
11401            };
11402            this.path.push(obj);
11403        },
11404
11405        arc: function arc(x, y, radius, startAngle, endAngle, anticlockwise) {
11406            x = this._wrapX(x);
11407            y = this._wrapY(y);
11408
11409            if (!this._matrix_is_identity(this.ctx._transform)) {
11410                var xpt = this._matrix_map_point(this.ctx._transform, [x, y]);
11411                x = xpt[0];
11412                y = xpt[1];
11413
11414                var x_radPt0 = this._matrix_map_point(this.ctx._transform, [0, 0]);
11415                var x_radPt = this._matrix_map_point(this.ctx._transform, [0, radius]);
11416                radius = Math.sqrt(Math.pow(x_radPt[0] - x_radPt0[0], 2) + Math.pow(x_radPt[1] - x_radPt0[1], 2));
11417
11418                //TODO angles need to be transformed
11419            }
11420
11421            var obj = {
11422                type: 'arc',
11423                x: x,
11424                y: y,
11425                radius: radius,
11426                startAngle: startAngle,
11427                endAngle: endAngle,
11428                anticlockwise: anticlockwise
11429            };
11430            this.path.push(obj);
11431        },
11432
11433        drawImage: function drawImage(img, x, y, w, h, x2, y2, w2, h2) {
11434            if (x2 !== undefined) {
11435                x = x2;
11436                y = y2;
11437                w = w2;
11438                h = h2;
11439            }
11440            x = this._wrapX(x);
11441            y = this._wrapY(y);
11442
11443            var xRect = this._matrix_map_rect(this.ctx._transform, { x: x, y: y, w: w, h: h });
11444            var xRect2 = this._matrix_map_rect(this.ctx._transform, { x: x2, y: y2, w: w2, h: h2 });
11445
11446            // TODO implement source clipping and image scaling
11447            var format;
11448            var rx = /data:image\/(\w+).*/i;
11449            var m = rx.exec(img);
11450            if (m != null) {
11451                format = m[1];
11452            } else {
11453                // format = "jpeg";
11454                format = "png";
11455            }
11456
11457            this.pdf.addImage(img, format, xRect.x, xRect.y, xRect.w, xRect.h);
11458        },
11459
11460        /**
11461         * Multiply the first matrix by the second
11462         * @param m1
11463         * @param m2
11464         * @returns {*[]}
11465         * @private
11466         */
11467        _matrix_multiply: function _matrix_multiply(m2, m1) {
11468            var sx = m1[0];
11469            var shy = m1[1];
11470            var shx = m1[2];
11471            var sy = m1[3];
11472            var tx = m1[4];
11473            var ty = m1[5];
11474
11475            var t0 = sx * m2[0] + shy * m2[2];
11476            var t2 = shx * m2[0] + sy * m2[2];
11477            var t4 = tx * m2[0] + ty * m2[2] + m2[4];
11478            shy = sx * m2[1] + shy * m2[3];
11479            sy = shx * m2[1] + sy * m2[3];
11480            ty = tx * m2[1] + ty * m2[3] + m2[5];
11481            sx = t0;
11482            shx = t2;
11483            tx = t4;
11484
11485            return [sx, shy, shx, sy, tx, ty];
11486        },
11487
11488        _matrix_rotation: function _matrix_rotation(m) {
11489            return Math.atan2(m[2], m[0]);
11490        },
11491
11492        _matrix_decompose: function _matrix_decompose(matrix) {
11493
11494            var a = matrix[0];
11495            var b = matrix[1];
11496            var c = matrix[2];
11497            var d = matrix[3];
11498
11499            var scaleX = Math.sqrt(a * a + b * b);
11500            a /= scaleX;
11501            b /= scaleX;
11502
11503            var shear = a * c + b * d;
11504            c -= a * shear;
11505            d -= b * shear;
11506
11507            var scaleY = Math.sqrt(c * c + d * d);
11508            c /= scaleY;
11509            d /= scaleY;
11510            shear /= scaleY;
11511
11512            if (a * d < b * c) {
11513                a = -a;
11514                b = -b;
11515                shear = -shear;
11516                scaleX = -scaleX;
11517            }
11518
11519            return {
11520                scale: [scaleX, 0, 0, scaleY, 0, 0],
11521                translate: [1, 0, 0, 1, matrix[4], matrix[5]],
11522                rotate: [a, b, -b, a, 0, 0],
11523                skew: [1, 0, shear, 1, 0, 0]
11524            };
11525        },
11526
11527        _matrix_map_point: function _matrix_map_point(m1, pt) {
11528            var sx = m1[0];
11529            var shy = m1[1];
11530            var shx = m1[2];
11531            var sy = m1[3];
11532            var tx = m1[4];
11533            var ty = m1[5];
11534
11535            var px = pt[0];
11536            var py = pt[1];
11537
11538            var x = px * sx + py * shx + tx;
11539            var y = px * shy + py * sy + ty;
11540            return [x, y];
11541        },
11542
11543        _matrix_map_point_obj: function _matrix_map_point_obj(m1, pt) {
11544            var xpt = this._matrix_map_point(m1, [pt.x, pt.y]);
11545            return { x: xpt[0], y: xpt[1] };
11546        },
11547
11548        _matrix_map_rect: function _matrix_map_rect(m1, rect) {
11549            var p1 = this._matrix_map_point(m1, [rect.x, rect.y]);
11550            var p2 = this._matrix_map_point(m1, [rect.x + rect.w, rect.y + rect.h]);
11551            return { x: p1[0], y: p1[1], w: p2[0] - p1[0], h: p2[1] - p1[1] };
11552        },
11553
11554        _matrix_is_identity: function _matrix_is_identity(m1) {
11555            if (m1[0] != 1) {
11556                return false;
11557            }
11558            if (m1[1] != 0) {
11559                return false;
11560            }
11561            if (m1[2] != 0) {
11562                return false;
11563            }
11564            if (m1[3] != 1) {
11565                return false;
11566            }
11567            if (m1[4] != 0) {
11568                return false;
11569            }
11570            if (m1[5] != 0) {
11571                return false;
11572            }
11573            return true;
11574        },
11575
11576        rotate: function rotate(angle) {
11577            var matrix = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0.0, 0.0];
11578            this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
11579        },
11580
11581        scale: function scale(sx, sy) {
11582            var matrix = [sx, 0.0, 0.0, sy, 0.0, 0.0];
11583            this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
11584        },
11585
11586        translate: function translate(x, y) {
11587            var matrix = [1.0, 0.0, 0.0, 1.0, x, y];
11588            this.ctx._transform = this._matrix_multiply(this.ctx._transform, matrix);
11589        },
11590
11591        stroke: function stroke() {
11592            if (this.ctx._clip_path.length > 0) {
11593
11594                var lines;
11595                if (window.outIntercept) {
11596                    lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
11597                } else {
11598                    lines = this.internal.getCurrentPage();
11599                }
11600                lines.push("q");
11601
11602                var origPath = this.path;
11603                this.path = this.ctx._clip_path;
11604                this.ctx._clip_path = [];
11605                this._stroke(true);
11606
11607                this.ctx._clip_path = this.path;
11608                this.path = origPath;
11609                this._stroke(false);
11610
11611                lines.push("Q");
11612            } else {
11613                this._stroke(false);
11614            }
11615        },
11616
11617        _stroke: function _stroke(isClip) {
11618            if (!isClip && this._isStrokeTransparent()) {
11619                return;
11620            }
11621
11622            //TODO opacity
11623
11624            var moves = [];
11625            var xPath = this.path;
11626
11627            for (var i = 0; i < xPath.length; i++) {
11628                var pt = xPath[i];
11629                switch (pt.type) {
11630                    case 'mt':
11631                        moves.push({ start: pt, deltas: [], abs: [] });
11632                        break;
11633                    case 'lt':
11634                        var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
11635                        moves[moves.length - 1].deltas.push(delta);
11636                        moves[moves.length - 1].abs.push(pt);
11637                        break;
11638                    case 'bct':
11639                        var delta = [pt.x1 - xPath[i - 1].x, pt.y1 - xPath[i - 1].y, pt.x2 - xPath[i - 1].x, pt.y2 - xPath[i - 1].y, pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
11640                        moves[moves.length - 1].deltas.push(delta);
11641                        break;
11642                    case 'qct':
11643                        // convert to bezier
11644                        var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
11645                        var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
11646                        var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
11647                        var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
11648                        var x3 = pt.x;
11649                        var y3 = pt.y;
11650                        var delta = [x1 - xPath[i - 1].x, y1 - xPath[i - 1].y, x2 - xPath[i - 1].x, y2 - xPath[i - 1].y, x3 - xPath[i - 1].x, y3 - xPath[i - 1].y];
11651                        moves[moves.length - 1].deltas.push(delta);
11652                        break;
11653                    case 'arc':
11654                        //TODO this was hack to avoid out-of-bounds issue
11655                        // No move-to before drawing the arc
11656                        if (moves.length == 0) {
11657                            moves.push({ start: { x: 0, y: 0 }, deltas: [], abs: [] });
11658                        }
11659                        moves[moves.length - 1].arc = true;
11660                        moves[moves.length - 1].abs.push(pt);
11661                        break;
11662                    case 'close':
11663                        
11664                        break;
11665                }
11666            }
11667
11668            for (var i = 0; i < moves.length; i++) {
11669                var style;
11670                if (i == moves.length - 1) {
11671                    style = 's';
11672                } else {
11673                    style = null;
11674                }
11675                if (moves[i].arc) {
11676                    var arcs = moves[i].abs;
11677                    for (var ii = 0; ii < arcs.length; ii++) {
11678                        var arc = arcs[ii];
11679                        var start = arc.startAngle * 360 / (2 * Math.PI);
11680                        var end = arc.endAngle * 360 / (2 * Math.PI);
11681                        var x = arc.x;
11682                        var y = arc.y;
11683                        this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, style, isClip);
11684                    }
11685                } else {
11686                    var x = moves[i].start.x;
11687                    var y = moves[i].start.y;
11688                    if (!isClip) {
11689                        this.pdf.lines(moves[i].deltas, x, y, null, style);
11690                    } else {
11691                        this.pdf.lines(moves[i].deltas, x, y, null, null);
11692                        this.pdf.clip_fixed();
11693                    }
11694                }
11695            }
11696        },
11697
11698        _isFillTransparent: function _isFillTransparent() {
11699            return this.ctx._isFillTransparent || this.globalAlpha == 0;
11700        },
11701
11702        _isStrokeTransparent: function _isStrokeTransparent() {
11703            return this.ctx._isStrokeTransparent || this.globalAlpha == 0;
11704        },
11705
11706        fill: function fill(fillRule) {
11707            //evenodd or nonzero (default)
11708            if (this.ctx._clip_path.length > 0) {
11709
11710                var lines;
11711                if (window.outIntercept) {
11712                    lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
11713                } else {
11714                    lines = this.internal.getCurrentPage();
11715                }
11716                lines.push("q");
11717
11718                var origPath = this.path;
11719                this.path = this.ctx._clip_path;
11720                this.ctx._clip_path = [];
11721                this._fill(fillRule, true);
11722
11723                this.ctx._clip_path = this.path;
11724                this.path = origPath;
11725                this._fill(fillRule, false);
11726
11727                lines.push('Q');
11728            } else {
11729                this._fill(fillRule, false);
11730            }
11731        },
11732
11733        _fill: function _fill(fillRule, isClip) {
11734            if (this._isFillTransparent()) {
11735                return;
11736            }
11737            var v2Support = typeof this.pdf.internal.newObject2 === 'function';
11738
11739            var lines;
11740            if (window.outIntercept) {
11741                lines = window.outIntercept.type === 'group' ? window.outIntercept.stream : window.outIntercept;
11742            } else {
11743                lines = this.internal.getCurrentPage();
11744            }
11745
11746            // if (this.ctx._clip_path.length > 0) {
11747            //     lines.push('q');
11748            //     var oldPath = this.path;
11749            //     this.path = this.ctx._clip_path;
11750            //     this.ctx._clip_path = [];
11751            //     this._fill(fillRule, true);
11752            //     this.ctx._clip_path = this.path;
11753            //     this.path = oldPath;
11754            // }
11755
11756            var moves = [];
11757            var outInterceptOld = window.outIntercept;
11758
11759            if (v2Support) {
11760                // Blend and Mask
11761                switch (this.ctx.globalCompositeOperation) {
11762                    case 'normal':
11763                    case 'source-over':
11764                        break;
11765                    case 'destination-in':
11766                    case 'destination-out':
11767                        //TODO this need to be added to the current group or page
11768                        // define a mask stream
11769                        var obj = this.pdf.internal.newStreamObject();
11770
11771                        // define a mask state
11772                        var obj2 = this.pdf.internal.newObject2();
11773                        obj2.push('<</Type /ExtGState');
11774                        obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
11775                        obj2.push('>>');
11776
11777                        // add mask to page resources
11778                        var gsName = 'MASK' + obj2.objId;
11779                        this.pdf.internal.addGraphicsState(gsName, obj2.objId);
11780
11781                        var instruction = '/' + gsName + ' gs';
11782                        // add mask to page, group, or stream
11783                        lines.splice(0, 0, 'q');
11784                        lines.splice(1, 0, instruction);
11785                        lines.push('Q');
11786
11787                        window.outIntercept = obj;
11788                        break;
11789                    default:
11790                        var dictionaryEntry = '/' + this.pdf.internal.blendModeMap[this.ctx.globalCompositeOperation.toUpperCase()];
11791                        if (dictionaryEntry) {
11792                            this.pdf.internal.out(dictionaryEntry + ' gs');
11793                        }
11794                        break;
11795                }
11796            }
11797
11798            var alpha = this.ctx.globalAlpha;
11799            if (this.ctx._fillOpacity < 1) {
11800                // TODO combine this with global opacity
11801                alpha = this.ctx._fillOpacity;
11802            }
11803
11804            //TODO check for an opacity graphics state that was already created
11805            //TODO do not set opacity if current value is already active
11806            if (v2Support) {
11807                var objOpac = this.pdf.internal.newObject2();
11808                objOpac.push('<</Type /ExtGState');
11809                //objOpac.push(this.ctx.globalAlpha + " CA"); // Stroke
11810                //objOpac.push(this.ctx.globalAlpha + " ca"); // Not Stroke
11811                objOpac.push('/CA ' + alpha); // Stroke
11812                objOpac.push('/ca ' + alpha); // Not Stroke
11813                objOpac.push('>>');
11814                var gsName = 'GS_O_' + objOpac.objId;
11815                this.pdf.internal.addGraphicsState(gsName, objOpac.objId);
11816                this.pdf.internal.out('/' + gsName + ' gs');
11817            }
11818
11819            var xPath = this.path;
11820
11821            for (var i = 0; i < xPath.length; i++) {
11822                var pt = xPath[i];
11823                switch (pt.type) {
11824                    case 'mt':
11825                        moves.push({ start: pt, deltas: [], abs: [] });
11826                        break;
11827                    case 'lt':
11828                        var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
11829                        moves[moves.length - 1].deltas.push(delta);
11830                        moves[moves.length - 1].abs.push(pt);
11831                        break;
11832                    case 'bct':
11833                        var delta = [pt.x1 - xPath[i - 1].x, pt.y1 - xPath[i - 1].y, pt.x2 - xPath[i - 1].x, pt.y2 - xPath[i - 1].y, pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
11834                        moves[moves.length - 1].deltas.push(delta);
11835                        break;
11836                    case 'qct':
11837                        // convert to bezier
11838                        var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
11839                        var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
11840                        var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
11841                        var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
11842                        var x3 = pt.x;
11843                        var y3 = pt.y;
11844                        var delta = [x1 - xPath[i - 1].x, y1 - xPath[i - 1].y, x2 - xPath[i - 1].x, y2 - xPath[i - 1].y, x3 - xPath[i - 1].x, y3 - xPath[i - 1].y];
11845                        moves[moves.length - 1].deltas.push(delta);
11846                        break;
11847                    case 'arc':
11848                        //TODO this was hack to avoid out-of-bounds issue when drawing circle
11849                        // No move-to before drawing the arc
11850                        if (moves.length === 0) {
11851                            moves.push({ deltas: [], abs: [] });
11852                        }
11853                        moves[moves.length - 1].arc = true;
11854                        moves[moves.length - 1].abs.push(pt);
11855                        break;
11856                    case 'close':
11857                        moves.push({ close: true });
11858                        break;
11859                }
11860            }
11861
11862            for (var i = 0; i < moves.length; i++) {
11863                var style;
11864                if (i == moves.length - 1) {
11865                    style = 'f';
11866                    if (fillRule === 'evenodd') {
11867                        style += '*';
11868                    }
11869                } else {
11870                    style = null;
11871                }
11872
11873                if (moves[i].close) {
11874                    this.pdf.internal.out('h');
11875                    this.pdf.internal.out('f');
11876                } else if (moves[i].arc) {
11877                    if (moves[i].start) {
11878                        this.internal.move2(this, moves[i].start.x, moves[i].start.y);
11879                    }
11880                    var arcs = moves[i].abs;
11881                    for (var ii = 0; ii < arcs.length; ii++) {
11882                        var arc = arcs[ii];
11883                        //TODO lines deltas were getting in here
11884                        if (typeof arc.startAngle !== 'undefined') {
11885                            var start = arc.startAngle * 360 / (2 * Math.PI);
11886                            var end = arc.endAngle * 360 / (2 * Math.PI);
11887                            var x = arc.x;
11888                            var y = arc.y;
11889                            if (ii === 0) {
11890                                this.internal.move2(this, x, y);
11891                            }
11892                            this.internal.arc2(this, x, y, arc.radius, start, end, arc.anticlockwise, null, isClip);
11893                            if (ii === arcs.length - 1) {
11894                                // The original arc move did not occur because of the algorithm
11895                                if (moves[i].start) {
11896                                    var x = moves[i].start.x;
11897                                    var y = moves[i].start.y;
11898                                    this.internal.line2(c2d, x, y);
11899                                }
11900                            }
11901                        } else {
11902                            this.internal.line2(c2d, arc.x, arc.y);
11903                        }
11904                    }
11905                } else {
11906                    var x = moves[i].start.x;
11907                    var y = moves[i].start.y;
11908                    if (!isClip) {
11909                        this.pdf.lines(moves[i].deltas, x, y, null, style);
11910                    } else {
11911                        this.pdf.lines(moves[i].deltas, x, y, null, null);
11912                        this.pdf.clip_fixed();
11913                    }
11914                }
11915            }
11916
11917            window.outIntercept = outInterceptOld;
11918
11919            // if (this.ctx._clip_path.length > 0) {
11920            //     lines.push('Q');
11921            // }
11922        },
11923
11924        pushMask: function pushMask() {
11925            var v2Support = typeof this.pdf.internal.newObject2 === 'function';
11926
11927            if (!v2Support) {
11928                console.log('jsPDF v2 not enabled');
11929                return;
11930            }
11931
11932            // define a mask stream
11933            var obj = this.pdf.internal.newStreamObject();
11934
11935            // define a mask state
11936            var obj2 = this.pdf.internal.newObject2();
11937            obj2.push('<</Type /ExtGState');
11938            obj2.push('/SMask <</S /Alpha /G ' + obj.objId + ' 0 R>>'); // /S /Luminosity will need to define color space
11939            obj2.push('>>');
11940
11941            // add mask to page resources
11942            var gsName = 'MASK' + obj2.objId;
11943            this.pdf.internal.addGraphicsState(gsName, obj2.objId);
11944
11945            var instruction = '/' + gsName + ' gs';
11946            this.pdf.internal.out(instruction);
11947        },
11948
11949        clip: function clip() {
11950            //TODO do we reset the path, or just copy it?
11951            if (this.ctx._clip_path.length > 0) {
11952                for (var i = 0; i < this.path.length; i++) {
11953                    this.ctx._clip_path.push(this.path[i]);
11954                }
11955            } else {
11956                this.ctx._clip_path = this.path;
11957            }
11958            this.path = [];
11959        },
11960
11961        measureText: function measureText(text) {
11962            var pdf = this.pdf;
11963            return {
11964                getWidth: function getWidth() {
11965                    var fontSize = pdf.internal.getFontSize();
11966                    var txtWidth = pdf.getStringUnitWidth(text) * fontSize / pdf.internal.scaleFactor;
11967                    // Convert points to pixels
11968                    txtWidth *= 1.3333;
11969                    return txtWidth;
11970                },
11971
11972                get width() {
11973                    return this.getWidth(text);
11974                }
11975            };
11976        },
11977        _getBaseline: function _getBaseline(y) {
11978            var height = parseInt(this.pdf.internal.getFontSize());
11979            // TODO Get descent from font descriptor
11980            var descent = height * .25;
11981            switch (this.ctx.textBaseline) {
11982                case 'bottom':
11983                    return y - descent;
11984                case 'top':
11985                    return y + height;
11986                case 'hanging':
11987                    return y + height - descent;
11988                case 'middle':
11989                    return y + height / 2 - descent;
11990                case 'ideographic':
11991                    // TODO not implemented
11992                    return y;
11993                case 'alphabetic':
11994                default:
11995                    return y;
11996            }
11997        }
11998    };
11999
12000    var c2d = jsPDFAPI.context2d;
12001
12002    // accessor methods
12003    Object.defineProperty(c2d, 'fillStyle', {
12004        set: function set(value) {
12005            this.setFillStyle(value);
12006        },
12007        get: function get() {
12008            return this.ctx.fillStyle;
12009        }
12010    });
12011    Object.defineProperty(c2d, 'strokeStyle', {
12012        set: function set(value) {
12013            this.setStrokeStyle(value);
12014        },
12015        get: function get() {
12016            return this.ctx.strokeStyle;
12017        }
12018    });
12019    Object.defineProperty(c2d, 'lineWidth', {
12020        set: function set(value) {
12021            this.setLineWidth(value);
12022        },
12023        get: function get() {
12024            return this.ctx.lineWidth;
12025        }
12026    });
12027    Object.defineProperty(c2d, 'lineCap', {
12028        set: function set(val) {
12029            this.setLineCap(val);
12030        },
12031        get: function get() {
12032            return this.ctx.lineCap;
12033        }
12034    });
12035    Object.defineProperty(c2d, 'lineJoin', {
12036        set: function set(val) {
12037            this.setLineJoin(val);
12038        },
12039        get: function get() {
12040            return this.ctx.lineJoin;
12041        }
12042    });
12043    Object.defineProperty(c2d, 'miterLimit', {
12044        set: function set(val) {
12045            this.ctx.miterLimit = val;
12046        },
12047        get: function get() {
12048            return this.ctx.miterLimit;
12049        }
12050    });
12051    Object.defineProperty(c2d, 'textBaseline', {
12052        set: function set(value) {
12053            this.setTextBaseline(value);
12054        },
12055        get: function get() {
12056            return this.getTextBaseline();
12057        }
12058    });
12059    Object.defineProperty(c2d, 'textAlign', {
12060        set: function set(value) {
12061            this.setTextAlign(value);
12062        },
12063        get: function get() {
12064            return this.getTextAlign();
12065        }
12066    });
12067    Object.defineProperty(c2d, 'font', {
12068        set: function set(value) {
12069            this.setFont(value);
12070        },
12071        get: function get() {
12072            return this.ctx.font;
12073        }
12074    });
12075    Object.defineProperty(c2d, 'globalCompositeOperation', {
12076        set: function set(value) {
12077            this.ctx.globalCompositeOperation = value;
12078        },
12079        get: function get() {
12080            return this.ctx.globalCompositeOperation;
12081        }
12082    });
12083    Object.defineProperty(c2d, 'globalAlpha', {
12084        set: function set(value) {
12085            this.ctx.globalAlpha = value;
12086        },
12087        get: function get() {
12088            return this.ctx.globalAlpha;
12089        }
12090    });
12091    // Not HTML API
12092    Object.defineProperty(c2d, 'ignoreClearRect', {
12093        set: function set(value) {
12094            this.ctx.ignoreClearRect = value;
12095        },
12096        get: function get() {
12097            return this.ctx.ignoreClearRect;
12098        }
12099    });
12100    // End Not HTML API
12101
12102    c2d.internal = {};
12103
12104    c2d.internal.rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
12105    c2d.internal.rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/;
12106    c2d.internal.rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;
12107
12108    // http://hansmuller-flex.blogspot.com/2011/10/more-about-approximating-circular-arcs.html
12109    c2d.internal.arc = function (c2d, xc, yc, r, a1, a2, anticlockwise, style) {
12110        var includeMove = true;
12111
12112        var k = this.pdf.internal.scaleFactor;
12113        var pageHeight = this.pdf.internal.pageSize.height;
12114        var f2 = this.pdf.internal.f2;
12115
12116        var a1r = a1 * (Math.PI / 180);
12117        var a2r = a2 * (Math.PI / 180);
12118        var curves = this.createArc(r, a1r, a2r, anticlockwise);
12119        for (var i = 0; i < curves.length; i++) {
12120            var curve = curves[i];
12121            if (includeMove && i === 0) {
12122                this.pdf.internal.out([f2((curve.x1 + xc) * k), f2((pageHeight - (curve.y1 + yc)) * k), 'm', f2((curve.x2 + xc) * k), f2((pageHeight - (curve.y2 + yc)) * k), f2((curve.x3 + xc) * k), f2((pageHeight - (curve.y3 + yc)) * k), f2((curve.x4 + xc) * k), f2((pageHeight - (curve.y4 + yc)) * k), 'c'].join(' '));
12123            } else {
12124                this.pdf.internal.out([f2((curve.x2 + xc) * k), f2((pageHeight - (curve.y2 + yc)) * k), f2((curve.x3 + xc) * k), f2((pageHeight - (curve.y3 + yc)) * k), f2((curve.x4 + xc) * k), f2((pageHeight - (curve.y4 + yc)) * k), 'c'].join(' '));
12125            }
12126
12127            //c2d._lastPoint = {x: curve.x1 + xc, y: curve.y1 + yc};
12128            c2d._lastPoint = { x: xc, y: yc };
12129            // f2((curve.x1 + xc) * k), f2((pageHeight - (curve.y1 + yc)) * k), 'm', f2((curve.x2 + xc) * k), f2((pageHeight - (curve.y2 + yc)) * k), f2((curve.x3 + xc) * k), f2((pageHeight - (curve.y3 + yc)) * k), f2((curve.x4 + xc) * k), f2((pageHeight - (curve.y4 + yc)) * k), 'c'
12130        }
12131
12132        if (style !== null) {
12133            this.pdf.internal.out(this.pdf.internal.getStyle(style));
12134        }
12135    };
12136
12137    /**
12138     *
12139     * @param x Edge point X
12140     * @param y Edge point Y
12141     * @param r Radius
12142     * @param a1 start angle
12143     * @param a2 end angle
12144     * @param anticlockwise
12145     * @param style
12146     * @param isClip
12147     */
12148    c2d.internal.arc2 = function (c2d, x, y, r, a1, a2, anticlockwise, style, isClip) {
12149        // we need to convert from cartesian to polar here methinks.
12150        var centerX = x; // + r;
12151        var centerY = y;
12152
12153        if (!isClip) {
12154            this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, style);
12155        } else {
12156            this.arc(c2d, centerX, centerY, r, a1, a2, anticlockwise, null);
12157            this.pdf.clip_fixed();
12158        }
12159    };
12160
12161    c2d.internal.move2 = function (c2d, x, y) {
12162        var k = this.pdf.internal.scaleFactor;
12163        var pageHeight = this.pdf.internal.pageSize.height;
12164        var f2 = this.pdf.internal.f2;
12165
12166        this.pdf.internal.out([f2(x * k), f2((pageHeight - y) * k), 'm'].join(' '));
12167        c2d._lastPoint = { x: x, y: y };
12168    };
12169
12170    c2d.internal.line2 = function (c2d, dx, dy) {
12171        var k = this.pdf.internal.scaleFactor;
12172        var pageHeight = this.pdf.internal.pageSize.height;
12173        var f2 = this.pdf.internal.f2;
12174
12175        //var pt = {x: c2d._lastPoint.x + dx, y: c2d._lastPoint.y + dy};
12176        var pt = { x: dx, y: dy };
12177
12178        this.pdf.internal.out([f2(pt.x * k), f2((pageHeight - pt.y) * k), 'l'].join(' '));
12179        //this.pdf.internal.out('f');
12180        c2d._lastPoint = pt;
12181    };
12182
12183    /**
12184     * Return a array of objects that represent bezier curves which approximate the circular arc centered at the origin, from startAngle to endAngle (radians) with the specified radius.
12185     *
12186     * Each bezier curve is an object with four points, where x1,y1 and x4,y4 are the arc's end points and x2,y2 and x3,y3 are the cubic bezier's control points.
12187     */
12188
12189    c2d.internal.createArc = function (radius, startAngle, endAngle, anticlockwise) {
12190        var EPSILON = 0.00001; // Roughly 1/1000th of a degree, see below
12191        var twoPI = Math.PI * 2;
12192        var piOverTwo = Math.PI / 2.0;
12193
12194        // normalize startAngle, endAngle to [0, 2PI]
12195        var startAngleN = startAngle;
12196        if (startAngleN < twoPI || startAngleN > twoPI) {
12197            startAngleN = startAngleN % twoPI;
12198        }
12199        if (startAngleN < 0) {
12200            startAngleN = twoPI + startAngleN;
12201        }
12202
12203        while (startAngle > endAngle) {
12204            startAngle = startAngle - twoPI;
12205        }
12206        var totalAngle = Math.abs(endAngle - startAngle);
12207        if (totalAngle < twoPI) {
12208            if (anticlockwise) {
12209                totalAngle = twoPI - totalAngle;
12210            }
12211        }
12212
12213        // Compute the sequence of arc curves, up to PI/2 at a time.
12214        var curves = [];
12215        var sgn = anticlockwise ? -1 : +1;
12216
12217        var a1 = startAngleN;
12218        for (; totalAngle > EPSILON;) {
12219            var remain = sgn * Math.min(totalAngle, piOverTwo);
12220            var a2 = a1 + remain;
12221            curves.push(this.createSmallArc(radius, a1, a2));
12222            totalAngle -= Math.abs(a2 - a1);
12223            a1 = a2;
12224        }
12225
12226        return curves;
12227    };
12228
12229    c2d.internal.getCurrentPage = function () {
12230        return this.pdf.internal.pages[this.pdf.internal.getCurrentPageInfo().pageNumber];
12231    };
12232
12233    /**
12234     * Cubic bezier approximation of a circular arc centered at the origin, from (radians) a1 to a2, where a2-a1 < pi/2. The arc's radius is r.
12235     *
12236     * Returns an object with four points, where x1,y1 and x4,y4 are the arc's end points and x2,y2 and x3,y3 are the cubic bezier's control points.
12237     *
12238     * This algorithm is based on the approach described in: A. Riškus, "Approximation of a Cubic Bezier Curve by Circular Arcs and Vice Versa," Information Technology and Control, 35(4), 2006 pp. 371-378.
12239     */
12240
12241    c2d.internal.createSmallArc = function (r, a1, a2) {
12242        // Compute all four points for an arc that subtends the same total angle
12243        // but is centered on the X-axis
12244
12245        var a = (a2 - a1) / 2.0;
12246
12247        var x4 = r * Math.cos(a);
12248        var y4 = r * Math.sin(a);
12249        var x1 = x4;
12250        var y1 = -y4;
12251
12252        var q1 = x1 * x1 + y1 * y1;
12253        var q2 = q1 + x1 * x4 + y1 * y4;
12254        var k2 = 4 / 3 * (Math.sqrt(2 * q1 * q2) - q2) / (x1 * y4 - y1 * x4);
12255
12256        var x2 = x1 - k2 * y1;
12257        var y2 = y1 + k2 * x1;
12258        var x3 = x2;
12259        var y3 = -y2;
12260
12261        // Find the arc points' actual locations by computing x1,y1 and x4,y4
12262        // and rotating the control points by a + a1
12263
12264        var ar = a + a1;
12265        var cos_ar = Math.cos(ar);
12266        var sin_ar = Math.sin(ar);
12267
12268        return {
12269            x1: r * Math.cos(a1),
12270            y1: r * Math.sin(a1),
12271            x2: x2 * cos_ar - y2 * sin_ar,
12272            y2: x2 * sin_ar + y2 * cos_ar,
12273            x3: x3 * cos_ar - y3 * sin_ar,
12274            y3: x3 * sin_ar + y3 * cos_ar,
12275            x4: r * Math.cos(a2),
12276            y4: r * Math.sin(a2)
12277        };
12278    };
12279
12280    function context() {
12281        this._isStrokeTransparent = false;
12282        this._strokeOpacity = 1;
12283        this.strokeStyle = '#000000';
12284        this.fillStyle = '#000000';
12285        this._isFillTransparent = false;
12286        this._fillOpacity = 1;
12287        this.font = "12pt times";
12288        this.textBaseline = 'alphabetic'; // top,bottom,middle,ideographic,alphabetic,hanging
12289        this.textAlign = 'start';
12290        this.lineWidth = 1;
12291        this.lineJoin = 'miter'; // round, bevel, miter
12292        this.lineCap = 'butt'; // butt, round, square
12293        this._transform = [1, 0, 0, 1, 0, 0]; // sx, shy, shx, sy, tx, ty
12294        this.globalCompositeOperation = 'normal';
12295        this.globalAlpha = 1.0;
12296        this._clip_path = [];
12297        // TODO miter limit //default 10
12298
12299        // Not HTML API
12300        this.ignoreClearRect = false;
12301
12302        this.copy = function (ctx) {
12303            this._isStrokeTransparent = ctx._isStrokeTransparent;
12304            this._strokeOpacity = ctx._strokeOpacity;
12305            this.strokeStyle = ctx.strokeStyle;
12306            this._isFillTransparent = ctx._isFillTransparent;
12307            this._fillOpacity = ctx._fillOpacity;
12308            this.fillStyle = ctx.fillStyle;
12309            this.font = ctx.font;
12310            this.lineWidth = ctx.lineWidth;
12311            this.lineJoin = ctx.lineJoin;
12312            this.lineCap = ctx.lineCap;
12313            this.textBaseline = ctx.textBaseline;
12314            this.textAlign = ctx.textAlign;
12315            this._fontSize = ctx._fontSize;
12316            this._transform = ctx._transform.slice(0);
12317            this.globalCompositeOperation = ctx.globalCompositeOperation;
12318            this.globalAlpha = ctx.globalAlpha;
12319            this._clip_path = ctx._clip_path.slice(0); //TODO deep copy?
12320
12321            // Not HTML API
12322            this.ignoreClearRect = ctx.ignoreClearRect;
12323        };
12324    }
12325
12326    return this;
12327})(jsPDF.API);
12328
12329/** @preserve
12330 * jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser
12331 * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
12332 *               2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
12333 *               2014 Diego Casorran, https://github.com/diegocr
12334 *               2014 Daniel Husar, https://github.com/danielhusar
12335 *               2014 Wolfgang Gassler, https://github.com/woolfg
12336 *               2014 Steven Spungin, https://github.com/flamenco
12337 *
12338 * 
12339 * ====================================================================
12340 */
12341
12342(function (jsPDFAPI) {
12343	var clone, _DrillForContent, FontNameDB, FontStyleMap, TextAlignMap, FontWeightMap, FloatMap, ClearMap, GetCSS, PurgeWhiteSpace, Renderer, ResolveFont, ResolveUnitedNumber, UnitedNumberMap, elementHandledElsewhere, images, loadImgs, checkForFooter, process, tableToJson;
12344	clone = function () {
12345		return function (obj) {
12346			Clone.prototype = obj;
12347			return new Clone();
12348		};
12349		function Clone() {}
12350	}();
12351	PurgeWhiteSpace = function PurgeWhiteSpace(array) {
12352		var fragment, i, l, lTrimmed, r, rTrimmed, trailingSpace;
12353		i = 0;
12354		l = array.length;
12355		fragment = void 0;
12356		lTrimmed = false;
12357		rTrimmed = false;
12358		while (!lTrimmed && i !== l) {
12359			fragment = array[i] = array[i].trimLeft();
12360			if (fragment) {
12361				lTrimmed = true;
12362			}
12363			i++;
12364		}
12365		i = l - 1;
12366		while (l && !rTrimmed && i !== -1) {
12367			fragment = array[i] = array[i].trimRight();
12368			if (fragment) {
12369				rTrimmed = true;
12370			}
12371			i--;
12372		}
12373		r = /\s+$/g;
12374		trailingSpace = true;
12375		i = 0;
12376		while (i !== l) {
12377			// Leave the line breaks intact
12378			if (array[i] != "\u2028") {
12379				fragment = array[i].replace(/\s+/g, " ");
12380				if (trailingSpace) {
12381					fragment = fragment.trimLeft();
12382				}
12383				if (fragment) {
12384					trailingSpace = r.test(fragment);
12385				}
12386				array[i] = fragment;
12387			}
12388			i++;
12389		}
12390		return array;
12391	};
12392	Renderer = function Renderer(pdf, x, y, settings) {
12393		this.pdf = pdf;
12394		this.x = x;
12395		this.y = y;
12396		this.settings = settings;
12397		//list of functions which are called after each element-rendering process
12398		this.watchFunctions = [];
12399		this.init();
12400		return this;
12401	};
12402	ResolveFont = function ResolveFont(css_font_family_string) {
12403		var name, part, parts;
12404		name = void 0;
12405		parts = css_font_family_string.split(",");
12406		part = parts.shift();
12407		while (!name && part) {
12408			name = FontNameDB[part.trim().toLowerCase()];
12409			part = parts.shift();
12410		}
12411		return name;
12412	};
12413	ResolveUnitedNumber = function ResolveUnitedNumber(css_line_height_string) {
12414
12415		//IE8 issues
12416		css_line_height_string = css_line_height_string === "auto" ? "0px" : css_line_height_string;
12417		if (css_line_height_string.indexOf("em") > -1 && !isNaN(Number(css_line_height_string.replace("em", "")))) {
12418			css_line_height_string = Number(css_line_height_string.replace("em", "")) * 18.719 + "px";
12419		}
12420		if (css_line_height_string.indexOf("pt") > -1 && !isNaN(Number(css_line_height_string.replace("pt", "")))) {
12421			css_line_height_string = Number(css_line_height_string.replace("pt", "")) * 1.333 + "px";
12422		}
12423
12424		var normal, undef, value;
12425		undef = void 0;
12426		normal = 16.00;
12427		value = UnitedNumberMap[css_line_height_string];
12428		if (value) {
12429			return value;
12430		}
12431		value = {
12432			"xx-small": 9,
12433			"x-small": 11,
12434			small: 13,
12435			medium: 16,
12436			large: 19,
12437			"x-large": 23,
12438			"xx-large": 28,
12439			auto: 0
12440		}[{ css_line_height_string: css_line_height_string }];
12441
12442		if (value !== undef) {
12443			return UnitedNumberMap[css_line_height_string] = value / normal;
12444		}
12445		if (value = parseFloat(css_line_height_string)) {
12446			return UnitedNumberMap[css_line_height_string] = value / normal;
12447		}
12448		value = css_line_height_string.match(/([\d\.]+)(px)/);
12449		if (value.length === 3) {
12450			return UnitedNumberMap[css_line_height_string] = parseFloat(value[1]) / normal;
12451		}
12452		return UnitedNumberMap[css_line_height_string] = 1;
12453	};
12454	GetCSS = function GetCSS(element) {
12455		var css, tmp, computedCSSElement;
12456		computedCSSElement = function (el) {
12457			var compCSS;
12458			compCSS = function (el) {
12459				if (document.defaultView && document.defaultView.getComputedStyle) {
12460					return document.defaultView.getComputedStyle(el, null);
12461				} else if (el.currentStyle) {
12462					return el.currentStyle;
12463				} else {
12464					return el.style;
12465				}
12466			}(el);
12467			return function (prop) {
12468				prop = prop.replace(/-\D/g, function (match) {
12469					return match.charAt(1).toUpperCase();
12470				});
12471				return compCSS[prop];
12472			};
12473		}(element);
12474		css = {};
12475		tmp = void 0;
12476		css["font-family"] = ResolveFont(computedCSSElement("font-family")) || "times";
12477		css["font-style"] = FontStyleMap[computedCSSElement("font-style")] || "normal";
12478		css["text-align"] = TextAlignMap[computedCSSElement("text-align")] || "left";
12479		tmp = FontWeightMap[computedCSSElement("font-weight")] || "normal";
12480		if (tmp === "bold") {
12481			if (css["font-style"] === "normal") {
12482				css["font-style"] = tmp;
12483			} else {
12484				css["font-style"] = tmp + css["font-style"];
12485			}
12486		}
12487		css["font-size"] = ResolveUnitedNumber(computedCSSElement("font-size")) || 1;
12488		css["line-height"] = ResolveUnitedNumber(computedCSSElement("line-height")) || 1;
12489		css["display"] = computedCSSElement("display") === "inline" ? "inline" : "block";
12490
12491		tmp = css["display"] === "block";
12492		css["margin-top"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-top")) || 0;
12493		css["margin-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-bottom")) || 0;
12494		css["padding-top"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-top")) || 0;
12495		css["padding-bottom"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-bottom")) || 0;
12496		css["margin-left"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-left")) || 0;
12497		css["margin-right"] = tmp && ResolveUnitedNumber(computedCSSElement("margin-right")) || 0;
12498		css["padding-left"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-left")) || 0;
12499		css["padding-right"] = tmp && ResolveUnitedNumber(computedCSSElement("padding-right")) || 0;
12500
12501		css["page-break-before"] = computedCSSElement("page-break-before") || "auto";
12502
12503		//float and clearing of floats
12504		css["float"] = FloatMap[computedCSSElement("cssFloat")] || "none";
12505		css["clear"] = ClearMap[computedCSSElement("clear")] || "none";
12506
12507		css["color"] = computedCSSElement("color");
12508
12509		return css;
12510	};
12511	elementHandledElsewhere = function elementHandledElsewhere(element, renderer, elementHandlers) {
12512		var handlers, i, isHandledElsewhere, l, classNames;
12513		isHandledElsewhere = false;
12514		i = void 0;
12515		l = void 0;
12516		handlers = elementHandlers["#" + element.id];
12517		if (handlers) {
12518			if (typeof handlers === "function") {
12519				isHandledElsewhere = handlers(element, renderer);
12520			} else {
12521				i = 0;
12522				l = handlers.length;
12523				while (!isHandledElsewhere && i !== l) {
12524					isHandledElsewhere = handlers[i](element, renderer);
12525					i++;
12526				}
12527			}
12528		}
12529		handlers = elementHandlers[element.nodeName];
12530		if (!isHandledElsewhere && handlers) {
12531			if (typeof handlers === "function") {
12532				isHandledElsewhere = handlers(element, renderer);
12533			} else {
12534				i = 0;
12535				l = handlers.length;
12536				while (!isHandledElsewhere && i !== l) {
12537					isHandledElsewhere = handlers[i](element, renderer);
12538					i++;
12539				}
12540			}
12541		}
12542
12543		// Try class names
12544		classNames = element.className ? element.className.split(' ') : [];
12545		for (i = 0; i < classNames.length; i++) {
12546			handlers = elementHandlers['.' + classNames[i]];
12547			if (!isHandledElsewhere && handlers) {
12548				if (typeof handlers === "function") {
12549					isHandledElsewhere = handlers(element, renderer);
12550				} else {
12551					i = 0;
12552					l = handlers.length;
12553					while (!isHandledElsewhere && i !== l) {
12554						isHandledElsewhere = handlers[i](element, renderer);
12555						i++;
12556					}
12557				}
12558			}
12559		}
12560
12561		return isHandledElsewhere;
12562	};
12563	tableToJson = function tableToJson(table, renderer) {
12564		var data, headers, i, j, rowData, tableRow, table_obj, table_with, cell, l;
12565		data = [];
12566		headers = [];
12567		i = 0;
12568		l = table.rows[0].cells.length;
12569		table_with = table.clientWidth;
12570		while (i < l) {
12571			cell = table.rows[0].cells[i];
12572			headers[i] = {
12573				name: cell.textContent.toLowerCase().replace(/\s+/g, ''),
12574				prompt: cell.textContent.replace(/\r?\n/g, ''),
12575				width: cell.clientWidth / table_with * renderer.pdf.internal.pageSize.width
12576			};
12577			i++;
12578		}
12579		i = 1;
12580		while (i < table.rows.length) {
12581			tableRow = table.rows[i];
12582			rowData = {};
12583			j = 0;
12584			while (j < tableRow.cells.length) {
12585				rowData[headers[j].name] = tableRow.cells[j].textContent.replace(/\r?\n/g, '');
12586				j++;
12587			}
12588			data.push(rowData);
12589			i++;
12590		}
12591		return table_obj = {
12592			rows: data,
12593			headers: headers
12594		};
12595	};
12596	var SkipNode = {
12597		SCRIPT: 1,
12598		STYLE: 1,
12599		NOSCRIPT: 1,
12600		OBJECT: 1,
12601		EMBED: 1,
12602		SELECT: 1
12603	};
12604	var listCount = 1;
12605	_DrillForContent = function DrillForContent(element, renderer, elementHandlers) {
12606		var cn, cns, fragmentCSS, i, isBlock, l, px2pt, table2json, cb;
12607		cns = element.childNodes;
12608		cn = void 0;
12609		fragmentCSS = GetCSS(element);
12610		isBlock = fragmentCSS.display === "block";
12611		if (isBlock) {
12612			renderer.setBlockBoundary();
12613			renderer.setBlockStyle(fragmentCSS);
12614		}
12615		i = 0;
12616		l = cns.length;
12617		while (i < l) {
12618			cn = cns[i];
12619			if ((typeof cn === "undefined" ? "undefined" : _typeof(cn)) === "object") {
12620
12621				//execute all watcher functions to e.g. reset floating
12622				renderer.executeWatchFunctions(cn);
12623
12624				/*** HEADER rendering **/
12625				if (cn.nodeType === 1 && cn.nodeName === 'HEADER') {
12626					var header = cn;
12627					//store old top margin
12628					var oldMarginTop = renderer.pdf.margins_doc.top;
12629					//subscribe for new page event and render header first on every page
12630					renderer.pdf.internal.events.subscribe('addPage', function (pageInfo) {
12631						//set current y position to old margin
12632						renderer.y = oldMarginTop;
12633						//render all child nodes of the header element
12634						_DrillForContent(header, renderer, elementHandlers);
12635						//set margin to old margin + rendered header + 10 space to prevent overlapping
12636						//important for other plugins (e.g. table) to start rendering at correct position after header
12637						renderer.pdf.margins_doc.top = renderer.y + 10;
12638						renderer.y += 10;
12639					}, false);
12640				}
12641
12642				if (cn.nodeType === 8 && cn.nodeName === "#comment") {
12643					if (~cn.textContent.indexOf("ADD_PAGE")) {
12644						renderer.pdf.addPage();
12645						renderer.y = renderer.pdf.margins_doc.top;
12646					}
12647				} else if (cn.nodeType === 1 && !SkipNode[cn.nodeName]) {
12648					/*** IMAGE RENDERING ***/
12649					var cached_image;
12650					if (cn.nodeName === "IMG") {
12651						var url = cn.getAttribute("src");
12652						cached_image = images[renderer.pdf.sHashCode(url) || url];
12653					}
12654					if (cached_image) {
12655						if (renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom < renderer.y + cn.height && renderer.y > renderer.pdf.margins_doc.top) {
12656							renderer.pdf.addPage();
12657							renderer.y = renderer.pdf.margins_doc.top;
12658							//check if we have to set back some values due to e.g. header rendering for new page
12659							renderer.executeWatchFunctions(cn);
12660						}
12661
12662						var imagesCSS = GetCSS(cn);
12663						var imageX = renderer.x;
12664						var fontToUnitRatio = 12 / renderer.pdf.internal.scaleFactor;
12665
12666						//define additional paddings, margins which have to be taken into account for margin calculations
12667						var additionalSpaceLeft = (imagesCSS["margin-left"] + imagesCSS["padding-left"]) * fontToUnitRatio;
12668						var additionalSpaceRight = (imagesCSS["margin-right"] + imagesCSS["padding-right"]) * fontToUnitRatio;
12669						var additionalSpaceTop = (imagesCSS["margin-top"] + imagesCSS["padding-top"]) * fontToUnitRatio;
12670						var additionalSpaceBottom = (imagesCSS["margin-bottom"] + imagesCSS["padding-bottom"]) * fontToUnitRatio;
12671
12672						//if float is set to right, move the image to the right border
12673						//add space if margin is set
12674						if (imagesCSS['float'] !== undefined && imagesCSS['float'] === 'right') {
12675							imageX += renderer.settings.width - cn.width - additionalSpaceRight;
12676						} else {
12677							imageX += additionalSpaceLeft;
12678						}
12679
12680						renderer.pdf.addImage(cached_image, imageX, renderer.y + additionalSpaceTop, cn.width, cn.height);
12681						cached_image = undefined;
12682						//if the float prop is specified we have to float the text around the image
12683						if (imagesCSS['float'] === 'right' || imagesCSS['float'] === 'left') {
12684							//add functiont to set back coordinates after image rendering
12685							renderer.watchFunctions.push(function (diffX, thresholdY, diffWidth, el) {
12686								//undo drawing box adaptions which were set by floating
12687								if (renderer.y >= thresholdY) {
12688									renderer.x += diffX;
12689									renderer.settings.width += diffWidth;
12690									return true;
12691								} else if (el && el.nodeType === 1 && !SkipNode[el.nodeName] && renderer.x + el.width > renderer.pdf.margins_doc.left + renderer.pdf.margins_doc.width) {
12692									renderer.x += diffX;
12693									renderer.y = thresholdY;
12694									renderer.settings.width += diffWidth;
12695									return true;
12696								} else {
12697									return false;
12698								}
12699							}.bind(this, imagesCSS['float'] === 'left' ? -cn.width - additionalSpaceLeft - additionalSpaceRight : 0, renderer.y + cn.height + additionalSpaceTop + additionalSpaceBottom, cn.width));
12700							//reset floating by clear:both divs
12701							//just set cursorY after the floating element
12702							renderer.watchFunctions.push(function (yPositionAfterFloating, pages, el) {
12703								if (renderer.y < yPositionAfterFloating && pages === renderer.pdf.internal.getNumberOfPages()) {
12704									if (el.nodeType === 1 && GetCSS(el).clear === 'both') {
12705										renderer.y = yPositionAfterFloating;
12706										return true;
12707									} else {
12708										return false;
12709									}
12710								} else {
12711									return true;
12712								}
12713							}.bind(this, renderer.y + cn.height, renderer.pdf.internal.getNumberOfPages()));
12714
12715							//if floating is set we decrease the available width by the image width
12716							renderer.settings.width -= cn.width + additionalSpaceLeft + additionalSpaceRight;
12717							//if left just add the image width to the X coordinate
12718							if (imagesCSS['float'] === 'left') {
12719								renderer.x += cn.width + additionalSpaceLeft + additionalSpaceRight;
12720							}
12721						} else {
12722							//if no floating is set, move the rendering cursor after the image height
12723							renderer.y += cn.height + additionalSpaceTop + additionalSpaceBottom;
12724						}
12725
12726						/*** TABLE RENDERING ***/
12727					} else if (cn.nodeName === "TABLE") {
12728						table2json = tableToJson(cn, renderer);
12729						renderer.y += 10;
12730						renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
12731							autoSize: false,
12732							printHeaders: elementHandlers.printHeaders,
12733							margins: renderer.pdf.margins_doc,
12734							css: GetCSS(cn)
12735						});
12736						renderer.y = renderer.pdf.lastCellPos.y + renderer.pdf.lastCellPos.h + 20;
12737					} else if (cn.nodeName === "OL" || cn.nodeName === "UL") {
12738						listCount = 1;
12739						if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
12740							_DrillForContent(cn, renderer, elementHandlers);
12741						}
12742						renderer.y += 10;
12743					} else if (cn.nodeName === "LI") {
12744						var temp = renderer.x;
12745						renderer.x += 20 / renderer.pdf.internal.scaleFactor;
12746						renderer.y += 3;
12747						if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
12748							_DrillForContent(cn, renderer, elementHandlers);
12749						}
12750						renderer.x = temp;
12751					} else if (cn.nodeName === "BR") {
12752						renderer.y += fragmentCSS["font-size"] * renderer.pdf.internal.scaleFactor;
12753						renderer.addText("\u2028", clone(fragmentCSS));
12754					} else {
12755						if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
12756							_DrillForContent(cn, renderer, elementHandlers);
12757						}
12758					}
12759				} else if (cn.nodeType === 3) {
12760					var value = cn.nodeValue;
12761					if (cn.nodeValue && cn.parentNode.nodeName === "LI") {
12762						if (cn.parentNode.parentNode.nodeName === "OL") {
12763							value = listCount++ + '. ' + value;
12764						} else {
12765							var fontSize = fragmentCSS["font-size"];
12766							var offsetX = (3 - fontSize * 0.75) * renderer.pdf.internal.scaleFactor;
12767							var offsetY = fontSize * 0.75 * renderer.pdf.internal.scaleFactor;
12768							var radius = fontSize * 1.74 / renderer.pdf.internal.scaleFactor;
12769							cb = function cb(x, y) {
12770								this.pdf.circle(x + offsetX, y + offsetY, radius, 'FD');
12771							};
12772						}
12773					}
12774					// Only add the text if the text node is in the body element
12775					// Add compatibility with IE11
12776					if (!!(cn.ownerDocument.body.compareDocumentPosition(cn) & 16)) {
12777						renderer.addText(value, fragmentCSS);
12778					}
12779				} else if (typeof cn === "string") {
12780					renderer.addText(cn, fragmentCSS);
12781				}
12782			}
12783			i++;
12784		}
12785		elementHandlers.outY = renderer.y;
12786
12787		if (isBlock) {
12788			return renderer.setBlockBoundary(cb);
12789		}
12790	};
12791	images = {};
12792	loadImgs = function loadImgs(element, renderer, elementHandlers, cb) {
12793		var imgs = element.getElementsByTagName('img'),
12794		    l = imgs.length,
12795		    found_images,
12796		    x = 0;
12797		function done() {
12798			renderer.pdf.internal.events.publish('imagesLoaded');
12799			cb(found_images);
12800		}
12801		function loadImage(url, width, height) {
12802			if (!url) return;
12803			var img = new Image();
12804			found_images = ++x;
12805			img.crossOrigin = '';
12806			img.onerror = img.onload = function () {
12807				if (img.complete) {
12808					//to support data urls in images, set width and height
12809					//as those values are not recognized automatically
12810					if (img.src.indexOf('data:image/') === 0) {
12811						img.width = width || img.width || 0;
12812						img.height = height || img.height || 0;
12813					}
12814					//if valid image add to known images array
12815					if (img.width + img.height) {
12816						var hash = renderer.pdf.sHashCode(url) || url;
12817						images[hash] = images[hash] || img;
12818					}
12819				}
12820				if (! --x) {
12821					done();
12822				}
12823			};
12824			img.src = url;
12825		}
12826		while (l--) {
12827			loadImage(imgs[l].getAttribute("src"), imgs[l].width, imgs[l].height);
12828		}return x || done();
12829	};
12830	checkForFooter = function checkForFooter(elem, renderer, elementHandlers) {
12831		//check if we can found a <footer> element
12832		var footer = elem.getElementsByTagName("footer");
12833		if (footer.length > 0) {
12834
12835			footer = footer[0];
12836
12837			//bad hack to get height of footer
12838			//creat dummy out and check new y after fake rendering
12839			var oldOut = renderer.pdf.internal.write;
12840			var oldY = renderer.y;
12841			renderer.pdf.internal.write = function () {};
12842			_DrillForContent(footer, renderer, elementHandlers);
12843			var footerHeight = Math.ceil(renderer.y - oldY) + 5;
12844			renderer.y = oldY;
12845			renderer.pdf.internal.write = oldOut;
12846
12847			//add 20% to prevent overlapping
12848			renderer.pdf.margins_doc.bottom += footerHeight;
12849
12850			//Create function render header on every page
12851			var renderFooter = function renderFooter(pageInfo) {
12852				var pageNumber = pageInfo !== undefined ? pageInfo.pageNumber : 1;
12853				//set current y position to old margin
12854				var oldPosition = renderer.y;
12855				//render all child nodes of the header element
12856				renderer.y = renderer.pdf.internal.pageSize.height - renderer.pdf.margins_doc.bottom;
12857				renderer.pdf.margins_doc.bottom -= footerHeight;
12858
12859				//check if we have to add page numbers
12860				var spans = footer.getElementsByTagName('span');
12861				for (var i = 0; i < spans.length; ++i) {
12862					//if we find some span element with class pageCounter, set the page
12863					if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" pageCounter ") > -1) {
12864						spans[i].innerHTML = pageNumber;
12865					}
12866					//if we find some span element with class totalPages, set a variable which is replaced after rendering of all pages
12867					if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
12868						spans[i].innerHTML = '###jsPDFVarTotalPages###';
12869					}
12870				}
12871
12872				//render footer content
12873				_DrillForContent(footer, renderer, elementHandlers);
12874				//set bottom margin to previous height including the footer height
12875				renderer.pdf.margins_doc.bottom += footerHeight;
12876				//important for other plugins (e.g. table) to start rendering at correct position after header
12877				renderer.y = oldPosition;
12878			};
12879
12880			//check if footer contains totalPages which should be replace at the disoposal of the document
12881			var spans = footer.getElementsByTagName('span');
12882			for (var i = 0; i < spans.length; ++i) {
12883				if ((" " + spans[i].className + " ").replace(/[\n\t]/g, " ").indexOf(" totalPages ") > -1) {
12884					renderer.pdf.internal.events.subscribe('htmlRenderingFinished', renderer.pdf.putTotalPages.bind(renderer.pdf, '###jsPDFVarTotalPages###'), true);
12885				}
12886			}
12887
12888			//register event to render footer on every new page
12889			renderer.pdf.internal.events.subscribe('addPage', renderFooter, false);
12890			//render footer on first page
12891			renderFooter();
12892
12893			//prevent footer rendering
12894			SkipNode['FOOTER'] = 1;
12895		}
12896	};
12897	process = function process(pdf, element, x, y, settings, callback) {
12898		if (!element) return false;
12899		if (typeof element !== "string" && !element.parentNode) element = '' + element.innerHTML;
12900		if (typeof element === "string") {
12901			element = function (element) {
12902				var $frame, $hiddendiv, framename, visuallyhidden;
12903				framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0);
12904				visuallyhidden = "position: absolute !important;" + "clip: rect(1px 1px 1px 1px); /* IE6, IE7 */" + "clip: rect(1px, 1px, 1px, 1px);" + "padding:0 !important;" + "border:0 !important;" + "height: 1px !important;" + "width: 1px !important; " + "top:auto;" + "left:-100px;" + "overflow: hidden;";
12905				$hiddendiv = document.createElement('div');
12906				$hiddendiv.style.cssText = visuallyhidden;
12907				$hiddendiv.innerHTML = "<iframe style=\"height:1px;width:1px\" name=\"" + framename + "\" />";
12908				document.body.appendChild($hiddendiv);
12909				$frame = window.frames[framename];
12910				$frame.document.open();
12911				$frame.document.writeln(element);
12912				$frame.document.close();
12913				return $frame.document.body;
12914			}(element.replace(/<\/?script[^>]*?>/gi, ''));
12915		}
12916		var r = new Renderer(pdf, x, y, settings),
12917		    out;
12918
12919		// 1. load images
12920		// 2. prepare optional footer elements
12921		// 3. render content
12922		loadImgs.call(this, element, r, settings.elementHandlers, function (found_images) {
12923			checkForFooter(element, r, settings.elementHandlers);
12924			_DrillForContent(element, r, settings.elementHandlers);
12925			//send event dispose for final taks (e.g. footer totalpage replacement)
12926			r.pdf.internal.events.publish('htmlRenderingFinished');
12927			out = r.dispose();
12928			if (typeof callback === 'function') callback(out);else if (found_images) console.error('jsPDF Warning: rendering issues? provide a callback to fromHTML!');
12929		});
12930		return out || { x: r.x, y: r.y };
12931	};
12932	Renderer.prototype.init = function () {
12933		this.paragraph = {
12934			text: [],
12935			style: []
12936		};
12937		return this.pdf.internal.write("q");
12938	};
12939	Renderer.prototype.dispose = function () {
12940		this.pdf.internal.write("Q");
12941		return {
12942			x: this.x,
12943			y: this.y,
12944			ready: true
12945		};
12946	};
12947
12948	//Checks if we have to execute some watcher functions
12949	//e.g. to end text floating around an image
12950	Renderer.prototype.executeWatchFunctions = function (el) {
12951		var ret = false;
12952		var narray = [];
12953		if (this.watchFunctions.length > 0) {
12954			for (var i = 0; i < this.watchFunctions.length; ++i) {
12955				if (this.watchFunctions[i](el) === true) {
12956					ret = true;
12957				} else {
12958					narray.push(this.watchFunctions[i]);
12959				}
12960			}
12961			this.watchFunctions = narray;
12962		}
12963		return ret;
12964	};
12965
12966	Renderer.prototype.splitFragmentsIntoLines = function (fragments, styles) {
12967		var currentLineLength, defaultFontSize, ff, fontMetrics, fontMetricsCache, fragment, fragmentChopped, fragmentLength, fragmentSpecificMetrics, fs, k, line, lines, maxLineLength, style;
12968		defaultFontSize = 12;
12969		k = this.pdf.internal.scaleFactor;
12970		fontMetricsCache = {};
12971		ff = void 0;
12972		fs = void 0;
12973		fontMetrics = void 0;
12974		fragment = void 0;
12975		style = void 0;
12976		fragmentSpecificMetrics = void 0;
12977		fragmentLength = void 0;
12978		fragmentChopped = void 0;
12979		line = [];
12980		lines = [line];
12981		currentLineLength = 0;
12982		maxLineLength = this.settings.width;
12983		while (fragments.length) {
12984			fragment = fragments.shift();
12985			style = styles.shift();
12986			if (fragment) {
12987				ff = style["font-family"];
12988				fs = style["font-style"];
12989				fontMetrics = fontMetricsCache[ff + fs];
12990				if (!fontMetrics) {
12991					fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode;
12992					fontMetricsCache[ff + fs] = fontMetrics;
12993				}
12994				fragmentSpecificMetrics = {
12995					widths: fontMetrics.widths,
12996					kerning: fontMetrics.kerning,
12997					fontSize: style["font-size"] * defaultFontSize,
12998					textIndent: currentLineLength
12999				};
13000				fragmentLength = this.pdf.getStringUnitWidth(fragment, fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
13001				if (fragment == "\u2028") {
13002					line = [];
13003					lines.push(line);
13004				} else if (currentLineLength + fragmentLength > maxLineLength) {
13005					fragmentChopped = this.pdf.splitTextToSize(fragment, maxLineLength, fragmentSpecificMetrics);
13006					line.push([fragmentChopped.shift(), style]);
13007					while (fragmentChopped.length) {
13008						line = [[fragmentChopped.shift(), style]];
13009						lines.push(line);
13010					}
13011					currentLineLength = this.pdf.getStringUnitWidth(line[0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
13012				} else {
13013					line.push([fragment, style]);
13014					currentLineLength += fragmentLength;
13015				}
13016			}
13017		}
13018
13019		//if text alignment was set, set margin/indent of each line
13020		if (style['text-align'] !== undefined && (style['text-align'] === 'center' || style['text-align'] === 'right' || style['text-align'] === 'justify')) {
13021			for (var i = 0; i < lines.length; ++i) {
13022				var length = this.pdf.getStringUnitWidth(lines[i][0][0], fragmentSpecificMetrics) * fragmentSpecificMetrics.fontSize / k;
13023				//if there is more than on line we have to clone the style object as all lines hold a reference on this object
13024				if (i > 0) {
13025					lines[i][0][1] = clone(lines[i][0][1]);
13026				}
13027				var space = maxLineLength - length;
13028
13029				if (style['text-align'] === 'right') {
13030					lines[i][0][1]['margin-left'] = space;
13031					//if alignment is not right, it has to be center so split the space to the left and the right
13032				} else if (style['text-align'] === 'center') {
13033					lines[i][0][1]['margin-left'] = space / 2;
13034					//if justify was set, calculate the word spacing and define in by using the css property
13035				} else if (style['text-align'] === 'justify') {
13036					var countSpaces = lines[i][0][0].split(' ').length - 1;
13037					lines[i][0][1]['word-spacing'] = space / countSpaces;
13038					//ignore the last line in justify mode
13039					if (i === lines.length - 1) {
13040						lines[i][0][1]['word-spacing'] = 0;
13041					}
13042				}
13043			}
13044		}
13045
13046		return lines;
13047	};
13048	Renderer.prototype.RenderTextFragment = function (text, style) {
13049		var defaultFontSize, font, maxLineHeight;
13050
13051		maxLineHeight = 0;
13052		defaultFontSize = 12;
13053
13054		if (this.pdf.internal.pageSize.height - this.pdf.margins_doc.bottom < this.y + this.pdf.internal.getFontSize()) {
13055			this.pdf.internal.write("ET", "Q");
13056			this.pdf.addPage();
13057			this.y = this.pdf.margins_doc.top;
13058			this.pdf.internal.write("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), style.color, "Td");
13059			//move cursor by one line on new page
13060			maxLineHeight = Math.max(maxLineHeight, style["line-height"], style["font-size"]);
13061			this.pdf.internal.write(0, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
13062		}
13063
13064		font = this.pdf.internal.getFont(style["font-family"], style["font-style"]);
13065
13066		// text color
13067		var pdfTextColor = this.getPdfColor(style["color"]);
13068		if (pdfTextColor !== this.lastTextColor) {
13069			this.pdf.internal.write(pdfTextColor);
13070			this.lastTextColor = pdfTextColor;
13071		}
13072
13073		//set the word spacing for e.g. justify style
13074		if (style['word-spacing'] !== undefined && style['word-spacing'] > 0) {
13075			this.pdf.internal.write(style['word-spacing'].toFixed(2), "Tw");
13076		}
13077
13078		this.pdf.internal.write("/" + font.id, (defaultFontSize * style["font-size"]).toFixed(2), "Tf", "(" + this.pdf.internal.pdfEscape(text) + ") Tj");
13079
13080		//set the word spacing back to neutral => 0
13081		if (style['word-spacing'] !== undefined) {
13082			this.pdf.internal.write(0, "Tw");
13083		}
13084	};
13085
13086	// Accepts #FFFFFF, rgb(int,int,int), or CSS Color Name
13087	Renderer.prototype.getPdfColor = function (style) {
13088		var textColor;
13089		var r, g, b;
13090
13091		var rx = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/;
13092		var m = rx.exec(style);
13093		if (m != null) {
13094			r = parseInt(m[1]);
13095			g = parseInt(m[2]);
13096			b = parseInt(m[3]);
13097		} else {
13098			if (style.charAt(0) != '#') {
13099				style = CssColors.colorNameToHex(style);
13100				if (!style) {
13101					style = '#000000';
13102				}
13103			}
13104			r = style.substring(1, 3);
13105			r = parseInt(r, 16);
13106			g = style.substring(3, 5);
13107			g = parseInt(g, 16);
13108			b = style.substring(5, 7);
13109			b = parseInt(b, 16);
13110		}
13111
13112		if (typeof r === 'string' && /^#[0-9A-Fa-f]{6}$/.test(r)) {
13113			var hex = parseInt(r.substr(1), 16);
13114			r = hex >> 16 & 255;
13115			g = hex >> 8 & 255;
13116			b = hex & 255;
13117		}
13118
13119		var f3 = this.f3;
13120		if (r === 0 && g === 0 && b === 0 || typeof g === 'undefined') {
13121			textColor = f3(r / 255) + ' g';
13122		} else {
13123			textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
13124		}
13125		return textColor;
13126	};
13127
13128	Renderer.prototype.f3 = function (number) {
13129		return number.toFixed(3); // Ie, %.3f
13130	}, Renderer.prototype.renderParagraph = function (cb) {
13131		var blockstyle, defaultFontSize, fontToUnitRatio, fragments, i, l, line, lines, maxLineHeight, out, paragraphspacing_after, paragraphspacing_before, priorblockstyle, styles, fontSize;
13132		fragments = PurgeWhiteSpace(this.paragraph.text);
13133		styles = this.paragraph.style;
13134		blockstyle = this.paragraph.blockstyle;
13135		this.paragraph = {
13136			text: [],
13137			style: [],
13138			blockstyle: {},
13139			priorblockstyle: blockstyle
13140		};
13141		if (!fragments.join("").trim()) {
13142			return;
13143		}
13144		lines = this.splitFragmentsIntoLines(fragments, styles);
13145		line = void 0;
13146		maxLineHeight = void 0;
13147		defaultFontSize = 12;
13148		fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor;
13149		this.priorMarginBottom = this.priorMarginBottom || 0;
13150		paragraphspacing_before = (Math.max((blockstyle["margin-top"] || 0) - this.priorMarginBottom, 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
13151		paragraphspacing_after = ((blockstyle["margin-bottom"] || 0) + (blockstyle["padding-bottom"] || 0)) * fontToUnitRatio;
13152		this.priorMarginBottom = blockstyle["margin-bottom"] || 0;
13153
13154		if (blockstyle['page-break-before'] === 'always') {
13155			this.pdf.addPage();
13156			this.y = 0;
13157			paragraphspacing_before = ((blockstyle["margin-top"] || 0) + (blockstyle["padding-top"] || 0)) * fontToUnitRatio;
13158		}
13159
13160		out = this.pdf.internal.write;
13161		i = void 0;
13162		l = void 0;
13163		this.y += paragraphspacing_before;
13164		out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
13165
13166		//stores the current indent of cursor position
13167		var currentIndent = 0;
13168
13169		while (lines.length) {
13170			line = lines.shift();
13171			maxLineHeight = 0;
13172			i = 0;
13173			l = line.length;
13174			while (i !== l) {
13175				if (line[i][0].trim()) {
13176					maxLineHeight = Math.max(maxLineHeight, line[i][1]["line-height"], line[i][1]["font-size"]);
13177					fontSize = line[i][1]["font-size"] * 7;
13178				}
13179				i++;
13180			}
13181			//if we have to move the cursor to adapt the indent
13182			var indentMove = 0;
13183			var wantedIndent = 0;
13184			//if a margin was added (by e.g. a text-alignment), move the cursor
13185			if (line[0][1]["margin-left"] !== undefined && line[0][1]["margin-left"] > 0) {
13186				wantedIndent = this.pdf.internal.getCoordinateString(line[0][1]["margin-left"]);
13187				indentMove = wantedIndent - currentIndent;
13188				currentIndent = wantedIndent;
13189			}
13190			var indentMore = Math.max(blockstyle["margin-left"] || 0, 0) * fontToUnitRatio;
13191			//move the cursor
13192			out(indentMove + indentMore, (-1 * defaultFontSize * maxLineHeight).toFixed(2), "Td");
13193			i = 0;
13194			l = line.length;
13195			while (i !== l) {
13196				if (line[i][0]) {
13197					this.RenderTextFragment(line[i][0], line[i][1]);
13198				}
13199				i++;
13200			}
13201			this.y += maxLineHeight * fontToUnitRatio;
13202
13203			//if some watcher function was executed successful, so e.g. margin and widths were changed,
13204			//reset line drawing and calculate position and lines again
13205			//e.g. to stop text floating around an image
13206			if (this.executeWatchFunctions(line[0][1]) && lines.length > 0) {
13207				var localFragments = [];
13208				var localStyles = [];
13209				//create fragment array of
13210				lines.forEach(function (localLine) {
13211					var i = 0;
13212					var l = localLine.length;
13213					while (i !== l) {
13214						if (localLine[i][0]) {
13215							localFragments.push(localLine[i][0] + ' ');
13216							localStyles.push(localLine[i][1]);
13217						}
13218						++i;
13219					}
13220				});
13221				//split lines again due to possible coordinate changes
13222				lines = this.splitFragmentsIntoLines(PurgeWhiteSpace(localFragments), localStyles);
13223				//reposition the current cursor
13224				out("ET", "Q");
13225				out("q", "BT 0 g", this.pdf.internal.getCoordinateString(this.x), this.pdf.internal.getVerticalCoordinateString(this.y), "Td");
13226			}
13227		}
13228		if (cb && typeof cb === "function") {
13229			cb.call(this, this.x - 9, this.y - fontSize / 2);
13230		}
13231		out("ET", "Q");
13232		return this.y += paragraphspacing_after;
13233	};
13234	Renderer.prototype.setBlockBoundary = function (cb) {
13235		return this.renderParagraph(cb);
13236	};
13237	Renderer.prototype.setBlockStyle = function (css) {
13238		return this.paragraph.blockstyle = css;
13239	};
13240	Renderer.prototype.addText = function (text, css) {
13241		this.paragraph.text.push(text);
13242		return this.paragraph.style.push(css);
13243	};
13244	FontNameDB = {
13245		helvetica: "helvetica",
13246		"sans-serif": "helvetica",
13247		"times new roman": "times",
13248		serif: "times",
13249		times: "times",
13250		monospace: "courier",
13251		courier: "courier"
13252	};
13253	FontWeightMap = {
13254		100: "normal",
13255		200: "normal",
13256		300: "normal",
13257		400: "normal",
13258		500: "bold",
13259		600: "bold",
13260		700: "bold",
13261		800: "bold",
13262		900: "bold",
13263		normal: "normal",
13264		bold: "bold",
13265		bolder: "bold",
13266		lighter: "normal"
13267	};
13268	FontStyleMap = {
13269		normal: "normal",
13270		italic: "italic",
13271		oblique: "italic"
13272	};
13273	TextAlignMap = {
13274		left: "left",
13275		right: "right",
13276		center: "center",
13277		justify: "justify"
13278	};
13279	FloatMap = {
13280		none: 'none',
13281		right: 'right',
13282		left: 'left'
13283	};
13284	ClearMap = {
13285		none: 'none',
13286		both: 'both'
13287	};
13288	UnitedNumberMap = {
13289		normal: 1
13290	};
13291	/**
13292  * Converts HTML-formatted text into formatted PDF text.
13293  *
13294  * Notes:
13295  * 2012-07-18
13296  * Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
13297  * Plugin relies on jQuery for CSS extraction.
13298  * Targeting HTML output from Markdown templating, which is a very simple
13299  * markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
13300  * Images, tables are NOT supported.
13301  *
13302  * @public
13303  * @function
13304  * @param HTML {String or DOM Element} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF.
13305  * @param x {Number} starting X coordinate in jsPDF instance's declared units.
13306  * @param y {Number} starting Y coordinate in jsPDF instance's declared units.
13307  * @param settings {Object} Additional / optional variables controlling parsing, rendering.
13308  * @returns {Object} jsPDF instance
13309  */
13310	jsPDFAPI.fromHTML = function (HTML, x, y, settings, callback, margins) {
13311		"use strict";
13312
13313		this.margins_doc = margins || {
13314			top: 0,
13315			bottom: 0
13316		};
13317		if (!settings) settings = {};
13318		if (!settings.elementHandlers) settings.elementHandlers = {};
13319
13320		return process(this, HTML, isNaN(x) ? 4 : x, isNaN(y) ? 4 : y, settings, callback);
13321	};
13322})(jsPDF.API);
13323
13324/** ==================================================================== 
13325 * jsPDF JavaScript plugin
13326 * Copyright (c) 2013 Youssef Beddad, [email protected]
13327 * 
13328 * 
13329 * ====================================================================
13330 */
13331
13332/*global jsPDF */
13333
13334(function (jsPDFAPI) {
13335    'use strict';
13336
13337    var jsNamesObj, jsJsObj, text;
13338    jsPDFAPI.addJS = function (txt) {
13339        text = txt;
13340        this.internal.events.subscribe('postPutResources', function (txt) {
13341            jsNamesObj = this.internal.newObject();
13342            this.internal.write('<< /Names [(EmbeddedJS) ' + (jsNamesObj + 1) + ' 0 R] >>', 'endobj');
13343            jsJsObj = this.internal.newObject();
13344            this.internal.write('<< /S /JavaScript /JS (', text, ') >>', 'endobj');
13345        });
13346        this.internal.events.subscribe('putCatalog', function () {
13347            if (jsNamesObj !== undefined && jsJsObj !== undefined) {
13348                this.internal.write('/Names <</JavaScript ' + jsNamesObj + ' 0 R>>');
13349            }
13350        });
13351        return this;
13352    };
13353})(jsPDF.API);
13354
13355/**
13356 * jsPDF Outline PlugIn
13357 * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  [email protected]
13358 *
13359 * Licensed under the MIT License.
13360 * http://opensource.org/licenses/mit-license
13361 */
13362
13363/**
13364 * Generates a PDF Outline
13365 */
13366
13367(function (jsPDFAPI) {
13368	'use strict';
13369
13370	jsPDFAPI.events.push(['postPutResources', function () {
13371		var pdf = this;
13372		var rx = /^(\d+) 0 obj$/;
13373
13374		// Write action goto objects for each page
13375		// this.outline.destsGoto = [];
13376		// for (var i = 0; i < totalPages; i++) {
13377		// var id = pdf.internal.newObject();
13378		// this.outline.destsGoto.push(id);
13379		// pdf.internal.write("<</D[" + (i * 2 + 3) + " 0 R /XYZ null
13380		// null null]/S/GoTo>> endobj");
13381		// }
13382		//
13383		// for (var i = 0; i < dests.length; i++) {
13384		// pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0
13385		// R");
13386		// }
13387		//				
13388		if (this.outline.root.children.length > 0) {
13389			var lines = pdf.outline.render().split(/\r\n/);
13390			for (var i = 0; i < lines.length; i++) {
13391				var line = lines[i];
13392				var m = rx.exec(line);
13393				if (m != null) {
13394					var oid = m[1];
13395					pdf.internal.newObjectDeferredBegin(oid);
13396				}
13397				pdf.internal.write(line);
13398			}
13399		}
13400
13401		// This code will write named destination for each page reference
13402		// (page_1, etc)
13403		if (this.outline.createNamedDestinations) {
13404			var totalPages = this.internal.pages.length;
13405			// WARNING: this assumes jsPDF starts on page 3 and pageIDs
13406			// follow 5, 7, 9, etc
13407			// Write destination objects for each page
13408			var dests = [];
13409			for (var i = 0; i < totalPages; i++) {
13410				var id = pdf.internal.newObject();
13411				dests.push(id);
13412				var info = pdf.internal.getPageInfo(i + 1);
13413				pdf.internal.write("<< /D[" + info.objId + " 0 R /XYZ null null null]>> endobj");
13414			}
13415
13416			// assign a name for each destination
13417			var names2Oid = pdf.internal.newObject();
vendor: 4,985 bytes, lines 13418-13601
13418			pdf.internal.write('<< /Names [ ');
13419			for (var i = 0; i < dests.length; i++) {
13420				pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0 R");
13421			}
13422			pdf.internal.write(' ] >>', 'endobj');
13423
13424			// var kids = pdf.internal.newObject();
13425			// pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');
13426			// pdf.internal.write(' ] >>', 'endobj');
13427
13428			var namesOid = pdf.internal.newObject();
13429			pdf.internal.write('<< /Dests ' + names2Oid + " 0 R");
13430			pdf.internal.write('>>', 'endobj');
13431		}
13432	}]);
13433
13434	jsPDFAPI.events.push(['putCatalog', function () {
13435		var pdf = this;
13436		if (pdf.outline.root.children.length > 0) {
13437			pdf.internal.write("/Outlines", this.outline.makeRef(this.outline.root));
13438			if (this.outline.createNamedDestinations) {
13439				pdf.internal.write("/Names " + namesOid + " 0 R");
13440			}
13441			// Open with Bookmarks showing
13442			// pdf.internal.write("/PageMode /UseOutlines");
13443		}
13444	}]);
13445
13446	jsPDFAPI.events.push(['initialized', function () {
13447		var pdf = this;
13448
13449		pdf.outline = {
13450			createNamedDestinations: false,
13451			root: {
13452				children: []
13453			}
13454		};
13455
13456		pdf.outline.add = function (parent, title, options) {
13457			var item = {
13458				title: title,
13459				options: options,
13460				children: []
13461			};
13462			if (parent == null) {
13463				parent = this.root;
13464			}
13465			parent.children.push(item);
13466			return item;
13467		};
13468
13469		pdf.outline.render = function () {
13470			this.ctx = {};
13471			this.ctx.val = '';
13472			this.ctx.pdf = pdf;
13473
13474			this.genIds_r(this.root);
13475			this.renderRoot(this.root);
13476			this.renderItems(this.root);
13477
13478			return this.ctx.val;
13479		};
13480
13481		pdf.outline.genIds_r = function (node) {
13482			node.id = pdf.internal.newObjectDeferred();
13483			for (var i = 0; i < node.children.length; i++) {
13484				this.genIds_r(node.children[i]);
13485			}
13486		};
13487
13488		pdf.outline.renderRoot = function (node) {
13489			this.objStart(node);
13490			this.line('/Type /Outlines');
13491			if (node.children.length > 0) {
13492				this.line('/First ' + this.makeRef(node.children[0]));
13493				this.line('/Last ' + this.makeRef(node.children[node.children.length - 1]));
13494			}
13495			this.line('/Count ' + this.count_r({
13496				count: 0
13497			}, node));
13498			this.objEnd();
13499		};
13500
13501		pdf.outline.renderItems = function (node) {
13502			for (var i = 0; i < node.children.length; i++) {
13503				var item = node.children[i];
13504				this.objStart(item);
13505
13506				this.line('/Title ' + this.makeString(item.title));
13507
13508				this.line('/Parent ' + this.makeRef(node));
13509				if (i > 0) {
13510					this.line('/Prev ' + this.makeRef(node.children[i - 1]));
13511				}
13512				if (i < node.children.length - 1) {
13513					this.line('/Next ' + this.makeRef(node.children[i + 1]));
13514				}
13515				if (item.children.length > 0) {
13516					this.line('/First ' + this.makeRef(item.children[0]));
13517					this.line('/Last ' + this.makeRef(item.children[item.children.length - 1]));
13518				}
13519
13520				var count = this.count = this.count_r({
13521					count: 0
13522				}, item);
13523				if (count > 0) {
13524					this.line('/Count ' + count);
13525				}
13526
13527				if (item.options) {
13528					if (item.options.pageNumber) {
13529						// Explicit Destination
13530						//WARNING this assumes page ids are 3,5,7, etc.
13531						var info = pdf.internal.getPageInfo(item.options.pageNumber);
13532						this.line('/Dest ' + '[' + info.objId + ' 0 R /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
13533						// this line does not work on all clients (pageNumber instead of page ref)
13534						//this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.height + ' 0]');
13535
13536						// Named Destination
13537						// this.line('/Dest (page_' + (item.options.pageNumber) + ')');
13538
13539						// Action Destination
13540						// var id = pdf.internal.newObject();
13541						// pdf.internal.write('<</D[' + (item.options.pageNumber - 1) + ' /XYZ null null null]/S/GoTo>> endobj');
13542						// this.line('/A ' + id + ' 0 R' );
13543					}
13544				}
13545				this.objEnd();
13546			}
13547			for (var i = 0; i < node.children.length; i++) {
13548				var item = node.children[i];
13549				this.renderItems(item);
13550			}
13551		};
13552
13553		pdf.outline.line = function (text) {
13554			this.ctx.val += text + '\r\n';
13555		};
13556
13557		pdf.outline.makeRef = function (node) {
13558			return node.id + ' 0 R';
13559		};
13560
13561		pdf.outline.makeString = function (val) {
13562			return '(' + pdf.internal.pdfEscape(val) + ')';
13563		};
13564
13565		pdf.outline.objStart = function (node) {
13566			this.ctx.val += '\r\n' + node.id + ' 0 obj' + '\r\n<<\r\n';
13567		};
13568
13569		pdf.outline.objEnd = function (node) {
13570			this.ctx.val += '>> \r\n' + 'endobj' + '\r\n';
13571		};
13572
13573		pdf.outline.count_r = function (ctx, node) {
13574			for (var i = 0; i < node.children.length; i++) {
13575				ctx.count++;
13576				this.count_r(ctx, node.children[i]);
13577			}
13578			return ctx.count;
13579		};
13580	}]);
13581
13582	return this;
13583})(jsPDF.API);
13584
13585/**@preserve
13586 *  ====================================================================
13587 * jsPDF PNG PlugIn
13588 * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
13589 *
13590 * 
13591 * ====================================================================
13592 */
13593
13594(function (jsPDFAPI) {
13595	'use strict';
13596
13597	/*
13598  * @see http://www.w3.org/TR/PNG-Chunks.html
13599  *
13600  Color    Allowed      Interpretation
13601  Type     Bit Depths
13602 	   0       1,2,4,8,16  Each pixel is a grayscale sample.
13603 	   2       8,16        Each pixel is an R,G,B triple.
13604 	   3       1,2,4,8     Each pixel is a palette index;
13605                        a PLTE chunk must appear.
13606 	   4       8,16        Each pixel is a grayscale sample,
13607                        followed by an alpha sample.
13608 	   6       8,16        Each pixel is an R,G,B triple,
13609                        followed by an alpha sample.
13610 */
13611
13612	/*
13613  * PNG filter method types
13614  *
13615  * @see http://www.w3.org/TR/PNG-Filters.html
13616  * @see http://www.libpng.org/pub/png/book/chapter09.html
13617  *
13618  * This is what the value 'Predictor' in decode params relates to
13619  *
13620  * 15 is "optimal prediction", which means the prediction algorithm can change from line to line.
13621  * In that case, you actually have to read the first byte off each line for the prediction algorthim (which should be 0-4, corresponding to PDF 10-14) and select the appropriate unprediction algorithm based on that byte.
13622  *
13623    0       None
13624    1       Sub
13625    2       Up
13626    3       Average
13627    4       Paeth
13628  */
13629
13630	var doesNotHavePngJS = function doesNotHavePngJS() {
13631		return typeof PNG !== 'function' || typeof FlateStream !== 'function';
13632	},
13633	    canCompress = function canCompress(value) {
13634		return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
13635	},
13636	    hasCompressionJS = function hasCompressionJS() {
13637		var inst = typeof Deflater === 'function';
13638		if (!inst) throw new Error("requires deflate.js for compression");
13639		return inst;
13640	},
13641	    compressBytes = function compressBytes(bytes, lineLength, colorsPerPixel, compression) {
13642
13643		var level = 5,
13644		    filter_method = filterUp;
13645
13646		switch (compression) {
13647
13648			case jsPDFAPI.image_compression.FAST:
13649
13650				level = 3;
13651				filter_method = filterSub;
13652				break;
13653
13654			case jsPDFAPI.image_compression.MEDIUM:
13655
13656				level = 6;
13657				filter_method = filterAverage;
13658				break;
13659
13660			case jsPDFAPI.image_compression.SLOW:
13661
13662				level = 9;
13663				filter_method = filterPaeth; //uses to sum to choose best filter for each line
13664				break;
13665		}
13666
13667		bytes = applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method);
13668
13669		var header = new Uint8Array(createZlibHeader(level));
13670		var checksum = adler32(bytes);
13671
13672		var deflate = new Deflater(level);
13673		var a = deflate.append(bytes);
13674		var cBytes = deflate.flush();
13675
13676		var len = header.length + a.length + cBytes.length;
13677
13678		var cmpd = new Uint8Array(len + 4);
13679		cmpd.set(header);
13680		cmpd.set(a, header.length);
13681		cmpd.set(cBytes, header.length + a.length);
13682
13683		cmpd[len++] = checksum >>> 24 & 0xff;
13684		cmpd[len++] = checksum >>> 16 & 0xff;
13685		cmpd[len++] = checksum >>> 8 & 0xff;
13686		cmpd[len++] = checksum & 0xff;
13687
13688		return jsPDFAPI.arrayBufferToBinaryString(cmpd);
13689	},
13690	    createZlibHeader = function createZlibHeader(bytes, level) {
13691		/*
13692   * @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
13693   */
13694		var cm = 8;
13695		var cinfo = Math.LOG2E * Math.log(0x8000) - 8;
13696		var cmf = cinfo << 4 | cm;
13697
13698		var hdr = cmf << 8;
13699		var flevel = Math.min(3, (level - 1 & 0xff) >> 1);
13700
13701		hdr |= flevel << 6;
13702		hdr |= 0; //FDICT
13703		hdr += 31 - hdr % 31;
13704
13705		return [cmf, hdr & 0xff & 0xff];
13706	},
13707	    adler32 = function adler32(array, param) {
13708		var adler = 1;
13709		var s1 = adler & 0xffff,
13710		    s2 = adler >>> 16 & 0xffff;
13711		var len = array.length;
13712		var tlen;
13713		var i = 0;
13714
13715		while (len > 0) {
13716			tlen = len > param ? param : len;
13717			len -= tlen;
13718			do {
13719				s1 += array[i++];
13720				s2 += s1;
13721			} while (--tlen);
13722
13723			s1 %= 65521;
13724			s2 %= 65521;
13725		}
13726
13727		return (s2 << 16 | s1) >>> 0;
13728	},
13729	    applyPngFilterMethod = function applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method) {
13730		var lines = bytes.length / lineLength,
13731		    result = new Uint8Array(bytes.length + lines),
13732		    filter_methods = getFilterMethods(),
13733		    i = 0,
13734		    line,
13735		    prevLine,
13736		    offset;
13737
13738		for (; i < lines; i++) {
13739			offset = i * lineLength;
13740			line = bytes.subarray(offset, offset + lineLength);
13741
13742			if (filter_method) {
13743				result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
13744			} else {
13745
13746				var j = 0,
13747				    len = filter_methods.length,
13748				    results = [];
13749
13750				for (; j < len; j++) {
13751					results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
13752				}var ind = getIndexOfSmallestSum(results.concat());
13753
13754				result.set(results[ind], offset + i);
13755			}
13756
13757			prevLine = line;
13758		}
13759
13760		return result;
13761	},
13762	    filterNone = function filterNone(line, colorsPerPixel, prevLine) {
13763		/*var result = new Uint8Array(line.length + 1);
13764  result[0] = 0;
13765  result.set(line, 1);*/
13766
13767		var result = Array.apply([], line);
13768		result.unshift(0);
13769
13770		return result;
13771	},
13772	    filterSub = function filterSub(line, colorsPerPixel, prevLine) {
13773		var result = [],
13774		    i = 0,
13775		    len = line.length,
13776		    left;
13777
13778		result[0] = 1;
13779
13780		for (; i < len; i++) {
13781			left = line[i - colorsPerPixel] || 0;
13782			result[i + 1] = line[i] - left + 0x0100 & 0xff;
13783		}
13784
13785		return result;
13786	},
13787	    filterUp = function filterUp(line, colorsPerPixel, prevLine) {
13788		var result = [],
13789		    i = 0,
13790		    len = line.length,
13791		    up;
13792
13793		result[0] = 2;
13794
13795		for (; i < len; i++) {
13796			up = prevLine && prevLine[i] || 0;
13797			result[i + 1] = line[i] - up + 0x0100 & 0xff;
13798		}
13799
13800		return result;
13801	},
13802	    filterAverage = function filterAverage(line, colorsPerPixel, prevLine) {
13803		var result = [],
13804		    i = 0,
13805		    len = line.length,
13806		    left,
13807		    up;
13808
13809		result[0] = 3;
13810
13811		for (; i < len; i++) {
13812			left = line[i - colorsPerPixel] || 0;
13813			up = prevLine && prevLine[i] || 0;
13814			result[i + 1] = line[i] + 0x0100 - (left + up >>> 1) & 0xff;
13815		}
13816
13817		return result;
13818	},
13819	    filterPaeth = function filterPaeth(line, colorsPerPixel, prevLine) {
13820		var result = [],
13821		    i = 0,
13822		    len = line.length,
13823		    left,
13824		    up,
13825		    upLeft,
13826		    paeth;
13827
13828		result[0] = 4;
13829
13830		for (; i < len; i++) {
13831			left = line[i - colorsPerPixel] || 0;
13832			up = prevLine && prevLine[i] || 0;
13833			upLeft = prevLine && prevLine[i - colorsPerPixel] || 0;
13834			paeth = paethPredictor(left, up, upLeft);
13835			result[i + 1] = line[i] - paeth + 0x0100 & 0xff;
13836		}
13837
13838		return result;
13839	},
13840	    paethPredictor = function paethPredictor(left, up, upLeft) {
13841
13842		var p = left + up - upLeft,
13843		    pLeft = Math.abs(p - left),
13844		    pUp = Math.abs(p - up),
13845		    pUpLeft = Math.abs(p - upLeft);
13846
13847		return pLeft <= pUp && pLeft <= pUpLeft ? left : pUp <= pUpLeft ? up : upLeft;
13848	},
13849	    getFilterMethods = function getFilterMethods() {
13850		return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
13851	},
13852	    getIndexOfSmallestSum = function getIndexOfSmallestSum(arrays) {
13853		var i = 0,
13854		    len = arrays.length,
13855		    sum,
13856		    min,
13857		    ind;
13858
13859		while (i < len) {
13860			sum = absSum(arrays[i].slice(1));
13861
13862			if (sum < min || !min) {
13863				min = sum;
13864				ind = i;
13865			}
13866
13867			i++;
13868		}
13869
13870		return ind;
13871	},
13872	    absSum = function absSum(array) {
13873		var i = 0,
13874		    len = array.length,
13875		    sum = 0;
13876
13877		while (i < len) {
13878			sum += Math.abs(array[i++]);
13879		}return sum;
13880	},
13881	    getPredictorFromCompression = function getPredictorFromCompression(compression) {
13882		var predictor;
13883		switch (compression) {
13884			case jsPDFAPI.image_compression.FAST:
13885				predictor = 11;
13886				break;
13887
13888			case jsPDFAPI.image_compression.MEDIUM:
13889				predictor = 13;
13890				break;
13891
13892			case jsPDFAPI.image_compression.SLOW:
13893				predictor = 14;
13894				break;
13895
13896			default:
13897				predictor = 12;
13898				break;
13899		}
13900		return predictor;
13901	};
13902
13903	jsPDFAPI.processPNG = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
13904		'use strict';
13905
13906		var colorSpace = this.color_spaces.DEVICE_RGB,
13907		    decode = this.decode.FLATE_DECODE,
13908		    bpc = 8,
13909		    img,
13910		    dp,
13911		    trns,
13912		    colors,
13913		    pal,
13914		    smask;
13915
13916		/*	if(this.isString(imageData)) {
13917  		}*/
13918
13919		if (this.isArrayBuffer(imageData)) imageData = new Uint8Array(imageData);
13920
13921		if (this.isArrayBufferView(imageData)) {
13922
13923			if (doesNotHavePngJS()) throw new Error("PNG support requires png.js and zlib.js");
13924
13925			img = new PNG(imageData);
13926			imageData = img.imgData;
13927			bpc = img.bits;
13928			colorSpace = img.colorSpace;
13929			colors = img.colors;
13930
13931			//logImg(img);
13932
13933			/*
13934    * colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.
13935    *
13936    * colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.
13937    *
13938    * Extract alpha to create two separate images, using the alpha as a sMask
13939    */
13940			if ([4, 6].indexOf(img.colorType) !== -1) {
13941
13942				/*
13943     * processes 8 bit RGBA and grayscale + alpha images
13944     */
13945				if (img.bits === 8) {
13946
13947					var pixels = img.pixelBitlength == 32 ? new Uint32Array(img.decodePixels().buffer) : img.pixelBitlength == 16 ? new Uint16Array(img.decodePixels().buffer) : new Uint8Array(img.decodePixels().buffer),
13948					    len = pixels.length,
13949					    imgData = new Uint8Array(len * img.colors),
13950					    alphaData = new Uint8Array(len),
13951					    pDiff = img.pixelBitlength - img.bits,
13952					    i = 0,
13953					    n = 0,
13954					    pixel,
13955					    pbl;
13956
13957					for (; i < len; i++) {
13958						pixel = pixels[i];
13959						pbl = 0;
13960
13961						while (pbl < pDiff) {
13962
13963							imgData[n++] = pixel >>> pbl & 0xff;
13964							pbl = pbl + img.bits;
13965						}
13966
13967						alphaData[i] = pixel >>> pbl & 0xff;
13968					}
13969				}
13970
13971				/*
13972     * processes 16 bit RGBA and grayscale + alpha images
13973     */
13974				if (img.bits === 16) {
13975
13976					var pixels = new Uint32Array(img.decodePixels().buffer),
13977					    len = pixels.length,
13978					    imgData = new Uint8Array(len * (32 / img.pixelBitlength) * img.colors),
13979					    alphaData = new Uint8Array(len * (32 / img.pixelBitlength)),
13980					    hasColors = img.colors > 1,
13981					    i = 0,
13982					    n = 0,
13983					    a = 0,
13984					    pixel;
13985
13986					while (i < len) {
13987						pixel = pixels[i++];
13988
13989						imgData[n++] = pixel >>> 0 & 0xFF;
13990
13991						if (hasColors) {
13992							imgData[n++] = pixel >>> 16 & 0xFF;
13993
13994							pixel = pixels[i++];
13995							imgData[n++] = pixel >>> 0 & 0xFF;
13996						}
13997
13998						alphaData[a++] = pixel >>> 16 & 0xFF;
13999					}
14000
14001					bpc = 8;
14002				}
14003
14004				if (canCompress(compression)) {
14005
14006					imageData = compressBytes(imgData, img.width * img.colors, img.colors, compression);
14007					smask = compressBytes(alphaData, img.width, 1, compression);
14008				} else {
14009
14010					imageData = imgData;
14011					smask = alphaData;
14012					decode = null;
14013				}
14014			}
14015
14016			/*
14017    * Indexed png. Each pixel is a palette index.
14018    */
14019			if (img.colorType === 3) {
14020
14021				colorSpace = this.color_spaces.INDEXED;
14022				pal = img.palette;
14023
14024				if (img.transparency.indexed) {
14025
14026					var trans = img.transparency.indexed;
14027
14028					var total = 0,
14029					    i = 0,
14030					    len = trans.length;
14031
14032					for (; i < len; ++i) {
14033						total += trans[i];
14034					}total = total / 255;
14035
14036					/*
14037      * a single color is specified as 100% transparent (0),
14038      * so we set trns to use a /Mask with that index
14039      */
14040					if (total === len - 1 && trans.indexOf(0) !== -1) {
14041						trns = [trans.indexOf(0)];
14042
14043						/*
14044       * there's more than one colour within the palette that specifies
14045       * a transparency value less than 255, so we unroll the pixels to create an image sMask
14046       */
14047					} else if (total !== len) {
14048
14049						var pixels = img.decodePixels(),
14050						    alphaData = new Uint8Array(pixels.length),
14051						    i = 0,
14052						    len = pixels.length;
14053
14054						for (; i < len; i++) {
14055							alphaData[i] = trans[pixels[i]];
14056						}smask = compressBytes(alphaData, img.width, 1);
14057					}
14058				}
14059			}
14060
14061			var predictor = getPredictorFromCompression(compression);
14062
14063			if (decode === this.decode.FLATE_DECODE) dp = '/Predictor ' + predictor + ' /Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;else
14064				//remove 'Predictor' as it applies to the type of png filter applied to its IDAT - we only apply with compression
14065				dp = '/Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;
14066
14067			if (this.isArrayBuffer(imageData) || this.isArrayBufferView(imageData)) imageData = this.arrayBufferToBinaryString(imageData);
14068
14069			if (smask && this.isArrayBuffer(smask) || this.isArrayBufferView(smask)) smask = this.arrayBufferToBinaryString(smask);
14070
14071			return this.createImageInfo(imageData, img.width, img.height, colorSpace, bpc, decode, imageIndex, alias, dp, trns, pal, smask, predictor);
14072		}
14073
14074		throw new Error("Unsupported PNG image data, try using JPEG instead.");
14075	};
14076})(jsPDF.API);
14077
14078/**
14079 * jsPDF Autoprint Plugin
14080 *
14081 * Licensed under the MIT License.
14082 * http://opensource.org/licenses/mit-license
14083 */
14084
14085(function (jsPDFAPI) {
14086  'use strict';
14087
14088  jsPDFAPI.autoPrint = function () {
14089    'use strict';
14090
14091    var refAutoPrintTag;
14092
14093    this.internal.events.subscribe('postPutResources', function () {
14094      refAutoPrintTag = this.internal.newObject();
14095      this.internal.write("<< /S/Named /Type/Action /N/Print >>", "endobj");
14096    });
14097
14098    this.internal.events.subscribe("putCatalog", function () {
14099      this.internal.write("/OpenAction " + refAutoPrintTag + " 0" + " R");
14100    });
14101    return this;
14102  };
14103})(jsPDF.API);
14104
14105/** @preserve
14106 * jsPDF split_text_to_size plugin - MIT license.
14107 * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
14108 *               2014 Diego Casorran, https://github.com/diegocr
14109 */
14110/**
14111 * 
14112 * ====================================================================
14113 */
14114
14115(function (API) {
14116	'use strict';
14117
14118	/**
14119 Returns an array of length matching length of the 'word' string, with each
14120 cell ocupied by the width of the char in that position.
14121 
14122 @function
14123 @param word {String}
14124 @param widths {Object}
14125 @param kerning {Object}
14126 @returns {Array}
14127 */
14128
14129	var getCharWidthsArray = API.getCharWidthsArray = function (text, options) {
14130
14131		if (!options) {
14132			options = {};
14133		}
14134
14135		var widths = options.widths ? options.widths : this.internal.getFont().metadata.Unicode.widths,
14136		    widthsFractionOf = widths.fof ? widths.fof : 1,
14137		    kerning = options.kerning ? options.kerning : this.internal.getFont().metadata.Unicode.kerning,
14138		    kerningFractionOf = kerning.fof ? kerning.fof : 1;
14139
14140		// console.log("widths, kergnings", widths, kerning)
14141
14142		var i,
14143		    l,
14144		    char_code,
14145		    prior_char_code = 0 // for kerning
14146		,
14147		    default_char_width = widths[0] || widthsFractionOf,
14148		    output = [];
14149
14150		for (i = 0, l = text.length; i < l; i++) {
14151			char_code = text.charCodeAt(i);
14152			output.push((widths[char_code] || default_char_width) / widthsFractionOf + (kerning[char_code] && kerning[char_code][prior_char_code] || 0) / kerningFractionOf);
14153			prior_char_code = char_code;
14154		}
14155
14156		return output;
14157	};
14158	var getArraySum = function getArraySum(array) {
14159		var i = array.length,
14160		    output = 0;
14161		while (i) {
14162			i--;
14163			output += array[i];
14164		}
14165		return output;
14166	};
14167	/**
14168 Returns a widths of string in a given font, if the font size is set as 1 point.
14169 
14170 In other words, this is "proportional" value. For 1 unit of font size, the length
14171 of the string will be that much.
14172 
14173 Multiply by font size to get actual width in *points*
14174 Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
14175 
14176 @public
14177 @function
14178 @param
14179 @returns {Type}
14180 */
14181	var getStringUnitWidth = API.getStringUnitWidth = function (text, options) {
14182		return getArraySum(getCharWidthsArray.call(this, text, options));
14183	};
14184
14185	/**
14186 returns array of lines
14187 */
14188	var splitLongWord = function splitLongWord(word, widths_array, firstLineMaxLen, maxLen) {
14189		var answer = [];
14190
14191		// 1st, chop off the piece that can fit on the hanging line.
14192		var i = 0,
14193		    l = word.length,
14194		    workingLen = 0;
14195		while (i !== l && workingLen + widths_array[i] < firstLineMaxLen) {
14196			workingLen += widths_array[i];i++;
14197		}
14198		// this is first line.
14199		answer.push(word.slice(0, i));
14200
14201		// 2nd. Split the rest into maxLen pieces.
14202		var startOfLine = i;
14203		workingLen = 0;
14204		while (i !== l) {
14205			if (workingLen + widths_array[i] > maxLen) {
14206				answer.push(word.slice(startOfLine, i));
14207				workingLen = 0;
14208				startOfLine = i;
14209			}
14210			workingLen += widths_array[i];i++;
14211		}
14212		if (startOfLine !== i) {
14213			answer.push(word.slice(startOfLine, i));
14214		}
14215
14216		return answer;
14217	};
14218
14219	// Note, all sizing inputs for this function must be in "font measurement units"
14220	// By default, for PDF, it's "point".
14221	var splitParagraphIntoLines = function splitParagraphIntoLines(text, maxlen, options) {
14222		// at this time works only on Western scripts, ones with space char
14223		// separating the words. Feel free to expand.
14224
14225		if (!options) {
14226			options = {};
14227		}
14228
14229		var line = [],
14230		    lines = [line],
14231		    line_length = options.textIndent || 0,
14232		    separator_length = 0,
14233		    current_word_length = 0,
14234		    word,
14235		    widths_array,
14236		    words = text.split(' '),
14237		    spaceCharWidth = getCharWidthsArray(' ', options)[0],
14238		    i,
14239		    l,
14240		    tmp,
14241		    lineIndent;
14242
14243		if (options.lineIndent === -1) {
14244			lineIndent = words[0].length + 2;
14245		} else {
14246			lineIndent = options.lineIndent || 0;
14247		}
14248		if (lineIndent) {
14249			var pad = Array(lineIndent).join(" "),
14250			    wrds = [];
14251			words.map(function (wrd) {
14252				wrd = wrd.split(/\s*\n/);
14253				if (wrd.length > 1) {
14254					wrds = wrds.concat(wrd.map(function (wrd, idx) {
14255						return (idx && wrd.length ? "\n" : "") + wrd;
14256					}));
14257				} else {
14258					wrds.push(wrd[0]);
14259				}
14260			});
14261			words = wrds;
14262			lineIndent = getStringUnitWidth(pad, options);
14263		}
14264
14265		for (i = 0, l = words.length; i < l; i++) {
14266			var force = 0;
14267
14268			word = words[i];
14269			if (lineIndent && word[0] == "\n") {
14270				word = word.substr(1);
14271				force = 1;
14272			}
14273			widths_array = getCharWidthsArray(word, options);
14274			current_word_length = getArraySum(widths_array);
14275
14276			if (line_length + separator_length + current_word_length > maxlen || force) {
14277				if (current_word_length > maxlen) {
14278					// this happens when you have space-less long URLs for example.
14279					// we just chop these to size. We do NOT insert hiphens
14280					tmp = splitLongWord(word, widths_array, maxlen - (line_length + separator_length), maxlen);
14281					// first line we add to existing line object
14282					line.push(tmp.shift()); // it's ok to have extra space indicator there
14283					// last line we make into new line object
14284					line = [tmp.pop()];
14285					// lines in the middle we apped to lines object as whole lines
14286					while (tmp.length) {
14287						lines.push([tmp.shift()]); // single fragment occupies whole line
14288					}
14289					current_word_length = getArraySum(widths_array.slice(word.length - line[0].length));
14290				} else {
14291					// just put it on a new line
14292					line = [word];
14293				}
14294
14295				// now we attach new line to lines
14296				lines.push(line);
14297				line_length = current_word_length + lineIndent;
14298				separator_length = spaceCharWidth;
14299			} else {
14300				line.push(word);
14301
14302				line_length += separator_length + current_word_length;
14303				separator_length = spaceCharWidth;
14304			}
14305		}
14306
14307		if (lineIndent) {
14308			var postProcess = function postProcess(ln, idx) {
14309				return (idx ? pad : '') + ln.join(" ");
14310			};
14311		} else {
14312			var postProcess = function postProcess(ln) {
14313				return ln.join(" ");
14314			};
14315		}
14316
14317		return lines.map(postProcess);
14318	};
14319
14320	/**
14321 Splits a given string into an array of strings. Uses 'size' value
14322 (in measurement units declared as default for the jsPDF instance)
14323 and the font's "widths" and "Kerning" tables, where available, to
14324 determine display length of a given string for a given font.
14325 
14326 We use character's 100% of unit size (height) as width when Width
14327 table or other default width is not available.
14328 
14329 @public
14330 @function
14331 @param text {String} Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
14332 @param size {Number} Nominal number, measured in units default to this instance of jsPDF.
14333 @param options {Object} Optional flags needed for chopper to do the right thing.
14334 @returns {Array} with strings chopped to size.
14335 */
14336	API.splitTextToSize = function (text, maxlen, options) {
14337		'use strict';
14338
14339		if (!options) {
14340			options = {};
14341		}
14342
14343		var fsize = options.fontSize || this.internal.getFontSize(),
14344		    newOptions = function (options) {
14345			var widths = { 0: 1 },
14346			    kerning = {};
14347
14348			if (!options.widths || !options.kerning) {
14349				var f = this.internal.getFont(options.fontName, options.fontStyle),
14350				    encoding = 'Unicode';
14351				// NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
14352				// Actual JavaScript-native String's 16bit char codes used.
14353				// no multi-byte logic here
14354
14355				if (f.metadata[encoding]) {
14356					return {
14357						widths: f.metadata[encoding].widths || widths,
14358						kerning: f.metadata[encoding].kerning || kerning
14359					};
14360				}
14361			} else {
14362				return {
14363					widths: options.widths,
14364					kerning: options.kerning
14365				};
14366			}
14367
14368			// then use default values
14369			return {
14370				widths: widths,
14371				kerning: kerning
14372			};
14373		}.call(this, options);
14374
14375		// first we split on end-of-line chars
14376		var paragraphs;
14377		if (Array.isArray(text)) {
14378			paragraphs = text;
14379		} else {
14380			paragraphs = text.split(/\r?\n/);
14381		}
14382
14383		// now we convert size (max length of line) into "font size units"
14384		// at present time, the "font size unit" is always 'point'
14385		// 'proportional' means, "in proportion to font size"
14386		var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize;
14387		// at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
14388		// this may change in the future?
14389		// until then, proportional_maxlen is likely to be in 'points'
14390
14391		// If first line is to be indented (shorter or longer) than maxLen
14392		// we indicate that by using CSS-style "text-indent" option.
14393		// here it's in font units too (which is likely 'points')
14394		// it can be negative (which makes the first line longer than maxLen)
14395		newOptions.textIndent = options.textIndent ? options.textIndent * 1.0 * this.internal.scaleFactor / fsize : 0;
14396		newOptions.lineIndent = options.lineIndent;
14397
14398		var i,
14399		    l,
14400		    output = [];
14401		for (i = 0, l = paragraphs.length; i < l; i++) {
14402			output = output.concat(splitParagraphIntoLines(paragraphs[i], fontUnit_maxLen, newOptions));
14403		}
14404
14405		return output;
14406	};
14407})(jsPDF.API);
14408
14409/** @preserve 
14410jsPDF standard_fonts_metrics plugin
14411Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
14412MIT license.
14413*/
14414/**
14415 * 
14416 * ====================================================================
14417 */
14418
14419(function (API) {
14420	'use strict';
14421
14422	/*
14423 # reference (Python) versions of 'compress' and 'uncompress'
14424 # only 'uncompress' function is featured lower as JavaScript
14425 # if you want to unit test "roundtrip", just transcribe the reference
14426 # 'compress' function from Python into JavaScript
14427 
14428 def compress(data):
14429 
14430 	keys =   '0123456789abcdef'
14431 	values = 'klmnopqrstuvwxyz'
14432 	mapping = dict(zip(keys, values))
14433 	vals = []
14434 	for key in data.keys():
14435 		value = data[key]
14436 		try:
14437 			keystring = hex(key)[2:]
14438 			keystring = keystring[:-1] + mapping[keystring[-1:]]
14439 		except:
14440 			keystring = key.join(["'","'"])
14441 			#print('Keystring is %s' % keystring)
14442 
14443 		try:
14444 			if value < 0:
14445 				valuestring = hex(value)[3:]
14446 				numberprefix = '-'
14447 			else:
14448 				valuestring = hex(value)[2:]
14449 				numberprefix = ''
14450 			valuestring = numberprefix + valuestring[:-1] + mapping[valuestring[-1:]]
14451 		except:
14452 			if type(value) == dict:
14453 				valuestring = compress(value)
14454 			else:
14455 				raise Exception("Don't know what to do with value type %s" % type(value))
14456 
14457 		vals.append(keystring+valuestring)
14458 	
14459 	return '{' + ''.join(vals) + '}'
14460 
14461 def uncompress(data):
14462 
14463 	decoded = '0123456789abcdef'
14464 	encoded = 'klmnopqrstuvwxyz'
14465 	mapping = dict(zip(encoded, decoded))
14466 
14467 	sign = +1
14468 	stringmode = False
14469 	stringparts = []
14470 
14471 	output = {}
14472 
14473 	activeobject = output
14474 	parentchain = []
14475 
14476 	keyparts = ''
14477 	valueparts = ''
14478 
14479 	key = None
14480 
14481 	ending = set(encoded)
14482 
14483 	i = 1
14484 	l = len(data) - 1 # stripping starting, ending {}
14485 	while i != l: # stripping {}
14486 		# -, {, }, ' are special.
14487 
14488 		ch = data[i]
14489 		i += 1
14490 
14491 		if ch == "'":
14492 			if stringmode:
14493 				# end of string mode
14494 				stringmode = False
14495 				key = ''.join(stringparts)
14496 			else:
14497 				# start of string mode
14498 				stringmode = True
14499 				stringparts = []
14500 		elif stringmode == True:
14501 			#print("Adding %s to stringpart" % ch)
14502 			stringparts.append(ch)
14503 
14504 		elif ch == '{':
14505 			# start of object
14506 			parentchain.append( [activeobject, key] )
14507 			activeobject = {}
14508 			key = None
14509 			#DEBUG = True
14510 		elif ch == '}':
14511 			# end of object
14512 			parent, key = parentchain.pop()
14513 			parent[key] = activeobject
14514 			key = None
14515 			activeobject = parent
14516 			#DEBUG = False
14517 
14518 		elif ch == '-':
14519 			sign = -1
14520 		else:
14521 			# must be number
14522 			if key == None:
14523 				#debug("In Key. It is '%s', ch is '%s'" % (keyparts, ch))
14524 				if ch in ending:
14525 					#debug("End of key")
14526 					keyparts += mapping[ch]
14527 					key = int(keyparts, 16) * sign
14528 					sign = +1
14529 					keyparts = ''
14530 				else:
14531 					keyparts += ch
14532 			else:
14533 				#debug("In value. It is '%s', ch is '%s'" % (valueparts, ch))
14534 				if ch in ending:
14535 					#debug("End of value")
14536 					valueparts += mapping[ch]
14537 					activeobject[key] = int(valueparts, 16) * sign
14538 					sign = +1
14539 					key = None
14540 					valueparts = ''
14541 				else:
14542 					valueparts += ch
14543 
14544 			#debug(activeobject)
14545 
14546 	return output
14547 
14548 */
14549
14550	/**
14551 Uncompresses data compressed into custom, base16-like format. 
14552 @public
14553 @function
14554 @param
14555 @returns {Type}
14556 */
14557
14558	var uncompress = function uncompress(data) {
14559
14560		var decoded = '0123456789abcdef',
14561		    encoded = 'klmnopqrstuvwxyz',
14562		    mapping = {};
14563
14564		for (var i = 0; i < encoded.length; i++) {
14565			mapping[encoded[i]] = decoded[i];
14566		}
14567
14568		var undef,
14569		    output = {},
14570		    sign = 1,
14571		    stringparts // undef. will be [] in string mode
14572
14573		,
14574		    activeobject = output,
14575		    parentchain = [],
14576		    parent_key_pair,
14577		    keyparts = '',
14578		    valueparts = '',
14579		    key // undef. will be Truthy when Key is resolved.
14580		,
14581		    datalen = data.length - 1 // stripping ending }
14582		,
14583		    ch;
14584
14585		i = 1; // stripping starting {
14586
14587		while (i != datalen) {
14588			// - { } ' are special.
14589
14590			ch = data[i];
14591			i += 1;
14592
14593			if (ch == "'") {
14594				if (stringparts) {
14595					// end of string mode
14596					key = stringparts.join('');
14597					stringparts = undef;
14598				} else {
14599					// start of string mode
14600					stringparts = [];
14601				}
14602			} else if (stringparts) {
14603				stringparts.push(ch);
14604			} else if (ch == '{') {
14605				// start of object
14606				parentchain.push([activeobject, key]);
14607				activeobject = {};
14608				key = undef;
14609			} else if (ch == '}') {
14610				// end of object
14611				parent_key_pair = parentchain.pop();
14612				parent_key_pair[0][parent_key_pair[1]] = activeobject;
14613				key = undef;
14614				activeobject = parent_key_pair[0];
14615			} else if (ch == '-') {
14616				sign = -1;
14617			} else {
14618				// must be number
14619				if (key === undef) {
14620					if (mapping.hasOwnProperty(ch)) {
14621						keyparts += mapping[ch];
14622						key = parseInt(keyparts, 16) * sign;
14623						sign = +1;
14624						keyparts = '';
14625					} else {
14626						keyparts += ch;
14627					}
14628				} else {
14629					if (mapping.hasOwnProperty(ch)) {
14630						valueparts += mapping[ch];
14631						activeobject[key] = parseInt(valueparts, 16) * sign;
14632						sign = +1;
14633						key = undef;
14634						valueparts = '';
14635					} else {
14636						valueparts += ch;
14637					}
14638				}
14639			}
14640		} // end while
14641
14642		return output;
14643	};
14644
14645	// encoding = 'Unicode' 
14646	// NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior
14647	// Actual 16bit char codes used.
14648	// no multi-byte logic here
14649
14650	// Unicode characters to WinAnsiEncoding:
14651	// {402: 131, 8211: 150, 8212: 151, 8216: 145, 8217: 146, 8218: 130, 8220: 147, 8221: 148, 8222: 132, 8224: 134, 8225: 135, 8226: 149, 8230: 133, 8364: 128, 8240:137, 8249: 139, 8250: 155, 710: 136, 8482: 153, 338: 140, 339: 156, 732: 152, 352: 138, 353: 154, 376: 159, 381: 142, 382: 158}
14652	// as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.
14653	// this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly
14654	// as well as give strings with some (supported by these fonts) Unicode characters and 
14655	// these will be mapped to win cp1252 
14656	// for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.
14657
14658	var encodingBlock = {
14659		'codePages': ['WinAnsiEncoding'],
14660		'WinAnsiEncoding': uncompress("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")
14661	},
14662	    encodings = { 'Unicode': {
14663			'Courier': encodingBlock,
14664			'Courier-Bold': encodingBlock,
14665			'Courier-BoldOblique': encodingBlock,
14666			'Courier-Oblique': encodingBlock,
14667			'Helvetica': encodingBlock,
14668			'Helvetica-Bold': encodingBlock,
14669			'Helvetica-BoldOblique': encodingBlock,
14670			'Helvetica-Oblique': encodingBlock,
14671			'Times-Roman': encodingBlock,
14672			'Times-Bold': encodingBlock,
14673			'Times-BoldItalic': encodingBlock,
14674			'Times-Italic': encodingBlock
14675			//	, 'Symbol'
14676			//	, 'ZapfDingbats'
14677		}
14678		/** 
14679  Resources:
14680  Font metrics data is reprocessed derivative of contents of
14681  "Font Metrics for PDF Core 14 Fonts" package, which exhibits the following copyright and license:
14682  
14683  Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
14684  
14685  This file and the 14 PostScript(R) AFM files it accompanies may be used,
14686  copied, and distributed for any purpose and without charge, with or without
14687  modification, provided that all copyright notices are retained; that the AFM
14688  files are not distributed without this file; that all modifications to this
14689  file or any of the AFM files are prominently noted in the modified file(s);
14690  and that this paragraph is not modified. Adobe Systems has no responsibility
14691  or obligation to support the use of the AFM files.
14692  
14693  */
14694	},
14695	    fontMetrics = { 'Unicode': {
14696			// all sizing numbers are n/fontMetricsFractionOf = one font size unit
14697			// this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's
14698			// width is 476/1000 or 47.6% of its height (regardless of font size)
14699			// At this time this value applies to "widths" and "kerning" numbers.
14700
14701			// char code 0 represents "default" (average) width - use it for chars missing in this table.
14702			// key 'fof' represents the "fontMetricsFractionOf" value
14703
14704			'Courier-Oblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
14705			'Times-BoldItalic': uncompress("{'widths'{k3o2q4ycx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2r202m2n2n3m2o3m2p5n202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5n4l4m4m4m4n4m4o4s4p4m4q4m4r4s4s4y4t2r4u3m4v4m4w3x4x5t4y4s4z4s5k3x5l4s5m4m5n3r5o3x5p4s5q4m5r5t5s4m5t3x5u3x5v2l5w1w5x2l5y3t5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q2l6r3m6s3r6t1w6u1w6v3m6w1w6x4y6y3r6z3m7k3m7l3m7m2r7n2r7o1w7p3r7q2w7r4m7s3m7t2w7u2r7v2n7w1q7x2n7y3t202l3mcl4mal2ram3man3mao3map3mar3mas2lat4uau1uav3maw3way4uaz2lbk2sbl3t'fof'6obo2lbp3tbq3mbr1tbs2lbu1ybv3mbz3mck4m202k3mcm4mcn4mco4mcp4mcq5ycr4mcs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz2w203k6o212m6o2dw2l2cq2l3t3m3u2l17s3x19m3m}'kerning'{cl{4qu5kt5qt5rs17ss5ts}201s{201ss}201t{cks4lscmscnscoscpscls2wu2yu201ts}201x{2wu2yu}2k{201ts}2w{4qx5kx5ou5qx5rs17su5tu}2x{17su5tu5ou}2y{4qx5kx5ou5qx5rs17ss5ts}'fof'-6ofn{17sw5tw5ou5qw5rs}7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qs}3v{17su5tu5os5qs}7p{17su5tu}ck{4qu5kt5qt5rs17ss5ts}4l{4qu5kt5qt5rs17ss5ts}cm{4qu5kt5qt5rs17ss5ts}cn{4qu5kt5qt5rs17ss5ts}co{4qu5kt5qt5rs17ss5ts}cp{4qu5kt5qt5rs17ss5ts}6l{4qu5ou5qw5rt17su5tu}5q{ckuclucmucnucoucpu4lu}5r{ckuclucmucnucoucpu4lu}7q{cksclscmscnscoscps4ls}6p{4qu5ou5qw5rt17sw5tw}ek{4qu5ou5qw5rt17su5tu}el{4qu5ou5qw5rt17su5tu}em{4qu5ou5qw5rt17su5tu}en{4qu5ou5qw5rt17su5tu}eo{4qu5ou5qw5rt17su5tu}ep{4qu5ou5qw5rt17su5tu}es{17ss5ts5qs4qu}et{4qu5ou5qw5rt17sw5tw}eu{4qu5ou5qw5rt17ss5ts}ev{17ss5ts5qs4qu}6z{17sw5tw5ou5qw5rs}fm{17sw5tw5ou5qw5rs}7n{201ts}fo{17sw5tw5ou5qw5rs}fp{17sw5tw5ou5qw5rs}fq{17sw5tw5ou5qw5rs}7r{cksclscmscnscoscps4ls}fs{17sw5tw5ou5qw5rs}ft{17su5tu}fu{17su5tu}fv{17su5tu}fw{17su5tu}fz{cksclscmscnscoscps4ls}}}"),
14706			'Helvetica-Bold': uncompress("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4y
14706dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"),
14707			'Courier': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
14708			'Courier-BoldOblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
14709			'Times-Bold': uncompress("{'widths'{k3q2q5ncx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2l202m2n2n3m2o3m2p6o202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5x4l4s4m4m4n4s4o4s4p4m4q3x4r4y4s4y4t2r4u3m4v4y4w4m4x5y4y4s4z4y5k3x5l4y5m4s5n3r5o4m5p4s5q4s5r6o5s4s5t4s5u4m5v2l5w1w5x2l5y3u5z3m6k2l6l3m6m3r6n2w6o3r6p2w6q2l6r3m6s3r6t1w6u2l6v3r6w1w6x5n6y3r6z3m7k3r7l3r7m2w7n2r7o2l7p3r7q3m7r4s7s3m7t3m7u2w7v2r7w1q7x2r7y3o202l3mcl4sal2lam3man3mao3map3mar3mas2lat4uau1yav3maw3tay4uaz2lbk2sbl3t'fof'6obo2lbp3rbr1tbs2lbu2lbv3mbz3mck4s202k3mcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3rek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3m3u2l17s4s19m3m}'kerning'{cl{4qt5ks5ot5qy5rw17sv5tv}201t{cks4lscmscnscoscpscls4wv}2k{201ts}2w{4qu5ku7mu5os5qx5ru17su5tu}2x{17su5tu5ou5qs}2y{4qv5kv7mu5ot5qz5ru17su5tu}'fof'-6o7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qu}3v{17su5tu5os5qu}fu{17su5tu5ou5qu}7p{17su5tu5ou5qu}ck{4qt5ks5ot5qy5rw17sv5tv}4l{4qt5ks5ot5qy5rw17sv5tv}cm{4qt5ks5ot5qy5rw17sv5tv}cn{4qt5ks5ot5qy5rw17sv5tv}co{4qt5ks5ot5qy5rw17sv5tv}cp{4qt5ks5ot5qy5rw17sv5tv}6l{17st5tt5ou5qu}17s{ckuclucmucnucoucpu4lu4wu}5o{ckuclucmucnucoucpu4lu4wu}5q{ckzclzcmzcnzcozcpz4lz4wu}5r{ckxclxcmxcnxcoxcpx4lx4wu}5t{ckuclucmucnucoucpu4lu4wu}7q{ckuclucmucnucoucpu4lu}6p{17sw5tw5ou5qu}ek{17st5tt5qu}el{17st5tt5ou5qu}em{17st5tt5qu}en{17st5tt5qu}eo{17st5tt5qu}ep{17st5tt5ou5qu}es{17ss5ts5qu}et{17sw5tw5ou5qu}eu{17sw5tw5ou5qu}ev{17ss5ts5qu}6z{17sw5tw5ou5qu5rs}fm{17sw5tw5ou5qu5rs}fn{17sw5tw5ou5qu5rs}fo{17sw5tw5ou5qu5rs}fp{17sw5tw5ou5qu5rs}fq{17sw5tw5ou5qu5rs}7r{cktcltcmtcntcotcpt4lt5os}fs{17sw5tw5ou5qu5rs}ft{17su5tu5ou5qu}7m{5os}fv{17su5tu5ou5qu}fw{17su5tu5ou5qu}fz{cksclscmscnscoscps4ls}}}")
14710			//, 'Symbol': uncompress("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}")
14711			, 'Helvetica': uncompress("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4y
14711dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}"),
14712			'Helvetica-BoldOblique': uncompress("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4y
14712dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}")
14713			//, 'ZapfDingbats': uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}")
14714			, 'Courier-Bold': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
14715			'Times-Italic': uncompress("{'widths'{k3n2q4ycx2l201n3m201o5t201s2l201t2l201u2l201w3r201x3r201y3r2k1t2l2l202m2n2n3m2o3m2p5n202q5t2r1p2s2l2t2l2u3m2v4n2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w4n3x4n3y4n3z3m4k5w4l3x4m3x4n4m4o4s4p3x4q3x4r4s4s4s4t2l4u2w4v4m4w3r4x5n4y4m4z4s5k3x5l4s5m3x5n3m5o3r5p4s5q3x5r5n5s3x5t3r5u3r5v2r5w1w5x2r5y2u5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q1w6r3m6s3m6t1w6u1w6v2w6w1w6x4s6y3m6z3m7k3m7l3m7m2r7n2r7o1w7p3m7q2w7r4m7s2w7t2w7u2r7v2s7w1v7x2s7y3q202l3mcl3xal2ram3man3mao3map3mar3mas2lat4wau1vav3maw4nay4waz2lbk2sbl4n'fof'6obo2lbp3mbq3obr1tbs2lbu1zbv3mbz3mck3x202k3mcm3xcn3xco3xcp3xcq5tcr4mcs3xct3xcu3xcv3xcw2l2m2ucy2lcz2ldl4mdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr4nfs3mft3mfu3mfv3mfw3mfz2w203k6o212m6m2dw2l2cq2l3t3m3u2l17s3r19m3m}'kerning'{cl{5kt4qw}201s{201sw}201t{201tw2wy2yy6q-t}201x{2wy2yy}2k{201tw}2w{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}2x{17ss5ts5os}2y{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}'fof'-6o6t{17ss5ts5qs}7t{5os}3v{5qs}7p{17su5tu5qs}ck{5kt4qw}4l{5kt4qw}cm{5kt4qw}cn{5kt4qw}co{5kt4qw}cp{5kt4qw}6l{4qs5ks5ou5qw5ru17su5tu}17s{2ks}5q{ckvclvcmvcnvcovcpv4lv}5r{ckuclucmucnucoucpu4lu}5t{2ks}6p{4qs5ks5ou5qw5ru17su5tu}ek{4qs5ks5ou5qw5ru17su5tu}el{4qs5ks5ou5qw5ru17su5tu}em{4qs5ks5ou5qw5ru17su5tu}en{4qs5ks5ou5qw5ru17su5tu}eo{4qs5ks5ou5qw5ru17su5tu}ep{4qs5ks5ou5qw5ru17su5tu}es{5ks5qs4qs}et{4qs5ks5ou5qw5ru17su5tu}eu{4qs5ks5qw5ru17su5tu}ev{5ks5qs4qs}ex{17ss5ts5qs}6z{4qv5ks5ou5qw5ru17su5tu}fm{4qv5ks5ou5qw5ru17su5tu}fn{4qv5ks5ou5qw5ru17su5tu}fo{4qv5ks5ou5qw5ru17su5tu}fp{4qv5ks5ou5qw5ru17su5tu}fq{4qv5ks5ou5qw5ru17su5tu}7r{5os}fs{4qv5ks5ou5qw5ru17su5tu}ft{17su5tu5qs}fu{17su5tu5qs}
14715fv{17su5tu5qs}fw{17su5tu5qs}}}"),
14716			'Times-Roman': uncompress("{'widths'{k3n2q4ycx2l201n3m201o6o201s2l201t2l201u2l201w2w201x2w201y2w2k1t2l2l202m2n2n3m2o3m2p5n202q6o2r1m2s2l2t2l2u3m2v3s2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v1w3w3s3x3s3y3s3z2w4k5w4l4s4m4m4n4m4o4s4p3x4q3r4r4s4s4s4t2l4u2r4v4s4w3x4x5t4y4s4z4s5k3r5l4s5m4m5n3r5o3x5p4s5q4s5r5y5s4s5t4s5u3x5v2l5w1w5x2l5y2z5z3m6k2l6l2w6m3m6n2w6o3m6p2w6q2l6r3m6s3m6t1w6u1w6v3m6w1w6x4y6y3m6z3m7k3m7l3m7m2l7n2r7o1w7p3m7q3m7r4s7s3m7t3m7u2w7v3k7w1o7x3k7y3q202l3mcl4sal2lam3man3mao3map3mar3mas2lat4wau1vav3maw3say4waz2lbk2sbl3s'fof'6obo2lbp3mbq2xbr1tbs2lbu1zbv3mbz2wck4s202k3mcm4scn4sco4scp4scq5tcr4mcs3xct3xcu3xcv3xcw2l2m2tcy2lcz2ldl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek2wel2wem2wen2weo2wep2weq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr3sfs3mft3mfu3mfv3mfw3mfz3m203k6o212m6m2dw2l2cq2l3t3m3u1w17s4s19m3m}'kerning'{cl{4qs5ku17sw5ou5qy5rw201ss5tw201ws}201s{201ss}201t{ckw4lwcmwcnwcowcpwclw4wu201ts}2k{201ts}2w{4qs5kw5os5qx5ru17sx5tx}2x{17sw5tw5ou5qu}2y{4qs5kw5os5qx5ru17sx5tx}'fof'-6o7t{ckuclucmucnucoucpu4lu5os5rs}3u{17su5tu5qs}3v{17su5tu5qs}7p{17sw5tw5qs}ck{4qs5ku17sw5ou5qy5rw201ss5tw201ws}4l{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cm{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cn{4qs5ku17sw5ou5qy5rw201ss5tw201ws}co{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cp{4qs5ku17sw5ou5qy5rw201ss5tw201ws}6l{17su5tu5os5qw5rs}17s{2ktclvcmvcnvcovcpv4lv4wuckv}5o{ckwclwcmwcnwcowcpw4lw4wu}5q{ckyclycmycnycoycpy4ly4wu5ms}5r{cktcltcmtcntcotcpt4lt4ws}5t{2ktclvcmvcnvcovcpv4lv4wuckv}7q{cksclscmscnscoscps4ls}6p{17su5tu5qw5rs}ek{5qs5rs}el{17su5tu5os5qw5rs}em{17su5tu5os5qs5rs}en{17su5qs5rs}eo{5qs5rs}ep{17su5tu5os5qw5rs}es{5qs}et{17su5tu5qw5rs}eu{17su5tu5qs5rs}ev{5qs}6z{17sv5tv5os5qx5rs}fm{5os5qt5rs}fn{17sv5tv5os5qx5rs}fo{17sv5tv5os5qx5rs}fp{5os5qt5rs}fq{5os5qt5rs}7r{ckuclucmucnucoucpu4lu5os}fs{17sv5tv5os5qx5rs}ft{17ss5ts5qs}fu{17sw5tw5qs}fv{17sw5tw5qs}fw{17ss5ts5qs}fz{ckuclucmucnucoucpu4lu5os5rs}}}"),
14717			'Helvetica-Oblique': uncompress("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4y
14717dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}")
14718		} };
14719
14720	/*
14721 This event handler is fired when a new jsPDF object is initialized
14722 This event handler appends metrics data to standard fonts within
14723 that jsPDF instance. The metrics are mapped over Unicode character
14724 codes, NOT CIDs or other codes matching the StandardEncoding table of the
14725 standard PDF fonts.
14726 Future:
14727 Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)
14728 char codes to StandardEncoding character codes. The encoding table is to be used
14729 somewhere around "pdfEscape" call.
14730 */
14731
14732	API.events.push(['addFont', function (font) {
14733		var metrics,
14734		    unicode_section,
14735		    encoding = 'Unicode',
14736		    encodingBlock;
14737
14738		metrics = fontMetrics[encoding][font.PostScriptName];
14739		if (metrics) {
14740			if (font.metadata[encoding]) {
14741				unicode_section = font.metadata[encoding];
14742			} else {
14743				unicode_section = font.metadata[encoding] = {};
14744			}
14745
14746			unicode_section.widths = metrics.widths;
14747			unicode_section.kerning = metrics.kerning;
14748		}
14749
14750		encodingBlock = encodings[encoding][font.PostScriptName];
14751		if (encodingBlock) {
14752			if (font.metadata[encoding]) {
14753				unicode_section = font.metadata[encoding];
14754			} else {
14755				unicode_section = font.metadata[encoding] = {};
14756			}
14757
14758			unicode_section.encoding = encodingBlock;
14759			if (encodingBlock.codePages && encodingBlock.codePages.length) {
14760				font.encoding = encodingBlock.codePages[0];
14761			}
14762		}
14763	}]); // end of adding event handler
14764})(jsPDF.API);
14765
14766/** @preserve
14767jsPDF SVG plugin
14768Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
14769*/
14770/**
14771 * 
14772 * ====================================================================
14773 */
14774
14775(function (jsPDFAPI) {
14776	'use strict';
14777
14778	/**
14779 Parses SVG XML and converts only some of the SVG elements into
14780 PDF elements.
14781 
14782 Supports:
14783  paths
14784 
14785 @public
14786 @function
14787 @param
14788 @returns {Type}
14789 */
14790
14791	jsPDFAPI.addSVG = function (svgtext, x, y, w, h) {
14792		// 'this' is _jsPDF object returned when jsPDF is inited (new jsPDF())
14793
14794		var undef;
14795
14796		if (x === undef || y === undef) {
14797			throw new Error("addSVG needs values for 'x' and 'y'");
14798		}
14799
14800		function InjectCSS(cssbody, document) {
14801			var styletag = document.createElement('style');
14802			styletag.type = 'text/css';
14803			if (styletag.styleSheet) {
14804				// ie
14805				styletag.styleSheet.cssText = cssbody;
14806			} else {
14807				// others
14808				styletag.appendChild(document.createTextNode(cssbody));
14809			}
14810			document.getElementsByTagName("head")[0].appendChild(styletag);
14811		}
14812
14813		function createWorkerNode(document) {
14814
14815			var frameID = 'childframe' // Date.now().toString() + '_' + (Math.random() * 100).toString()
14816			,
14817			    frame = document.createElement('iframe');
14818
14819			InjectCSS('.jsPDF_sillysvg_iframe {display:none;position:absolute;}', document);
14820
14821			frame.name = frameID;
14822			frame.setAttribute("width", 0);
14823			frame.setAttribute("height", 0);
14824			frame.setAttribute("frameborder", "0");
14825			frame.setAttribute("scrolling", "no");
14826			frame.setAttribute("seamless", "seamless");
14827			frame.setAttribute("class", "jsPDF_sillysvg_iframe");
14828
14829			document.body.appendChild(frame);
14830
14831			return frame;
14832		}
14833
14834		function attachSVGToWorkerNode(svgtext, frame) {
14835			var framedoc = (frame.contentWindow || frame.contentDocument).document;
14836			framedoc.write(svgtext);
14837			framedoc.close();
14838			return framedoc.getElementsByTagName('svg')[0];
14839		}
14840
14841		function convertPathToPDFLinesArgs(path) {
14842			'use strict';
14843			// we will use 'lines' method call. it needs:
14844			// - starting coordinate pair
14845			// - array of arrays of vector shifts (2-len for line, 6 len for bezier)
14846			// - scale array [horizontal, vertical] ratios
14847			// - style (stroke, fill, both)
14848
14849			var x = parseFloat(path[1]),
14850			    y = parseFloat(path[2]),
14851			    vectors = [],
14852			    position = 3,
14853			    len = path.length;
14854
14855			while (position < len) {
14856				if (path[position] === 'c') {
14857					vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2]), parseFloat(path[position + 3]), parseFloat(path[position + 4]), parseFloat(path[position + 5]), parseFloat(path[position + 6])]);
14858					position += 7;
14859				} else if (path[position] === 'l') {
14860					vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2])]);
14861					position += 3;
14862				} else {
14863					position += 1;
14864				}
14865			}
14866			return [x, y, vectors];
14867		}
14868
14869		var workernode = createWorkerNode(document),
14870		    svgnode = attachSVGToWorkerNode(svgtext, workernode),
14871		    scale = [1, 1],
14872		    svgw = parseFloat(svgnode.getAttribute('width')),
14873		    svgh = parseFloat(svgnode.getAttribute('height'));
14874
14875		if (svgw && svgh) {
14876			// setting both w and h makes image stretch to size.
14877			// this may distort the image, but fits your demanded size
14878			if (w && h) {
14879				scale = [w / svgw, h / svgh];
14880			}
14881			// if only one is set, that value is set as max and SVG
14882			// is scaled proportionately.
14883			else if (w) {
14884					scale = [w / svgw, w / svgw];
14885				} else if (h) {
14886					scale = [h / svgh, h / svgh];
14887				}
14888		}
14889
14890		var i,
14891		    l,
14892		    tmp,
14893		    linesargs,
14894		    items = svgnode.childNodes;
14895		for (i = 0, l = items.length; i < l; i++) {
14896			tmp = items[i];
14897			if (tmp.tagName && tmp.tagName.toUpperCase() === 'PATH') {
14898				linesargs = convertPathToPDFLinesArgs(tmp.getAttribute("d").split(' '));
14899				// path start x coordinate
14900				linesargs[0] = linesargs[0] * scale[0] + x; // where x is upper left X of image
14901				// path start y coordinate
14902				linesargs[1] = linesargs[1] * scale[1] + y; // where y is upper left Y of image
14903				// the rest of lines are vectors. these will adjust with scale value auto.
14904				this.lines.call(this, linesargs[2] // lines
14905				, linesargs[0] // starting x
14906				, linesargs[1] // starting y
14907				, scale);
14908			}
14909		}
14910
14911		// clean up
14912		// workernode.parentNode.removeChild(workernode)
14913
14914		return this;
14915	};
14916})(jsPDF.API);
14917
14918/** ==================================================================== 
14919 * jsPDF total_pages plugin
14920 * Copyright (c) 2013 Eduardo Menezes de Morais, [email protected]
14921 * 
14922 * 
14923 * ====================================================================
14924 */
14925
14926(function (jsPDFAPI) {
14927  'use strict';
14928
14929  jsPDFAPI.putTotalPages = function (pageExpression) {
14930    'use strict';
14931
14932    var replaceExpression = new RegExp(pageExpression, 'g');
14933    for (var n = 1; n <= this.internal.getNumberOfPages(); n++) {
14934      for (var i = 0; i < this.internal.pages[n].length; i++) {
14935        this.internal.pages[n][i] = this.internal.pages[n][i].replace(replaceExpression, this.internal.getNumberOfPages());
14936      }
14937    }
14938    return this;
14939  };
14940})(jsPDF.API);
14941
14942/** ==================================================================== 
14943 * jsPDF XMP metadata plugin
14944 * Copyright (c) 2016 Jussi Utunen, [email protected]
14945 * 
14946 * 
14947 * ====================================================================
14948 */
14949
14950/*global jsPDF */
14951
14952/**
14953* Adds XMP formatted metadata to PDF
14954*
14955* @param {String} metadata The actual metadata to be added. The metadata shall be stored as XMP simple value. Note that if the metadata string contains XML markup characters "<", ">" or "&", those characters should be written using XML entities.
14956* @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.
14957* @function
14958* @returns {jsPDF}
14959* @methodOf jsPDF#
14960* @name addMetadata
14961*/
14962
14963(function (jsPDFAPI) {
14964    'use strict';
14965
14966    var xmpmetadata = "";
14967    var xmpnamespaceuri = "";
14968    var metadata_object_number = "";
14969
14970    jsPDFAPI.addMetadata = function (metadata, namespaceuri) {
14971        xmpnamespaceuri = namespaceuri || "http://jspdf.default.namespaceuri/"; //The namespace URI for an XMP name shall not be empty
14972        xmpmetadata = metadata;
14973        this.internal.events.subscribe('postPutResources', function () {
14974            if (!xmpmetadata) {
14975                metadata_object_number = "";
14976            } else {
14977                var xmpmeta_beginning = '<x:xmpmeta xmlns:x="adobe:ns:meta/">';
14978                var rdf_beginning = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:jspdf="' + xmpnamespaceuri + '"><jspdf:metadata>';
14979                var rdf_ending = '</jspdf:metadata></rdf:Description></rdf:RDF>';
14980                var xmpmeta_ending = '</x:xmpmeta>';
14981                var utf8_xmpmeta_beginning = unescape(encodeURIComponent(xmpmeta_beginning));
14982                var utf8_rdf_beginning = unescape(encodeURIComponent(rdf_beginning));
14983                var utf8_metadata = unescape(encodeURIComponent(xmpmetadata));
14984                var utf8_rdf_ending = unescape(encodeURIComponent(rdf_ending));
14985                var utf8_xmpmeta_ending = unescape(encodeURIComponent(xmpmeta_ending));
14986
14987                var total_len = utf8_rdf_beginning.length + utf8_metadata.length + utf8_rdf_ending.length + utf8_xmpmeta_beginning.length + utf8_xmpmeta_ending.length;
14988
14989                metadata_object_number = this.internal.newObject();
vendor: 7,148 bytes, lines 14990-15219
14990                this.internal.write('<< /Type /Metadata /Subtype /XML /Length ' + total_len + ' >>');
14991                this.internal.write('stream');
14992                this.internal.write(utf8_xmpmeta_beginning + utf8_rdf_beginning + utf8_metadata + utf8_rdf_ending + utf8_xmpmeta_ending);
14993                this.internal.write('endstream');
14994                this.internal.write('endobj');
14995            }
14996        });
14997        this.internal.events.subscribe('putCatalog', function () {
14998            if (metadata_object_number) {
14999                this.internal.write('/Metadata ' + metadata_object_number + ' 0 R');
15000            }
15001        });
15002        return this;
15003    };
15004})(jsPDF.API);
15005
15006/* Blob.js
15007 * A Blob implementation.
15008 * 2014-07-24
15009 *
15010 * By Eli Grey, http://eligrey.com
15011 * By Devin Samarin, https://github.com/dsamarin
15012 * License: X11/MIT
15013 *   See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md
15014 */
15015
15016/*global self, unescape */
15017/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
15018  plusplus: true */
15019
15020/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
15021
15022(function (view) {
15023	"use strict";
15024
15025	view.URL = view.URL || view.webkitURL;
15026
15027	if (view.Blob && view.URL) {
15028		try {
15029			new Blob;
15030			return;
15031		} catch (e) {}
15032	}
15033
15034	// Internally we use a BlobBuilder implementation to base Blob off of
15035	// in order to support older browsers that only have BlobBuilder
15036	var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
15037		var
15038			  get_class = function(object) {
15039				return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
15040			}
15041			, FakeBlobBuilder = function BlobBuilder() {
15042				this.data = [];
15043			}
15044			, FakeBlob = function Blob(data, type, encoding) {
15045				this.data = data;
15046				this.size = data.length;
15047				this.type = type;
15048				this.encoding = encoding;
15049			}
15050			, FBB_proto = FakeBlobBuilder.prototype
15051			, FB_proto = FakeBlob.prototype
15052			, FileReaderSync = view.FileReaderSync
15053			, FileException = function(type) {
15054				this.code = this[this.name = type];
15055			}
15056			, file_ex_codes = (
15057				  "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
15058				+ "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
15059			).split(" ")
15060			, file_ex_code = file_ex_codes.length
15061			, real_URL = view.URL || view.webkitURL || view
15062			, real_create_object_URL = real_URL.createObjectURL
15063			, real_revoke_object_URL = real_URL.revokeObjectURL
15064			, URL = real_URL
15065			, btoa = view.btoa
15066			, atob = view.atob
15067
15068			, ArrayBuffer = view.ArrayBuffer
15069			, Uint8Array = view.Uint8Array
15070
15071			, origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/;
15072		FakeBlob.fake = FB_proto.fake = true;
15073		while (file_ex_code--) {
15074			FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
15075		}
15076		// Polyfill URL
15077		if (!real_URL.createObjectURL) {
15078			URL = view.URL = function(uri) {
15079				var
15080					  uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
15081					, uri_origin;
15082				uri_info.href = uri;
15083				if (!("origin" in uri_info)) {
15084					if (uri_info.protocol.toLowerCase() === "data:") {
15085						uri_info.origin = null;
15086					} else {
15087						uri_origin = uri.match(origin);
15088						uri_info.origin = uri_origin && uri_origin[1];
15089					}
15090				}
15091				return uri_info;
15092			};
15093		}
15094		URL.createObjectURL = function(blob) {
15095			var
15096				  type = blob.type
15097				, data_URI_header;
15098			if (type === null) {
15099				type = "application/octet-stream";
15100			}
15101			if (blob instanceof FakeBlob) {
15102				data_URI_header = "data:" + type;
15103				if (blob.encoding === "base64") {
15104					return data_URI_header + ";base64," + blob.data;
15105				} else if (blob.encoding === "URI") {
15106					return data_URI_header + "," + decodeURIComponent(blob.data);
15107				} if (btoa) {
15108					return data_URI_header + ";base64," + btoa(blob.data);
15109				} else {
15110					return data_URI_header + "," + encodeURIComponent(blob.data);
15111				}
15112			} else if (real_create_object_URL) {
15113				return real_create_object_URL.call(real_URL, blob);
15114			}
15115		};
15116		URL.revokeObjectURL = function(object_URL) {
15117			if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
15118				real_revoke_object_URL.call(real_URL, object_URL);
15119			}
15120		};
15121		FBB_proto.append = function(data/*, endings*/) {
15122			var bb = this.data;
15123			// decode data to a binary string
15124			if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
15125				var
15126					  str = ""
15127					, buf = new Uint8Array(data)
15128					, i = 0
15129					, buf_len = buf.length;
15130				for (; i < buf_len; i++) {
15131					str += String.fromCharCode(buf[i]);
15132				}
15133				bb.push(str);
15134			} else if (get_class(data) === "Blob" || get_class(data) === "File") {
15135				if (FileReaderSync) {
15136					var fr = new FileReaderSync;
15137					bb.push(fr.readAsBinaryString(data));
15138				} else {
15139					// async FileReader won't work as BlobBuilder is sync
15140					throw new FileException("NOT_READABLE_ERR");
15141				}
15142			} else if (data instanceof FakeBlob) {
15143				if (data.encoding === "base64" && atob) {
15144					bb.push(atob(data.data));
15145				} else if (data.encoding === "URI") {
15146					bb.push(decodeURIComponent(data.data));
15147				} else if (data.encoding === "raw") {
15148					bb.push(data.data);
15149				}
15150			} else {
15151				if (typeof data !== "string") {
15152					data += ""; // convert unsupported types to strings
15153				}
15154				// decode UTF-16 to binary string
15155				bb.push(unescape(encodeURIComponent(data)));
15156			}
15157		};
15158		FBB_proto.getBlob = function(type) {
15159			if (!arguments.length) {
15160				type = null;
15161			}
15162			return new FakeBlob(this.data.join(""), type, "raw");
15163		};
15164		FBB_proto.toString = function() {
15165			return "[object BlobBuilder]";
15166		};
15167		FB_proto.slice = function(start, end, type) {
15168			var args = arguments.length;
15169			if (args < 3) {
15170				type = null;
15171			}
15172			return new FakeBlob(
15173				  this.data.slice(start, args > 1 ? end : this.data.length)
15174				, type
15175				, this.encoding
15176			);
15177		};
15178		FB_proto.toString = function() {
15179			return "[object Blob]";
15180		};
15181		FB_proto.close = function() {
15182			this.size = 0;
15183			delete this.data;
15184		};
15185		return FakeBlobBuilder;
15186	}(view));
15187
15188	view.Blob = function(blobParts, options) {
15189		var type = options ? (options.type || "") : "";
15190		var builder = new BlobBuilder();
15191		if (blobParts) {
15192			for (var i = 0, len = blobParts.length; i < len; i++) {
15193				if (Uint8Array && blobParts[i] instanceof Uint8Array) {
15194					builder.append(blobParts[i].buffer);
15195				}
15196				else {
15197					builder.append(blobParts[i]);
15198				}
15199			}
15200		}
15201		var blob = builder.getBlob(type);
15202		if (!blob.slice && blob.webkitSlice) {
15203			blob.slice = blob.webkitSlice;
15204		}
15205		return blob;
15206	};
15207
15208	var getPrototypeOf = Object.getPrototypeOf || function(object) {
15209		return object.__proto__;
15210	};
15211	view.Blob.prototype = getPrototypeOf(new view.Blob());
15212}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content || undefined));
15213
15214/* FileSaver.js
15215 * A saveAs() FileSaver implementation.
15216 * 1.3.2
15217 * 2016-06-16 18:25:19
15218 *
15219 * By Eli Grey, http://eligrey.com
15220 * License: MIT
15221 *   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
15222 */
15223
15224/*global self */
15225/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
15226
15227/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
15228
15229var saveAs = saveAs || (function(view) {
15230	"use strict";
15231	// IE <10 is explicitly unsupported
15232	if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
15233		return;
15234	}
15235	var
15236		  doc = view.document
15237		  // only get URL when necessary in case Blob.js hasn't overridden it yet
15238		, get_URL = function() {
15239			return view.URL || view.webkitURL || view;
15240		}
15241		, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
15242		, can_use_save_link = "download" in save_link
15243		, click = function(node) {
15244			var event = new MouseEvent("click");
15245			node.dispatchEvent(event);
15246		}
15247		, is_safari = /constructor/i.test(view.HTMLElement) || view.safari
15248		, is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent)
15249		, throw_outside = function(ex) {
15250			(view.setImmediate || view.setTimeout)(function() {
15251				throw ex;
15252			}, 0);
15253		}
15254		, force_saveable_type = "application/octet-stream"
15255		// the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
15256		, arbitrary_revoke_timeout = 1000 * 40 // in ms
15257		, revoke = function(file) {
15258			var revoker = function() {
15259				if (typeof file === "string") { // file is an object URL
15260					get_URL().revokeObjectURL(file);
15261				} else { // file is a File
15262					file.remove();
15263				}
15264			};
15265			setTimeout(revoker, arbitrary_revoke_timeout);
15266		}
15267		, dispatch = function(filesaver, event_types, event) {
15268			event_types = [].concat(event_types);
15269			var i = event_types.length;
15270			while (i--) {
15271				var listener = filesaver["on" + event_types[i]];
15272				if (typeof listener === "function") {
15273					try {
15274						listener.call(filesaver, event || filesaver);
15275					} catch (ex) {
15276						throw_outside(ex);
15277					}
15278				}
15279			}
15280		}
15281		, auto_bom = function(blob) {
15282			// prepend BOM for UTF-8 XML and text/* types (including HTML)
15283			// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
15284			if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
15285				return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
15286			}
15287			return blob;
15288		}
15289		, FileSaver = function(blob, name, no_auto_bom) {
15290			if (!no_auto_bom) {
15291				blob = auto_bom(blob);
15292			}
15293			// First try a.download, then web filesystem, then object URLs
15294			var
15295				  filesaver = this
15296				, type = blob.type
15297				, force = type === force_saveable_type
15298				, object_url
15299				, dispatch_all = function() {
15300					dispatch(filesaver, "writestart progress write writeend".split(" "));
15301				}
15302				// on any filesys errors revert to saving with object URLs
15303				, fs_error = function() {
15304					if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
15305						// Safari doesn't allow downloading of blob urls
15306						var reader = new FileReader();
15307						reader.onloadend = function() {
15308							var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
15309							var popup = view.open(url, '_blank');
15310							if(!popup) view.location.href = url;
15311							url=undefined; // release reference before dispatching
15312							filesaver.readyState = filesaver.DONE;
15313							dispatch_all();
15314						};
15315						reader.readAsDataURL(blob);
15316						filesaver.readyState = filesaver.INIT;
15317						return;
15318					}
15319					// don't create more object URLs than needed
15320					if (!object_url) {
15321						object_url = get_URL().createObjectURL(blob);
15322					}
15323					if (force) {
15324						view.location.href = object_url;
15325					} else {
15326						var opened = view.open(object_url, "_blank");
15327						if (!opened) {
15328							// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
15329							view.location.href = object_url;
15330						}
15331					}
15332					filesaver.readyState = filesaver.DONE;
15333					dispatch_all();
15334					revoke(object_url);
15335				};
15336			filesaver.readyState = filesaver.INIT;
15337
15338			if (can_use_save_link) {
15339				object_url = get_URL().createObjectURL(blob);
15340				setTimeout(function() {
15341					save_link.href = object_url;
15342					save_link.download = name;
15343					click(save_link);
15344					dispatch_all();
15345					revoke(object_url);
15346					filesaver.readyState = filesaver.DONE;
15347				});
15348				return;
15349			}
15350
15351			fs_error();
15352		}
15353		, FS_proto = FileSaver.prototype
15354		, saveAs = function(blob, name, no_auto_bom) {
15355			return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
15356		};
15357	// IE 10+ (native saveAs)
15358	if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
15359		return function(blob, name, no_auto_bom) {
15360			name = name || blob.name || "download";
15361
15362			if (!no_auto_bom) {
15363				blob = auto_bom(blob);
15364			}
15365			return navigator.msSaveOrOpenBlob(blob, name);
15366		};
15367	}
15368
15369	FS_proto.abort = function(){};
15370	FS_proto.readyState = FS_proto.INIT = 0;
15371	FS_proto.WRITING = 1;
15372	FS_proto.DONE = 2;
15373
15374	FS_proto.error =
15375	FS_proto.onwritestart =
15376	FS_proto.onprogress =
15377	FS_proto.onwrite =
15378	FS_proto.onabort =
15379	FS_proto.onerror =
15380	FS_proto.onwriteend =
15381		null;
15382
15383	return saveAs;
15384}(
15385	   typeof self !== "undefined" && self
15386	|| typeof window !== "undefined" && window
15387	|| undefined.content
15388));
15389// `self` is undefined in Firefox for Android content script context
15390// while `this` is nsIContentFrameMessageManager
15391// with an attribute `content` that corresponds to the window
15392
15393if (typeof module !== "undefined" && module.exports) {
15394  module.exports.saveAs = saveAs;
15395} else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
15396  define("FileSaver.js", function() {
15397    return saveAs;
15398  });
15399}
15400
15401/*
15402 * Copyright (c) 2012 chick307 <[email protected]>
15403 *
15404 * Licensed under the MIT License.
15405 * http://opensource.org/licenses/mit-license
15406 */
15407
15408void function(global, callback) {
15409	if (typeof module === 'object') {
15410		module.exports = callback();
15411	} else if (typeof define === 'function') {
15412		define(callback);
15413	} else {
15414		global.adler32cs = callback();
15415	}
15416}(jsPDF, function() {
15417	var _hasArrayBuffer = typeof ArrayBuffer === 'function' &&
15418		typeof Uint8Array === 'function';
15419
15420	var _Buffer = null, _isBuffer = (function() {
15421		if (!_hasArrayBuffer)
15422			return function _isBuffer() { return false };
15423
15424		try {
15425			var buffer = {};
15426			if (typeof buffer.Buffer === 'function')
15427				_Buffer = buffer.Buffer;
15428		} catch (error) {}
15429
15430		return function _isBuffer(value) {
15431			return value instanceof ArrayBuffer ||
15432				_Buffer !== null && value instanceof _Buffer;
15433		};
15434	}());
15435
15436	var _utf8ToBinary = (function() {
15437		if (_Buffer !== null) {
15438			return function _utf8ToBinary(utf8String) {
15439				return new _Buffer(utf8String, 'utf8').toString('binary');
15440			};
15441		} else {
15442			return function _utf8ToBinary(utf8String) {
15443				return unescape(encodeURIComponent(utf8String));
15444			};
15445		}
15446	}());
15447
15448	var MOD = 65521;
15449
15450	var _update = function _update(checksum, binaryString) {
15451		var a = checksum & 0xFFFF, b = checksum >>> 16;
15452		for (var i = 0, length = binaryString.length; i < length; i++) {
15453			a = (a + (binaryString.charCodeAt(i) & 0xFF)) % MOD;
15454			b = (b + a) % MOD;
15455		}
15456		return (b << 16 | a) >>> 0;
15457	};
15458
15459	var _updateUint8Array = function _updateUint8Array(checksum, uint8Array) {
15460		var a = checksum & 0xFFFF, b = checksum >>> 16;
15461		for (var i = 0, length = uint8Array.length; i < length; i++) {
15462			a = (a + uint8Array[i]) % MOD;
15463			b = (b + a) % MOD;
15464		}
15465		return (b << 16 | a) >>> 0
15466	};
15467
15468	var exports = {};
15469
15470	var Adler32 = exports.Adler32 = (function() {
15471		var ctor = function Adler32(checksum) {
15472			if (!(this instanceof ctor)) {
15473				throw new TypeError(
15474					'Constructor cannot called be as a function.');
15475			}
15476			if (!isFinite(checksum = checksum == null ? 1 : +checksum)) {
15477				throw new Error(
15478					'First arguments needs to be a finite number.');
15479			}
15480			this.checksum = checksum >>> 0;
15481		};
15482
15483		var proto = ctor.prototype = {};
15484		proto.constructor = ctor;
15485
15486		ctor.from = function(from) {
15487			from.prototype = proto;
15488			return from;
15489		}(function from(binaryString) {
15490			if (!(this instanceof ctor)) {
15491				throw new TypeError(
15492					'Constructor cannot called be as a function.');
15493			}
15494			if (binaryString == null)
15495				throw new Error('First argument needs to be a string.');
15496			this.checksum = _update(1, binaryString.toString());
15497		});
15498
15499		ctor.fromUtf8 = function(fromUtf8) {
15500			fromUtf8.prototype = proto;
15501			return fromUtf8;
15502		}
15502(function fromUtf8(utf8String) {
15503			if (!(this instanceof ctor)) {
15504				throw new TypeError(
15505					'Constructor cannot called be as a function.');
15506			}
15507			if (utf8String == null)
15508				throw new Error('First argument needs to be a string.');
15509			var binaryString = _utf8ToBinary(utf8String.toString());
15510			this.checksum = _update(1, binaryString);
15511		});
15512
15513		if (_hasArrayBuffer) {
15514			ctor.fromBuffer = function(fromBuffer) {
15515				fromBuffer.prototype = proto;
15516				return fromBuffer;
15517			}(function fromBuffer(buffer) {
15518				if (!(this instanceof ctor)) {
15519					throw new TypeError(
15520						'Constructor cannot called be as a function.');
15521				}
15522				if (!_isBuffer(buffer))
15523					throw new Error('First argument needs to be ArrayBuffer.');
15524				var array = new Uint8Array(buffer);
15525				return this.checksum = _updateUint8Array(1, array);
15526			});
15527		}
15528
15529		proto.update = function update(binaryString) {
15530			if (binaryString == null)
15531				throw new Error('First argument needs to be a string.');
15532			binaryString = binaryString.toString();
15533			return this.checksum = _update(this.checksum, binaryString);
15534		};
15535
15536		proto.updateUtf8 = function updateUtf8(utf8String) {
15537			if (utf8String == null)
15538				throw new Error('First argument needs to be a string.');
15539			var binaryString = _utf8ToBinary(utf8String.toString());
15540			return this.checksum = _update(this.checksum, binaryString);
15541		};
15542
15543		if (_hasArrayBuffer) {
15544			proto.updateBuffer = function updateBuffer(buffer) {
15545				if (!_isBuffer(buffer))
15546					throw new Error('First argument needs to be ArrayBuffer.');
15547				var array = new Uint8Array(buffer);
15548				return this.checksum = _updateUint8Array(this.checksum, array);
15549			};
15550		}
15551
15552		proto.clone = function clone() {
15553			return new Adler32(this.checksum);
15554		};
15555
15556		return ctor;
15557	}());
15558
15559	exports.from = function from(binaryString) {
15560		if (binaryString == null)
15561			throw new Error('First argument needs to be a string.');
15562		return _update(1, binaryString.toString());
15563	};
15564
15565	exports.fromUtf8 = function fromUtf8(utf8String) {
15566		if (utf8String == null)
15567			throw new Error('First argument needs to be a string.');
15568		var binaryString = _utf8ToBinary(utf8String.toString());
15569		return _update(1, binaryString);
15570	};
15571
15572	if (_hasArrayBuffer) {
15573		exports.fromBuffer = function fromBuffer(buffer) {
15574			if (!_isBuffer(buffer))
15575				throw new Error('First argument need to be ArrayBuffer.');
15576			var array = new Uint8Array(buffer);
15577			return _updateUint8Array(1, array);
15578		};
15579	}
15580
15581	return exports;
15582});
15583
15584/**
15585 * CssColors
15586 * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  [email protected]
15587 *
15588 * Licensed under the MIT License.
15589 * http://opensource.org/licenses/mit-license
15590 */
15591
15592/**
15593 * Usage CssColors('red');
15594 * Returns RGB hex color with '#' prefix
15595 */
15596
15597var CssColors = {};
15598CssColors._colorsTable = {
15599	"aliceblue" : "#f0f8ff",
15600	"antiquewhite" : "#faebd7",
15601	"aqua" : "#00ffff",
15602	"aquamarine" : "#7fffd4",
15603	"azure" : "#f0ffff",
15604	"beige" : "#f5f5dc",
15605	"bisque" : "#ffe4c4",
15606	"black" : "#000000",
15607	"blanchedalmond" : "#ffebcd",
15608	"blue" : "#0000ff",
15609	"blueviolet" : "#8a2be2",
15610	"brown" : "#a52a2a",
15611	"burlywood" : "#deb887",
15612	"cadetblue" : "#5f9ea0",
15613	"chartreuse" : "#7fff00",
15614	"chocolate" : "#d2691e",
15615	"coral" : "#ff7f50",
15616	"cornflowerblue" : "#6495ed",
15617	"cornsilk" : "#fff8dc",
15618	"crimson" : "#dc143c",
15619	"cyan" : "#00ffff",
15620	"darkblue" : "#00008b",
15621	"darkcyan" : "#008b8b",
15622	"darkgoldenrod" : "#b8860b",
15623	"darkgray" : "#a9a9a9",
15624	"darkgreen" : "#006400",
15625	"darkkhaki" : "#bdb76b",
15626	"darkmagenta" : "#8b008b",
15627	"darkolivegreen" : "#556b2f",
15628	"darkorange" : "#ff8c00",
15629	"darkorchid" : "#9932cc",
15630	"darkred" : "#8b0000",
15631	"darksalmon" : "#e9967a",
15632	"darkseagreen" : "#8fbc8f",
15633	"darkslateblue" : "#483d8b",
15634	"darkslategray" : "#2f4f4f",
15635	"darkturquoise" : "#00ced1",
15636	"darkviolet" : "#9400d3",
15637	"deeppink" : "#ff1493",
15638	"deepskyblue" : "#00bfff",
15639	"dimgray" : "#696969",
15640	"dodgerblue" : "#1e90ff",
15641	"firebrick" : "#b22222",
15642	"floralwhite" : "#fffaf0",
15643	"forestgreen" : "#228b22",
15644	"fuchsia" : "#ff00ff",
15645	"gainsboro" : "#dcdcdc",
15646	"ghostwhite" : "#f8f8ff",
15647	"gold" : "#ffd700",
15648	"goldenrod" : "#daa520",
15649	"gray" : "#808080",
15650	"green" : "#008000",
15651	"greenyellow" : "#adff2f",
15652	"honeydew" : "#f0fff0",
15653	"hotpink" : "#ff69b4",
15654	"indianred " : "#cd5c5c",
15655	"indigo" : "#4b0082",
15656	"ivory" : "#fffff0",
15657	"khaki" : "#f0e68c",
15658	"lavender" : "#e6e6fa",
15659	"lavenderblush" : "#fff0f5",
15660	"lawngreen" : "#7cfc00",
15661	"lemonchiffon" : "#fffacd",
15662	"lightblue" : "#add8e6",
15663	"lightcoral" : "#f08080",
15664	"lightcyan" : "#e0ffff",
15665	"lightgoldenrodyellow" : "#fafad2",
15666	"lightgrey" : "#d3d3d3",
15667	"lightgreen" : "#90ee90",
15668	"lightpink" : "#ffb6c1",
15669	"lightsalmon" : "#ffa07a",
15670	"lightseagreen" : "#20b2aa",
15671	"lightskyblue" : "#87cefa",
15672	"lightslategray" : "#778899",
15673	"lightsteelblue" : "#b0c4de",
15674	"lightyellow" : "#ffffe0",
15675	"lime" : "#00ff00",
15676	"limegreen" : "#32cd32",
15677	"linen" : "#faf0e6",
15678	"magenta" : "#ff00ff",
15679	"maroon" : "#800000",
15680	"mediumaquamarine" : "#66cdaa",
15681	"mediumblue" : "#0000cd",
15682	"mediumorchid" : "#ba55d3",
15683	"mediumpurple" : "#9370d8",
15684	"mediumseagreen" : "#3cb371",
15685	"mediumslateblue" : "#7b68ee",
15686	"mediumspringgreen" : "#00fa9a",
15687	"mediumturquoise" : "#48d1cc",
15688	"mediumvioletred" : "#c71585",
15689	"midnightblue" : "#191970",
15690	"mintcream" : "#f5fffa",
15691	"mistyrose" : "#ffe4e1",
15692	"moccasin" : "#ffe4b5",
15693	"navajowhite" : "#ffdead",
15694	"navy" : "#000080",
15695	"oldlace" : "#fdf5e6",
15696	"olive" : "#808000",
15697	"olivedrab" : "#6b8e23",
15698	"orange" : "#ffa500",
15699	"orangered" : "#ff4500",
15700	"orchid" : "#da70d6",
15701	"palegoldenrod" : "#eee8aa",
15702	"palegreen" : "#98fb98",
15703	"paleturquoise" : "#afeeee",
15704	"palevioletred" : "#d87093",
15705	"papayawhip" : "#ffefd5",
15706	"peachpuff" : "#ffdab9",
15707	"peru" : "#cd853f",
15708	"pink" : "#ffc0cb",
15709	"plum" : "#dda0dd",
15710	"powderblue" : "#b0e0e6",
15711	"purple" : "#800080",
15712	"red" : "#ff0000",
15713	"rosybrown" : "#bc8f8f",
15714	"royalblue" : "#4169e1",
15715	"saddlebrown" : "#8b4513",
15716	"salmon" : "#fa8072",
15717	"sandybrown" : "#f4a460",
15718	"seagreen" : "#2e8b57",
15719	"seashell" : "#fff5ee",
15720	"sienna" : "#a0522d",
15721	"silver" : "#c0c0c0",
15722	"skyblue" : "#87ceeb",
15723	"slateblue" : "#6a5acd",
15724	"slategray" : "#708090",
15725	"snow" : "#fffafa",
15726	"springgreen" : "#00ff7f",
15727	"steelblue" : "#4682b4",
15728	"tan" : "#d2b48c",
15729	"teal" : "#008080",
15730	"thistle" : "#d8bfd8",
15731	"tomato" : "#ff6347",
15732	"turquoise" : "#40e0d0",
15733	"violet" : "#ee82ee",
15734	"wheat" : "#f5deb3",
15735	"white" : "#ffffff",
15736	"whitesmoke" : "#f5f5f5",
15737	"yellow" : "#ffff00",
15738	"yellowgreen" : "#9acd32"
15739};
15740
15741CssColors.colorNameToHex = function(color) {
15742	color = color.toLowerCase();
15743	if (typeof this._colorsTable[color] != 'undefined')
15744		return this._colorsTable[color];
15745
15746	return false;
15747};
15748
15749/*
15750 Deflate.js - https://github.com/gildas-lormeau/zip.js
15751 Copyright (c) 2013 Gildas Lormeau. All rights reserved.
15752
15753 Redistribution and use in source and binary forms, with or without
15754 modification, are permitted provided that the following conditions are met:
15755
15756 1. Redistributions of source code must retain the above copyright notice,
15757 this list of conditions and the following disclaimer.
15758
15759 2. Redistributions in binary form must reproduce the above copyright 
15760 notice, this list of conditions and the following disclaimer in 
15761 the documentation and/or other materials provided with the distribution.
15762
15763 3. The names of the authors may not be used to endorse or promote products
15764 derived from this software without specific prior written permission.
15765
15766 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
15767 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
15768 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
15769 INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
15770 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
15771 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
15772 OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
15773 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
15774 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
15775 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15776 */
15777
15778/*
15779 * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
15780 * JZlib is based on zlib-1.1.3, so all credit should go authors
15781 * Jean-loup Gailly([email protected]) and Mark Adler([email protected])
15782 * and contributors of zlib.
15783 */
15784
15785var Deflater = (function(obj) {
15786
15787	// Global
15788
15789	var MAX_BITS = 15;
15790	var D_CODES = 30;
15791	var BL_CODES = 19;
15792
15793	var LENGTH_CODES = 29;
15794	var LITERALS = 256;
15795	var L_CODES = (LITERALS + 1 + LENGTH_CODES);
15796	var HEAP_SIZE = (2 * L_CODES + 1);
15797
15798	var END_BLOCK = 256;
15799
15800	// Bit length codes must not exceed MAX_BL_BITS bits
15801	var MAX_BL_BITS = 7;
15802
15803	// repeat previous bit length 3-6 times (2 bits of repeat count)
15804	var REP_3_6 = 16;
15805
15806	// repeat a zero length 3-10 times (3 bits of repeat count)
15807	var REPZ_3_10 = 17;
15808
15809	// repeat a zero length 11-138 times (7 bits of repeat count)
15810	var REPZ_11_138 = 18;
15811
15812	// The lengths of the bit length codes are sent in order of decreasing
15813	// probability, to avoid transmitting the lengths for unused bit
15814	// length codes.
15815
15816	var Buf_size = 8 * 2;
15817
15818	// JZlib version : "1.0.2"
15819	var Z_DEFAULT_COMPRESSION = -1;
15820
15821	// compression strategy
15822	var Z_FILTERED = 1;
15823	var Z_HUFFMAN_ONLY = 2;
15824	var Z_DEFAULT_STRATEGY = 0;
15825
15826	var Z_NO_FLUSH = 0;
15827	var Z_PARTIAL_FLUSH = 1;
15828	var Z_FULL_FLUSH = 3;
15829	var Z_FINISH = 4;
15830
15831	var Z_OK = 0;
15832	var Z_STREAM_END = 1;
15833	var Z_NEED_DICT = 2;
15834	var Z_STREAM_ERROR = -2;
15835	var Z_DATA_ERROR = -3;
15836	var Z_BUF_ERROR = -5;
15837
15838	// Tree
15839
15840	// see definition of array dist_code below
15841	var _dist_code = [ 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
15842			10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
15843			12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
15844			13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
15845			14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
15846			14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15847			15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19,
15848			20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
15849			24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
15850			26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
15851			27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
15852			28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29,
15853			29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
15854			29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 ];
15855
15856	function Tree() {
15857		var that = this;
15858
15859		// dyn_tree; // the dynamic tree
15860		// max_code; // largest code with non zero frequency
15861		// stat_desc; // the corresponding static tree
15862
15863		// Compute the optimal bit lengths for a tree and update the total bit
15864		// length
15865		// for the current block.
15866		// IN assertion: the fields freq and dad are set, heap[heap_max] and
15867		// above are the tree nodes sorted by increasing frequency.
15868		// OUT assertions: the field len is set to the optimal bit length, the
15869		// array bl_count contains the frequencies for each bit length.
15870		// The length opt_len is updated; static_len is also updated if stree is
15871		// not null.
15872		function gen_bitlen(s) {
15873			var tree = that.dyn_tree;
15874			var stree = that.stat_desc.static_tree;
15875			var extra = that.stat_desc.extra_bits;
15876			var base = that.stat_desc.extra_base;
15877			var max_length = that.stat_desc.max_length;
15878			var h; // heap index
15879			var n, m; // iterate over the tree elements
15880			var bits; // bit length
15881			var xbits; // extra bits
15882			var f; // frequency
15883			var overflow = 0; // number of elements with bit length too large
15884
15885			for (bits = 0; bits <= MAX_BITS; bits++)
15886				s.bl_count[bits] = 0;
15887
15888			// In a first pass, compute the optimal bit lengths (which may
15889			// overflow in the case of the bit length tree).
15890			tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
15891
15892			for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
15893				n = s.heap[h];
15894				bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
15895				if (bits > max_length) {
15896					bits = max_length;
15897					overflow++;
15898				}
15899				tree[n * 2 + 1] = bits;
15900				// We overwrite tree[n*2+1] which is no longer needed
15901
15902				if (n > that.max_code)
15903					continue; // not a leaf node
15904
15905				s.bl_count[bits]++;
15906				xbits = 0;
15907				if (n >= base)
15908					xbits = extra[n - base];
15909				f = tree[n * 2];
15910				s.opt_len += f * (bits + xbits);
15911				if (stree)
15912					s.static_len += f * (stree[n * 2 + 1] + xbits);
15913			}
15914			if (overflow === 0)
15915				return;
15916
15917			// This happens for example on obj2 and pic of the Calgary corpus
15918			// Find the first bit length which could increase:
15919			do {
15920				bits = max_length - 1;
15921				while (s.bl_count[bits] === 0)
15922					bits--;
15923				s.bl_count[bits]--; // move one leaf down the tree
15924				s.bl_count[bits + 1] += 2; // move one overflow item as its brother
15925				s.bl_count[max_length]--;
15926				// The brother of the overflow item also moves one step up,
15927				// but this does not affect bl_count[max_length]
15928				overflow -= 2;
15929			} while (overflow > 0);
15930
15931			for (bits = max_length; bits !== 0; bits--) {
15932				n = s.bl_count[bits];
15933				while (n !== 0) {
15934					m = s.heap[--h];
15935					if (m > that.max_code)
15936						continue;
15937					if (tree[m * 2 + 1] != bits) {
15938						s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
15939						tree[m * 2 + 1] = bits;
15940					}
15941					n--;
15942				}
15943			}
15944		}
15945
15946		// Reverse the first len bits of a code, using straightforward code (a
15947		// faster
15948		// method would use a table)
15949		// IN assertion: 1 <= len <= 15
15950		function bi_reverse(code, // the value to invert
15951		len // its bit length
15952		) {
15953			var res = 0;
15954			do {
15955				res |= code & 1;
15956				code >>>= 1;
15957				res <<= 1;
15958			} while (--len > 0);
15959			return res >>> 1;
15960		}
15961
15962		// Generate the codes for a given tree and bit counts (which need not be
15963		// optimal).
15964		// IN assertion: the array bl_count contains the bit length statistics for
15965		// the given tree and the field len is set for all tree elements.
15966		// OUT assertion: the field code is set for all tree elements of non
15967		// zero code length.
15968		function gen_codes(tree, // the tree to decorate
15969		max_code, // largest code with non zero frequency
15970		bl_count // number of codes at each bit length
15971		) {
15972			var next_code = []; // next code value for each
15973			// bit length
15974			var code = 0; // running code value
15975			var bits; // bit index
15976			var n; // code index
15977			var len;
15978
15979			// The distribution counts are first used to generate the code values
15980			// without bit reversal.
15981			for (bits = 1; bits <= MAX_BITS; bits++) {
15982				next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
15983			}
15984
15985			// Check that the bit counts in bl_count are consistent. The last code
15986			// must be all ones.
15987			// Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
15988			// "inconsistent bit counts");
15989			// Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
15990
15991			for (n = 0; n <= max_code; n++) {
15992				len = tree[n * 2 + 1];
15993				if (len === 0)
15994					continue;
15995				// Now reverse the bits
15996				tree[n * 2] = bi_reverse(next_code[len]++, len);
15997			}
15998		}
15999
16000		// Construct one Huffman tree and assigns the code bit strings and lengths.
16001		// Update the total bit length for the current block.
16002		// IN assertion: the field freq is set for all tree elements.
16003		// OUT assertions: the fields len and code are set to the optimal bit length
16004		// and corresponding code. The length opt_len is updated; static_len is
16005		// also updated if stree is not null. The field max_code is set.
16006		that.build_tree = function(s) {
16007			var tree = that.dyn_tree;
16008			var stree = that.stat_desc.static_tree;
16009			var elems = that.stat_desc.elems;
16010			var n, m; // iterate over heap elements
16011			var max_code = -1; // largest code with non zero frequency
16012			var node; // new node being created
16013
16014			// Construct the initial heap, with least frequent element in
16015			// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
16016			// heap[0] is not used.
16017			s.heap_len = 0;
16018			s.heap_max = HEAP_SIZE;
16019
16020			for (n = 0; n < elems; n++) {
16021				if (tree[n * 2] !== 0) {
16022					s.heap[++s.heap_len] = max_code = n;
16023					s.depth[n] = 0;
16024				} else {
16025					tree[n * 2 + 1] = 0;
16026				}
16027			}
16028
16029			// The pkzip format requires that at least one distance code exists,
16030			// and that at least one bit should be sent even if there is only one
16031			// possible code. So to avoid special checks later on we force at least
16032			// two codes of non zero frequency.
16033			while (s.heap_len < 2) {
16034				node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
16035				tree[node * 2] = 1;
16036				s.depth[node] = 0;
16037				s.opt_len--;
16038				if (stree)
16039					s.static_len -= stree[node * 2 + 1];
16040				// node is 0 or 1 so it does not have extra bits
16041			}
16042			that.max_code = max_code;
16043
16044			// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
16045			// establish sub-heaps of increasing lengths:
16046
16047			for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
16048				s.pqdownheap(tree, n);
16049
16050			// Construct the Huffman tree by repeatedly combining the least two
16051			// frequent nodes.
16052
16053			node = elems; // next internal node of the tree
16054			do {
16055				// n = node of least frequency
16056				n = s.heap[1];
16057				s.heap[1] = s.heap[s.heap_len--];
16058				s.pqdownheap(tree, 1);
16059				m = s.heap[1]; // m = node of next least frequency
16060
16061				s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
16062				s.heap[--s.heap_max] = m;
16063
16064				// Create a new node father of n and m
16065				tree[node * 2] = (tree[n * 2] + tree[m * 2]);
16066				s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
16067				tree[n * 2 + 1] = tree[m * 2 + 1] = node;
16068
16069				// and insert the new node in the heap
16070				s.heap[1] = node++;
16071				s.pqdownheap(tree, 1);
16072			} while (s.heap_len >= 2);
16073
16074			s.heap[--s.heap_max] = s.heap[1];
16075
16076			// At this point, the fields freq and dad are set. We can now
16077			// generate the bit lengths.
16078
16079			gen_bitlen(s);
16080
16081			// The field len is now set, we can generate the bit codes
16082			gen_codes(tree, that.max_code, s.bl_count);
16083		};
16084
16085	}
16086
16087	Tree._length_code = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16,
16088			16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20,
16089			20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
16090			22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
16091			24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
16092			25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
16093			26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 ];
16094
16095	Tree.base_length = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 ];
16096
16097	Tree.base_dist = [ 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384,
16098			24576 ];
16099
16100	// Mapping from a distance to a distance code. dist is the distance - 1 and
16101	// must not have side effects. _dist_code[256] and _dist_code[257] are never
16102	// used.
16103	Tree.d_code = function(dist) {
16104		return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
16105	};
16106
16107	// extra bits for each length code
16108	Tree.extra_lbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 ];
16109
16110	// extra bits for each distance code
16111	Tree.extra_dbits = [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 ];
16112
16113	// extra bits for each bit length code
16114	Tree.extra_blbits = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 ];
16115
16116	Tree.bl_order = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
16117
16118	// StaticTree
16119
16120	function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
16121		var that = this;
16122		that.static_tree = static_tree;
16123		that.extra_bits = extra_bits;
16124		that.extra_base = extra_base;
16125		that.elems = elems;
16126		that.max_length = max_length;
16127	}
16128
16129	StaticTree.static_ltree = [ 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8,
16130			130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42,
16131			8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8,
16132			22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8,
16133			222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113,
16134			8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8,
16135			69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8,
16136			173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 27
161365, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9,
16137			51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9,
16138			427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379,
16139			9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23,
16140			9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9,
16141			399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9,
16142			223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7,
16143			40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8,
16144			99, 8, 227, 8 ];
16145
16146	StaticTree.static_dtree = [ 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5,
16147			25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 ];
16148
16149	StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
16150
16151	StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
16152
16153	StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
16154
16155	// Deflate
16156
16157	var MAX_MEM_LEVEL = 9;
16158	var DEF_MEM_LEVEL = 8;
16159
16160	function Config(good_length, max_lazy, nice_length, max_chain, func) {
16161		var that = this;
16162		that.good_length = good_length;
16163		that.max_lazy = max_lazy;
16164		that.nice_length = nice_length;
16165		that.max_chain = max_chain;
16166		that.func = func;
16167	}
16168
16169	var STORED = 0;
16170	var FAST = 1;
16171	var SLOW = 2;
16172	var config_table = [ new Config(0, 0, 0, 0, STORED), new Config(4, 4, 8, 4, FAST), new Config(4, 5, 16, 8, FAST), new Config(4, 6, 32, 32, FAST),
16173			new Config(4, 4, 16, 16, SLOW), new Config(8, 16, 32, 32, SLOW), new Config(8, 16, 128, 128, SLOW), new Config(8, 32, 128, 256, SLOW),
16174			new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW) ];
16175
16176	var z_errmsg = [ "need dictionary", // Z_NEED_DICT
16177	// 2
16178	"stream end", // Z_STREAM_END 1
16179	"", // Z_OK 0
16180	"", // Z_ERRNO (-1)
16181	"stream error", // Z_STREAM_ERROR (-2)
16182	"data error", // Z_DATA_ERROR (-3)
16183	"", // Z_MEM_ERROR (-4)
16184	"buffer error", // Z_BUF_ERROR (-5)
16185	"",// Z_VERSION_ERROR (-6)
16186	"" ];
16187
16188	// block not completed, need more input or more output
16189	var NeedMore = 0;
16190
16191	// block flush performed
16192	var BlockDone = 1;
16193
16194	// finish started, need only more output at next deflate
16195	var FinishStarted = 2;
16196
16197	// finish done, accept no more input or output
16198	var FinishDone = 3;
16199
16200	// preset dictionary flag in zlib header
16201	var PRESET_DICT = 0x20;
16202
16203	var INIT_STATE = 42;
16204	var BUSY_STATE = 113;
16205	var FINISH_STATE = 666;
16206
16207	// The deflate compression method
16208	var Z_DEFLATED = 8;
16209
16210	var STORED_BLOCK = 0;
16211	var STATIC_TREES = 1;
16212	var DYN_TREES = 2;
16213
16214	var MIN_MATCH = 3;
16215	var MAX_MATCH = 258;
16216	var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
16217
16218	function smaller(tree, n, m, depth) {
16219		var tn2 = tree[n * 2];
16220		var tm2 = tree[m * 2];
16221		return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
16222	}
16223
16224	function Deflate() {
16225
16226		var that = this;
16227		var strm; // pointer back to this zlib stream
16228		var status; // as the name implies
16229		// pending_buf; // output still pending
16230		var pending_buf_size; // size of pending_buf
16231		// pending_out; // next pending byte to output to the stream
16232		// pending; // nb of bytes in the pending buffer
16233		var last_flush; // value of flush param for previous deflate call
16234
16235		var w_size; // LZ77 window size (32K by default)
16236		var w_bits; // log2(w_size) (8..16)
16237		var w_mask; // w_size - 1
16238
16239		var window;
16240		// Sliding window. Input bytes are read into the second half of the window,
16241		// and move to the first half later to keep a dictionary of at least wSize
16242		// bytes. With this organization, matches are limited to a distance of
16243		// wSize-MAX_MATCH bytes, but this ensures that IO is always
16244		// performed with a length multiple of the block size. Also, it limits
16245		// the window size to 64K, which is quite useful on MSDOS.
16246		// To do: use the user input buffer as sliding window.
16247
16248		var window_size;
16249		// Actual size of window: 2*wSize, except when the user input buffer
16250		// is directly used as sliding window.
16251
16252		var prev;
16253		// Link to older string with same hash index. To limit the size of this
16254		// array to 64K, this link is maintained only for the last 32K strings.
16255		// An index in this array is thus a window index modulo 32K.
16256
16257		var head; // Heads of the hash chains or NIL.
16258
16259		var ins_h;
16259 // hash index of string to be inserted
16260		var hash_size; // number of elements in hash table
16261		var hash_bits; // log2(hash_size)
16262		var hash_mask; // hash_size-1
16263
16264		// Number of bits by which ins_h must be shifted at each input
16265		// step. It must be such that after MIN_MATCH steps, the oldest
16266		// byte no longer takes part in the hash key, that is:
16267		// hash_shift * MIN_MATCH >= hash_bits
16268		var hash_shift;
16269
16270		// Window position at the beginning of the current output block. Gets
16271		// negative when the window is moved backwards.
16272
16273		var block_start;
16274
16275		var match_length; // length of best match
16276		var prev_match; // previous match
16277		var match_available; // set if previous match exists
16278		var strstart; // start of string to insert
16279		var match_start; // start of matching string
16280		var lookahead; // number of valid bytes ahead in window
16281
16282		// Length of the best match at previous step. Matches not greater than this
16283		// are discarded. This is used in the lazy match evaluation.
16284		var prev_length;
16285
16286		// To speed up deflation, hash chains are never searched beyond this
16287		// length. A higher limit improves compression ratio but degrades the speed.
16288		var max_chain_length;
16289
16290		// Attempt to find a better match only when the current match is strictly
16291		// smaller than this value. This mechanism is used only for compression
16292		// levels >= 4.
16293		var max_lazy_match;
16294
16295		// Insert new strings in the hash table only if the match length is not
16296		// greater than this length. This saves time but degrades compression.
16297		// max_insert_length is used only for compression levels <= 3.
16298
16299		var level; // compression level (1..9)
16300		var strategy; // favor or force Huffman coding
16301
16302		// Use a faster search when the previous match is longer than this
16303		var good_match;
16304
16305		// Stop searching when current match exceeds this
16306		var nice_match;
16307
16308		var dyn_ltree; // literal and length tree
16309		var dyn_dtree; // distance tree
16310		var bl_tree; // Huffman tree for bit lengths
16311
16312		var l_desc = new Tree(); // desc for literal tree
16313		var d_desc = new Tree(); // desc for distance tree
16314		var bl_desc = new Tree(); // desc for bit length tree
16315
16316		// that.heap_len; // number of elements in the heap
16317		// that.heap_max; // element of largest frequency
16318		// The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
16319		// The same heap array is used to build all trees.
16320
16321		// Depth of each subtree used as tie breaker for trees of equal frequency
16322		that.depth = [];
16323
16324		var l_buf; // index for literals or lengths */
16325
16326		// Size of match buffer for literals/lengths. There are 4 reasons for
16327		// limiting lit_bufsize to 64K:
16328		// - frequencies can be kept in 16 bit counters
16329		// - if compression is not successful for the first block, all input
16330		// data is still in the window so we can still emit a stored block even
16331		// when input comes from standard input. (This can also be done for
16332		// all blocks if lit_bufsize is not greater than 32K.)
16333		// - if compression is not successful for a file smaller than 64K, we can
16334		// even emit a stored file instead of a stored block (saving 5 bytes).
16335		// This is applicable only for zip (not gzip or zlib).
16336		// - creating new Huffman trees less frequently may not provide fast
16337		// adaptation to changes in the input data statistics. (Take for
16338		// example a binary file with poorly compressible code followed by
16339		// a highly compressible string table.) Smaller buffer sizes give
16340		// fast adaptation but have of course the overhead of transmitting
16341		// trees more frequently.
16342		// - I can't count above 4
16343		var lit_bufsize;
16344
16345		var last_lit; // running index in l_buf
16346
16347		// Buffer for distances. To simplify the code, d_buf and l_buf have
16348		// the same number of elements. To use different lengths, an extra flag
16349		// array would be necessary.
16350
16351		var d_buf; // index of pendig_buf
16352
16353		// that.opt_len; // bit length of current block with optimal trees
16354		// that.static_len; // bit length of current block with static trees
16355		var matches; // number of string matches in current block
16356		var last_eob_len; // bit length of EOB code for last block
16357
16358		// Output buffer. bits are inserted starting at the bottom (least
16359		// significant bits).
16360		var bi_buf;
16361
16362		// Number of valid bits in bi_buf. All bits above the last valid bit
16363		// are always zero.
16364		var bi_valid;
16365
16366		// number of codes at each bit length for an optimal tree
16367		that.bl_count = [];
16368
16369		// heap used to build the Huffman trees
16370		that.heap = [];
16371
16372		dyn_ltree = [];
16373		dyn_dtree = [];
16374		bl_tree = [];
16375
16376		function lm_init() {
16377			var i;
16378			window_size = 2 * w_size;
16379
16380			head[hash_size - 1] = 0;
16381			for (i = 0; i < hash_size - 1; i++) {
16382				head[i] = 0;
16383			}
16384
16385			// Set the default configuration parameters:
16386			max_lazy_match = config_table[level].max_lazy;
16387			good_match = config_table[level].good_length;
16388			nice_match = config_table[level].nice_length;
16389			max_chain_length = config_table[level].max_chain;
16390
16391			strstart = 0;
16392			block_start = 0;
16393			lookahead = 0;
16394			match_length = prev_length = MIN_MATCH - 1;
16395			match_available = 0;
16396			ins_h = 0;
16397		}
16398
16399		function init_block() {
16400			var i;
16401			// Initialize the trees.
16402			for (i = 0; i < L_CODES; i++)
16403				dyn_ltree[i * 2] = 0;
16404			for (i = 0; i < D_CODES; i++)
16405				dyn_dtree[i * 2] = 0;
16406			for (i = 0; i < BL_CODES; i++)
16407				bl_tree[i * 2] = 0;
16408
16409			dyn_ltree[END_BLOCK * 2] = 1;
16410			that.opt_len = that.static_len = 0;
16411			last_lit = matches = 0;
16412		}
16413
16414		// Initialize the tree data structures for a new zlib stream.
16415		function tr_init() {
16416
16417			l_desc.dyn_tree = dyn_ltree;
16418			l_desc.stat_desc = StaticTree.static_l_desc;
16419
16420			d_desc.dyn_tree = dyn_dtree;
16421			d_desc.stat_desc = StaticTree.static_d_desc;
16422
16423			bl_desc.dyn_tree = bl_tree;
16424			bl_desc.stat_desc = StaticTree.static_bl_desc;
16425
16426			bi_buf = 0;
16427			bi_valid = 0;
16428			last_eob_len = 8; // enough lookahead for inflate
16429
16430			// Initialize the first block of the first file:
16431			init_block();
16432		}
16433
16434		// Restore the heap property by moving down the tree starting at node k,
16435		// exchanging a node with the smallest of its two sons if necessary,
16436		// stopping
16437		// when the heap property is re-established (each father smaller than its
16438		// two sons).
16439		that.pqdownheap = function(tree, // the tree to restore
16440		k // node to move down
16441		) {
16442			var heap = that.heap;
16443			var v = heap[k];
16444			var j = k << 1; // left son of k
16445			while (j <= that.heap_len) {
16446				// Set j to the smallest of the two sons:
16447				if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
16448					j++;
16449				}
16450				// Exit if v is smaller than both sons
16451				if (smaller(tree, v, heap[j], that.depth))
16452					break;
16453
16454				// Exchange v with the smallest son
16455				heap[k] = heap[j];
16456				k = j;
16457				// And continue down the tree, setting j to the left son of k
16458				j <<= 1;
16459			}
16460			heap[k] = v;
16461		};
16462
16463		// Scan a literal or distance tree to determine the frequencies of the codes
16464		// in the bit length tree.
16465		function scan_tree(tree,// the tree to be scanned
16466		max_code // and its largest code of non zero frequency
16467		) {
16468			var n; // iterates over all tree elements
16469			var prevlen = -1; // last emitted length
16470			var curlen; // length of current code
16471			var nextlen = tree[0 * 2 + 1]; // length of next code
16472			var count = 0; // repeat count of the current code
16473			var max_count = 7; // max repeat count
16474			var min_count = 4; // min repeat count
16475
16476			if (nextlen === 0) {
16477				max_count = 138;
16478				min_count = 3;
16479			}
16480			tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
16481
16482			for (n = 0; n <= max_code; n++) {
16483				curlen = nextlen;
16484				nextlen = tree[(n + 1) * 2 + 1];
16485				if (++count < max_count && curlen == nextlen) {
16486					continue;
16487				} else if (count < min_count) {
16488					bl_tree[curlen * 2] += count;
16489				} else if (curlen !== 0) {
16490					if (curlen != prevlen)
16491						bl_tree[curlen * 2]++;
16492					bl_tree[REP_3_6 * 2]++;
16493				} else if (count <= 10) {
16494					bl_tree[REPZ_3_10 * 2]++;
16495				} else {
16496					bl_tree[REPZ_11_138 * 2]++;
16497				}
16498				count = 0;
16499				prevlen = curlen;
16500				if (nextlen === 0) {
16501					max_count = 138;
16502					min_count = 3;
16503				} else if (curlen == nextlen) {
16504					max_count = 6;
16505					min_count = 3;
16506				} else {
16507					max_count = 7;
16508					min_count = 4;
16509				}
16510			}
16511		}
16512
16513		// Construct the Huffman tree for the bit lengths and return the index in
16514		// bl_order of the last bit length code to send.
16515		function build_bl_tree() {
16516			var max_blindex; // index of last bit length code of non zero freq
16517
16518			// Determine the bit length frequencies for literal and distance trees
16519			scan_tree(dyn_ltree, l_desc.max_code);
16520			scan_tree(dyn_dtree, d_desc.max_code);
16521
16522			// Build the bit length tree:
16523			bl_desc.build_tree(that);
16524			// opt_len now includes the length of the tree representations, except
16525			// the lengths of the bit lengths codes and the 5+5+4 bits for the
16526			// counts.
16527
16528			// Determine the number of bit length codes to send. The pkzip format
16529			// requires that at least 4 bit length codes be sent. (appnote.txt says
16530			// 3 but the actual value used is 4.)
16531			for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
16532				if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
16533					break;
16534			}
16535			// Update opt_len to include the bit length tree and counts
16536			that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
16537
16538			return max_blindex;
16539		}
16540
16541		// Output a byte on the stream.
16542		// IN assertion: there is enough room in pending_buf.
16543		function put_byte(p) {
16544			that.pending_buf[that.pending++] = p;
16545		}
16546
16547		function put_short(w) {
16548			put_byte(w & 0xff);
16549			put_byte((w >>> 8) & 0xff);
16550		}
16551
16552		function putShortMSB(b) {
16553			put_byte((b >> 8) & 0xff);
16554			put_byte((b & 0xff) & 0xff);
16555		}
16556
16557		function send_bits(value, length) {
16558			var val, len = length;
16559			if (bi_valid > Buf_size - len) {
16560				val = value;
16561				// bi_buf |= (val << bi_valid);
16562				bi_buf |= ((val << bi_valid) & 0xffff);
16563				put_short(bi_buf);
16564				bi_buf = val >>> (Buf_size - bi_valid);
16565				bi_valid += len - Buf_size;
16566			} else {
16567				// bi_buf |= (value) << bi_valid;
16568				bi_buf |= (((value) << bi_valid) & 0xffff);
16569				bi_valid += len;
16570			}
16571		}
16572
16573		function send_code(c, tree) {
16574			var c2 = c * 2;
16575			send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
16576		}
16577
16578		// Send a literal or distance tree in compressed form, using the codes in
16579		// bl_tree.
16580		function send_tree(tree,// the tree to be sent
16581		max_code // and its largest code of non zero frequency
16582		) {
16583			var n; // iterates over all tree elements
16584			var prevlen = -1; // last emitted length
16585			var curlen; // length of current code
16586			var nextlen = tree[0 * 2 + 1]; // length of next code
16587			var count = 0; // repeat count of the current code
16588			var max_count = 7; // max repeat count
16589			var min_count = 4; // min repeat count
16590
16591			if (nextlen === 0) {
16592				max_count = 138;
16593				min_count = 3;
16594			}
16595
16596			for (n = 0; n <= max_code; n++) {
16597				curlen = nextlen;
16598				nextlen = tree[(n + 1) * 2 + 1];
16599				if (++count < max_count && curlen == nextlen) {
16600					continue;
16601				} else if (count < min_count) {
16602					do {
16603						send_code(curlen, bl_tree);
16604					} while (--count !== 0);
16605				} else if (curlen !== 0) {
16606					if (curlen != prevlen) {
16607						send_code(curlen, bl_tree);
16608						count--;
16609					}
16610					send_code(REP_3_6, bl_tree);
16611					send_bits(count - 3, 2);
16612				} else if (count <= 10) {
16613					send_code(REPZ_3_10, bl_tree);
16614					send_bits(count - 3, 3);
16615				} else {
16616					send_code(REPZ_11_138, bl_tree);
16617					send_bits(count - 11, 7);
16618				}
16619				count = 0;
16620				prevlen = curlen;
16621				if (nextlen === 0) {
16622					max_count = 138;
16623					min_count = 3;
16624				} else if (curlen == nextlen) {
16625					max_count = 6;
16626					min_count = 3;
16627				} else {
16628					max_count = 7;
16629					min_count = 4;
16630				}
16631			}
16632		}
16633
16634		// Send the header for a block using dynamic Huffman trees: the counts, the
16635		// lengths of the bit length codes, the literal tree and the distance tree.
16636		// IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
16637		function send_all_trees(lcodes, dcodes, blcodes) {
16638			var rank; // index in bl_order
16639
16640			send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
16641			send_bits(dcodes - 1, 5);
16642			send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
16643			for (rank = 0; rank < blcodes; rank++) {
16644				send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
16645			}
16646			send_tree(dyn_ltree, lcodes - 1); // literal tree
16647			send_tree(dyn_dtree, dcodes - 1); // distance tree
16648		}
16649
16650		// Flush the bit buffer, keeping at most 7 bits in it.
16651		function bi_flush() {
16652			if (bi_valid == 16) {
16653				put_short(bi_buf);
16654				bi_buf = 0;
16655				bi_valid = 0;
16656			} else if (bi_valid >= 8) {
16657				put_byte(bi_buf & 0xff);
16658				bi_buf >>>= 8;
16659				bi_valid -= 8;
16660			}
16661		}
16662
16663		// Send one empty static block to give enough lookahead for inflate.
16664		// This takes 10 bits, of which 7 may remain in the bit buffer.
16665		// The current inflate code requires 9 bits of lookahead. If the
16666		// last two codes for the previous block (real code plus EOB) were coded
16667		// on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
16668		// the last real code. In this case we send two empty static blocks instead
16669		// of one. (There are no problems if the previous block is stored or fixed.)
16670		// To simplify the code, we assume the worst case of last real code encoded
16671		// on one bit only.
16672		function _tr_align() {
16673			send_bits(STATIC_TREES << 1, 3);
16674			send_code(END_BLOCK, StaticTree.static_ltree);
16675
16676			bi_flush();
16677
16678			// Of the 10 bits for the empty block, we have already sent
16679			// (10 - bi_valid) bits. The lookahead for the last real code (before
16680			// the EOB of the previous block) was thus at least one plus the length
16681			// of the EOB plus what we have just sent of the empty static block.
16682			if (1 + last_eob_len + 10 - bi_valid < 9) {
16683				send_bits(STATIC_TREES << 1, 3);
16684				send_code(END_BLOCK, StaticTree.static_ltree);
16685				bi_flush();
16686			}
16687			last_eob_len = 7;
16688		}
16689
16690		// Save the match info and tally the frequency counts. Return true if
16691		// the current block must be flushed.
16692		function _tr_tally(dist, // distance of matched string
16693		lc // match length-MIN_MATCH or unmatched char (if dist==0)
16694		) {
16695			var out_length, in_length, dcode;
16696			that.pending_buf[d_buf + last_lit * 2] = (dist >>> 8) & 0xff;
16697			that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
16698
16699			that.pending_buf[l_buf + last_lit] = lc & 0xff;
16700			last_lit++;
16701
16702			if (dist === 0) {
16703				// lc is the unmatched char
16704				dyn_ltree[lc * 2]++;
16705			} else {
16706				matches++;
16707				// Here, lc is the match length - MIN_MATCH
16708				dist--; // dist = match distance - 1
16709				dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
16710				dyn_dtree[Tree.d_code(dist) * 2]++;
16711			}
16712
16713			if ((last_lit & 0x1fff) === 0 && level > 2) {
16714				// Compute an upper bound for the compressed length
16715				out_length = last_lit * 8;
16716				in_length = strstart - block_start;
16717				for (dcode = 0; dcode < D_CODES; dcode++) {
16718					out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
16719				}
16720				out_length >>>= 3;
16721				if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
16722					return true;
16723			}
16724
16725			return (last_lit == lit_bufsize - 1);
16726			// We avoid equality with lit_bufsize because of wraparound at 64K
16727			// on 16 bit machines and because stored blocks are restricted to
16728			// 64K-1 bytes.
16729		}
16730
16731		// Send the block data compressed using the given Huffman trees
16732		function compress_block(ltree, dtree) {
16733			var dist; // distance of matched string
16734			var lc; // match length or unmatched char (if dist === 0)
16735			var lx = 0; // running index in l_buf
16736			var code; // the code to send
16737			var extra; // number of extra bits to send
16738
16739			if (last_lit !== 0) {
16740				do {
16741					dist = ((that.pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (that.pending_buf[d_buf + lx * 2 + 1] & 0xff);
16742					lc = (that.pending_buf[l_buf + lx]) & 0xff;
16743					lx++;
16744
16745					if (dist === 0) {
16746						send_code(lc, ltree); // send a literal byte
16747					} else {
16748						// Here, lc is the match length - MIN_MATCH
16749						code = Tree._length_code[lc];
16750
16751						send_code(code + LITERALS + 1, ltree); // send the length
16752						// code
16753						extra = Tree.extra_lbits[code];
16754						if (extra !== 0) {
16755							lc -= Tree.base_length[code];
16756							send_bits(lc, extra); // send the extra length bits
16757						}
16758						dist--; // dist is now the match distance - 1
16759						code = Tree.d_code(dist);
16760
16761						send_code(code, dtree); // send the distance code
16762						extra = Tree.extra_dbits[code];
16763						if (extra !== 0) {
16764							dist -= Tree.base_dist[code];
16765							send_bits(dist, extra); // send the extra distance bits
16766						}
16767					} // literal or match pair ?
16768
16769					// Check that the overlay between pending_buf and d_buf+l_buf is
16770					// ok:
16771				} while (lx < last_lit);
16772			}
16773
16774			send_code(END_BLOCK, ltree);
16775			last_eob_len = ltree[END_BLOCK * 2 + 1];
16776		}
16777
16778		// Flush the bit buffer and align the output on a byte boundary
16779		function bi_windup() {
16780			if (bi_valid > 8) {
16781				put_short(bi_buf);
16782			} else if (bi_valid > 0) {
16783				put_byte(bi_buf & 0xff);
16784			}
16785			bi_buf = 0;
16786			bi_valid = 0;
16787		}
16788
16789		// Copy a stored block, storing first the length and its
16790		// one's complement if requested.
16791		function copy_block(buf, // the input data
16792		len, // its length
16793		header // true if block header must be written
16794		) {
16795			bi_windup(); // align on byte boundary
16796			last_eob_len = 8; // enough lookahead for inflate
16797
16798			if (header) {
16799				put_short(len);
16800				put_short(~len);
16801			}
16802
16803			that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
16804			that.pending += len;
16805		}
16806
16807		// Send a stored block
16808		function _tr_stored_block(buf, // input block
16809		stored_len, // length of input block
16810		eof // true if this is the last block for a file
16811		) {
16812			send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
16813			copy_block(buf, stored_len, true); // with header
16814		}
16815
16816		// Determine the best encoding for the current block: dynamic trees, static
16817		// trees or store, and output the encoded block to the zip file.
16818		function _tr_flush_block(buf, // input block, or NULL if too old
16819		stored_len, // length of input block
16820		eof // true if this is the last block for a file
16821		) {
16822			var opt_lenb, static_lenb;// opt_len and static_len in bytes
16823			var max_blindex = 0; // index of last bit length code of non zero freq
16824
16825			// Build the Huffman trees unless a stored block is forced
16826			if (level > 0) {
16827				// Construct the literal and distance trees
16828				l_desc.build_tree(that);
16829
16830				d_desc.build_tree(that);
16831
16832				// At this point, opt_len and static_len are the total bit lengths
16833				// of
16834				// the compressed block data, excluding the tree representations.
16835
16836				// Build the bit length tree for the above two trees, and get the
16837				// index
16838				// in bl_order of the last bit length code to send.
16839				max_blindex = build_bl_tree();
16840
16841				// Determine the best encoding. Compute first the block length in
16842				// bytes
16843				opt_lenb = (that.opt_len + 3 + 7) >>> 3;
16844				static_lenb = (that.static_len + 3 + 7) >>> 3;
16845
16846				if (static_lenb <= opt_lenb)
16847					opt_lenb = static_lenb;
16848			} else {
16849				opt_lenb = static_lenb = stored_len + 5; // force a stored block
16850			}
16851
16852			if ((stored_len + 4 <= opt_lenb) && buf != -1) {
16853				// 4: two words for the lengths
16854				// The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
16855				// Otherwise we can't have processed more than WSIZE input bytes
16856				// since
16857				// the last block flush, because compression would have been
16858				// successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
16859				// transform a block into a stored block.
16860				_tr_stored_block(buf, stored_len, eof);
16861			} else if (static_lenb == opt_lenb) {
16862				send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
16863				compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
16864			} else {
16865				send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
16866				send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
16867				compress_block(dyn_ltree, dyn_dtree);
16868			}
16869
16870			// The above check is made mod 2^32, for files larger than 512 MB
16871			// and uLong implemented on 32 bits.
16872
16873			init_block();
16874
16875			if (eof) {
16876				bi_windup();
16877			}
16878		}
16879
16880		function flush_block_only(eof) {
16881			_tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
16882			block_start = strstart;
16883			strm.flush_pending();
16884		}
16885
16886		// Fill the window when the lookahead becomes insufficient.
16887		// Updates strstart and lookahead.
16888		//
16889		// IN assertion: lookahead < MIN_LOOKAHEAD
16890		// OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
16891		// At least one byte has been read, or avail_in === 0; reads are
16892		// performed for at least two bytes (required for the zip translate_eol
16893		// option -- not supported here).
16894		function fill_window() {
16895			var n, m;
16896			var p;
16897			var more; // Amount of free space at the end of the window.
16898
16899			do {
16900				more = (window_size - lookahead - strstart);
16901
16902				// Deal with !@#$% 64K limit:
16903				if (more === 0 && strstart === 0 && lookahead === 0) {
16904					more = w_size;
16905				} else if (more == -1) {
16906					// Very unlikely, but possible on 16 bit machine if strstart ==
16907					// 0
16908					// and lookahead == 1 (input done one byte at time)
16909					more--;
16910
16911					// If the window is almost full and there is insufficient
16912					// lookahead,
16913					// move the upper half to the lower one to make room in the
16914					// upper half.
16915				} else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
16916					window.set(window.subarray(w_size, w_size + w_size), 0);
16917
16918					match_start -= w_size;
16919					strstart -= w_size; // we now have strstart >= MAX_DIST
16920					block_start -= w_size;
16921
16922					// Slide the hash table (could be avoided with 32 bit values
16923					// at the expense of memory usage). We slide even when level ==
16924					// 0
16925					// to keep the hash table consistent if we switch back to level
16926					// > 0
16927					// later. (Using level 0 permanently is not an optimal usage of
16928					// zlib, so we don't care about this pathological case.)
16929
16930					n = hash_size;
16931					p = n;
16932					do {
16933						m = (head[--p] & 0xffff);
16934						head[p] = (m >= w_size ? m - w_size : 0);
16935					} while (--n !== 0);
16936
16937					n = w_size;
16938					p = n;
16939					do {
16940						m = (prev[--p] & 0xffff);
16941						prev[p] = (m >= w_size ? m - w_size : 0);
16942						// If n is not on any hash chain, prev[n] is garbage but
16943						// its value will never be used.
16944					} while (--n !== 0);
16945					more += w_size;
16946				}
16947
16948				if (strm.avail_in === 0)
16949					return;
16950
16951				// If there was no sliding:
16952				// strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
16953				// more == window_size - lookahead - strstart
16954				// => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
16955				// => more >= window_size - 2*WSIZE + 2
16956				// In the BIG_MEM or MMAP case (not yet supported),
16957				// window_size == input_size + MIN_LOOKAHEAD &&
16958				// strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
16959				// Otherwise, window_size == 2*WSIZE so more >= 2.
16960				// If there was sliding, more >= WSIZE. So in all cases, more >= 2.
16961
16962				n = strm.read_buf(window, strstart + lookahead, more);
16963				lookahead += n;
16964
16965				// Initialize the hash value now that we have some input:
16966				if (lookahead >= MIN_MATCH) {
16967					ins_h = window[strstart] & 0xff;
16968					ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
16969				}
16970				// If the whole input has less than MIN_MATCH bytes, ins_h is
16971				// garbage,
16972				// but this is not important since only literal bytes will be
16973				// emitted.
16974			} while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
16975		}
16976
16977		// Copy without compression as much as possible from the input stream,
16978		// return
16979		// the current block state.
16980		// This function does not insert new strings in the dictionary since
16981		// uncompressible data is probably not useful. This function is used
16982		// only for the level=0 compression option.
16983		// NOTE: this function should be optimized to avoid extra copying from
16984		// window to pending_buf.
16985		function deflate_stored(flush) {
16986			// Stored blocks are limited to 0xffff bytes, pending_buf is limited
16987			// to pending_buf_size, and each stored block has a 5 byte header:
16988
16989			var max_block_size = 0xffff;
16990			var max_start;
16991
16992			if (max_block_size > pending_buf_size - 5) {
16993				max_block_size = pending_buf_size - 5;
16994			}
16995
16996			// Copy as much as possible from input to output:
16997			while (true) {
16998				// Fill the window as much as possible:
16999				if (lookahead <= 1) {
17000					fill_window();
17001					if (lookahead === 0 && flush == Z_NO_FLUSH)
17002						return NeedMore;
17003					if (lookahead === 0)
17004						break; // flush the current block
17005				}
17006
17007				strstart += lookahead;
17008				lookahead = 0;
17009
17010				// Emit a stored block if pending_buf will be full:
17011				max_start = block_start + max_block_size;
17012				if (strstart === 0 || strstart >= max_start) {
17013					// strstart === 0 is possible when wraparound on 16-bit machine
17014					lookahead = (strstart - max_start);
17015					strstart = max_start;
17016
17017					flush_block_only(false);
17018					if (strm.avail_out === 0)
17019						return NeedMore;
17020
17021				}
17022
17023				// Flush if we may have to slide, otherwise block_start may become
17024				// negative and the data will be gone:
17025				if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
17026					flush_block_only(false);
17027					if (strm.avail_out === 0)
17028						return NeedMore;
17029				}
17030			}
17031
17032			flush_block_only(flush == Z_FINISH);
17033			if (strm.avail_out === 0)
17034				return (flush == Z_FINISH) ? FinishStarted : NeedMore;
17035
17036			return flush == Z_FINISH ? FinishDone : BlockDone;
17037		}
17038
17039		function longest_match(cur_match) {
17040			var chain_length = max_chain_length; // max hash chain length
17041			var scan = strstart; // current string
17042			var match; // matched string
17043			var len; // length of current match
17044			var best_len = prev_length; // best match length so far
17045			var limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
17046			var _nice_match = nice_match;
17047
17048			// Stop when cur_match becomes <= limit. To simplify the code,
17049			// we prevent matches with the string of window index 0.
17050
17051			var wmask = w_mask;
17052
17053			var strend = strstart + MAX_MATCH;
17054			var scan_end1 = window[scan + best_len - 1];
17055			var scan_end = window[scan + best_len];
17056
17057			// The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
17058			// 16.
17059			// It is easy to get rid of this optimization if necessary.
17060
17061			// Do not waste too much time if we already have a good match:
17062			if (prev_length >= good_match) {
17063				chain_length >>= 2;
17064			}
17065
17066			// Do not look for matches beyond the end of the input. This is
17067			// necessary
17068			// to make deflate deterministic.
17069			if (_nice_match > lookahead)
17070				_nice_match = lookahead;
17071
17072			do {
17073				match = cur_match;
17074
17075				// Skip to next match if the match length cannot increase
17076				// or if the match length is less than 2:
17077				if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan]
17078						|| window[++match] != window[scan + 1])
17079					continue;
17080
17081				// The check at best_len-1 can be removed because it will be made
17082				// again later. (This heuristic is not always a win.)
17083				// It is not necessary to compare scan[2] and match[2] since they
17084				// are always equal when the other bytes match, given that
17085				// the hash keys are equal and that HASH_BITS >= 8.
17086				scan += 2;
17087				match++;
17088
17089				// We check for insufficient lookahead only every 8th comparison;
17090				// the 256th check will be made at strstart+258.
17091				do {
17092				} while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
17093						&& window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match]
17094						&& window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
17095
17096				len = MAX_MATCH - (strend - scan);
17097				scan = strend - MAX_MATCH;
17098
17099				if (len > best_len) {
17100					match_start = cur_match;
17101					best_len = len;
17102					if (len >= _nice_match)
17103						break;
17104					scan_end1 = window[scan + best_len - 1];
17105					scan_end = window[scan + best_len];
17106				}
17107
17108			} while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);
17109
17110			if (best_len <= lookahead)
17111				return best_len;
17112			return lookahead;
17113		}
17114
17115		// Compress as much as possible from the input stream, return the current
17116		// block state.
17117		// This function does not perform lazy evaluation of matches and inserts
17118		// new strings in the dictionary only for unmatched strings or for short
17119		// matches. It is used only for the fast compression options.
17120		function deflate_fast(flush) {
17121			// short hash_head = 0; // head of the hash chain
17122			var hash_head = 0; // head of the hash chain
17123			var bflush; // set if current block must be flushed
17124
17125			while (true) {
17126				// Make sure that we always have enough lookahead, except
17127				// at the end of the input file. We need MAX_MATCH bytes
17128				// for the next match, plus MIN_MATCH bytes to insert the
17129				// string following the next match.
17130				if (lookahead < MIN_LOOKAHEAD) {
17131					fill_window();
17132					if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
17133						return NeedMore;
17134					}
17135					if (lookahead === 0)
17136						break; // flush the current block
17137				}
17138
17139				// Insert the string window[strstart .. strstart+2] in the
17140				// dictionary, and set hash_head to the head of the hash chain:
17141				if (lookahead >= MIN_MATCH) {
17142					ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
17143
17144					// prev[strstart&w_mask]=hash_head=head[ins_h];
17145					hash_head = (head[ins_h] & 0xffff);
17146					prev[strstart & w_mask] = head[ins_h];
17147					head[ins_h] = strstart;
17148				}
17149
17150				// Find the longest match, discarding those <= prev_length.
17151				// At this point we have always match_length < MIN_MATCH
17152
17153				if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
17154					// To simplify the code, we prevent matches with the string
17155					// of window index 0 (in particular we have to avoid a match
17156					// of the string with itself at the start of the input file).
17157					if (strategy != Z_HUFFMAN_ONLY) {
17158						match_length = longest_match(hash_head);
17159					}
17160					// longest_match() sets match_start
17161				}
17162				if (match_length >= MIN_MATCH) {
17163					// check_match(strstart, match_start, match_length);
17164
17165					bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
17166
17167					lookahead -= match_length;
17168
17169					// Insert new strings in the hash table only if the match length
17170					// is not too large. This saves time but degrades compression.
17171					if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
17172						match_length--; // string at strstart already in hash table
17173						do {
17174							strstart++;
17175
17176							ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
17177							// prev[strstart&w_mask]=hash_head=head[ins_h];
17178							hash_head = (head[ins_h] & 0xffff);
17179							prev[strstart & w_mask] = head[ins_h];
17180							head[ins_h] = strstart;
17181
17182							// strstart never exceeds WSIZE-MAX_MATCH, so there are
17183							// always MIN_MATCH bytes ahead.
17184						} while (--match_length !== 0);
17185						strstart++;
17186					} else {
17187						strstart += match_length;
17188						match_length = 0;
17189						ins_h = window[strstart] & 0xff;
17190
17191						ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
17192						// If lookahead < MIN_MATCH, ins_h is garbage, but it does
17193						// not
17194						// matter since it will be recomputed at next deflate call.
17195					}
17196				} else {
17197					// No match, output a literal byte
17198
17199					bflush = _tr_tally(0, window[strstart] & 0xff);
17200					lookahead--;
17201					strstart++;
17202				}
17203				if (bflush) {
17204
17205					flush_block_only(false);
17206					if (strm.avail_out === 0)
17207						return NeedMore;
17208				}
17209			}
17210
17211			flush_block_only(flush == Z_FINISH);
17212			if (strm.avail_out === 0) {
17213				if (flush == Z_FINISH)
17214					return FinishStarted;
17215				else
17216					return NeedMore;
17217			}
17218			return flush == Z_FINISH ? FinishDone : BlockDone;
17219		}
17220
17221		// Same as above, but achieves better compression. We use a lazy
17222		// evaluation for matches: a match is finally adopted only if there is
17223		// no better match at the next window position.
17224		function deflate_slow(flush) {
17225			// short hash_head = 0; // head of hash chain
17226			var hash_head = 0; // head of hash chain
17227			var bflush; // set if current block must be flushed
17228			var max_insert;
17229
17230			// Process the input block.
17231			while (true) {
17232				// Make sure that we always have enough lookahead, except
17233				// at the end of the input file. We need MAX_MATCH bytes
17234				// for the next match, plus MIN_MATCH bytes to insert the
17235				// string following the next match.
17236
17237				if (lookahead < MIN_LOOKAHEAD) {
17238					fill_window();
17239					if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
17240						return NeedMore;
17241					}
17242					if (lookahead === 0)
17243						break; // flush the current block
17244				}
17245
17246				// Insert the string window[strstart .. strstart+2] in the
17247				// dictionary, and set hash_head to the head of the hash chain:
17248
17249				if (lookahead >= MIN_MATCH) {
17250					ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
17251					// prev[strstart&w_mask]=hash_head=head[ins_h];
17252					hash_head = (head[ins_h] & 0xffff);
17253					prev[strstart & w_mask] = head[ins_h];
17254					head[ins_h] = strstart;
17255				}
17256
17257				// Find the longest match, discarding those <= prev_length.
17258				prev_length = match_length;
17259				prev_match = match_start;
17260				match_length = MIN_MATCH - 1;
17261
17262				if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
17263					// To simplify the code, we prevent matches with the string
17264					// of window index 0 (in particular we have to avoid a match
17265					// of the string with itself at the start of the input file).
17266
17267					if (strategy != Z_HUFFMAN_ONLY) {
17268						match_length = longest_match(hash_head);
17269					}
17270					// longest_match() sets match_start
17271
17272					if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
17273
17274						// If prev_match is also MIN_MATCH, match_start is garbage
17275						// but we will ignore the current match anyway.
17276						match_length = MIN_MATCH - 1;
17277					}
17278				}
17279
17280				// If there was a match at the previous step and the current
17281				// match is not better, output the previous match:
17282				if (prev_length >= MIN_MATCH && match_length <= prev_length) {
17283					max_insert = strstart + lookahead - MIN_MATCH;
17284					// Do not insert strings in hash table beyond this.
17285
17286					// check_match(strstart-1, prev_match, prev_length);
17287
17288					bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
17289
17290					// Insert in hash table all strings up to the end of the match.
17291					// strstart-1 and strstart are already inserted. If there is not
17292					// enough lookahead, the last two strings are not inserted in
17293					// the hash table.
17294					lookahead -= prev_length - 1;
17295					prev_length -= 2;
17296					do {
17297						if (++strstart <= max_insert) {
17298							ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
17299							// prev[strstart&w_mask]=hash_head=head[ins_h];
17300							hash_head = (head[ins_h] & 0xffff);
17301							prev[strstart & w_mask] = head[ins_h];
17302							head[ins_h] = strstart;
17303						}
17304					} while (--prev_length !== 0);
17305					match_available = 0;
17306					match_length = MIN_MATCH - 1;
17307					strstart++;
17308
17309					if (bflush) {
17310						flush_block_only(false);
17311						if (strm.avail_out === 0)
17312							return NeedMore;
17313					}
17314				} else if (match_available !== 0) {
17315
17316					// If there was no match at the previous position, output a
17317					// single literal. If there was a match but the current match
17318					// is longer, truncate the previous match to a single literal.
17319
17320					bflush = _tr_tally(0, window[strstart - 1] & 0xff);
17321
17322					if (bflush) {
17323						flush_block_only(false);
17324					}
17325					strstart++;
17326					lookahead--;
17327					if (strm.avail_out === 0)
17328						return NeedMore;
17329				} else {
17330					// There is no previous match to compare with, wait for
17331					// the next step to decide.
17332
17333					match_available = 1;
17334					strstart++;
17335					lookahead--;
17336				}
17337			}
17338
17339			if (match_available !== 0) {
17340				bflush = _tr_tally(0, window[strstart - 1] & 0xff);
17341				match_available = 0;
17342			}
17343			flush_block_only(flush == Z_FINISH);
17344
17345			if (strm.avail_out === 0) {
17346				if (flush == Z_FINISH)
17347					return FinishStarted;
17348				else
17349					return NeedMore;
17350			}
17351
17352			return flush == Z_FINISH ? FinishDone : BlockDone;
17353		}
17354
17355		function deflateReset(strm) {
17356			strm.total_in = strm.total_out = 0;
17357			strm.msg = null; //
17358			
17359			that.pending = 0;
17360			that.pending_out = 0;
17361
17362			status = BUSY_STATE;
17363
17364			last_flush = Z_NO_FLUSH;
17365
17366			tr_init();
17367			lm_init();
17368			return Z_OK;
17369		}
17370
17371		that.deflateInit = function(strm, _level, bits, _method, memLevel, _strategy) {
17372			if (!_method)
17373				_method = Z_DEFLATED;
17374			if (!memLevel)
17375				memLevel = DEF_MEM_LEVEL;
17376			if (!_strategy)
17377				_strategy = Z_DEFAULT_STRATEGY;
17378
17379			// byte[] my_version=ZLIB_VERSION;
17380
17381			//
17382			// if (!version || version[0] != my_version[0]
17383			// || stream_size != sizeof(z_stream)) {
17384			// return Z_VERSION_ERROR;
17385			// }
17386
17387			strm.msg = null;
17388
17389			if (_level == Z_DEFAULT_COMPRESSION)
17390				_level = 6;
17391
17392			if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0
17393					|| _strategy > Z_HUFFMAN_ONLY) {
17394				return Z_STREAM_ERROR;
17395			}
17396
17397			strm.dstate = that;
17398
17399			w_bits = bits;
17400			w_size = 1 << w_bits;
17401			w_mask = w_size - 1;
17402
17403			hash_bits = memLevel + 7;
17404			hash_size = 1 << hash_bits;
17405			hash_mask = hash_size - 1;
17406			hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
17407
17408			window = new Uint8Array(w_size * 2);
17409			prev = [];
17410			head = [];
17411
17412			lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
17413
17414			// We overlay pending_buf and d_buf+l_buf. This works since the average
17415			// output size for (length,distance) codes is <= 24 bits.
17416			that.pending_buf = new Uint8Array(lit_bufsize * 4);
17417			pending_buf_size = lit_bufsize * 4;
17418
17419			d_buf = Math.floor(lit_bufsize / 2);
17420			l_buf = (1 + 2) * lit_bufsize;
17421
17422			level = _level;
17423
17424			strategy = _strategy;
17425			return deflateReset(strm);
17426		};
17427
17428		that.deflateEnd = function() {
17429			if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
17430				return Z_STREAM_ERROR;
17431			}
17432			// Deallocate in reverse order of allocations:
17433			that.pending_buf = null;
17434			head = null;
17435			prev = null;
17436			window = null;
17437			// free
17438			that.dstate = null;
17439			return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
17440		};
17441
17442		that.deflateParams = function(strm, _level, _strategy) {
17443			var err = Z_OK;
17444
17445			if (_level == Z_DEFAULT_COMPRESSION) {
17446				_level = 6;
17447			}
17448			if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
17449				return Z_STREAM_ERROR;
17450			}
17451
17452			if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
17453				// Flush the last buffer:
17454				err = strm.deflate(Z_PARTIAL_FLUSH);
17455			}
17456
17457			if (level != _level) {
17458				level = _level;
17459				max_lazy_match = config_table[level].max_lazy;
17460				good_match = config_table[level].good_length;
17461				nice_match = config_table[level].nice_length;
17462				max_chain_length = config_table[level].max_chain;
17463			}
17464			strategy = _strategy;
17465			return err;
17466		};
17467
17468		that.deflateSetDictionary = function(strm, dictionary, dictLength) {
17469			var length = dictLength;
17470			var n, index = 0;
17471
17472			if (!dictionary || status != INIT_STATE)
17473				return Z_STREAM_ERROR;
17474
17475			if (length < MIN_MATCH)
17476				return Z_OK;
17477			if (length > w_size - MIN_LOOKAHEAD) {
17478				length = w_size - MIN_LOOKAHEAD;
17479				index = dictLength - length; // use the tail of the dictionary
17480			}
17481			window.set(dictionary.subarray(index, index + length), 0);
17482
17483			strstart = length;
17484			block_start = length;
17485
17486			// Insert all strings in the hash table (except for the last two bytes).
17487			// s->lookahead stays null, so s->ins_h will be recomputed at the next
17488			// call of fill_window.
17489
17490			ins_h = window[0] & 0xff;
17491			ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
17492
17493			for (n = 0; n <= length - MIN_MATCH; n++) {
17494				ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
17495				prev[n & w_mask] = head[ins_h];
17496				head[ins_h] = n;
17497			}
17498			return Z_OK;
17499		};
17500
17501		that.deflate = function(_strm, flush) {
17502			var i, header, level_flags, old_flush, bstate;
17503
17504			if (flush > Z_FINISH || flush < 0) {
17505				return Z_STREAM_ERROR;
17506			}
17507
17508			if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH)) {
17509				_strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
17510				return Z_STREAM_ERROR;
17511			}
17512			if (_strm.avail_out === 0) {
17513				_strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
17514				return Z_BUF_ERROR;
17515			}
17516
17517			strm = _strm; // just in case
17518			old_flush = last_flush;
17519			last_flush = flush;
17520
17521			// Write the zlib header
17522			if (status == INIT_STATE) {
17523				header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
17524				level_flags = ((level - 1) & 0xff) >> 1;
17525
17526				if (level_flags > 3)
17527					level_flags = 3;
17528				header |= (level_flags << 6);
17529				if (strstart !== 0)
17530					header |= PRESET_DICT;
17531				header += 31 - (header % 31);
17532
17533				status = BUSY_STATE;
17534				putShortMSB(header);
17535			}
17536
17537			// Flush as much pending output as possible
17538			if (that.pending !== 0) {
17539				strm.flush_pending();
17540				if (strm.avail_out === 0) {
17541					// console.log(" avail_out==0");
17542					// Since avail_out is 0, deflate will be called again with
17543					// more output space, but possibly with both pending and
17544					// avail_in equal to zero. There won't be anything to do,
17545					// but this is not an error situation so make sure we
17546					// return OK instead of BUF_ERROR at next call of deflate:
17547					last_flush = -1;
17548					return Z_OK;
17549				}
17550
17551				// Make sure there is something to do and avoid duplicate
17552				// consecutive
17553				// flushes. For repeated and useless calls with Z_FINISH, we keep
17554				// returning Z_STREAM_END instead of Z_BUFF_ERROR.
17555			} else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
17556				strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
17557				return Z_BUF_ERROR;
17558			}
17559
17560			// User must not provide more input after the first FINISH:
17561			if (status == FINISH_STATE && strm.avail_in !== 0) {
17562				_strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
17563				return Z_BUF_ERROR;
17564			}
17565
17566			// Start a new block or continue the current one.
17567			if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
17568				bstate = -1;
17569				switch (config_table[level].func) {
17570				case STORED:
17571					bstate = deflate_stored(flush);
17572					break;
17573				case FAST:
17574					bstate = deflate_fast(flush);
17575					break;
17576				case SLOW:
17577					bstate = deflate_slow(flush);
17578					break;
17579				default:
17580				}
17581
17582				if (bstate == FinishStarted || bstate == FinishDone) {
17583					status = FINISH_STATE;
17584				}
17585				if (bstate == NeedMore || bstate == FinishStarted) {
17586					if (strm.avail_out === 0) {
17587						last_flush = -1; // avoid BUF_ERROR next call, see above
17588					}
17589					return Z_OK;
17590					// If flush != Z_NO_FLUSH && avail_out === 0, the next call
17591					// of deflate should use the same flush parameter to make sure
17592					// that the flush is complete. So we don't have to output an
17593					// empty block here, this will be done at next call. This also
17594					// ensures that for a very small output buffer, we emit at most
17595					// one empty block.
17596				}
17597
17598				if (bstate == BlockDone) {
17599					if (flush == Z_PARTIAL_FLUSH) {
17600						_tr_align();
17601					} else { // FULL_FLUSH or SYNC_FLUSH
17602						_tr_stored_block(0, 0, false);
17603						// For a full flush, this empty block will be recognized
17604						// as a special marker by inflate_sync().
17605						if (flush == Z_FULL_FLUSH) {
17606							// state.head[s.hash_size-1]=0;
17607							for (i = 0; i < hash_size/*-1*/; i++)
17608								// forget history
17609								head[i] = 0;
17610						}
17611					}
17612					strm.flush_pending();
17613					if (strm.avail_out === 0) {
17614						last_flush = -1; // avoid BUF_ERROR at next call, see above
17615						return Z_OK;
17616					}
17617				}
17618			}
17619
17620			if (flush != Z_FINISH)
17621				return Z_OK;
17622			return Z_STREAM_END;
17623		};
17624	}
17625
17626	// ZStream
17627
17628	function ZStream() {
17629		var that = this;
17630		that.next_in_index = 0;
17631		that.next_out_index = 0;
17632		// that.next_in; // next input byte
17633		that.avail_in = 0; // number of bytes available at next_in
17634		that.total_in = 0; // total nb of input bytes read so far
17635		// that.next_out; // next output byte should be put there
17636		that.avail_out = 0; // remaining free space at next_out
17637		that.total_out = 0; // total nb of bytes output so far
17638		// that.msg;
17639		// that.dstate;
17640	}
17641
17642	ZStream.prototype = {
17643		deflateInit : function(level, bits) {
17644			var that = this;
17645			that.dstate = new Deflate();
17646			if (!bits)
17647				bits = MAX_BITS;
17648			return that.dstate.deflateInit(that, level, bits);
17649		},
17650
17651		deflate : function(flush) {
17652			var that = this;
17653			if (!that.dstate) {
17654				return Z_STREAM_ERROR;
17655			}
17656			return that.dstate.deflate(that, flush);
17657		},
17658
17659		deflateEnd : function() {
17660			var that = this;
17661			if (!that.dstate)
17662				return Z_STREAM_ERROR;
17663			var ret = that.dstate.deflateEnd();
17664			that.dstate = null;
17665			return ret;
17666		},
17667
17668		deflateParams : function(level, strategy) {
17669			var that = this;
17670			if (!that.dstate)
17671				return Z_STREAM_ERROR;
17672			return that.dstate.deflateParams(that, level, strategy);
17673		},
17674
17675		deflateSetDictionary : function(dictionary, dictLength) {
17676			var that = this;
17677			if (!that.dstate)
17678				return Z_STREAM_ERROR;
17679			return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
17680		},
17681
17682		// Read a new buffer from the current input stream, update the
17683		// total number of bytes read. All deflate() input goes through
17684		// this function so some applications may wish to modify it to avoid
17685		// allocating a large strm->next_in buffer and copying from it.
17686		// (See also flush_pending()).
17687		read_buf : function(buf, start, size) {
17688			var that = this;
17689			var len = that.avail_in;
17690			if (len > size)
17691				len = size;
17692			if (len === 0)
17693				return 0;
17694			that.avail_in -= len;
17695			buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
17696			that.next_in_index += len;
17697			that.total_in += len;
17698			return len;
17699		},
17700
17701		// Flush as much pending output as possible. All deflate() output goes
17702		// through this function so some applications may wish to modify it
17703		// to avoid allocating a large strm->next_out buffer and copying into it.
17704		// (See also read_buf()).
17705		flush_pending : function() {
17706			var that = this;
17707			var len = that.dstate.pending;
17708
17709			if (len > that.avail_out)
17710				len = that.avail_out;
17711			if (len === 0)
17712				return;
17713
17714			// if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
17715			// || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
17716			// len)) {
17717			// console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
17718			// that.next_out_index + ", " + len);
17719			// console.log("avail_out=" + that.avail_out);
17720			// }
17721
17722			that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
17723
17724			that.next_out_index += len;
17725			that.dstate.pending_out += len;
17726			that.total_out += len;
17727			that.avail_out -= len;
17728			that.dstate.pending -= len;
17729			if (that.dstate.pending === 0) {
17730				that.dstate.pending_out = 0;
17731			}
17732		}
17733	};
17734
17735	// Deflater
17736
17737	return function Deflater(level) {
17738		var that = this;
17739		var z = new ZStream();
17740		var bufsize = 512;
17741		var flush = Z_NO_FLUSH;
17742		var buf = new Uint8Array(bufsize);
17743
17744		if (typeof level == "undefined")
17745			level = Z_DEFAULT_COMPRESSION;
17746		z.deflateInit(level);
17747		z.next_out = buf;
17748
17749		that.append = function(data, onprogress) {
17750			var err, buffers = [], lastIndex = 0, bufferIndex = 0, bufferSize = 0, array;
17751			if (!data.length)
17752				return;
17753			z.next_in_index = 0;
17754			z.next_in = data;
17755			z.avail_in = data.length;
17756			do {
17757				z.next_out_index = 0;
17758				z.avail_out = bufsize;
17759				err = z.deflate(flush);
17760				if (err != Z_OK)
17761					throw "deflating: " + z.msg;
17762				if (z.next_out_index)
17763					if (z.next_out_index == bufsize)
17764						buffers.push(new Uint8Array(buf));
17765					else
17766						buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
17767				bufferSize += z.next_out_index;
17768				if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
17769					onprogress(z.next_in_index);
17770					lastIndex = z.next_in_index;
17771				}
17772			} while (z.avail_in > 0 || z.avail_out === 0);
17773			array = new Uint8Array(bufferSize);
17774			buffers.forEach(function(chunk) {
17775				array.set(chunk, bufferIndex);
17776				bufferIndex += chunk.length;
17777			});
17778			return array;
17779		};
17780		that.flush = function() {
17781			var err, buffers = [], bufferIndex = 0, bufferSize = 0, array;
17782			do {
17783				z.next_out_index = 0;
17784				z.avail_out = bufsize;
17785				err = z.deflate(Z_FINISH);
17786				if (err != Z_STREAM_END && err != Z_OK)
17787					throw "deflating: " + z.msg;
17788				if (bufsize - z.avail_out > 0)
17789					buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
17790				bufferSize += z.next_out_index;
17791			} while (z.avail_in > 0 || z.avail_out === 0);
17792			z.deflateEnd();
17793			array = new Uint8Array(bufferSize);
17794			buffers.forEach(function(chunk) {
17795				array.set(chunk, bufferIndex);
17796				bufferIndex += chunk.length;
17797			});
17798			return array;
17799		};
17800	};
17801})(undefined);
17802
17803
17804/*
17805  html2canvas 0.5.0-beta3 <http://html2canvas.hertzen.com>
17806  Copyright (c) 2016 Niklas von Hertzen
17807
17808  Released under  License
17809*/
17810
17811!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.html2canvas=e();}}(function(){var define;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
17812(function (global){
17813/*! http://mths.be/punycode v1.2.4 by @mathias */
17814(function(root) {
17815
17816	/** Detect free variables */
17817	var freeExports = typeof exports == 'object' && exports;
17818	var freeModule = typeof module == 'object' && module &&
17819		module.exports == freeExports && module;
17820	var freeGlobal = typeof global == 'object' && global;
17821	if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
17822		root = freeGlobal;
17823	}
17824
17825	/**
17826	 * The `punycode` object.
17827	 * @name punycode
17828	 * @type Object
17829	 */
17830	var punycode,
17831
17832	/** Highest positive signed 32-bit float value */
17833	maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
17834
17835	/** Bootstring parameters */
17836	base = 36,
17837	tMin = 1,
17838	tMax = 26,
17839	skew = 38,
17840	damp = 700,
17841	initialBias = 72,
17842	initialN = 128, // 0x80
17843	delimiter = '-', // '\x2D'
17844
17845	/** Regular expressions */
17846	regexPunycode = /^xn--/,
17847	regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
17848	regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
17849
17850	/** Error messages */
17851	errors = {
17852		'overflow': 'Overflow: input needs wider integers to process',
17853		'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
17854		'invalid-input': 'Invalid input'
17855	},
17856
17857	/** Convenience shortcuts */
17858	baseMinusTMin = base - tMin,
17859	floor = Math.floor,
17860	stringFromCharCode = String.fromCharCode,
17861
17862	/** Temporary variable */
17863	key;
17864
17865	/*--------------------------------------------------------------------------*/
17866
17867	/**
17868	 * A generic error utility function.
17869	 * @private
17870	 * @param {String} type The error type.
17871	 * @returns {Error} Throws a `RangeError` with the applicable error message.
17872	 */
17873	function error(type) {
17874		throw RangeError(errors[type]);
17875	}
17876
17877	/**
17878	 * A generic `Array#map` utility function.
17879	 * @private
17880	 * @param {Array} array The array to iterate over.
17881	 * @param {Function} callback The function that gets called for every array
17882	 * item.
17883	 * @returns {Array} A new array of values returned by the callback function.
17884	 */
17885	function map(array, fn) {
17886		var length = array.length;
17887		while (length--) {
17888			array[length] = fn(array[length]);
17889		}
17890		return array;
17891	}
17892
17893	/**
17894	 * A simple `Array#map`-like wrapper to work with domain name strings.
17895	 * @private
17896	 * @param {String} domain The domain name.
17897	 * @param {Function} callback The function that gets called for every
17898	 * character.
17899	 * @returns {Array} A new string of characters returned by the callback
17900	 * function.
17901	 */
17902	function mapDomain(string, fn) {
17903		return map(string.split(regexSeparators), fn).join('.');
17904	}
17905
17906	/**
17907	 * Creates an array containing the numeric code points of each Unicode
17908	 * character in the string. While JavaScript uses UCS-2 internally,
17909	 * this function will convert a pair of surrogate halves (each of which
17910	 * UCS-2 exposes as separate characters) into a single code point,
17911	 * matching UTF-16.
17912	 * @see `punycode.ucs2.encode`
17913	 * @see <http://mathiasbynens.be/notes/javascript-encoding>
17914	 * @memberOf punycode.ucs2
17915	 * @name decode
17916	 * @param {String} string The Unicode input string (UCS-2).
17917	 * @returns {Array} The new array of code points.
17918	 */
17919	function ucs2decode(string) {
17920		var output = [],
17921		    counter = 0,
17922		    length = string.length,
17923		    value,
17924		    extra;
17925		while (counter < length) {
17926			value = string.charCodeAt(counter++);
17927			if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
17928				// high surrogate, and there is a next character
17929				extra = string.charCodeAt(counter++);
17930				if ((extra & 0xFC00) == 0xDC00) { // low surrogate
vendor: 9,396 bytes, lines 17931-18275
17931					output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
17932				} else {
17933					// unmatched surrogate; only append this code unit, in case the next
17934					// code unit is the high surrogate of a surrogate pair
17935					output.push(value);
17936					counter--;
17937				}
17938			} else {
17939				output.push(value);
17940			}
17941		}
17942		return output;
17943	}
17944
17945	/**
17946	 * Creates a string based on an array of numeric code points.
17947	 * @see `punycode.ucs2.decode`
17948	 * @memberOf punycode.ucs2
17949	 * @name encode
17950	 * @param {Array} codePoints The array of numeric code points.
17951	 * @returns {String} The new Unicode string (UCS-2).
17952	 */
17953	function ucs2encode(array) {
17954		return map(array, function(value) {
17955			var output = '';
17956			if (value > 0xFFFF) {
17957				value -= 0x10000;
17958				output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
17959				value = 0xDC00 | value & 0x3FF;
17960			}
17961			output += stringFromCharCode(value);
17962			return output;
17963		}).join('');
17964	}
17965
17966	/**
17967	 * Converts a basic code point into a digit/integer.
17968	 * @see `digitToBasic()`
17969	 * @private
17970	 * @param {Number} codePoint The basic numeric code point value.
17971	 * @returns {Number} The numeric value of a basic code point (for use in
17972	 * representing integers) in the range `0` to `base - 1`, or `base` if
17973	 * the code point does not represent a value.
17974	 */
17975	function basicToDigit(codePoint) {
17976		if (codePoint - 48 < 10) {
17977			return codePoint - 22;
17978		}
17979		if (codePoint - 65 < 26) {
17980			return codePoint - 65;
17981		}
17982		if (codePoint - 97 < 26) {
17983			return codePoint - 97;
17984		}
17985		return base;
17986	}
17987
17988	/**
17989	 * Converts a digit/integer into a basic code point.
17990	 * @see `basicToDigit()`
17991	 * @private
17992	 * @param {Number} digit The numeric value of a basic code point.
17993	 * @returns {Number} The basic code point whose value (when used for
17994	 * representing integers) is `digit`, which needs to be in the range
17995	 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
17996	 * used; else, the lowercase form is used. The behavior is undefined
17997	 * if `flag` is non-zero and `digit` has no uppercase form.
17998	 */
17999	function digitToBasic(digit, flag) {
18000		//  0..25 map to ASCII a..z or A..Z
18001		// 26..35 map to ASCII 0..9
18002		return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
18003	}
18004
18005	/**
18006	 * Bias adaptation function as per section 3.4 of RFC 3492.
18007	 * http://tools.ietf.org/html/rfc3492#section-3.4
18008	 * @private
18009	 */
18010	function adapt(delta, numPoints, firstTime) {
18011		var k = 0;
18012		delta = firstTime ? floor(delta / damp) : delta >> 1;
18013		delta += floor(delta / numPoints);
18014		for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
18015			delta = floor(delta / baseMinusTMin);
18016		}
18017		return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
18018	}
18019
18020	/**
18021	 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
18022	 * symbols.
18023	 * @memberOf punycode
18024	 * @param {String} input The Punycode string of ASCII-only symbols.
18025	 * @returns {String} The resulting string of Unicode symbols.
18026	 */
18027	function decode(input) {
18028		// Don't use UCS-2
18029		var output = [],
18030		    inputLength = input.length,
18031		    out,
18032		    i = 0,
18033		    n = initialN,
18034		    bias = initialBias,
18035		    basic,
18036		    j,
18037		    index,
18038		    oldi,
18039		    w,
18040		    k,
18041		    digit,
18042		    t,
18043		    /** Cached calculation results */
18044		    baseMinusT;
18045
18046		// Handle the basic code points: let `basic` be the number of input code
18047		// points before the last delimiter, or `0` if there is none, then copy
18048		// the first basic code points to the output.
18049
18050		basic = input.lastIndexOf(delimiter);
18051		if (basic < 0) {
18052			basic = 0;
18053		}
18054
18055		for (j = 0; j < basic; ++j) {
18056			// if it's not a basic code point
18057			if (input.charCodeAt(j) >= 0x80) {
18058				error('not-basic');
18059			}
18060			output.push(input.charCodeAt(j));
18061		}
18062
18063		// Main decoding loop: start just after the last delimiter if any basic code
18064		// points were copied; start at the beginning otherwise.
18065
18066		for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
18067
18068			// `index` is the index of the next character to be consumed.
18069			// Decode a generalized variable-length integer into `delta`,
18070			// which gets added to `i`. The overflow checking is easier
18071			// if we increase `i` as we go, then subtract off its starting
18072			// value at the end to obtain `delta`.
18073			for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
18074
18075				if (index >= inputLength) {
18076					error('invalid-input');
18077				}
18078
18079				digit = basicToDigit(input.charCodeAt(index++));
18080
18081				if (digit >= base || digit > floor((maxInt - i) / w)) {
18082					error('overflow');
18083				}
18084
18085				i += digit * w;
18086				t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
18087
18088				if (digit < t) {
18089					break;
18090				}
18091
18092				baseMinusT = base - t;
18093				if (w > floor(maxInt / baseMinusT)) {
18094					error('overflow');
18095				}
18096
18097				w *= baseMinusT;
18098
18099			}
18100
18101			out = output.length + 1;
18102			bias = adapt(i - oldi, out, oldi == 0);
18103
18104			// `i` was supposed to wrap around from `out` to `0`,
18105			// incrementing `n` each time, so we'll fix that now:
18106			if (floor(i / out) > maxInt - n) {
18107				error('overflow');
18108			}
18109
18110			n += floor(i / out);
18111			i %= out;
18112
18113			// Insert `n` at position `i` of the output
18114			output.splice(i++, 0, n);
18115
18116		}
18117
18118		return ucs2encode(output);
18119	}
18120
18121	/**
18122	 * Converts a string of Unicode symbols to a Punycode string of ASCII-only
18123	 * symbols.
18124	 * @memberOf punycode
18125	 * @param {String} input The string of Unicode symbols.
18126	 * @returns {String} The resulting Punycode string of ASCII-only symbols.
18127	 */
18128	function encode(input) {
18129		var n,
18130		    delta,
18131		    handledCPCount,
18132		    basicLength,
18133		    bias,
18134		    j,
18135		    m,
18136		    q,
18137		    k,
18138		    t,
18139		    currentValue,
18140		    output = [],
18141		    /** `inputLength` will hold the number of code points in `input`. */
18142		    inputLength,
18143		    /** Cached calculation results */
18144		    handledCPCountPlusOne,
18145		    baseMinusT,
18146		    qMinusT;
18147
18148		// Convert the input in UCS-2 to Unicode
18149		input = ucs2decode(input);
18150
18151		// Cache the length
18152		inputLength = input.length;
18153
18154		// Initialize the state
18155		n = initialN;
18156		delta = 0;
18157		bias = initialBias;
18158
18159		// Handle the basic code points
18160		for (j = 0; j < inputLength; ++j) {
18161			currentValue = input[j];
18162			if (currentValue < 0x80) {
18163				output.push(stringFromCharCode(currentValue));
18164			}
18165		}
18166
18167		handledCPCount = basicLength = output.length;
18168
18169		// `handledCPCount` is the number of code points that have been handled;
18170		// `basicLength` is the number of basic code points.
18171
18172		// Finish the basic string - if it is not empty - with a delimiter
18173		if (basicLength) {
18174			output.push(delimiter);
18175		}
18176
18177		// Main encoding loop:
18178		while (handledCPCount < inputLength) {
18179
18180			// All non-basic code points < n have been handled already. Find the next
18181			// larger one:
18182			for (m = maxInt, j = 0; j < inputLength; ++j) {
18183				currentValue = input[j];
18184				if (currentValue >= n && currentValue < m) {
18185					m = currentValue;
18186				}
18187			}
18188
18189			// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
18190			// but guard against overflow
18191			handledCPCountPlusOne = handledCPCount + 1;
18192			if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
18193				error('overflow');
18194			}
18195
18196			delta += (m - n) * handledCPCountPlusOne;
18197			n = m;
18198
18199			for (j = 0; j < inputLength; ++j) {
18200				currentValue = input[j];
18201
18202				if (currentValue < n && ++delta > maxInt) {
18203					error('overflow');
18204				}
18205
18206				if (currentValue == n) {
18207					// Represent delta as a generalized variable-length integer
18208					for (q = delta, k = base; /* no condition */; k += base) {
18209						t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
18210						if (q < t) {
18211							break;
18212						}
18213						qMinusT = q - t;
18214						baseMinusT = base - t;
18215						output.push(
18216							stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
18217						);
18218						q = floor(qMinusT / baseMinusT);
18219					}
18220
18221					output.push(stringFromCharCode(digitToBasic(q, 0)));
18222					bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
18223					delta = 0;
18224					++handledCPCount;
18225				}
18226			}
18227
18228			++delta;
18229			++n;
18230
18231		}
18232		return output.join('');
18233	}
18234
18235	/**
18236	 * Converts a Punycode string representing a domain name to Unicode. Only the
18237	 * Punycoded parts of the domain name will be converted, i.e. it doesn't
18238	 * matter if you call it on a string that has already been converted to
18239	 * Unicode.
18240	 * @memberOf punycode
18241	 * @param {String} domain The Punycode domain name to convert to Unicode.
18242	 * @returns {String} The Unicode representation of the given Punycode
18243	 * string.
18244	 */
18245	function toUnicode(domain) {
18246		return mapDomain(domain, function(string) {
18247			return regexPunycode.test(string)
18248				? decode(string.slice(4).toLowerCase())
18249				: string;
18250		});
18251	}
18252
18253	/**
18254	 * Converts a Unicode string representing a domain name to Punycode. Only the
18255	 * non-ASCII parts of the domain name will be converted, i.e. it doesn't
18256	 * matter if you call it with a domain that's already in ASCII.
18257	 * @memberOf punycode
18258	 * @param {String} domain The domain name to convert, as a Unicode string.
18259	 * @returns {String} The Punycode representation of the given domain name.
18260	 */
18261	function toASCII(domain) {
18262		return mapDomain(domain, function(string) {
18263			return regexNonASCII.test(string)
18264				? 'xn--' + encode(string)
18265				: string;
18266		});
18267	}
18268
18269	/*--------------------------------------------------------------------------*/
18270
18271	/** Define the public API */
18272	punycode = {
18273		/**
18274		 * A string representing the current Punycode.js version number.
18275		 * @memberOf punycode
18276		 * @type String
18277		 */
18278		'version': '1.2.4',
18279		/**
18280		 * An object of methods to convert from JavaScript's internal character
18281		 * representation (UCS-2) to Unicode code points, and back.
18282		 * @see <http://mathiasbynens.be/notes/javascript-encoding>
18283		 * @memberOf punycode
18284		 * @type Object
18285		 */
18286		'ucs2': {
18287			'decode': ucs2decode,
18288			'encode': ucs2encode
18289		},
18290		'decode': decode,
18291		'encode': encode,
18292		'toASCII': toASCII,
18293		'toUnicode': toUnicode
18294	};
18295
18296	/** Expose `punycode` */
18297	// Some AMD build optimizers, like r.js, check for specific condition patterns
18298	// like the following:
18299	if (
18300		typeof define == 'function' &&
18301		typeof define.amd == 'object' &&
18302		define.amd
18303	) {
18304		
18305	} else if (freeExports && !freeExports.nodeType) {
18306		if (freeModule) { // in Node.js or RingoJS v0.8.0+
18307			freeModule.exports = punycode;
18308		} else { // in Narwhal or RingoJS v0.7.0-
18309			for (key in punycode) {
18310				punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
18311			}
18312		}
18313	} else { // in Rhino or a web browser
18314		root.punycode = punycode;
18315	}
18316
18317}(this));
18318
18319}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
18320},{}],2:[function(_dereq_,module,exports){
18321var log = _dereq_('./log');
18322
18323function restoreOwnerScroll(ownerDocument, x, y) {
18324    if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
18325        ownerDocument.defaultView.scrollTo(x, y);
18326    }
18327}
18328
18329function cloneCanvasContents(canvas, clonedCanvas) {
18330    try {
18331        if (clonedCanvas) {
18332            clonedCanvas.width = canvas.width;
18333            clonedCanvas.height = canvas.height;
18334            clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
18335        }
18336    } catch(e) {
18337        log("Unable to copy canvas content from", canvas, e);
18338    }
18339}
18340
18341function cloneNode(node, javascriptEnabled) {
18342    var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
18343
18344    var child = node.firstChild;
18345    while(child) {
18346        if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
18347            clone.appendChild(cloneNode(child, javascriptEnabled));
18348        }
18349        child = child.nextSibling;
18350    }
18351
18352    if (node.nodeType === 1) {
18353        clone._scrollTop = node.scrollTop;
18354        clone._scrollLeft = node.scrollLeft;
18355        if (node.nodeName === "CANVAS") {
18356            cloneCanvasContents(node, clone);
18357        } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
18358            clone.value = node.value;
18359        }
18360    }
18361
18362    return clone;
18363}
18364
18365function initNode(node) {
18366    if (node.nodeType === 1) {
18367        node.scrollTop = node._scrollTop;
18368        node.scrollLeft = node._scrollLeft;
18369
18370        var child = node.firstChild;
18371        while(child) {
18372            initNode(child);
18373            child = child.nextSibling;
18374        }
18375    }
18376}
18377
18378module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
18379    var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
18380    var container = containerDocument.createElement("iframe");
18381
18382    container.className = "html2canvas-container";
18383    container.style.visibility = "hidden";
18384    container.style.position = "fixed";
18385    container.style.left = "-10000px";
18386    container.style.top = "0px";
18387    container.style.border = "0";
18388    container.width = width;
18389    container.height = height;
18390    container.scrolling = "no"; // ios won't scroll without it
18391    containerDocument.body.appendChild(container);
18392
18393    return new Promise(function(resolve) {
18394        var documentClone = container.contentWindow.document;
18395
18396        /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
18397         if window url is about:blank, we can assign the url to current by writing onto the document
18398         */
18399        container.contentWindow.onload = container.onload = function() {
18400            var interval = setInterval(function() {
18401                if (documentClone.body.childNodes.length > 0) {
18402                    initNode(documentClone.documentElement);
18403                    clearInterval(interval);
18404                    if (options.type === "view") {
18405                        container.contentWindow.scrollTo(x, y);
18406                        if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
18407                            documentClone.documentElement.style.top = (-y) + "px";
18408                            documentClone.documentElement.style.left = (-x) + "px";
18409                            documentClone.documentElement.style.position = 'absolute';
18410                        }
18411                    }
18412                    resolve(container);
18413                }
18414            }, 50);
18415        };
18416
18417        documentClone.open();
18418        documentClone.write("<!DOCTYPE html><html></html>");
18419        // Chrome scrolls the parent document for some reason after the write to the cloned window???
18420        restoreOwnerScroll(ownerDocument, x, y);
18421        documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
18422        documentClone.close();
18423    });
18424};
18425
18426},{"./log":13}],3:[function(_dereq_,module,exports){
18427// http://dev.w3.org/csswg/css-color/
18428
18429function Color(value) {
18430    this.r = 0;
18431    this.g = 0;
18432    this.b = 0;
18433    this.a = null;
18434    var result = this.fromArray(value) ||
18435        this.namedColor(value) ||
18436        this.rgb(value) ||
18437        this.rgba(value) ||
18438        this.hex6(value) ||
18439        this.hex3(value);
18440}
18441
18442Color.prototype.darken = function(amount) {
18443    var a = 1 - amount;
18444    return  new Color([
18445        Math.round(this.r * a),
18446        Math.round(this.g * a),
18447        Math.round(this.b * a),
18448        this.a
18449    ]);
18450};
18451
18452Color.prototype.isTransparent = function() {
18453    return this.a === 0;
18454};
18455
18456Color.prototype.isBlack = function() {
18457    return this.r === 0 && this.g === 0 && this.b === 0;
18458};
18459
18460Color.prototype.fromArray = function(array) {
18461    if (Array.isArray(array)) {
18462        this.r = Math.min(array[0], 255);
18463        this.g = Math.min(array[1], 255);
18464        this.b = Math.min(array[2], 255);
18465        if (array.length > 3) {
18466            this.a = array[3];
18467        }
18468    }
18469
18470    return (Array.isArray(array));
18471};
18472
18473var _hex3 = /^#([a-f0-9]{3})$/i;
18474
18475Color.prototype.hex3 = function(value) {
18476    var match = null;
18477    if ((match = value.match(_hex3)) !== null) {
18478        this.r = parseInt(match[1][0] + match[1][0], 16);
18479        this.g = parseInt(match[1][1] + match[1][1], 16);
18480        this.b = parseInt(match[1][2] + match[1][2], 16);
18481    }
18482    return match !== null;
18483};
18484
18485var _hex6 = /^#([a-f0-9]{6})$/i;
18486
18487Color.prototype.hex6 = function(value) {
18488    var match = null;
18489    if ((match = value.match(_hex6)) !== null) {
18490        this.r = parseInt(match[1].substring(0, 2), 16);
18491        this.g = parseInt(match[1].substring(2, 4), 16);
18492        this.b = parseInt(match[1].substring(4, 6), 16);
18493    }
18494    return match !== null;
18495};
18496
18497
18498var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
18499
18500Color.prototype.rgb = function(value) {
18501    var match = null;
18502    if ((match = value.match(_rgb)) !== null) {
18503        this.r = Number(match[1]);
18504        this.g = Number(match[2]);
18505        this.b = Number(match[3]);
18506    }
18507    return match !== null;
18508};
18509
18510var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
18511
18512Color.prototype.rgba = function(value) {
18513    var match = null;
18514    if ((match = value.match(_rgba)) !== null) {
18515        this.r = Number(match[1]);
18516        this.g = Number(match[2]);
18517        this.b = Number(match[3]);
18518        this.a = Number(match[4]);
18519    }
18520    return match !== null;
18521};
18522
18523Color.prototype.toString = function() {
18524    return this.a !== null && this.a !== 1 ?
18525    "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
18526    "rgb(" + [this.r, this.g, this.b].join(",") + ")";
18527};
18528
18529Color.prototype.namedColor = function(value) {
18530    value = value.toLowerCase();
18531    var color = colors[value];
18532    if (color) {
18533        this.r = color[0];
18534        this.g = color[1];
18535        this.b = color[2];
18536    } else if (value === "transparent") {
18537        this.r = this.g = this.b = this.a = 0;
18538        return true;
18539    }
18540
18541    return !!color;
18542};
18543
18544Color.prototype.isColor = true;
18545
18546// JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {}))
18547var colors = {
18548    "aliceblue": [240, 248, 255],
18549    "antiquewhite": [250, 235, 215],
18550    "aqua": [0, 255, 255],
18551    "aquamarine": [127, 255, 212],
18552    "azure": [240, 255, 255],
18553    "beige": [245, 245, 220],
18554    "bisque": [255, 228, 196],
18555    "black": [0, 0, 0],
18556    "blanchedalmond": [255, 235, 205],
18557    "blue": [0, 0, 255],
18558    "blueviolet": [138, 43, 226],
18559    "brown": [165, 42, 42],
18560    "burlywood": [222, 184, 135],
18561    "cadetblue": [95, 158, 160],
18562    "chartreuse": [127, 255, 0],
18563    "chocolate": [210, 105, 30],
18564    "coral": [255, 127, 80],
18565    "cornflowerblue": [100, 149, 237],
18566    "cornsilk": [255, 248, 220],
18567    "crimson": [220, 20, 60],
18568    "cyan": [0, 255, 255],
18569    "darkblue": [0, 0, 139],
18570    "darkcyan": [0, 139, 139],
18571    "darkgoldenrod": [184, 134, 11],
18572    "darkgray": [169, 169, 169],
18573    "darkgreen": [0, 100, 0],
18574    "darkgrey": [169, 169, 169],
18575    "darkkhaki": [189, 183, 107],
18576    "darkmagenta": [139, 0, 139],
18577    "darkolivegreen": [85, 107, 47],
18578    "darkorange": [255, 140, 0],
18579    "darkorchid": [153, 50, 204],
18580    "darkred": [139, 0, 0],
18581    "darksalmon": [233, 150, 122],
18582    "darkseagreen": [143, 188, 143],
18583    "darkslateblue": [72, 61, 139],
18584    "darkslategray": [47, 79, 79],
18585    "darkslategrey": [47, 79, 79],
18586    "darkturquoise": [0, 206, 209],
18587    "darkviolet": [148, 0, 211],
18588    "deeppink": [255, 20, 147],
18589    "deepskyblue": [0, 191, 255],
18590    "dimgray": [105, 105, 105],
18591    "dimgrey": [105, 105, 105],
18592    "dodgerblue": [30, 144, 255],
18593    "firebrick": [178, 34, 34],
18594    "floralwhite": [255, 250, 240],
18595    "forestgreen": [34, 139, 34],
18596    "fuchsia": [255, 0, 255],
18597    "gainsboro": [220, 220, 220],
18598    "ghostwhite": [248, 248, 255],
18599    "gold": [255, 215, 0],
18600    "goldenrod": [218, 165, 32],
18601    "gray": [128, 128, 128],
18602    "green": [0, 128, 0],
18603    "greenyellow": [173, 255, 47],
18604    "grey": [128, 128, 128],
18605    "honeydew": [240, 255, 240],
18606    "hotpink": [255, 105, 180],
18607    "indianred": [205, 92, 92],
18608    "indigo": [75, 0, 130],
18609    "ivory": [255, 255, 240],
18610    "khaki": [240, 230, 140],
18611    "lavender": [230, 230, 250],
18612    "lavenderblush": [255, 240, 245],
18613    "lawngreen": [124, 252, 0],
18614    "lemonchiffon": [255, 250, 205],
18615    "lightblue": [173, 216, 230],
18616    "lightcoral": [240, 128, 128],
18617    "lightcyan": [224, 255, 255],
18618    "lightgoldenrodyellow": [250, 250, 210],
18619    "lightgray": [211, 211, 211],
18620    "lightgreen": [144, 238, 144],
18621    "lightgrey": [211, 211, 211],
18622    "lightpink": [255, 182, 193],
18623    "lightsalmon": [255, 160, 122],
18624    "lightseagreen": [32, 178, 170],
18625    "lightskyblue": [135, 206, 250],
18626    "lightslategray": [119, 136, 153],
18627    "lightslategrey": [119, 136, 153],
18628    "lightsteelblue": [176, 196, 222],
18629    "lightyellow": [255, 255, 224],
18630    "lime": [0, 255, 0],
18631    "limegreen": [50, 205, 50],
18632    "linen": [250, 240, 230],
18633    "magenta": [255, 0, 255],
18634    "maroon": [128, 0, 0],
18635    "mediumaquamarine": [102, 205, 170],
18636    "mediumblue": [0, 0, 205],
18637    "mediumorchid": [186, 85, 211],
18638    "mediumpurple": [147, 112, 219],
18639    "mediumseagreen": [60, 179, 113],
18640    "mediumslateblue": [123, 104, 238],
18641    "mediumspringgreen": [0, 250, 154],
18642    "mediumturquoise": [72, 209, 204],
18643    "mediumvioletred": [199, 21, 133],
18644    "midnightblue": [25, 25, 112],
18645    "mintcream": [245, 255, 250],
18646    "mistyrose": [255, 228, 225],
18647    "moccasin": [255, 228, 181],
18648    "navajowhite": [255, 222, 173],
18649    "navy": [0, 0, 128],
18650    "oldlace": [253, 245, 230],
18651    "olive": [128, 128, 0],
18652    "olivedrab": [107, 142, 35],
18653    "orange": [255, 165, 0],
18654    "orangered": [255, 69, 0],
18655    "orchid": [218, 112, 214],
18656    "palegoldenrod": [238, 232, 170],
18657    "palegreen": [152, 251, 152],
18658    "paleturquoise": [175, 238, 238],
18659    "palevioletred": [219, 112, 147],
18660    "papayawhip": [255, 239, 213],
18661    "peachpuff": [255, 218, 185],
18662    "peru": [205, 133, 63],
18663    "pink": [255, 192, 203],
18664    "plum": [221, 160, 221],
18665    "powderblue": [176, 224, 230],
18666    "purple": [128, 0, 128],
18667    "rebeccapurple": [102, 51, 153],
18668    "red": [255, 0, 0],
18669    "rosybrown": [188, 143, 143],
18670    "royalblue": [65, 105, 225],
18671    "saddlebrown": [139, 69, 19],
18672    "salmon": [250, 128, 114],
18673    "sandybrown": [244, 164, 96],
18674    "seagreen": [46, 139, 87],
18675    "seashell": [255, 245, 238],
18676    "sienna": [160, 82, 45],
18677    "silver": [192, 192, 192],
18678    "skyblue": [135, 206, 235],
18679    "slateblue": [106, 90, 205],
18680    "slategray": [112, 128, 144],
18681    "slategrey": [112, 128, 144],
18682    "snow": [255, 250, 250],
18683    "springgreen": [0, 255, 127],
18684    "steelblue": [70, 130, 180],
18685    "tan": [210, 180, 140],
18686    "teal": [0, 128, 128],
18687    "thistle": [216, 191, 216],
18688    "tomato": [255, 99, 71],
18689    "turquoise": [64, 224, 208],
18690    "violet": [238, 130, 238],
18691    "wheat": [245, 222, 179],
18692    "white": [255, 255, 255],
18693    "whitesmoke": [245, 245, 245],
18694    "yellow": [255, 255, 0],
18695    "yellowgreen": [154, 205, 50]
18696};
18697
18698module.exports = Color;
18699
18700},{}],4:[function(_dereq_,module,exports){
18701var Support = _dereq_('./support');
18702var CanvasRenderer = _dereq_('./renderers/canvas');
18703var ImageLoader = _dereq_('./imageloader');
18704var NodeParser = _dereq_('./nodeparser');
18705var NodeContainer = _dereq_('./nodecontainer');
18706var log = _dereq_('./log');
18707var utils = _dereq_('./utils');
18708var createWindowClone = _dereq_('./clone');
18709var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
18710var getBounds = utils.getBounds;
18711
18712var html2canvasNodeAttribute = "data-html2canvas-node";
18713var html2canvasCloneIndex = 0;
18714
18715function html2canvas(nodeList, options) {
18716    var index = html2canvasCloneIndex++;
18717    options = options || {};
18718    if (options.logging) {
18719        log.options.logging = true;
18720        log.options.start = Date.now();
18721    }
18722
18723    options.async = typeof(options.async) === "undefined" ? true : options.async;
18724    options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
18725    options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
18726    options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
18727    options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
18728    options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
18729    options.strict = !!options.strict;
18730
18731    if (typeof(nodeList) === "string") {
18732        if (typeof(options.proxy) !== "string") {
18733            return Promise.reject("Proxy must be used when rendering url");
18734        }
18735        var width = options.width != null ? options.width : window.innerWidth;
18736        var height = options.height != null ? options.height : window.innerHeight;
18737        return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
18738            return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
18739        });
18740    }
18741
18742    var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
18743    node.setAttribute(html2canvasNodeAttribute + index, index);
18744    return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
18745        if (typeof(options.onrendered) === "function") {
18746            log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
18747            options.onrendered(canvas);
18748        }
18749        return canvas;
18750    });
18751}
18752
18753html2canvas.CanvasRenderer = CanvasRenderer;
18754html2canvas.NodeContainer = NodeContainer;
18755html2canvas.log = log;
18756html2canvas.utils = utils;
18757
18758var html2canvasExport = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
18759    return Promise.reject("No canvas support");
18760} : html2canvas;
18761
18762module.exports = html2canvasExport;
18763
18764function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
18765    return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
18766        log("Document cloned");
18767        var attributeName = html2canvasNodeAttribute + html2canvasIndex;
18768        var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
18769        document.querySelector(selector).removeAttribute(attributeName);
18770        var clonedWindow = container.contentWindow;
18771        var node = clonedWindow.document.querySelector(selector);
18772        var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
18773        return oncloneHandler.then(function() {
18774            return renderWindow(node, container, options, windowWidth, windowHeight);
18775        });
18776    });
18777}
18778
18779function renderWindow(node, container, options, windowWidth, windowHeight) {
18780    var clonedWindow = container.contentWindow;
18781    var support = new Support(clonedWindow.document);
18782    var imageLoader = new ImageLoader(options, support);
18783    var bounds = getBounds(node);
18784    var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
18785    var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
18786    var renderer = new options.renderer(width, height, imageLoader, options, document);
18787    var parser = new NodeParser(node, renderer, support, imageLoader, options);
18788    return parser.ready.then(function() {
18789        log("Finished rendering");
18790        var canvas;
18791
18792        if (options.type === "view") {
18793            canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
18794        } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
18795            canvas = renderer.canvas;
18796        } else {
18797            canvas = crop(renderer.canvas, {width:  options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: 0, y: 0});
18798        }
18799
18800        cleanupContainer(container, options);
18801        return canvas;
18802    });
18803}
18804
18805function cleanupContainer(container, options) {
18806    if (options.removeContainer) {
18807        container.parentNode.removeChild(container);
18808        log("Cleaned up container");
18809    }
18810}
18811
18812function crop(canvas, bounds) {
18813    var croppedCanvas = document.createElement("canvas");
18814    var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
18815    var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
18816    var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
18817    var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
18818    croppedCanvas.width = bounds.width;
18819    croppedCanvas.height =  bounds.height;
18820    var width = x2-x1;
18821    var height = y2-y1;
18822    log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "height:", height);
18823    log("Resulting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
18824    croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
18825    return croppedCanvas;
18826}
18827
18828function documentWidth (doc) {
18829    return Math.max(
18830        Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
18831        Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
18832        Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
18833    );
18834}
18835
18836function documentHeight (doc) {
18837    return Math.max(
18838        Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
18839        Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
18840        Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
18841    );
18842}
18843
18844function absoluteUrl(url) {
18845    var link = document.createElement("a");
18846    link.href = url;
18847    link.href = link.href;
18848    return link;
18849}
18850
18851},{"./clone":2,"./imageloader":11,"./log":13,"./nodecontainer":14,"./nodeparser":15,"./proxy":16,"./renderers/canvas":20,"./support":22,"./utils":26}],5:[function(_dereq_,module,exports){
18852var log = _dereq_('./log');
18853var smallImage = _dereq_('./utils').smallImage;
18854
18855function DummyImageContainer(src) {
18856    this.src = src;
18857    log("DummyImageContainer for", src);
18858    if (!this.promise || !this.image) {
18859        log("Initiating DummyImageContainer");
18860        DummyImageContainer.prototype.image = new Image();
18861        var image = this.image;
18862        DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
18863            image.onload = resolve;
18864            image.onerror = reject;
18865            image.src = smallImage();
18866            if (image.complete === true) {
18867                resolve(image);
18868            }
18869        });
18870    }
18871}
18872
18873module.exports = DummyImageContainer;
18874
18875}
18875,{"./log":13,"./utils":26}],6:[function(_dereq_,module,exports){
18876var smallImage = _dereq_('./utils').smallImage;
18877
18878function Font(family, size) {
18879    var container = document.createElement('div'),
18880        img = document.createElement('img'),
18881        span = document.createElement('span'),
18882        sampleText = 'Hidden Text',
18883        baseline,
18884        middle;
18885
18886    container.style.visibility = "hidden";
18887    container.style.fontFamily = family;
18888    container.style.fontSize = size;
18889    container.style.margin = 0;
18890    container.style.padding = 0;
18891
18892    document.body.appendChild(container);
18893
18894    img.src = smallImage();
18895    img.width = 1;
18896    img.height = 1;
18897
18898    img.style.margin = 0;
18899    img.style.padding = 0;
18900    img.style.verticalAlign = "baseline";
18901
18902    span.style.fontFamily = family;
18903    span.style.fontSize = size;
18904    span.style.margin = 0;
18905    span.style.padding = 0;
18906
18907    span.appendChild(document.createTextNode(sampleText));
18908    container.appendChild(span);
18909    container.appendChild(img);
18910    baseline = (img.offsetTop - span.offsetTop) + 1;
18911
18912    container.removeChild(span);
18913    container.appendChild(document.createTextNode(sampleText));
18914
18915    container.style.lineHeight = "normal";
18916    img.style.verticalAlign = "super";
18917
18918    middle = (img.offsetTop-container.offsetTop) + 1;
18919
18920    document.body.removeChild(container);
18921
18922    this.baseline = baseline;
18923    this.lineWidth = 1;
18924    this.middle = middle;
18925}
18926
18927module.exports = Font;
18928
18929},{"./utils":26}],7:[function(_dereq_,module,exports){
18930var Font = _dereq_('./font');
18931
18932function FontMetrics() {
18933    this.data = {};
18934}
18935
18936FontMetrics.prototype.getMetrics = function(family, size) {
18937    if (this.data[family + "-" + size] === undefined) {
18938        this.data[family + "-" + size] = new Font(family, size);
18939    }
18940    return this.data[family + "-" + size];
18941};
18942
18943module.exports = FontMetrics;
18944
18945},{"./font":6}],8:[function(_dereq_,module,exports){
18946var utils = _dereq_('./utils');
18947var getBounds = utils.getBounds;
18948var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
18949
18950function FrameContainer(container, sameOrigin, options) {
18951    this.image = null;
18952    this.src = container;
18953    var self = this;
18954    var bounds = getBounds(container);
18955    this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
18956        if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
18957            container.contentWindow.onload = container.onload = function() {
18958                resolve(container);
18959            };
18960        } else {
18961            resolve(container);
18962        }
18963    })).then(function(container) {
18964        var html2canvas = _dereq_('./core');
18965        return html2canvas(container.contentWindow.document.documentElement, {type: 'view', width: container.width, height: container.height, proxy: options.proxy, javascriptEnabled: options.javascriptEnabled, removeContainer: options.removeContainer, allowTaint: options.allowTaint, imageTimeout: options.imageTimeout / 2});
18966    }).then(function(canvas) {
18967        return self.image = canvas;
18968    });
18969}
18970
18971FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
18972    var container = this.src;
18973    return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
18974};
18975
18976module.exports = FrameContainer;
18977
18978},{"./core":4,"./proxy":16,"./utils":26}],9:[function(_dereq_,module,exports){
18979function GradientContainer(imageData) {
18980    this.src = imageData.value;
18981    this.colorStops = [];
18982    this.type = null;
18983    this.x0 = 0.5;
18984    this.y0 = 0.5;
18985    this.x1 = 0.5;
18986    this.y1 = 0.5;
18987    this.promise = Promise.resolve(true);
18988}
18989
18990GradientContainer.TYPES = {
18991    LINEAR: 1,
18992    RADIAL: 2
18993};
18994
18995// TODO: support hsl[a], negative %/length values
18996// TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
18997GradientContainer.REGEXP_COLORSTOP = /^\s*(rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*[0-9\.]+)?\s*\)|[a-z]{3,20}|#[a-f0-9]{3,6})(?:\s+(\d{1,3}(?:\.\d+)?)(%|px)?)?(?:\s|$)/i;
18998
18999module.exports = GradientContainer;
19000
19001},{}],10:[function(_dereq_,module,exports){
19002function ImageContainer(src, cors) {
19003    this.src = src;
19004    this.image = new Image();
19005    var self = this;
19006    this.tainted = null;
19007    this.promise = new Promise(function(resolve, reject) {
19008        self.image.onload = resolve;
19009        self.image.onerror = reject;
19010        if (cors) {
19011            self.image.crossOrigin = "anonymous";
19012        }
19013        self.image.src = src;
19014        if (self.image.complete === true) {
19015            resolve(self.image);
19016        }
19017    });
19018}
19019
19020module.exports = ImageContainer;
19021
19022},{}],11:[function(_dereq_,module,exports){
19023var log = _dereq_('./log');
19024var ImageContainer = _dereq_('./imagecontainer');
19025var DummyImageContainer = _dereq_('./dummyimagecontainer');
19026var ProxyImageContainer = _dereq_('./proxyimagecontainer');
19027var FrameContainer = _dereq_('./framecontainer');
19028var SVGContainer = _dereq_('./svgcontainer');
19029var SVGNodeContainer = _dereq_('./svgnodecontainer');
19030var LinearGradientContainer = _dereq_('./lineargradientcontainer');
19031var WebkitGradientContainer = _dereq_('./webkitgradientcontainer');
19032var bind = _dereq_('./utils').bind;
19033
19034function ImageLoader(options, support) {
19035    this.link = null;
19036    this.options = options;
19037    this.support = support;
19038    this.origin = this.getOrigin(window.location.href);
19039}
19040
19041ImageLoader.prototype.findImages = function(nodes) {
19042    var images = [];
19043    nodes.reduce(function(imageNodes, container) {
19044        switch(container.node.nodeName) {
19045        case "IMG":
19046            return imageNodes.concat([{
19047                args: [container.node.src],
19048                method: "url"
19049            }]);
19050        case "svg":
19051        case "IFRAME":
19052            return imageNodes.concat([{
19053                args: [container.node],
19054                method: container.node.nodeName
19055            }]);
19056        }
19057        return imageNodes;
19058    }
19058, []).forEach(this.addImage(images, this.loadImage), this);
19059    return images;
19060};
19061
19062ImageLoader.prototype.findBackgroundImage = function(images, container) {
19063    container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
19064    return images;
19065};
19066
19067ImageLoader.prototype.addImage = function(images, callback) {
19068    return function(newImage) {
19069        newImage.args.forEach(function(image) {
19070            if (!this.imageExists(images, image)) {
19071                images.splice(0, 0, callback.call(this, newImage));
19072                log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
19073            }
19074        }, this);
19075    };
19076};
19077
19078ImageLoader.prototype.hasImageBackground = function(imageData) {
19079    return imageData.method !== "none";
19080};
19081
19082ImageLoader.prototype.loadImage = function(imageData) {
19083    if (imageData.method === "url") {
19084        var src = imageData.args[0];
19085        if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
19086            return new SVGContainer(src);
19087        } else if (src.match(/data:image\/.*;base64,/i)) {
19088            return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
19089        } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
19090            return new ImageContainer(src, false);
19091        } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
19092            return new ImageContainer(src, true);
19093        } else if (this.options.proxy) {
19094            return new ProxyImageContainer(src, this.options.proxy);
19095        } else {
19096            return new DummyImageContainer(src);
19097        }
19098    } else if (imageData.method === "linear-gradient") {
19099        return new LinearGradientContainer(imageData);
19100    } else if (imageData.method === "gradient") {
19101        return new WebkitGradientContainer(imageData);
19102    } else if (imageData.method === "svg") {
19103        return new SVGNodeContainer(imageData.args[0], this.support.svg);
19104    } else if (imageData.method === "IFRAME") {
19105        return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
19106    } else {
19107        return new DummyImageContainer(imageData);
19108    }
19109};
19110
19111ImageLoader.prototype.isSVG = function(src) {
19112    return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
19113};
19114
19115ImageLoader.prototype.imageExists = function(images, src) {
19116    return images.some(function(image) {
19117        return image.src === src;
19118    });
19119};
19120
19121ImageLoader.prototype.isSameOrigin = function(url) {
19122    return (this.getOrigin(url) === this.origin);
19123};
19124
19125ImageLoader.prototype.getOrigin = function(url) {
19126    var link = this.link || (this.link = document.createElement("a"));
19127    link.href = url;
19128    link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
19129    return link.protocol + link.hostname + link.port;
19130};
19131
19132ImageLoader.prototype.getPromise = function(container) {
19133    return this.timeout(container, this.options.imageTimeout)['catch'](function() {
19134        var dummy = new DummyImageContainer(container.src);
19135        return dummy.promise.then(function(image) {
19136            container.image = image;
19137        });
19138    });
19139};
19140
19141ImageLoader.prototype.get = function(src) {
19142    var found = null;
19143    return this.images.some(function(img) {
19144        return (found = img).src === src;
19145    }) ? found : null;
19146};
19147
19148ImageLoader.prototype.fetch = function(nodes) {
19149    this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
19150    this.images.forEach(function(image, index) {
19151        image.promise.then(function() {
19152            log("Succesfully loaded image #"+ (index+1), image);
19153        }, function(e) {
19154            log("Failed loading image #"+ (index+1), image, e);
19155        });
19156    });
19157    this.ready = Promise.all(this.images.map(this.getPromise, this));
19158    log("Finished searching images");
19159    return this;
19160};
19161
19162ImageLoader.prototype.timeout = function(container, timeout) {
19163    var timer;
19164    var promise = Promise.race([container.promise, new Promise(function(res, reject) {
19165        timer = setTimeout(function() {
19166            log("Timed out loading image", container);
19167            reject(container);
19168        }, timeout);
19169    })]).then(function(container) {
19170        clearTimeout(timer);
19171        return container;
19172    });
19173    promise['catch'](function() {
19174        clearTimeout(timer);
19175    });
19176    return promise;
19177};
19178
19179module.exports = ImageLoader;
19180
19181},{"./dummyimagecontainer":5,"./framecontainer":8,"./imagecontainer":10,"./lineargradientcontainer":12,"./log":13,"./proxyimagecontainer":17,"./svgcontainer":23,"./svgnodecontainer":24,"./ut
19181ils":26,"./webkitgradientcontainer":27}],12:[function(_dereq_,module,exports){
19182var GradientContainer = _dereq_('./gradientcontainer');
19183var Color = _dereq_('./color');
19184
19185function LinearGradientContainer(imageData) {
19186    GradientContainer.apply(this, arguments);
19187    this.type = GradientContainer.TYPES.LINEAR;
19188
19189    var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test( imageData.args[0] ) ||
19190        !GradientContainer.REGEXP_COLORSTOP.test( imageData.args[0] );
19191
19192    if (hasDirection) {
19193        imageData.args[0].split(/\s+/).reverse().forEach(function(position, index) {
19194            switch(position) {
19195            case "left":
19196                this.x0 = 0;
19197                this.x1 = 1;
19198                break;
19199            case "top":
19200                this.y0 = 0;
19201                this.y1 = 1;
19202                break;
19203            case "right":
19204                this.x0 = 1;
19205                this.x1 = 0;
19206                break;
19207            case "bottom":
19208                this.y0 = 1;
19209                this.y1 = 0;
19210                break;
19211            case "to":
19212                var y0 = this.y0;
19213                var x0 = this.x0;
19214                this.y0 = this.y1;
19215                this.x0 = this.x1;
19216                this.x1 = x0;
19217                this.y1 = y0;
19218                break;
19219            case "center":
19220                break; // centered by default
19221            // Firefox internally converts position keywords to percentages:
19222            // http://www.w3.org/TR/2010/WD-CSS2-20101207/colors.html#propdef-background-position
19223            default: // percentage or absolute length
19224                // TODO: support absolute start point positions (e.g., use bounds to convert px to a ratio)
19225                var ratio = parseFloat(position, 10) * 1e-2;
19226                if (isNaN(ratio)) { // invalid or unhandled value
19227                    break;
19228                }
19229                if (index === 0) {
19230                    this.y0 = ratio;
19231                    this.y1 = 1 - this.y0;
19232                } else {
19233                    this.x0 = ratio;
19234                    this.x1 = 1 - this.x0;
19235                }
19236                break;
19237            }
19238        }, this);
19239    } else {
19240        this.y0 = 0;
19241        this.y1 = 1;
19242    }
19243
19244    this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
19245        var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
19246        var value = +colorStopMatch[2];
19247        var unit = value === 0 ? "%" : colorStopMatch[3]; // treat "0" as "0%"
19248        return {
19249            color: new Color(colorStopMatch[1]),
19250            // TODO: support absolute stop positions (e.g., compute gradient line length & convert px to ratio)
19251            stop: unit === "%" ? value / 100 : null
19252        };
19253    });
19254
19255    if (this.colorStops[0].stop === null) {
19256        this.colorStops[0].stop = 0;
19257    }
19258
19259    if (this.colorStops[this.colorStops.length - 1].stop === null) {
19260        this.colorStops[this.colorStops.length - 1].stop = 1;
19261    }
19262
19263    // calculates and fills-in explicit stop positions when omitted from rule
19264    this.colorStops.forEach(function(colorStop, index) {
19265        if (colorStop.stop === null) {
19266            this.colorStops.slice(index).some(function(find, count) {
19267                if (find.stop !== null) {
19268                    colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
19269                    return true;
19270                } else {
19271                    return false;
19272                }
19273            }, this);
19274        }
19275    }, this);
19276}
19277
19278LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
19279
19280// TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
19281LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
19282
19283module.exports = LinearGradientContainer;
19284
19285},{"./color":3,"./gradientcontainer":9}],13:[function(_dereq_,module,exports){
19286var logger = function() {
19287    if (logger.options.logging && window.console && window.console.log) {
19288        Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
19289    }
19290};
19291
19292logger.options = {logging: false};
19293module.exports = logger;
19294
19295},{}],14:[function(_dereq_,module,exports){
19296var Color = _dereq_('./color');
19297var utils = _dereq_('./utils');
19298var getBounds = utils.getBounds;
19299var parseBackgrounds = utils.parseBackgrounds;
19300var offsetBounds = utils.offsetBounds;
19301
19302function NodeContainer(node, parent) {
19303    this.node = node;
19304    this.parent = parent;
19305    this.stack = null;
19306    this.bounds = null;
19307    this.borders = null;
19308    this.clip = [];
19309    this.backgroundClip = [];
19310    this.offsetBounds = null;
19311    this.visible = null;
19312    this.computedStyles = null;
19313    this.colors = {};
19314    this.styles = {};
19315    this.backgroundImages = null;
19316    this.transformData = null;
19317    this.transformMatrix = null;
19318    this.isPseudoElement = false;
19319    this.opacity = null;
19320}
19321
19322NodeContainer.prototype.cloneTo = function(stack) {
19323    stack.visible = this.visible;
19324    stack.borders = this.borders;
19325    stack.bounds = this.bounds;
19326    stack.clip = this.clip;
19327    stack.backgroundClip = this.backgroundClip;
19328    stack.computedStyles = this.computedStyles;
19329    stack.styles = this.styles;
19330    stack.backgroundImages = this.backgroundImages;
19331    stack.opacity = this.opacity;
19332};
19333
19334NodeContainer.prototype.getOpacity = function() {
19335    return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
19336};
19337
19338NodeContainer.prototype.assignStack = function(stack) {
19339    this.stack = stack;
19340    stack.children.push(this);
19341};
19342
19343NodeContainer.prototype.isElementVisible = function() {
19344    return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
19345        this.css('display') !== "none" &&
19346        this.css('visibility') !== "hidden" &&
19347        !this.node.hasAttribute("data-html2canvas-ignore") &&
19348        (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
19349    );
19350};
19351
19352NodeContainer.prototype.css = function(attribute) {
19353    if (!this.computedStyles) {
19354        this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
19355    }
19356
19357    return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
19358};
19359
19360NodeContainer.prototype.prefixedCss = function(attribute) {
19361    var prefixes = ["webkit", "moz", "ms", "o"];
19362    var value = this.css(attribute);
19363    if (value === undefined) {
19364        prefixes.some(function(prefix) {
19365            value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
19366            return value !== undefined;
19367        }, this);
19368    }
19369    return value === undefined ? null : value;
19370};
19371
19372NodeContainer.prototype.computedStyle = function(type) {
19373    return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
19374};
19375
19376NodeContainer.prototype.cssInt = function(attribute) {
19377    var value = parseInt(this.css(attribute), 10);
19378    return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
19379};
19380
19381NodeContainer.prototype.color = function(attribute) {
19382    return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
19383};
19384
19385NodeContainer.prototype.cssFloat = function(attribute) {
19386    var value = parseFloat(this.css(attribute));
19387    return (isNaN(value)) ? 0 : value;
19388};
19389
19390NodeContainer.prototype.fontWeight = function() {
19391    var weight = this.css("fontWeight");
19392    switch(parseInt(weight, 10)){
19393    case 401:
19394        weight = "bold";
19395        break;
19396    case 400:
19397        weight = "normal";
19398        break;
19399    }
19400    return weight;
19401};
19402
19403NodeContainer.prototype.parseClip = function() {
19404    var matches = this.css('clip').match(this.CLIP);
19405    if (matches) {
19406        return {
19407            top: parseInt(matches[1], 10),
19408            right: parseInt(matches[2], 10),
19409            bottom: parseInt(matches[3], 10),
19410            left: parseInt(matches[4], 10)
19411        };
19412    }
19413    return null;
19414};
19415
19416NodeContainer.prototype.parseBackgroundImages = function() {
19417    return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
19418};
19419
19420NodeContainer.prototype.cssList = function(property, index) {
19421    var value = (this.css(property) || '').split(',');
19422    value = value[index || 0] || value[0] || 'auto';
19423    value = value.trim().split(' ');
19424    if (value.length === 1) {
19425        value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
19426    }
19427    return value;
19428};
19429
19430NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
19431    var size = this.cssList("backgroundSize", index);
19432    var width, height;
19433
19434    if (isPercentage(size[0])) {
19435        width = bounds.width * parseFloat(size[0]) / 100;
19436    } else if (/contain|cover/.test(size[0])) {
19437        var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
19438        return (targetRatio < currentRatio ^ size[0] === 'contain') ?  {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
19439    } else {
19440        width = parseInt(size[0], 10);
19441    }
19442
19443    if (size[0] === 'auto' && size[1] === 'auto') {
19444        height = image.height;
19445    } else if (size[1] === 'auto') {
19446        height = width / image.width * image.height;
19447    } else if (isPercentage(size[1])) {
19448        height =  bounds.height * parseFloat(size[1]) / 100;
19449    } else {
19450        height = parseInt(size[1], 10);
19451    }
19452
19453    if (size[0] === 'auto') {
19454        width = height / image.height * image.width;
19455    }
19456
19457    return {width: width, height: height};
19458};
19459
19460NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
19461    var position = this.cssList('backgroundPosition', index);
19462    var left, top;
19463
19464    if (isPercentage(position[0])){
19465        left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
19466    } else {
19467        left = parseInt(position[0], 10);
19468    }
19469
19470    if (position[1] === 'auto') {
19471        top = left / image.width * image.height;
19472    } else if (isPercentage(position[1])){
19473        top =  (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
19474    } else {
19475        top = parseInt(position[1], 10);
19476    }
19477
19478    if (position[0] === 'auto') {
19479        left = top / image.height * image.width;
19480    }
19481
19482    return {left: left, top: top};
19483};
19484
19485NodeContainer.prototype.parseBackgroundRepeat = function(index) {
19486    return this.cssList("backgroundRepeat", index)[0];
19487};
19488
19489NodeContainer.prototype.parseTextShadows = function() {
19490    var textShadow = this.css("textShadow");
19491    var results = [];
19492
19493    if (textShadow && textShadow !== 'none') {
19494        var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
19495        for (var i = 0; shadows && (i < shadows.length); i++) {
19496            var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
19497            results.push({
19498                color: new Color(s[0]),
19499                offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
19500                offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
19501                blur: s[3] ? s[3].replace('px', '') : 0
19502            });
19503        }
19504    }
19505    return results;
19506};
19507
19508NodeContainer.prototype.parseTransform = function() {
19509    if (!this.transformData) {
19510        if (this.hasTransform()) {
19511            var offset = this.parseBounds();
19512            var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
19513            origin[0] += offset.left;
19514            origin[1] += offset.top;
19515            this.transformData = {
19516                origin: origin,
19517                matrix: this.parseTransformMatrix()
19518            };
19519        } else {
19520            this.transformData = {
19521                origin: [0, 0],
19522                matrix: [1, 0, 0, 1, 0, 0]
19523            };
19524        }
19525    }
19526    return this.transformData;
19527};
19528
19529NodeContainer.prototype.parseTransformMatrix = function() {
19530    if (!this.transformMatrix) {
19531        var transform = this.prefixedCss("transform");
19532        var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
19533        this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
19534    }
19535    return this.transformMatrix;
19536};
19537
19538NodeContainer.prototype.parseBounds = function() {
19539    return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
19540};
19541
19542NodeContainer.prototype.hasTransform = function() {
19543    return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
19544};
19545
19546NodeContainer.prototype.getValue = function() {
19547    var value = this.node.value || "";
19548    if (this.node.tagName === "SELECT") {
19549        value = selectionValue(this.node);
19550    } else if (this.node.type === "password") {
19551        value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
19552    }
19553    return value.length === 0 ? (this.node.placeholder || "") : value;
19554};
19555
19556NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
19557NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
19558NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
19559NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
19560
19561function selectionValue(node) {
19562    var option = node.options[node.selectedIndex || 0];
19563    return option ? (option.text || "") : "";
19564}
19565
19566function parseMatrix(match) {
19567    if (match && match[1] === "matrix") {
19568        return match[2].split(",").map(function(s) {
19569            return parseFloat(s.trim());
19570        });
19571    } else if (match && match[1] === "matrix3d") {
19572        var matrix3d = match[2].split(",").map(function(s) {
19573          return parseFloat(s.trim());
19574        });
19575        return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
19576    }
19577}
19578
19579function isPercentage(value) {
19580    return value.toString().indexOf("%") !== -1;
19581}
19582
19583function removePx(str) {
19584    return str.replace("px", "");
19585}
19586
19587function asFloat(str) {
19588    return parseFloat(str);
19589}
19590
19591module.exports = NodeContainer;
19592
19593},{"./color":3,"./utils":26}],15:[function(_dereq_,module,exports){
19594var log = _dereq_('./log');
19595var punycode = _dereq_('punycode');
19596var NodeContainer = _dereq_('./nodecontainer');
19597var TextContainer = _dereq_('./textcontainer');
19598var PseudoElementContainer = _dereq_('./pseudoelementcontainer');
19599var FontMetrics = _dereq_('./fontmetrics');
19600var Color = _dereq_('./color');
19601var StackingContext = _dereq_('./stackingcontext');
19602var utils = _dereq_('./utils');
19603var bind = utils.bind;
19604var getBounds = utils.getBounds;
19605var parseBackgrounds = utils.parseBackgrounds;
19606var offsetBounds = utils.offsetBounds;
19607
19608function NodeParser(element, renderer, support, imageLoader, options) {
19609    log("Starting NodeParser");
19610    this.renderer = renderer;
19611    this.options = options;
19612    this.range = null;
19613    this.support = support;
19614    this.renderQueue = [];
19615    this.stack = new StackingContext(true, 1, element.ownerDocument, null);
19616    var parent = new NodeContainer(element, null);
19617    if (options.background) {
19618        renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
19619    }
19620    if (element === element.ownerDocument.documentElement) {
19621        // http://www.w3.org/TR/css3-background/#special-backgrounds
19622        var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
19623        renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
19624    }
19625    parent.visibile = parent.isElementVisible();
19626    this.createPseudoHideStyles(element.ownerDocument);
19627    this.disableAnimations(element.ownerDocument);
19628    this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
19629        return container.visible = container.isElementVisible();
19630    }).map(this.getPseudoElements, this));
19631    this.fontMetrics = new FontMetrics();
19632    log("Fetched nodes, total:", this.nodes.length);
19633    log("Calculate overflow clips");
19634    this.calculateOverflowClips();
19635    log("Start fetching images");
19636    this.images = imageLoader.fetch(this.nodes.filter(isElement));
19637    this.ready = this.images.ready.then(bind(function() {
19638        log("Images loaded, starting parsing");
19639        log("Creating stacking contexts");
19640        this.createStackingContexts();
19641        log("Sorting stacking contexts");
19642        this.sortStackingContexts(this.stack);
19643        this.parse(this.stack);
19644        log("Render queue created with " + this.renderQueue.length + " items");
19645        return new Promise(bind(function(resolve) {
19646            if (!options.async) {
19647                this.renderQueue.forEach(this.paint, this);
19648                resolve();
19649            } else if (typeof(options.async) === "function") {
19650                options.async.call(this, this.renderQueue, resolve);
19651            } else if (this.renderQueue.length > 0){
19652                this.renderIndex = 0;
19653                this.asyncRenderer(this.renderQueue, resolve);
19654            } else {
19655                resolve();
19656            }
19657        }, this));
19658    }, this));
19659}
19660
19661NodeParser.prototype.calculateOverflowClips = function() {
19662    this.nodes.forEach(function(container) {
19663        if (isElement(container)) {
19664            if (isPseudoElement(container)) {
19665                container.appendToDOM();
19666            }
19667            container.borders = this.parseBorders(container);
19668            var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
19669            var cssClip = container.parseClip();
19670            if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
19671                clip.push([["rect",
19672                        container.bounds.left + cssClip.left,
19673                        container.bounds.top + cssClip.top,
19674                        cssClip.right - cssClip.left,
19675                        cssClip.bottom - cssClip.top
19676                ]]);
19677            }
19678            container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
19679            container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
19680            if (isPseudoElement(container)) {
19681                container.cleanDOM();
19682            }
19683        } else if (isTextNode(container)) {
19684            container.clip = hasParentClip(container) ? container.parent.clip : [];
19685        }
19686        if (!isPseudoElement(container)) {
19687            container.bounds = null;
19688        }
19689    }, this);
19690};
19691
19692function hasParentClip(container) {
19693    return container.parent && container.parent.clip.length;
19694}
19695
19696NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
19697    asyncTimer = asyncTimer || Date.now();
19698    this.paint(queue[this.renderIndex++]);
19699    if (queue.length === this.renderIndex) {
19700        resolve();
19701    } else if (asyncTimer + 20 > Date.now()) {
19702        this.asyncRenderer(queue, resolve, asyncTimer);
19703    } else {
19704        setTimeout(bind(function() {
19705            this.asyncRenderer(queue, resolve);
19706        }, this), 0);
19707    }
19708};
19709
19710NodeParser.prototype.createPseudoHideStyles = function(document) {
19711    this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
19712        '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
19713};
19714
19715NodeParser.prototype.disableAnimations = function(document) {
19716    this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
19717        '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
19718};
19719
19720NodeParser.prototype.createStyles = function(document, styles) {
19721    var hidePseudoElements = document.createElement('style');
19722    hidePseudoElements.innerHTML = styles;
19723    document.body.appendChild(hidePseudoElements);
19724};
19725
19726NodeParser.prototype.getPseudoElements = function(container) {
19727    var nodes = [[container]];
19728    if (container.node.nodeType === Node.ELEMENT_NODE) {
19729        var before = this.getPseudoElement(container, ":before");
19730        var after = this.getPseudoElement(container, ":after");
19731
19732        if (before) {
19733            nodes.push(before);
19734        }
19735
19736        if (after) {
19737            nodes.push(after);
19738        }
19739    }
19740    return flatten(nodes);
19741};
19742
19743function toCamelCase(str) {
19744    return str.replace(/(\-[a-z])/g, function(match){
19745        return match.toUpperCase().replace('-','');
19746    });
19747}
19748
19749NodeParser.prototype.getPseudoElement = function(container, type) {
19750    var style = container.computedStyle(type);
19751    if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
19752        return null;
19753    }
19754
19755    var content = stripQuotes(style.content);
19756    var isImage = content.substr(0, 3) === 'url';
19757    var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
19758    var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
19759
19760    for (var i = style.length-1; i >= 0; i--) {
19761        var property = toCamelCase(style.item(i));
19762        pseudoNode.style[property] = style[property];
19763    }
19764
19765    pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
19766
19767    if (isImage) {
19768        pseudoNode.src = parseBackgrounds(content)[0].args[0];
19769        return [pseudoContainer];
19770    } else {
19771        var text = document.createTextNode(content);
19772        pseudoNode.appendChild(text);
19773        return [pseudoContainer, new TextContainer(text, pseudoContainer)];
19774    }
19775};
19776
19777
19778NodeParser.prototype.getChildren = function(parentContainer) {
19779    return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
19780        var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
19781        return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
19782    }, this));
19783};
19784
19785NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
19786    var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
19787    container.cloneTo(stack);
19788    var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
19789    parentStack.contexts.push(stack);
19790    container.stack = stack;
19791};
19792
19793NodeParser.prototype.createStackingContexts = function() {
19794    this.nodes.forEach(function(container) {
19795        if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
19796            this.newStackingContext(container, true);
19797        } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
19798            this.newStackingContext(container, false);
19799        } else {
19800            container.assignStack(container.parent.stack);
19801        }
19802    }, this);
19803};
19804
19805NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
19806    return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
19807};
19808
19809NodeParser.prototype.isRootElement = function(container) {
19810    return container.parent === null;
19811};
19812
19813NodeParser.prototype.sortStackingContexts = function(stack) {
19814    stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
19815    stack.contexts.forEach(this.sortStackingContexts, this);
19816};
19817
19818NodeParser.prototype.parseTextBounds = function(container) {
19819    return function(text, index, textList) {
19820        if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
19821            if (this.support.rangeBounds && !container.parent.hasTransform()) {
19822                var offset = textList.slice(0, index).join("").length;
19823                return this.getRangeBounds(container.node, offset, text.length);
19824            } else if (container.node && typeof(container.node.data) === "string") {
19825                var replacementNode = container.node.splitText(text.length);
19826                var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
19827                container.node = replacementNode;
19828                return bounds;
19829            }
19830        } else if(!this.support.rangeBounds || container.parent.hasTransform()){
19831            container.node = container.node.splitText(text.length);
19832        }
19833        return {};
19834    };
19835};
19836
19837NodeParser.prototype.getWrapperBounds = function(node, transform) {
19838    var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
19839    var parent = node.parentNode,
19840        backupText = node.cloneNode(true);
19841
19842    wrapper.appendChild(node.cloneNode(true));
19843    parent.replaceChild(wrapper, node);
19844    var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
19845    parent.replaceChild(backupText, wrapper);
19846    return bounds;
19847};
19848
19849NodeParser.prototype.getRangeBounds = function(node, offset, length) {
19850    var range = this.range || (this.range = node.ownerDocument.createRange());
19851    range.setStart(node, offset);
19852    range.setEnd(node, offset + length);
19853    return range.getBoundingClientRect();
19854};
19855
19856function ClearTransform() {}
19857
19858NodeParser.prototype.parse = function(stack) {
19859    // http://www.w3.org/TR/CSS21/visuren.html#z-index
19860    var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
19861    var descendantElements = stack.children.filter(isElement);
19862    var descendantNonFloats = descendantElements.filter(not(isFloating));
19863    var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
19864    var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
19865    var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
19866    var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0); // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
19867    var text = stack.children.filter(isTextNode).filter(hasText);
19868    var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
19869    negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
19870        .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
19871            this.renderQueue.push(container);
19872            if (isStackingContext(container)) {
19873                this.parse(container);
19874                this.renderQueue.push(new ClearTransform());
19875            }
19876        }, this);
19877};
19878
19879NodeParser.prototype.paint = function(container) {
19880    try {
19881        if (container instanceof ClearTransform) {
19882            this.renderer.ctx.restore();
19883        } else if (isTextNode(container)) {
19884            if (isPseudoElement(container.parent)) {
19885                container.parent.appendToDOM();
19886            }
19887            this.paintText(container);
19888            if (isPseudoElement(container.parent)) {
19889                container.parent.cleanDOM();
19890            }
19891        } else {
19892            this.paintNode(container);
19893        }
19894    } catch(e) {
19895        log(e);
19896        if (this.options.strict) {
19897            throw e;
19898        }
19899    }
19900};
19901
19902NodeParser.prototype.paintNode = function(container) {
19903    if (isStackingContext(container)) {
19904        this.renderer.setOpacity(container.opacity);
19905        this.renderer.ctx.save();
19906        if (container.hasTransform()) {
19907            this.renderer.setTransform(container.parseTransform());
19908        }
19909    }
19910
19911    if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
19912        this.paintCheckbox(container);
19913    } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
19914        this.paintRadio(container);
19915    } else {
19916        this.paintElement(container);
19917    }
19918};
19919
19920NodeParser.prototype.paintElement = function(container) {
19921    var bounds = container.parseBounds();
19922    this.renderer.clip(container.backgroundClip, function() {
19923        this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
19924    }, this);
19925
19926    this.renderer.clip(container.clip, function() {
19927        this.renderer.renderBorders(container.borders.borders);
19928    }, this);
19929
19930    this.renderer.clip(container.backgroundClip, function() {
19931        switch (container.node.nodeName) {
19932        case "svg":
19933        case "IFRAME":
19934            var imgContainer = this.images.get(container.node);
19935            if (imgContainer) {
19936                this.renderer.renderImage(container, bounds, container.borders, imgContainer);
19937            } else {
19938                log("Error loading <" + container.node.nodeName + ">", container.node);
19939            }
19940            break;
19941        case "IMG":
19942            var imageContainer = this.images.get(container.node.src);
19943            if (imageContainer) {
19944                this.renderer.renderImage(container, bounds, container.borders, imageContainer);
19945            } else {
19946                log("Error loading <img>", container.node.src);
19947            }
19948            break;
19949        case "CANVAS":
19950            this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
19951            break;
19952        case "SELECT":
19953        case "INPUT":
19954        case "TEXTAREA":
19955            this.paintFormValue(container);
19956            break;
19957        }
19958    }, this);
19959};
19960
19961NodeParser.prototype.paintCheckbox = function(container) {
19962    var b = container.parseBounds();
19963
19964    var size = Math.min(b.width, b.height);
19965    var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
19966    var r = [3, 3];
19967    var radius = [r, r, r, r];
19968    var borders = [1,1,1,1].map(function(w) {
19969        return {color: new Color('#A5A5A5'), width: w};
19970    });
19971
19972    var borderPoints = calculateCurvePoints(bounds, radius, borders);
19973
19974    this.renderer.clip(container.backgroundClip, function() {
19975        this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
19976        this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
19977        if (container.node.checked) {
19978            this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
19979            this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
19980        }
19981    }, this);
19982};
19983
19984NodeParser.prototype.paintRadio = function(container) {
19985    var bounds = container.parseBounds();
19986
19987    var size = Math.min(bounds.width, bounds.height) - 2;
19988
19989    this.renderer.clip(container.backgroundClip, function() {
19990        this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
19991        if (container.node.checked) {
19992            this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
19993        }
19994    }, this);
19995};
19996
19997NodeParser.prototype.paintFormValue = function(container) {
19998    var value = container.getValue();
19999    if (value.length > 0) {
20000        var document = container.node.ownerDocument;
20001        var wrapper = document.createElement('html2canvaswrapper');
20002        var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
20003            'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
20004            'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
20005            'boxSizing', 'whiteSpace', 'wordWrap'];
20006
20007        properties.forEach(function(property) {
20008            try {
20009                wrapper.style[property] = container.css(property);
20010            } catch(e) {
20011                // Older IE has issues with "border"
20012                log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
20013            }
20014        });
20015        var bounds = container.parseBounds();
20016        wrapper.style.position = "fixed";
20017        wrapper.style.left = bounds.left + "px";
20018        wrapper.style.top = bounds.top + "px";
20019        wrapper.textContent = value;
20020        document.body.appendChild(wrapper);
20021        this.paintText(new TextContainer(wrapper.firstChild, container));
20022        document.body.removeChild(wrapper);
20023    }
20024};
20025
20026NodeParser.prototype.paintText = function(container) {
20027    container.applyTextTransform();
20028    var characters = punycode.ucs2.decode(container.node.data);
20029    var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(ch
20029aracter) {
20030        return punycode.ucs2.encode([character]);
20031    });
20032
20033    var weight = container.parent.fontWeight();
20034    var size = container.parent.css('fontSize');
20035    var family = container.parent.css('fontFamily');
20036    var shadows = container.parent.parseTextShadows();
20037
20038    this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
20039    if (shadows.length) {
20040        // TODO: support multiple text shadows
20041        this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
20042    } else {
20043        this.renderer.clearShadow();
20044    }
20045
20046    this.renderer.clip(container.parent.clip, function() {
20047        textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
20048            if (bounds) {
20049                this.renderer.text(textList[index], bounds.left, bounds.bottom);
20050                this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
20051            }
20052        }, this);
20053    }, this);
20054};
20055
20056NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
20057    switch(container.css("textDecoration").split(" ")[0]) {
20058    case "underline":
20059        // Draws a line at the baseline of the font
20060        // TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size
20061        this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
20062        break;
20063    case "overline":
20064        this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
20065        break;
20066    case "line-through":
20067        // TODO try and find exact position for line-through
20068        this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
20069        break;
20070    }
20071};
20072
20073var borderColorTransforms = {
20074    inset: [
20075        ["darken", 0.60],
20076        ["darken", 0.10],
20077        ["darken", 0.10],
20078        ["darken", 0.60]
20079    ]
20080};
20081
20082NodeParser.prototype.parseBorders = function(container) {
20083    var nodeBounds = container.parseBounds();
20084    var radius = getBorderRadiusData(container);
20085    var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
20086        var style = container.css('border' + side + 'Style');
20087        var color = container.color('border' + side + 'Color');
20088        if (style === "inset" && color.isBlack()) {
20089            color = new Color([255, 255, 255, color.a]); // this is wrong, but
20090        }
20091        var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
20092        return {
20093            width: container.cssInt('border' + side + 'Width'),
20094            color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
20095            args: null
20096        };
20097    });
20098    var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
20099
20100    return {
20101        clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
20102        borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
20103    };
20104};
20105
20106function calculateBorders(borders, nodeBounds, borderPoints, radius) {
20107    return borders.map(function(border, borderSide) {
20108        if (border.width > 0) {
20109            var bx = nodeBounds.left;
20110            var by = nodeBounds.top;
20111            var bw = nodeBounds.width;
20112            var bh = nodeBounds.height - (borders[2].width);
20113
20114            switch(borderSide) {
20115            case 0:
20116                // top border
20117                bh = borders[0].width;
20118                border.args = drawSide({
20119                        c1: [bx, by],
20120                        c2: [bx + bw, by],
20121                        c3: [bx + bw - borders[1].width, by + bh],
20122                        c4: [bx + borders[3].width, by + bh]
20123                    }, radius[0], radius[1],
20124                    borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
20125                break;
20126            case 1:
20127                // right border
20128                bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
20129                bw = borders[1].width;
20130
20131                border.args = drawSide({
20132                        c1: [bx + bw, by],
20133                        c2: [bx + bw, by + bh + borders[2].width],
20134                        c3: [bx, by + bh],
20135                        c4: [bx, by + borders[0].width]
20136                    }, radius[1], radius[2],
20137                    borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
20138                break;
20139            case 2:
20140                // bottom border
20141                by = (by + nodeBounds.height) - (borders[2].width);
20142                bh = borders[2].width;
20143                border.args = drawSide({
20144                        c1: [bx + bw, by + bh],
20145                        c2: [bx, by + bh],
20146                        c3: [bx + borders[3].width, by],
20147                        c4: [bx + bw - borders[3].width, by]
20148                    }, radius[2], radius[3],
20149                    borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
20150                break;
20151            case 3:
20152                // left border
20153                bw = borders[3].width;
20154                border.args = drawSide({
20155                        c1: [bx, by + bh + borders[2].width],
20156                        c2: [bx, by],
20157                        c3: [bx + bw, by + borders[0].width],
20158                        c4: [bx + bw, by + bh]
20159                    }, radius[3], radius[0],
20160                    borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
20161                break;
20162            }
20163        }
20164        return border;
20165    });
20166}
20167
20168NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
20169    var backgroundClip = container.css('backgroundClip'),
20170        borderArgs = [];
20171
20172    switch(backgroundClip) {
20173    case "content-box":
20174    case "padding-box":
20175        parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
20176        parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
20177        parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
20178        parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
20179        break;
20180
20181    default:
20182        parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
20183        parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
20184        parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
20185        parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
20186        break;
20187    }
20188
20189    return borderArgs;
20190};
20191
20192function getCurvePoints(x, y, r1, r2) {
20193    var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
20194    var ox = (r1) * kappa, // control point offset horizontal
20195        oy = (r2) * kappa, // control point offset vertical
20196        xm = x + r1, // x-middle
20197        ym = y + r2; // y-middle
20198    return {
20199        topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
20200        topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
20201        bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
20202        bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
20203    };
20204}
20205
20206function calculateCurvePoints(bounds, borderRadius, borders) {
20207    var x = bounds.left,
20208        y = bounds.top,
20209        width = bounds.width,
20210        height = bounds.height,
20211
20212        tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
20213        tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
20214        trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
20215        trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
20216        brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
20217        brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
20218        blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
20219        blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
20220
20221    var topWidth = width - trh,
20222        rightHeight = height - brv,
20223        bottomWidth = width - brh,
20224        leftHeight = height - blv;
20225
20226    return {
20227        topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
20228        topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5),
20229        topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
20230        topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5),
20231        bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
20232        bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width),  brv - borders[2].width).bottomRight.subdivide(0.5),
20233        bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
20234        bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
20235    };
20236}
20237
20238function bezierCurve(start, startControl, endControl, end) {
20239    var lerp = function (a, b, t) {
20240        return {
20241            x: a.x + (b.x - a.x) * t,
20242            y: a.y + (b.y - a.y) * t
20243        };
20244    };
20245
20246    return {
20247        start: start,
20248        startControl: startControl,
20249        endControl: endControl,
20250        end: end,
20251        subdivide: function(t) {
20252            var ab = lerp(start, startControl, t),
20253                bc = lerp(startControl, endControl, t),
20254                cd = lerp(endControl, end, t),
20255                abbc = lerp(ab, bc, t),
20256                bccd = lerp(bc, cd, t),
20257                dest = lerp(abbc, bccd, t);
20258            return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
20259        },
20260        curveTo: function(borderArgs) {
20261            borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
20262        },
20263        curveToReversed: function(borderArgs) {
20264            borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
20265        }
20266    };
20267}
20268
20269function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
20270    var borderArgs = [];
20271
20272    if (radius1[0] > 0 || radius1[1] > 0) {
20273        borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
20274        outer1[1].curveTo(borderArgs);
20275    } else {
20276        borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
20277    }
20278
20279    if (radius2[0] > 0 || radius2[1] > 0) {
20280        borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
20281        outer2[0].curveTo(borderArgs);
20282        borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
20283        inner2[0].curveToReversed(borderArgs);
20284    } else {
20285        borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
20286        borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
20287    }
20288
20289    if (radius1[0] > 0 || radius1[1] > 0) {
20290        borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
20291        inner1[1].curveToReversed(borderArgs);
20292    } else {
20293        borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
20294    }
20295
20296    return borderArgs;
20297}
20298
20299function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
20300    if (radius1[0] > 0 || radius1[1] > 0) {
20301        borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
20302        corner1[0].curveTo(borderArgs);
20303        corner1[1].curveTo(borderArgs);
20304    } else {
20305        borderArgs.push(["line", x, y]);
20306    }
20307
20308    if (radius2[0] > 0 || radius2[1] > 0) {
20309        borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
20310    }
20311}
20312
20313function negativeZIndex(container) {
20314    return container.cssInt("zIndex") < 0;
20315}
20316
20317function positiveZIndex(container) {
20318    return container.cssInt("zIndex") > 0;
20319}
20320
20321function zIndex0(container) {
20322    return container.cssInt("zIndex") === 0;
20323}
20324
20325function inlineLevel(container) {
20326    return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
20327}
20328
20329function isStackingContext(container) {
20330    return (container instanceof StackingContext);
20331}
20332
20333function hasText(container) {
20334    return container.node.data.trim().length > 0;
20335}
20336
20337function noLetterSpacing(container) {
20338    return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
20339}
20340
20341function getBorderRadiusData(container) {
20342    return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
20343        var value = container.css('border' + side + 'Radius');
20344        var arr = value.split(" ");
20345        if (arr.length <= 1) {
20346            arr[1] = arr[0];
20347        }
20348        return arr.map(asInt);
20349    });
20350}
20351
20352function renderableNode(node) {
20353    return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
20354}
20355
20356function isPositionedForStacking(container) {
20357    var position = container.css("position");
20358    var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
20359    return zIndex !== "auto";
20360}
20361
20362function isPositioned(container) {
20363    return container.css("position") !== "static";
20364}
20365
20366function isFloating(container) {
20367    return container.css("float") !== "none";
20368}
20369
20370function isInlineBlock(container) {
20371    return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
20372}
20373
20374function not(callback) {
20375    var context = this;
20376    return function() {
20377        return !callback.apply(context, arguments);
20378    };
20379}
20380
20381function isElement(container) {
20382    return container.node.nodeType === Node.ELEMENT_NODE;
20383}
20384
20385function isPseudoElement(container) {
20386    return container.isPseudoElement === true;
20387}
20388
20389function isTextNode(container) {
20390    return container.node.nodeType === Node.TEXT_NODE;
20391}
20392
20393function zIndexSort(contexts) {
20394    return function(a, b) {
20395        return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
20396    };
20397}
20398
20399function hasOpacity(container) {
20400    return container.getOpacity() < 1;
20401}
20402
20403function asInt(value) {
20404    return parseInt(value, 10);
20405}
20406
20407function getWidth(border) {
20408    return border.width;
20409}
20410
20411function nonIgnoredElement(nodeContainer) {
20412    return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
20413}
20414
20415function flatten(arrays) {
20416    return [].concat.apply([], arrays);
20417}
20418
20419function stripQuotes(content) {
20420    var first = content.substr(0, 1);
20421    return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
20422}
20423
20424function getWords(characters) {
20425    var words = [], i = 0, onWordBoundary = false, word;
20426    while(characters.length) {
20427        if (isWordBoundary(characters[i]) === onWordBoundary) {
20428            word = characters.splice(0, i);
20429            if (word.length) {
20430                words.push(punycode.ucs2.encode(word));
20431            }
20432            onWordBoundary =! onWordBoundary;
20433            i = 0;
20434        } else {
20435            i++;
20436        }
20437
20438        if (i >= characters.length) {
20439            word = characters.splice(0, i);
20440            if (word.length) {
20441                words.push(punycode.ucs2.encode(word));
20442            }
20443        }
20444    }
20445    return words;
20446}
20447
20448function isWordBoundary(characterCode) {
20449    return [
20450        32, // <space>
20451        13, // \r
20452        10, // \n
20453        9, // \t
20454        45 // -
20455    ].indexOf(characterCode) !== -1;
20456}
20457
20458function hasUnicode(string) {
20459    return (/[^\u0000-\u00ff]/).test(string);
20460}
20461
20462module.exports = NodeParser;
20463
20464},{"./color":3,"./fontmetrics":7,"./log":13,"./nodecontainer":14,"./pseudoelementcontainer":18,"./stackingcontext":21,"./textcontainer":25,"./utils":26,"pu
20464nycode":1}],16:[function(_dereq_,module,exports){
20465var XHR = _dereq_('./xhr');
20466var utils = _dereq_('./utils');
20467var log = _dereq_('./log');
20468var createWindowClone = _dereq_('./clone');
20469var decode64 = utils.decode64;
20470
20471function Proxy(src, proxyUrl, document) {
20472    var supportsCORS = ('withCredentials' in new XMLHttpRequest());
20473    if (!proxyUrl) {
20474        return Promise.reject("No proxy configured");
20475    }
20476    var callback = createCallback(supportsCORS);
20477    var url = createProxyUrl(proxyUrl, src, callback);
20478
20479    return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
20480        return decode64(response.content);
20481    }));
20482}
20483var proxyCount = 0;
20484
20485function ProxyURL(src, proxyUrl, document) {
20486    var supportsCORSImage = ('crossOrigin' in new Image());
20487    var callback = createCallback(supportsCORSImage);
20488    var url = createProxyUrl(proxyUrl, src, callback);
20489    return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
20490        return "data:" + response.type + ";base64," + response.content;
20491    }));
20492}
20493
20494function jsonp(document, url, callback) {
20495    return new Promise(function(resolve, reject) {
20496        var s = document.createElement("script");
20497        var cleanup = function() {
20498            delete window.html2canvas.proxy[callback];
20499            document.body.removeChild(s);
20500        };
20501        window.html2canvas.proxy[callback] = function(response) {
20502            cleanup();
20503            resolve(response);
20504        };
20505        s.src = url;
20506        s.onerror = function(e) {
20507            cleanup();
20508            reject(e);
20509        };
20510        document.body.appendChild(s);
20511    });
20512}
20513
20514function createCallback(useCORS) {
20515    return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
20516}
20517
20518function createProxyUrl(proxyUrl, src, callback) {
20519    return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
20520}
20521
20522function documentFromHTML(src) {
20523    return function(html) {
20524        var parser = new DOMParser(), doc;
20525        try {
20526            doc = parser.parseFromString(html, "text/html");
20527        } catch(e) {
20528            log("DOMParser not supported, falling back to createHTMLDocument");
20529            doc = document.implementation.createHTMLDocument("");
20530            try {
20531                doc.open();
20532                doc.write(html);
20533                doc.close();
20534            } catch(ee) {
20535                log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
20536                doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
20537            }
20538        }
20539
20540        var b = doc.querySelector("base");
20541        if (!b || !b.href.host) {
20542            var base = doc.createElement("base");
20543            base.href = src;
20544            doc.head.insertBefore(base, doc.head.firstChild);
20545        }
20546
20547        return doc;
20548    };
20549}
20550
20551function loadUrlDocument(src, proxy, document, width, height, options) {
20552    return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
20553        return createWindowClone(doc, document, width, height, options, 0, 0);
20554    });
20555}
20556
20557exports.Proxy = Proxy;
20558exports.ProxyURL = ProxyURL;
20559exports.loadUrlDocument = loadUrlDocument;
20560
20561},{"./clone":2,"./log":13,"./utils":26,"./xhr":28}],17:[function(_dereq_,module,exports){
20562var ProxyURL = _dereq_('./proxy').ProxyURL;
20563
20564function ProxyImageContainer(src, proxy) {
20565    var link = document.createElement("a");
20566    link.href = src;
20567    src = link.href;
20568    this.src = src;
20569    this.image = new Image();
20570    var self = this;
20571    this.promise = new Promise(function(resolve, reject) {
20572        self.image.crossOrigin = "Anonymous";
20573        self.image.onload = resolve;
20574        self.image.onerror = reject;
20575
20576        new ProxyURL(src, proxy, document).then(function(url) {
20577            self.image.src = url;
20578        })['catch'](reject);
20579    });
20580}
20581
20582module.exports = ProxyImageContainer;
20583
20584},{"./proxy":16}],18:[function(_dereq_,module,exports){
20585var NodeContainer = _dereq_('./nodecontainer');
20586
20587function PseudoElementContainer(node, parent, type) {
20588    NodeContainer.call(this, node, parent);
20589    this.isPseudoElement = true;
20590    this.before = type === ":before";
20591}
20592
20593PseudoElementContainer.prototype.cloneTo = function(stack) {
20594    PseudoElementContainer.prototype.cloneTo.call(this, stack);
20595    stack.isPseudoElement = true;
20596    stack.before = this.before;
20597};
20598
20599PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
20600
20601PseudoElementContainer.prototype.appendToDOM = function() {
20602    if (this.before) {
20603        this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
20604    } else {
20605        this.parent.node.appendChild(this.node);
20606    }
20607    this.parent.node.className += " " + this.getHideClass();
20608};
20609
20610PseudoElementContainer.prototype.cleanDOM = function() {
20611    this.node.parentNode.removeChild(this.node);
20612    this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
20613};
20614
20615PseudoElementContainer.prototype.getHideClass = function() {
20616    return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
20617};
20618
20619PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
20620PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
20621
20622module.exports = PseudoElementContainer;
20623
20624},{"./nodecontainer":14}],19:[function(_dereq_,module,exports){
20625var log = _dereq_('./log');
20626
20627function Renderer(width, height, images, options, document) {
20628    this.width = width;
20629    this.height = height;
20630    this.images = images;
20631    this.options = options;
20632    this.document = document;
20633}
20634
20635Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
20636    var paddingLeft = container.cssInt('paddingLeft'),
20637        paddingTop = container.cssInt('paddingTop'),
20638        paddingRight = container.cssInt('paddingRight'),
20639        paddingBottom = container.cssInt('paddingBottom'),
20640        borders = borderData.borders;
20641
20642    var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
20643    var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
20644    this.drawImage(
20645        imageContainer,
20646        0,
20647        0,
20648        imageContainer.image.width || width,
20649        imageContainer.image.height || height,
20650        bounds.left + paddingLeft + borders[3].width,
20651        bounds.top + paddingTop + borders[0].width,
20652        width,
20653        height
20654    );
20655};
20656
20657Renderer.prototype.renderBackground = function(container, bounds, borderData) {
20658    if (bounds.height > 0 && bounds.width > 0) {
20659        this.renderBackgroundColor(container, bounds);
20660        this.renderBackgroundImage(container, bounds, borderData);
20661    }
20662};
20663
20664Renderer.prototype.renderBackgroundColor = function(container, bounds) {
20665    var color = container.color("backgroundColor");
20666    if (!color.isTransparent()) {
20667        this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
20668    }
20669};
20670
20671Renderer.prototype.renderBorders = function(borders) {
20672    borders.forEach(this.renderBorder, this);
20673};
20674
20675Renderer.prototype.renderBorder = function(data) {
20676    if (!data.color.isTransparent() && data.args !== null) {
20677        this.drawShape(data.args, data.color);
20678    }
20679};
20680
20681Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
20682    var backgroundImages = container.parseBackgroundImages();
20683    backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
20684        switch(backgroundImage.method) {
20685        case "url":
20686            var image = this.images.get(backgroundImage.args[0]);
20687            if (image) {
20688                this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
20689            } else {
20690                log("Error loading background-image", backgroundImage.args[0]);
20691            }
20692            break;
20693        case "linear-gradient":
20694        case "gradient":
20695            var gradientImage = this.images.get(backgroundImage.value);
20696            if (gradientImage) {
20697                this.renderBackgroundGradient(gradientImage, bounds, borderData);
20698            } else {
20699                log("Error loading background-image", backgroundImage.args[0]);
20700            }
20701            break;
20702        case "none":
20703            break;
20704        default:
20705            log("Unknown background-image type", backgroundImage.args[0]);
20706        }
20707    }, this);
20708};
20709
20710Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
20711    var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
20712    var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
20713    var repeat = container.parseBackgroundRepeat(index);
20714    switch (repeat) {
20715    case "repeat-x":
20716    case "repeat no-repeat":
20717        this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
20718        break;
20719    case "repeat-y":
20720    case "no-repeat repeat":
20721        this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
20722        break;
20723    case "no-repeat":
20724        this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
20725        break;
20726    default:
20727        this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
20728        break;
20729    }
20730};
20731
20732module.exports = Renderer;
20733
20734},{"./log":13}],20:[function(_dereq_,module,exports){
20735var Renderer = _dereq_('../renderer');
20736var LinearGradientContainer = _dereq_('../lineargradientcontainer');
20737var log = _dereq_('../log');
20738
20739function CanvasRenderer(width, height) {
20740    Renderer.apply(this, arguments);
20741    this.canvas = this.options.canvas || this.document.createElement("canvas");
20742    if (!this.options.canvas) {
20743        this.canvas.width = width;
20744        this.canvas.height = height;
20745    }
20746    this.ctx = this.canvas.getContext("2d");
20747    this.taintCtx = this.document.createElement("canvas").getContext("2d");
20748    this.ctx.textBaseline = "bottom";
20749    this.variables = {};
20750    log("Initialized CanvasRenderer with size", width, "x", height);
20751}
20752
20753CanvasRenderer.prototype = Object.create(Renderer.prototype);
20754
20755CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
20756    this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
20757    return this.ctx;
20758};
20759
20760CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
20761    this.setFillStyle(color).fillRect(left, top, width, height);
20762};
20763
20764CanvasRenderer.prototype.circle = function(left, top, size, color) {
20765    this.setFillStyle(color);
20766    this.ctx.beginPath();
20767    this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
20768    this.ctx.closePath();
20769    this.ctx.fill();
20770};
20771
20772CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
20773    this.circle(left, top, size, color);
20774    this.ctx.strokeStyle = strokeColor.toString();
20775    this.ctx.stroke();
20776};
20777
20778CanvasRenderer.prototype.drawShape = function(shape, color) {
20779    this.shape(shape);
20780    this.setFillStyle(color).fill();
20781};
20782
20783CanvasRenderer.prototype.taints = function(imageContainer) {
20784    if (imageContainer.tainted === null) {
20785        this.taintCtx.drawImage(imageContainer.image, 0, 0);
20786        try {
20787            this.taintCtx.getImageData(0, 0, 1, 1);
20788            imageContainer.tainted = false;
20789        } catch(e) {
20790            this.taintCtx = document.createElement("canvas").getContext("2d");
20791            imageContainer.tainted = true;
20792        }
20793    }
20794
20795    return imageContainer.tainted;
20796};
20797
20798CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
20799    if (!this.taints(imageContainer) || this.options.allowTaint) {
20800        this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
20801    }
20802};
20803
20804CanvasRenderer.prototype.clip = function(shapes, callback, context) {
20805    this.ctx.save();
20806    shapes.filter(hasEntries).forEach(function(shape) {
20807        this.shape(shape).clip();
20808    }, this);
20809    callback.call(context);
20810    this.ctx.restore();
20811};
20812
20813CanvasRenderer.prototype.shape = function(shape) {
20814    this.ctx.beginPath();
20815    shape.forEach(function(point, index) {
20816        if (point[0] === "rect") {
20817            this.ctx.rect.apply(this.ctx, point.slice(1));
20818        } else {
20819            this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
20820        }
20821    }, this);
20822    this.ctx.closePath();
20823    return this.ctx;
20824};
20825
20826CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
20827    this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
20828};
20829
20830CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
20831    this.setVariable("shadowColor", color.toString())
20832        .setVariable("shadowOffsetY", offsetX)
20833        .setVariable("shadowOffsetX", offsetY)
20834        .setVariable("shadowBlur", blur);
20835};
20836
20837CanvasRenderer.prototype.clearShadow = function() {
20838    this.setVariable("shadowColor", "rgba(0,0,0,0)");
20839};
20840
20841CanvasRenderer.prototype.setOpacity = function(opacity) {
20842    this.ctx.globalAlpha = opacity;
20843};
20844
20845CanvasRenderer.prototype.setTransform = function(transform) {
20846    this.ctx.translate(transform.origin[0], transform.origin[1]);
20847    this.ctx.transform.apply(this.ctx, transform.matrix);
20848    this.ctx.translate(-transform.origin[0], -transform.origin[1]);
20849};
20850
20851CanvasRenderer.prototype.setVariable = function(property, value) {
20852    if (this.variables[property] !== value) {
20853        this.variables[property] = this.ctx[property] = value;
20854    }
20855
20856    return this;
20857};
20858
20859CanvasRenderer.prototype.text = function(text, left, bottom) {
20860    this.ctx.fillText(text, left, bottom);
20861};
20862
20863CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
20864    var shape = [
20865        ["line", Math.round(left), Math.round(top)],
20866        ["line", Math.round(left + width), Math.round(top)],
20867        ["line", Math.round(left + width), Math.round(height + top)],
20868        ["line", Math.round(left), Math.round(height + top)]
20869    ];
20870    this.clip([shape], function() {
20871        this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
20872    }, this);
20873};
20874
20875CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
20876    var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
20877    this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
20878    this.ctx.translate(offsetX, offsetY);
20879    this.ctx.fill();
20880    this.ctx.translate(-offsetX, -offsetY);
20881};
20882
20883CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
20884    if (gradientImage instanceof LinearGradientContainer) {
20885        var gradient = this.ctx.createLinearGradient(
20886            bounds.left + bounds.width * gradientImage.x0,
20887            bounds.top + bounds.height * gradientImage.y0,
20888            bounds.left +  bounds.width * gradientImage.x1,
20889            bounds.top +  bounds.height * gradientImage.y1);
20890        gradientImage.colorStops.forEach(function(colorStop) {
20891            gradient.addColorStop(colorStop.stop, colorStop.color.toString());
20892        });
20893        this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
20894    }
20895};
20896
20897CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
20898    var image = imageContainer.image;
20899    if(image.width === size.width && image.height === size.height) {
20900        return image;
20901    }
20902
20903    var ctx, canvas = document.createElement('canvas');
20904    canvas.width = size.width;
20905    canvas.height = size.height;
20906    ctx = canvas.getContext("2d");
20907    ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
20908    return canvas;
20909};
20910
20911function hasEntries(array) {
20912    return array.length > 0;
20913}
20914
20915module.exports = CanvasRenderer;
20916
20917},{"../lineargradientcontainer":12,"../log":13,"../renderer":19}],21:[function(_dereq_,module,exports){
20918var NodeContainer = _dereq_('./nodecontainer');
20919
20920function StackingContext(hasOwnStacking, opacity, element, parent) {
20921    NodeContainer.call(this, element, parent);
20922    this.ownStacking = hasOwnStacking;
20923    this.contexts = [];
20924    this.children = [];
20925    this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
20926}
20927
20928StackingContext.prototype = Object.create(NodeContainer.prototype);
20929
20930StackingContext.prototype.getParentStack = function(context) {
20931    var parentStack = (this.parent) ? this.parent.stack : null;
20932    return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
20933};
20934
20935module.exports = StackingContext;
20936
20937},{"./nodecontainer":14}],22:[function(_dereq_,module,exports){
20938function Support(document) {
20939    this.rangeBounds = this.testRangeBounds(document);
20940    this.cors = this.testCORS();
20941    this.svg = this.testSVG();
20942}
20943
20944Support.prototype.testRangeBounds = function(document) {
20945    var range, testElement, rangeBounds, rangeHeight, support = false;
20946
20947    if (document.createRange) {
20948        range = document.createRange();
20949        if (range.getBoundingClientRect) {
20950            testElement = document.createElement('boundtest');
20951            testElement.style.height = "123px";
20952            testElement.style.display = "block";
20953            document.body.appendChild(testElement);
20954
20955            range.selectNode(testElement);
20956            rangeBounds = range.getBoundingClientRect();
20957            rangeHeight = rangeBounds.height;
20958
20959            if (rangeHeight === 123) {
20960                support = true;
20961            }
20962            document.body.removeChild(testElement);
20963        }
20964    }
20965
20966    return support;
20967};
20968
20969Support.prototype.testCORS = function() {
20970    return typeof((new Image()).crossOrigin) !== "undefined";
20971};
20972
20973Support.prototype.testSVG = function() {
20974    var img = new Image();
20975    var canvas = document.createElement("canvas");
20976    var ctx =  canvas.getContext("2d");
20977    img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
20978
20979    try {
20980        ctx.drawImage(img, 0, 0);
20981        canvas.toDataURL();
20982    } catch(e) {
20983        return false;
20984    }
20985    return true;
20986};
20987
20988module.exports = Support;
20989
20990},{}],23:[function(_dereq_,module,exports){
20991var XHR = _dereq_('./xhr');
20992var decode64 = _dereq_('./utils').decode64;
20993
20994function SVGContainer(src) {
20995    this.src = src;
20996    this.image = null;
20997    var self = this;
20998
20999    this.promise = this.hasFabric().then(function() {
21000        return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
21001    }).then(function(svg) {
21002        return new Promise(function(resolve) {
21003            window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
21004        });
21005    });
21006}
21007
21008SVGContainer.prototype.hasFabric = function() {
21009    return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
21010};
21011
21012SVGContainer.prototype.inlineFormatting = function(src) {
21013    return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
21014};
21015
21016SVGContainer.prototype.removeContentType = function(src) {
21017    return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
21018};
21019
21020SVGContainer.prototype.isInline = function(src) {
21021    return (/^data:image\/svg\+xml/i.test(src));
21022};
21023
21024SVGContainer.prototype.createCanvas = function(resolve) {
21025    var self = this;
21026    return function (objects, options) {
21027        var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
21028        self.image = canvas.lowerCanvasEl;
21029        canvas
21030            .setWidth(options.width)
21031            .setHeight(options.height)
21032            .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
21033            .renderAll();
21034        resolve(canvas.lowerCanvasEl);
21035    };
21036};
21037
21038SVGContainer.prototype.decode64 = function(str) {
21039    return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
21040};
21041
21042module.exports = SVGContainer;
21043
21044},{"./utils":26,"./xhr":28}],24:[function(_dereq_,module,exports){
21045var SVGContainer = _dereq_('./svgcontainer');
21046
21047function SVGNodeContainer(node, _native) {
21048    this.src = node;
21049    this.image = null;
21050    var self = this;
21051
21052    this.promise = _native ? new Promise(function(resolve, reject) {
21053        self.image = new Image();
21054        self.image.onload = resolve;
21055        self.image.onerror = reject;
21056        self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
21057        if (self.image.complete === true) {
21058            resolve(self.image);
21059        }
21060    }) : this.hasFabric().then(function() {
21061        return new Promise(function(resolve) {
21062            window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
21063        });
21064    });
21065}
21066
21067SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
21068
21069module.exports = SVGNodeContainer;
21070
21071},{"./svgcontainer":23}],25:[function(_dereq_,module,exports){
21072var NodeContainer = _dereq_('./nodecontainer');
21073
21074function TextContainer(node, parent) {
21075    NodeContainer.call(this, node, parent);
21076}
21077
21078TextContainer.prototype = Object.create(NodeContainer.prototype);
21079
21080TextContainer.prototype.applyTextTransform = function() {
21081    this.node.data = this.transform(this.parent.css("textTransform"));
21082};
21083
21084TextContainer.prototype.transform = function(transform) {
21085    var text = this.node.data;
21086    switch(transform){
21087        case "lowercase":
21088            return text.toLowerCase();
21089        case "capitalize":
21090            return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
21091        case "uppercase":
21092            return text.toUpperCase();
21093        default:
21094            return text;
21095    }
21096};
21097
21098function capitalize(m, p1, p2) {
21099    if (m.length > 0) {
21100        return p1 + p2.toUpperCase();
21101    }
21102}
21103
21104module.exports = TextContainer;
21105
21106},{"./nodecontainer":14}],26:[function(_dereq_,module,exports){
21107exports.smallImage = function smallImage() {
21108    return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
21109};
21110
21111exports.bind = function(callback, context) {
21112    return function() {
21113        return callback.apply(context, arguments);
21114    };
21115};
21116
21117/*
21118 * base64-arraybuffer
21119 * https://github.com/niklasvh/base64-arraybuffer
21120 *
21121 * Copyright (c) 2012 Niklas von Hertzen
21122 * Licensed under the MIT license.
21123 */
21124
21125exports.decode64 = function(base64) {
21126    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
21126+/";
21127    var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
21128
21129    var output = "";
21130
21131    for (i = 0; i < len; i+=4) {
21132        encoded1 = chars.indexOf(base64[i]);
21133        encoded2 = chars.indexOf(base64[i+1]);
21134        encoded3 = chars.indexOf(base64[i+2]);
21135        encoded4 = chars.indexOf(base64[i+3]);
21136
21137        byte1 = (encoded1 << 2) | (encoded2 >> 4);
21138        byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
21139        byte3 = ((encoded3 & 3) << 6) | encoded4;
21140        if (encoded3 === 64) {
21141            output += String.fromCharCode(byte1);
21142        } else if (encoded4 === 64 || encoded4 === -1) {
21143            output += String.fromCharCode(byte1, byte2);
21144        } else{
21145            output += String.fromCharCode(byte1, byte2, byte3);
21146        }
21147    }
21148
21149    return output;
21150};
21151
21152exports.getBounds = function(node) {
21153    if (node.getBoundingClientRect) {
21154        var clientRect = node.getBoundingClientRect();
21155        var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
21156        return {
21157            top: clientRect.top,
21158            bottom: clientRect.bottom || (clientRect.top + clientRect.height),
21159            right: clientRect.left + width,
21160            left: clientRect.left,
21161            width:  width,
21162            height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
21163        };
21164    }
21165    return {};
21166};
21167
21168exports.offsetBounds = function(node) {
21169    var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
21170
21171    return {
21172        top: node.offsetTop + parent.top,
21173        bottom: node.offsetTop + node.offsetHeight + parent.top,
21174        right: node.offsetLeft + parent.left + node.offsetWidth,
21175        left: node.offsetLeft + parent.left,
21176        width: node.offsetWidth,
21177        height: node.offsetHeight
21178    };
21179};
21180
21181exports.parseBackgrounds = function(backgroundImage) {
21182    var whitespace = ' \r\n\t',
21183        method, definition, prefix, prefix_i, block, results = [],
21184        mode = 0, numParen = 0, quote, args;
21185    var appendResult = function() {
21186        if(method) {
21187            if (definition.substr(0, 1) === '"') {
21188                definition = definition.substr(1, definition.length - 2);
21189            }
21190            if (definition) {
21191                args.push(definition);
21192            }
21193            if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
21194                prefix = method.substr(0, prefix_i);
21195                method = method.substr(prefix_i);
21196            }
21197            results.push({
21198                prefix: prefix,
21199                method: method.toLowerCase(),
21200                value: block,
21201                args: args,
21202                image: null
21203            });
21204        }
21205        args = [];
21206        method = prefix = definition = block = '';
21207    };
21208    args = [];
21209    method = prefix = definition = block = '';
21210    backgroundImage.split("").forEach(function(c) {
21211        if (mode === 0 && whitespace.indexOf(c) > -1) {
21212            return;
21213        }
21214        switch(c) {
21215        case '"':
21216            if(!quote) {
21217                quote = c;
21218            } else if(quote === c) {
21219                quote = null;
21220            }
21221            break;
21222        case '(':
21223            if(quote) {
21224                break;
21225            } else if(mode === 0) {
21226                mode = 1;
21227                block += c;
21228                return;
21229            } else {
21230                numParen++;
21231            }
21232            break;
21233        case ')':
21234            if (quote) {
21235                break;
21236            } else if(mode === 1) {
21237                if(numParen === 0) {
21238                    mode = 0;
21239                    block += c;
21240                    appendResult();
21241                    return;
21242                } else {
21243                    numParen--;
21244                }
21245            }
21246            break;
21247
21248        case ',':
21249            if (quote) {
21250                break;
21251            } else if(mode === 0) {
21252                appendResult();
21253                return;
21254            } else if (mode === 1) {
21255                if (numParen === 0 && !method.match(/^url$/i)) {
21256                    args.push(definition);
21257                    definition = '';
21258                    block += c;
21259                    return;
21260                }
21261            }
21262            break;
21263        }
21264
21265        block += c;
21266        if (mode === 0) {
21267            method += c;
21268        } else {
21269            definition += c;
21270        }
21271    });
21272
21273    appendResult();
21274    return results;
21275};
21276
21277},{}],27:[function(_dereq_,module,exports){
21278var GradientContainer = _dereq_('./gradientcontainer');
21279
21280function WebkitGradientContainer(imageData) {
21281    GradientContainer.apply(this, arguments);
21282    this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR 
21282: GradientContainer.TYPES.RADIAL;
21283}
21284
21285WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
21286
21287module.exports = WebkitGradientContainer;
21288
21289},{"./gradientcontainer":9}],28:[function(_dereq_,module,exports){
21290function XHR(url) {
21291    return new Promise(function(resolve, reject) {
21292        var xhr = new XMLHttpRequest();
21293        xhr.open('GET', url);
21294
21295        xhr.onload = function() {
21296            if (xhr.status === 200) {
21297                resolve(xhr.responseText);
21298            } else {
21299                reject(new Error(xhr.statusText));
21300            }
21301        };
21302
21303        xhr.onerror = function() {
21304            reject(new Error("Network Error"));
21305        };
21306
21307        xhr.send();
21308    });
21309}
21310
21311module.exports = XHR;
21312
21313},{}]},{},[4])(4)
21314});
21315
21316// Generated by CoffeeScript 1.4.0
21317
21318/*
21319# PNG.js
21320# Copyright (c) 2011 Devon Govett
21321# MIT LICENSE
21322# 
21323# 
21324*/
21325
21326
21327(function(global) {
21328  var PNG;
21329
21330  PNG = (function() {
21331    var APNG_BLEND_OP_OVER, APNG_BLEND_OP_SOURCE, APNG_DISPOSE_OP_BACKGROUND, APNG_DISPOSE_OP_NONE, APNG_DISPOSE_OP_PREVIOUS, makeImage, scratchCanvas, scratchCtx;
21332
21333    PNG.load = function(url, canvas, callback) {
21334      var xhr;
21335      if (typeof canvas === 'function') {
21336        callback = canvas;
21337      }
21338      xhr = new XMLHttpRequest;
21339      xhr.open("GET", url, true);
21340      xhr.responseType = "arraybuffer";
21341      xhr.onload = function() {
21342        var data, png;
21343        data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
21344        png = new PNG(data);
21345        if (typeof (canvas != null ? canvas.getContext : void 0) === 'function') {
21346          png.render(canvas);
21347        }
21348        return typeof callback === "function" ? callback(png) : void 0;
21349      };
21350      return xhr.send(null);
21351    };
21352
21353    APNG_DISPOSE_OP_BACKGROUND = 1;
21354
21355    APNG_DISPOSE_OP_PREVIOUS = 2;
21356
21357    APNG_BLEND_OP_SOURCE = 0;
21358
21359    function PNG(data) {
21360      var chunkSize, colors, palLen, delayDen, delayNum, frame, i, index, key, section, palShort, text, _i, _j, _ref;
21361      this.data = data;
21362      this.pos = 8;
21363      this.palette = [];
21364      this.imgData = [];
21365      this.transparency = {};
21366      this.animation = null;
21367      this.text = {};
21368      frame = null;
21369      while (true) {
21370        chunkSize = this.readUInt32();
21371        section = ((function() {
21372          var _i, _results;
21373          _results = [];
21374          for (i = _i = 0; _i < 4; i = ++_i) {
21375            _results.push(String.fromCharCode(this.data[this.pos++]));
21376          }
21377          return _results;
21378        }).call(this)).join('');
21379        switch (section) {
21380          case 'IHDR':
21381            this.width = this.readUInt32();
21382            this.height = this.readUInt32();
21383            this.bits = this.data[this.pos++];
21384            this.colorType = this.data[this.pos++];
21385            this.compressionMethod = this.data[this.pos++];
21386            this.filterMethod = this.data[this.pos++];
21387            this.interlaceMethod = this.data[this.pos++];
21388            break;
21389          case 'acTL':
21390            this.animation = {
21391              numFrames: this.readUInt32(),
21392              numPlays: this.readUInt32() || Infinity,
21393              frames: []
21394            };
21395            break;
21396          case 'PLTE':
21397            this.palette = this.read(chunkSize);
21398            break;
21399          case 'fcTL':
21400            if (frame) {
21401              this.animation.frames.push(frame);
21402            }
21403            this.pos += 4;
21404            frame = {
21405              width: this.readUInt32(),
21406              height: this.readUInt32(),
21407              xOffset: this.readUInt32(),
21408              yOffset: this.readUInt32()
21409            };
21410            delayNum = this.readUInt16();
21411            delayDen = this.readUInt16() || 100;
21412            frame.delay = 1000 * delayNum / delayDen;
21413            frame.disposeOp = this.data[this.pos++];
21414            frame.blendOp = this.data[this.pos++];
21415            frame.data = [];
21416            break;
21417          case 'IDAT':
21418          case 'fdAT':
21419            if (section === 'fdAT') {
21420              this.pos += 4;
21421              chunkSize -= 4;
21422            }
21423            data = (frame != null ? frame.data : void 0) || this.imgData;
21424            for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
21425              data.push(this.data[this.pos++]);
21426            }
21427            break;
21428          case 'tRNS':
21429            this.transparency = {};
21430            switch (this.colorType) {
21431              case 3:
21432            	palLen = this.palette.length/3;
21433                this.transparency.indexed = this.read(chunkSize);
21434                if(this.transparency.indexed.length > palLen)
21435                	throw new Error('More transparent colors than palette size');
21436                /*
21437                 * According to the PNG spec trns should be increased to the same size as palette if shorter
21438                 */
21439                //palShort = 255 - this.transparency.indexed.length;
21440                palShort = palLen - this.transparency.indexed.length;
21441                if (palShort > 0) {
21442                  for (i = _j = 0; 0 <= palShort ? _j < palShort : _j > palShort; i = 0 <= palShort ? ++_j : --_j) {
21443                    this.transparency.indexed.push(255);
21444                  }
21445                }
21446                break;
21447              case 0:
21448                this.transparency.grayscale = this.read(chunkSize)[0];
21449                break;
21450              case 2:
21451                this.transparency.rgb = this.read(chunkSize);
21452            }
21453            break;
21454          case 'tEXt':
21455            text = this.read(chunkSize);
21456            index = text.indexOf(0);
21457            key = String.fromCharCode.apply(String, text.slice(0, index));
21458            this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
21459            break;
21460          case 'IEND':
21461            if (frame) {
21462              this.animation.frames.push(frame);
21463            }
21464            this.colors = (function() {
21465              switch (this.colorType) {
21466                case 0:
21467                case 3:
21468                case 4:
21469                  return 1;
21470                case 2:
21471                case 6:
21472                  return 3;
21473              }
21474            }).call(this);
21475            this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
21476            colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
21477            this.pixelBitlength = this.bits * colors;
21478            this.colorSpace = (function() {
21479              switch (this.colors) {
21480                case 1:
21481                  return 'DeviceGray';
21482                case 3:
21483                  return 'DeviceRGB';
21484              }
21485            }).call(this);
21486            this.imgData = new Uint8Array(this.imgData);
21487            return;
21488          default:
21489            this.pos += chunkSize;
21490        }
21491        this.pos += 4;
21492        if (this.pos > this.data.length) {
21493          throw new Error("Incomplete or corrupt PNG file");
21494        }
21495      }
21496      return;
21497    }
21498
21499    PNG.prototype.read = function(bytes) {
21500      var i, _i, _results;
21501      _results = [];
21502      for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
21503        _results.push(this.data[this.pos++]);
21504      }
21505      return _results;
21506    };
21507
21508    PNG.prototype.readUInt32 = function() {
21509      var b1, b2, b3, b4;
21510      b1 = this.data[this.pos++] << 24;
21511      b2 = this.data[this.pos++] << 16;
21512      b3 = this.data[this.pos++] << 8;
21513      b4 = this.data[this.pos++];
21514      return b1 | b2 | b3 | b4;
21515    };
21516
21517    PNG.prototype.readUInt16 = function() {
21518      var b1, b2;
21519      b1 = this.data[this.pos++] << 8;
21520      b2 = this.data[this.pos++];
21521      return b1 | b2;
21522    };
21523
21524    PNG.prototype.decodePixels = function(data) {
21525      var abyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
21526      if (data == null) {
21527        data = this.imgData;
21528      }
21529      if (data.length === 0) {
21530        return new Uint8Array(0);
21531      }
21532      data = new FlateStream(data);
21533      data = data.getBytes();
21534      pixelBytes = this.pixelBitlength / 8;
21535      scanlineLength = pixelBytes * this.width;
21536      pixels = new Uint8Array(scanlineLength * this.height);
21537      length = data.length;
21538      row = 0;
21539      pos = 0;
21540      c = 0;
21541      while (pos < length) {
21542        switch (data[pos++]) {
21543          case 0:
21544            for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
21545              pixels[c++] = data[pos++];
21546            }
21547            break;
21548          case 1:
21549            for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
21550              abyte = data[pos++];
21551              left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
21552              pixels[c++] = (abyte + left) % 256;
21553            }
21554            break;
21555          case 2:
21556            for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
21557              abyte = data[pos++];
21558              col = (i - (i % pixelBytes)) / pixelBytes;
21559              upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
21560              pixels[c++] = (upper + abyte) % 256;
21561            }
21562            break;
21563          case 3:
21564            for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
21565              abyte = data[pos++];
21566              col = (i - (i % pixelBytes)) / pixelBytes;
21567              left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
21568              upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
21569              pixels[c++] = (abyte + Math.floor((left + upper) / 2)) % 256;
21570            }
21571            break;
21572          case 4:
21573            for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
21574              abyte = data[pos++];
21575              col = (i - (i % pixelBytes)) / pixelBytes;
21576              left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
21577              if (row === 0) {
21578                upper = upperLeft = 0;
21579              } else {
21580                upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)];
21581                upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)];
21582              }
21583              p = left + upper - upperLeft;
21584              pa = Math.abs(p - left);
21585              pb = Math.abs(p - upper);
21586              pc = Math.abs(p - upperLeft);
21587              if (pa <= pb && pa <= pc) {
21588                paeth = left;
21589              } else if (pb <= pc) {
21590                paeth = upper;
21591              } else {
21592                paeth = upperLeft;
21593              }
21594              pixels[c++] = (abyte + paeth) % 256;
21595            }
21596            break;
21597          default:
21598            throw new Error("Invalid filter algorithm: " + data[pos - 1]);
21599        }
21600        row++;
21601      }
21602      return pixels;
21603    };
21604
21605    PNG.prototype.decodePalette = function() {
21606      var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
21607      palette = this.palette;
21608      transparency = this.transparency.indexed || [];
21609      ret = new Uint8Array((transparency.length || 0) + palette.length);
21610      pos = 0;
21611      c = 0;
21612      for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
21613        ret[pos++] = palette[i];
21614        ret[pos++] = palette[i + 1];
21615        ret[pos++] = palette[i + 2];
21616        ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
21617      }
21618      return ret;
21619    };
21620
21621    PNG.prototype.copyToImageData = function(imageData, pixels) {
21622      var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
21623      colors = this.colors;
21624      palette = null;
21625      alpha = this.hasAlphaChannel;
21626      if (this.palette.length) {
21627        palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
21628        colors = 4;
21629        alpha = true;
21630      }
21631      data = imageData.data || imageData;
21632      length = data.length;
21633      input = palette || pixels;
21634      i = j = 0;
21635      if (colors === 1) {
21636        while (i < length) {
21637          k = palette ? pixels[i / 4] * 4 : j;
21638          v = input[k++];
21639          data[i++] = v;
21640          data[i++] = v;
21641          data[i++] = v;
21642          data[i++] = alpha ? input[k++] : 255;
21643          j = k;
21644        }
21645      } else {
21646        while (i < length) {
21647          k = palette ? pixels[i / 4] * 4 : j;
21648          data[i++] = input[k++];
21649          data[i++] = input[k++];
21650          data[i++] = input[k++];
21651          data[i++] = alpha ? input[k++] : 255;
21652          j = k;
21653        }
21654      }
21655    };
21656
21657    PNG.prototype.decode = function() {
21658      var ret;
21659      ret = new Uint8Array(this.width * this.height * 4);
21660      this.copyToImageData(ret, this.decodePixels());
21661      return ret;
21662    };
21663
21664    try {
21665        scratchCanvas = global.document.createElement('canvas');
21666        scratchCtx = scratchCanvas.getContext('2d');
21667    } catch(e) {
21668        return -1;
21669    }
21670
21671    makeImage = function(imageData) {
21672      var img;
21673      scratchCtx.width = imageData.width;
21674      scratchCtx.height = imageData.height;
21675      scratchCtx.clearRect(0, 0, imageData.width, imageData.height);
21676      scratchCtx.putImageData(imageData, 0, 0);
21677      img = new Image;
21678      img.src = scratchCanvas.toDataURL();
21679      return img;
21680    };
21681
21682    PNG.prototype.decodeFrames = function(ctx) {
21683      var frame, i, imageData, pixels, _i, _len, _ref, _results;
21684      if (!this.animation) {
21685        return;
21686      }
21687      _ref = this.animation.frames;
21688      _results = [];
21689      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
21690        frame = _ref[i];
21691        imageData = ctx.createImageData(frame.width, frame.height);
21692        pixels = this.decodePixels(new Uint8Array(frame.data));
21693        this.copyToImageData(imageData, pixels);
21694        frame.imageData = imageData;
21695        _results.push(frame.image = makeImage(imageData));
21696      }
21697      return _results;
21698    };
21699
21700    PNG.prototype.renderFrame = function(ctx, number) {
21701      var frame, frames, prev;
21702      frames = this.animation.frames;
21703      frame = frames[number];
21704      prev = frames[number - 1];
21705      if (number === 0) {
21706        ctx.clearRect(0, 0, this.width, this.height);
21707      }
21708      if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_BACKGROUND) {
21709        ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height);
21710      } else if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_PREVIOUS) {
21711        ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset);
21712      }
21713      if (frame.blendOp === APNG_BLEND_OP_SOURCE) {
21714        ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height);
21715      }
21716      return ctx.drawImage(frame.image, frame.xOffset, frame.yOffset);
21717    };
21718
21719    PNG.prototype.animate = function(ctx) {
21720      var doFrame, frameNumber, frames, numFrames, numPlays, _ref,
21721        _this = this;
21722      frameNumber = 0;
21723      _ref = this.animation, numFrames = _ref.numFrames, frames = _ref.frames, numPlays = _ref.numPlays;
21724      return (doFrame = function() {
21725        var f, frame;
21726        f = frameNumber++ % numFrames;
21727        frame = frames[f];
21728        _this.renderFrame(ctx, f);
21729        if (numFrames > 1 && frameNumber / numFrames < numPlays) {
21730          return _this.animation._timeout = setTimeout(doFrame, frame.delay);
21731        }
21732      })();
21733    };
21734
21735    PNG.prototype.stopAnimation = function() {
21736      var _ref;
21737      return clearTimeout((_ref = this.animation) != null ? _ref._timeout : void 0);
21738    };
21739
21740    PNG.prototype.render = function(canvas) {
21741      var ctx, data;
21742      if (canvas._png) {
21743        canvas._png.stopAnimation();
21744      }
21745      canvas._png = this;
21746      canvas.width = this.width;
21747      canvas.height = this.height;
21748      ctx = canvas.getContext("2d");
21749      if (this.animation) {
21750        this.decodeFrames(ctx);
21751        return this.animate(ctx);
21752      } else {
21753        data = ctx.createImageData(this.width, this.height);
21754        this.copyToImageData(data, this.decodePixels());
21755        return ctx.putImageData(data, 0, 0);
21756      }
21757    };
21758
21759    return PNG;
21760
21761  })();
21762
21763  global.PNG = PNG;
21764
21765})(typeof window !== "undefined" && window || undefined);
21766
21767/*
21768 * Extracted from pdf.js
21769 * https://github.com/andreasgal/pdf.js
21770 *
21771 * Copyright (c) 2011 Mozilla Foundation
21772 *
21773 * Contributors: Andreas Gal <[email protected]>
21774 *               Chris G Jones <[email protected]>
21775 *               Shaon Barman <[email protected]>
21776 *               Vivien Nicolas <[email protected]>
21777 *               Justin D'Arcangelo <[email protected]>
21778 *               Yury Delendik
21779 *
21780 * 
21781 */
21782
21783var DecodeStream = (function() {
21784  function constructor() {
21785    this.pos = 0;
21786    this.bufferLength = 0;
21787    this.eof = false;
21788    this.buffer = null;
21789  }
21790
21791  constructor.prototype = {
21792    ensureBuffer: function decodestream_ensureBuffer(requested) {
21793      var buffer = this.buffer;
21794      var current = buffer ? buffer.byteLength : 0;
21795      if (requested < current)
21796        return buffer;
21797      var size = 512;
21798      while (size < requested)
21799        size <<= 1;
21800      var buffer2 = new Uint8Array(size);
21801      for (var i = 0; i < current; ++i)
21802        buffer2[i] = buffer[i];
21803      return this.buffer = buffer2;
21804    },
21805    getByte: function decodestream_getByte() {
21806      var pos = this.pos;
21807      while (this.bufferLength <= pos) {
21808        if (this.eof)
21809          return null;
21810        this.readBlock();
21811      }
21812      return this.buffer[this.pos++];
21813    },
21814    getBytes: function decodestream_getBytes(length) {
21815      var pos = this.pos;
21816
21817      if (length) {
21818        this.ensureBuffer(pos + length);
21819        var end = pos + length;
21820
21821        while (!this.eof && this.bufferLength < end)
21822          this.readBlock();
21823
21824        var bufEnd = this.bufferLength;
21825        if (end > bufEnd)
21826          end = bufEnd;
21827      } else {
21828        while (!this.eof)
21829          this.readBlock();
21830
21831        var end = this.bufferLength;
21832      }
21833
21834      this.pos = end;
21835      return this.buffer.subarray(pos, end);
21836    },
21837    lookChar: function decodestream_lookChar() {
21838      var pos = this.pos;
21839      while (this.bufferLength <= pos) {
21840        if (this.eof)
21841          return null;
21842        this.readBlock();
21843      }
21844      return String.fromCharCode(this.buffer[this.pos]);
21845    },
21846    getChar: function decodestream_getChar() {
21847      var pos = this.pos;
21848      while (this.bufferLength <= pos) {
21849        if (this.eof)
21850          return null;
21851        this.readBlock();
21852      }
21853      return String.fromCharCode(this.buffer[this.pos++]);
21854    },
21855    makeSubStream: function decodestream_makeSubstream(start, length, dict) {
21856      var end = start + length;
21857      while (this.bufferLength <= end && !this.eof)
21858        this.readBlock();
21859      return new Stream(this.buffer, start, length, dict);
21860    },
21861    skip: function decodestream_skip(n) {
21862      if (!n)
21863        n = 1;
21864      this.pos += n;
21865    },
21866    reset: function decodestream_reset() {
21867      this.pos = 0;
21868    }
21869  };
21870
21871  return constructor;
21872})();
21873
21874var FlateStream = (function() {
21875  if (typeof Uint32Array === 'undefined') {
21876    return undefined;
21877  }
21878  var codeLenCodeMap = new Uint32Array([
21879    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
21880  ]);
21881
21882  var lengthDecode = new Uint32Array([
21883    0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a,
21884    0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f,
21885    0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073,
21886    0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102
21887  ]);
21888
21889  var distDecode = new Uint32Array([
21890    0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d,
21891    0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1,
21892    0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01,
21893    0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001
21894  ]);
21895
21896  var fixedLitCodeTab = [new Uint32Array([
21897    0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0,
21898    0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0,
21899    0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0,
21900    0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0,
21901    0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8,
21902    0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8,
21903    0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8,
21904    0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8,
21905    0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4,
21906    0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4,
21907    0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4,
21908    0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4,
21909    0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc,
21910    0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec,
21911    0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc,
21912    0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc,
21913    0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2,
21914    0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2,
21915    0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2,
21916    0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2,
21917    0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca,
21918    0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea,
21919    0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da,
21920    0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa,
21921    0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6,
21922    0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6,
21923    0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6,
21924    0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6,
21925    0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce,
21926    0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee,
21927    0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de,
21928    0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe,
21929    0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1,
21930    0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1,
21931    0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1,
21932    0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1,
21933    0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9,
21934    0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9,
21935    0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9,
21936    0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9,
21937    0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5,
21938    0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5,
21939    0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5,
21940    0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5,
21941    0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd,
21942    0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed,
21943    0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd,
21944    0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd,
21945    0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3,
21946    0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3,
21947    0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3,
21948    0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3,
21949    0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb,
21950    0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb,
21951    0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db,
21952    0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb,
21953    0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7,
21954    0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7,
21955    0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7,
21956    0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7,
21957    0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf,
21958    0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef,
21959    0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df,
21960    0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff
21961  ]), 9];
21962
21963  var fixedDistCodeTab = [new Uint32Array([
21964    0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c,
21965    0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000,
21966    0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d,
21967    0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000
21968  ]), 5];
21969  
21970  function error(e) {
21971      throw new Error(e)
21972  }
21973
21974  function constructor(bytes) {
21975    //var bytes = stream.getBytes();
21976    var bytesPos = 0;
21977
21978    var cmf = bytes[bytesPos++];
21979    var flg = bytes[bytesPos++];
21980    if (cmf == -1 || flg == -1)
21981      error('Invalid header in flate stream');
21982    if ((cmf & 0x0f) != 0x08)
21983      error('Unknown compression method in flate stream');
21984    if ((((cmf << 8) + flg) % 31) != 0)
21985      error('Bad FCHECK in flate stream');
21986    if (flg & 0x20)
21987      error('FDICT bit set in flate stream');
21988
21989    this.bytes = bytes;
21990    this.bytesPos = bytesPos;
21991
21992    this.codeSize = 0;
21993    this.codeBuf = 0;
21994
21995    DecodeStream.call(this);
21996  }
21997
21998  constructor.prototype = Object.create(DecodeStream.prototype);
21999
22000  constructor.prototype.getBits = function(bits) {
22001    var codeSize = this.codeSize;
22002    var codeBuf = this.codeBuf;
22003    var bytes = this.bytes;
22004    var bytesPos = this.bytesPos;
22005
22006    var b;
22007    while (codeSize < bits) {
22008      if (typeof (b = bytes[bytesPos++]) == 'undefined')
22009        error('Bad encoding in flate stream');
22010      codeBuf |= b << codeSize;
22011      codeSize += 8;
22012    }
22013    b = codeBuf & ((1 << bits) - 1);
22014    this.codeBuf = codeBuf >> bits;
22015    this.codeSize = codeSize -= bits;
22016    this.bytesPos = bytesPos;
22017    return b;
22018  };
22019
22020  constructor.prototype.getCode = function(table) {
22021    var codes = table[0];
22022    var maxLen = table[1];
22023    var codeSize = this.codeSize;
22024    var codeBuf = this.codeBuf;
22025    var bytes = this.bytes;
22026    var bytesPos = this.bytesPos;
22027
22028    while (codeSize < maxLen) {
22029      var b;
22030      if (typeof (b = bytes[bytesPos++]) == 'undefined')
22031        error('Bad encoding in flate stream');
22032      codeBuf |= (b << codeSize);
22033      codeSize += 8;
22034    }
22035    var code = codes[codeBuf & ((1 << maxLen) - 1)];
22036    var codeLen = code >> 16;
22037    var codeVal = code & 0xffff;
22038    if (codeSize == 0 || codeSize < codeLen || codeLen == 0)
22039      error('Bad encoding in flate stream');
22040    this.codeBuf = (codeBuf >> codeLen);
22041    this.codeSize = (codeSize - codeLen);
22042    this.bytesPos = bytesPos;
22043    return codeVal;
22044  };
22045
22046  constructor.prototype.generateHuffmanTable = function(lengths) {
22047    var n = lengths.length;
22048
22049    // find max code length
22050    var maxLen = 0;
22051    for (var i = 0; i < n; ++i) {
22052      if (lengths[i] > maxLen)
22053        maxLen = lengths[i];
22054    }
22055
22056    // build the table
22057    var size = 1 << maxLen;
22058    var codes = new Uint32Array(size);
22059    for (var len = 1, code = 0, skip = 2;
22060         len <= maxLen;
22061         ++len, code <<= 1, skip <<= 1) {
22062      for (var val = 0; val < n; ++val) {
22063        if (lengths[val] == len) {
22064          // bit-reverse the code
22065          var code2 = 0;
22066          var t = code;
22067          for (var i = 0; i < len; ++i) {
22068            code2 = (code2 << 1) | (t & 1);
22069            t >>= 1;
22070          }
22071
22072          // fill the table entries
22073          for (var i = code2; i < size; i += skip)
22074            codes[i] = (len << 16) | val;
22075
22076          ++code;
22077        }
22078      }
22079    }
22080
22081    return [codes, maxLen];
22082  };
22083
22084  constructor.prototype.readBlock = function() {
22085    function repeat(stream, array, len, offset, what) {
22086      var repeat = stream.getBits(len) + offset;
22087      while (repeat-- > 0)
22088        array[i++] = what;
22089    }
22090
22091    // read block header
22092    var hdr = this.getBits(3);
22093    if (hdr & 1)
22094      this.eof = true;
22095    hdr >>= 1;
22096
22097    if (hdr == 0) { // uncompressed block
22098      var bytes = this.bytes;
22099      var bytesPos = this.bytesPos;
22100      var b;
22101
22102      if (typeof (b = bytes[bytesPos++]) == 'undefined')
22103        error('Bad block header in flate stream');
22104      var blockLen = b;
22105      if (typeof (b = bytes[bytesPos++]) == 'undefined')
22106        error('Bad block header in flate stream');
22107      blockLen |= (b << 8);
22108      if (typeof (b = bytes[bytesPos++]) == 'undefined')
22109        error('Bad block header in flate stream');
22110      var check = b;
22111      if (typeof (b = bytes[bytesPos++]) == 'undefined')
22112        error('Bad block header in flate stream');
22113      check |= (b << 8);
22114      if (check != (~blockLen & 0xffff))
22115        error('Bad uncompressed block length in flate stream');
22116
22117      this.codeBuf = 0;
22118      this.codeSize = 0;
22119
22120      var bufferLength = this.bufferLength;
22121      var buffer = this.ensureBuffer(bufferLength + blockLen);
22122      var end = bufferLength + blockLen;
22123      this.bufferLength = end;
22124      for (var n = bufferLength; n < end; ++n) {
22125        if (typeof (b = bytes[bytesPos++]) == 'undefined') {
22126          this.eof = true;
22127          break;
22128        }
22129        buffer[n] = b;
22130      }
22131      this.bytesPos = bytesPos;
22132      return;
22133    }
22134
22135    var litCodeTable;
22136    var distCodeTable;
22137    if (hdr == 1) { // compressed block, fixed codes
22138      litCodeTable = fixedLitCodeTab;
22139      distCodeTable = fixedDistCodeTab;
22140    } else if (hdr == 2) { // compressed block, dynamic codes
22141      var numLitCodes = this.getBits(5) + 257;
22142      var numDistCodes = this.getBits(5) + 1;
22143      var numCodeLenCodes = this.getBits(4) + 4;
22144
22145      // build the code lengths code table
22146      var codeLenCodeLengths = Array(codeLenCodeMap.length);
22147      var i = 0;
22148      while (i < numCodeLenCodes)
22149        codeLenCodeLengths[codeLenCodeMap[i++]] = this.getBits(3);
22150      var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
22151
22152      // build the literal and distance code tables
22153      var len = 0;
22154      var i = 0;
22155      var codes = numLitCodes + numDistCodes;
22156      var codeLengths = new Array(codes);
22157      while (i < codes) {
22158        var code = this.getCode(codeLenCodeTab);
22159        if (code == 16) {
22160          repeat(this, codeLengths, 2, 3, len);
22161        } else if (code == 17) {
22162          repeat(this, codeLengths, 3, 3, len = 0);
22163        } else if (code == 18) {
22164          repeat(this, codeLengths, 7, 11, len = 0);
22165        } else {
22166          codeLengths[i++] = len = code;
22167        }
22168      }
22169
22170      litCodeTable =
22171        this.generateHuffmanTable(codeLengths.slice(0, numLitCodes));
22172      distCodeTable =
22173        this.generateHuffmanTable(codeLengths.slice(numLitCodes, codes));
22174    } else {
22175      error('Unknown block type in flate stream');
22176    }
22177
22178    var buffer = this.buffer;
22179    var limit = buffer ? buffer.length : 0;
22180    var pos = this.bufferLength;
22181    while (true) {
22182      var code1 = this.getCode(litCodeTable);
22183      if (code1 < 256) {
22184        if (pos + 1 >= limit) {
22185          buffer = this.ensureBuffer(pos + 1);
22186          limit = buffer.length;
22187        }
22188        buffer[pos++] = code1;
22189        continue;
22190      }
22191      if (code1 == 256) {
22192        this.bufferLength = pos;
22193        return;
22194      }
22195      code1 -= 257;
22196      code1 = lengthDecode[code1];
22197      var code2 = code1 >> 16;
22198      if (code2 > 0)
22199        code2 = this.getBits(code2);
22200      var len = (code1 & 0xffff) + code2;
22201      code1 = this.getCode(distCodeTable);
22202      code1 = distDecode[code1];
22203      code2 = code1 >> 16;
22204      if (code2 > 0)
22205        code2 = this.getBits(code2);
22206      var dist = (code1 & 0xffff) + code2;
22207      if (pos + len >= limit) {
22208        buffer = this.ensureBuffer(pos + len);
22209        limit = buffer.length;
22210      }
22211      for (var k = 0; k < len; ++k, ++pos)
22212        buffer[pos] = buffer[pos - dist];
22213    }
22214  };
22215
22216  return constructor;
22217})();
22218
22219/**
22220 * JavaScript Polyfill functions for jsPDF
22221 * Collected from public resources by
22222 * https://github.com/diegocr
22223 */
22224
22225(function (global) {
22226	var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
22227
22228	if (typeof global.btoa === 'undefined') {
22229		global.btoa = function(data) {
22230			//  discuss at: http://phpjs.org/functions/base64_encode/
22231			// original by: Tyler Akins (http://rumkin.com)
22232			// improved by: Bayron Guevara
22233			// improved by: Thunder.m
22234			// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
22235			// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
22236			// improved by: Rafal Kukawski (http://kukawski.pl)
22237			// bugfixed by: Pellentesque Malesuada
22238			//   example 1: base64_encode('Kevin van Zonneveld');
22239			//   returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
22240
22241			var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,enc = '',tmp_arr = [];
22242
22243			if (!data) {
22244				return data;
22245			}
22246
22247			do { // pack three octets into four hexets
22248				o1 = data.charCodeAt(i++);
22249				o2 = data.charCodeAt(i++);
22250				o3 = data.charCodeAt(i++);
22251
22252				bits = o1 << 16 | o2 << 8 | o3;
22253
22254				h1 = bits >> 18 & 0x3f;
22255				h2 = bits >> 12 & 0x3f;
22256				h3 = bits >> 6 & 0x3f;
22257				h4 = bits & 0x3f;
22258
22259				// use hexets to index into b64, and append result to encoded string
22260				tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
22261			} while (i < data.length);
22262
22263			enc = tmp_arr.join('');
22264
22265			var r = data.length % 3;
22266
22267			return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
22268		};
22269	}
22270
22271	if (typeof global.atob === 'undefined') {
22272		global.atob = function(data) {
22273			//  discuss at: http://phpjs.org/functions/base64_decode/
22274			// original by: Tyler Akins (http://rumkin.com)
22275			// improved by: Thunder.m
22276			// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
22277			// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
22278			//    input by: Aman Gupta
22279			//    input by: Brett Zamir (http://brett-zamir.me)
22280			// bugfixed by: Onno Marsman
22281			// bugfixed by: Pellentesque Malesuada
22282			// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
22283			//   example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
22284			//   returns 1: 'Kevin van Zonneveld'
22285
22286			var o1,o2,o3,h1,h2,h3,h4,bits,i = 0,ac = 0,dec = '',tmp_arr = [];
22287
22288			if (!data) {
22289				return data;
22290			}
22291
22292			data += '';
22293
22294			do { // unpack four hexets into three octets using index points in b64
22295				h1 = b64.indexOf(data.charAt(i++));
22296				h2 = b64.indexOf(data.charAt(i++));
22297				h3 = b64.indexOf(data.charAt(i++));
22298				h4 = b64.indexOf(data.charAt(i++));
22299
22300				bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
22301
22302				o1 = bits >> 16 & 0xff;
22303				o2 = bits >> 8 & 0xff;
22304				o3 = bits & 0xff;
22305
22306				if (h3 == 64) {
22307					tmp_arr[ac++] = String.fromCharCode(o1);
22308				} else if (h4 == 64) {
22309					tmp_arr[ac++] = String.fromCharCode(o1, o2);
22310				} else {
22311					tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
22312				}
22313			} while (i < data.length);
22314
22315			dec = tmp_arr.join('');
22316
22317			return dec;
22318		};
22319	}
22320
22321	if (!Array.prototype.map) {
22322		Array.prototype.map = function(fun /*, thisArg */) {
22323			if (this === void 0 || this === null || typeof fun !== "function")
22324				throw new TypeError();
22325
22326			var t = Object(this), len = t.length >>> 0, res = new Array(len);
22327			var thisArg = arguments.length > 1 ? arguments[1] : void 0;
22328			for (var i = 0; i < len; i++) {
22329				// NOTE: Absolute correctness would demand Object.defineProperty
22330				//       be used.  But this method is fairly new, and failure is
22331				//       possible only if Object.prototype or Array.prototype
22332				//       has a property |i| (very unlikely), so use a less-correct
22333				//       but more portable alternative.
22334				if (i in t)
22335					res[i] = fun.call(thisArg, t[i], i, t);
22336			}
22337
22338			return res;
22339		};
22340	}
22341
22342
22343	if(!Array.isArray) {
22344		Array.isArray = function(arg) {
22345			return Object.prototype.toString.call(arg) === '[object Array]';
22346		};
22347	}
22348
22349	if (!Array.prototype.forEach) {
22350		Array.prototype.forEach = function(fun, thisArg) {
22351			"use strict";
22352
22353			if (this === void 0 || this === null || typeof fun !== "function")
22354				throw new TypeError();
22355
22356			var t = Object(this), len = t.length >>> 0;
22357			for (var i = 0; i < len; i++) {
22358				if (i in t)
22359					fun.call(thisArg, t[i], i, t);
22360			}
22361		};
22362	}
22363
22364	if (!Object.keys) {
22365		Object.keys = (function () {
22366			'use strict';
22367
22368			var hasOwnProperty = Object.prototype.hasOwnProperty,
22369				hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
22370				dontEnums = ['toString','toLocaleString','valueOf','hasOwnProperty',
22371					'isPrototypeOf','propertyIsEnumerable','constructor'],
22372				dontEnumsLength = dontEnums.length;
22373
22374			return function (obj) {
22375				if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
22376					throw new TypeError();
22377				}
22378				var result = [], prop, i;
22379
22380				for (prop in obj) {
22381					if (hasOwnProperty.call(obj, prop)) {
22382						result.push(prop);
22383					}
22384				}
22385
22386				if (hasDontEnumBug) {
22387					for (i = 0; i < dontEnumsLength; i++) {
22388						if (hasOwnProperty.call(obj, dontEnums[i])) {
22389							result.push(dontEnums[i]);
22390						}
22391					}
22392				}
22393				return result;
22394			};
22395		}());
22396	}
22397
22398	if (!String.prototype.trim) {
22399		String.prototype.trim = function () {
22400			return this.replace(/^\s+|\s+$/g, '');
22401		};
22402	}
22403	if (!String.prototype.trimLeft) {
22404		String.prototype.trimLeft = function() {
22405			return this.replace(/^\s+/g, "");
22406		};
22407	}
22408	if (!String.prototype.trimRight) {
22409		String.prototype.trimRight = function() {
22410			return this.replace(/\s+$/g, "");
22411		};
22412	}
22413
22414})(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined);
22415
22416return jsPDF;
22417
22418})));
22419
22420/*! algoliasearch 3.35.1 | © 2014, 2015 Algolia SAS | github.com/algolia/algoliasearch-client-js */
22421(function(f){var g;if(typeof window!=='undefined'){g=window}else if(typeof self!=='undefined'){g=self}g.ALGOLIA_MIGRATION_LAYER=f()})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
22422
22423module.exports = function load (src, opts, cb) {
22424  var head = document.head || document.getElementsByTagName('head')[0]
22425  var script = document.createElement('script')
22426
22427  if (typeof opts === 'function') {
22428    cb = opts
22429    opts = {}
22430  }
22431
22432  opts = opts || {}
22433  cb = cb || function() {}
22434
22435  script.type = opts.type || 'text/javascript'
22436  script.charset = opts.charset || 'utf8';
22437  script.async = 'async' in opts ? !!opts.async : true
22438  script.src = src
22439
22440  if (opts.attrs) {
22441    setAttributes(script, opts.attrs)
22442  }
22443
22444  if (opts.text) {
22445    script.text = '' + opts.text
22446  }
22447
22448  var onend = 'onload' in script ? stdOnEnd : ieOnEnd
22449  onend(script, cb)
22450
22451  // some good legacy browsers (firefox) fail the 'in' detection above
22452  // so as a fallback we always set onload
22453  // old IE will ignore this and new IE will set onload
22454  if (!script.onload) {
22455    stdOnEnd(script, cb);
22456  }
22457
22458  head.appendChild(script)
22459}
22460
22461function setAttributes(script, attrs) {
22462  for (var attr in attrs) {
22463    script.setAttribute(attr, attrs[attr]);
22464  }
22465}
22466
22467function stdOnEnd (script, cb) {
22468  script.onload = function () {
22469    this.onerror = this.onload = null
22470    cb(null, script)
22471  }
22472  script.onerror = function () {
22473    // this.onload = null here is necessary
22474    // because even IE9 works not like others
22475    this.onerror = this.onload = null
22476    cb(new Error('Failed to load ' + this.src), script)
22477  }
22478}
22479
22480function ieOnEnd (script, cb) {
22481  script.onreadystatechange = function () {
22482    if (this.readyState != 'complete' && this.readyState != 'loaded') return
22483    this.onreadystatechange = null
22484    cb(null, script) // there is no way to catch loading errors in IE8
22485  }
22486}
22487
22488},{}],2:[function(require,module,exports){
22489'use strict';
22490
22491// this module helps finding if the current page is using
22492// the cdn.jsdelivr.net/algoliasearch/latest/$BUILDNAME.min.js version
22493
22494module.exports = isUsingLatest;
22495
22496function isUsingLatest(buildName) {
22497  var toFind = new RegExp('cdn\\.jsdelivr\\.net/algoliasearch/latest/' +
22498    buildName.replace('.', '\\.') + // algoliasearch, algoliasearch.angular
22499    '(?:\\.min)?\\.js$'); // [.min].js
22500
22501  var scripts = document.getElementsByTagName('script');
22502  var found = false;
22503  for (var currentScript = 0, nbScripts = scripts.length; currentScript < nbScripts; currentScript++) {
22504    if (scripts[currentScript].src && toFind.test(scripts[currentScript].src)) {
22505      found = true;
22506      break;
22507    }
22508  }
22509
22510  return found;
22511}
22512
22513},{}],3:[function(require,module,exports){
22514'use strict';
22515
22516module.exports = loadV2;
22517
22518function loadV2(buildName) {
22519  var loadScript = require(1);
22520  var v2ScriptUrl = '//cdn.jsdelivr.net/algoliasearch/2/' + buildName + '.min.js';
22521
22522  var message = '-- AlgoliaSearch `latest` warning --\n' +
22523    'Warning, you are using the `latest` version string from jsDelivr to load the AlgoliaSearch library.\
22523n' +
22524    'Using `latest` is no more recommended, you should load //cdn.jsdelivr.net/algoliasearch/2/algoliasearch.min.js\n\n' +
22525    'Also, we updated the AlgoliaSearch JavaScript client to V3. If you want to upgrade,\n' +
22526    'please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n' +
22527    '-- /AlgoliaSearch  `latest` warning --';
22528
22529  if (window.console) {
22530    if (window.console.warn) {
22531      window.console.warn(message);
22532    } else if (window.console.log) {
22533      window.console.log(message);
22534    }
22535  }
22536
22537  // If current script loaded asynchronously,
22538  // it will load the script with DOMElement
22539  // otherwise, it will load the script with document.write
22540  try {
22541    // why \x3c? http://stackoverflow.com/a/236106/147079
22542    document.write('\x3Cscript>window.ALGOLIA_SUPPORTS_DOCWRITE = true\x3C/script>');
22543
22544    if (window.ALGOLIA_SUPPORTS_DOCWRITE === true) {
22545      document.write('\x3Cscript src="' + v2ScriptUrl + '">\x3C/script>');
22546      scriptLoaded('document.write')();
22547    } else {
22548      loadScript(v2ScriptUrl, scriptLoaded('DOMElement'));
22549    }
22550  } catch (e) {
22551    loadScript(v2ScriptUrl, scriptLoaded('DOMElement'));
22552  }
22553}
22554
22555function scriptLoaded(method) {
22556  return function log() {
22557    var message = 'AlgoliaSearch: loaded V2 script using ' + method;
22558
22559    if (window.console && window.console.log) {
22560      window.console.log(message);
22561    }
22562  };
22563}
22564
22565},{"1":1}],4:[function(require,module,exports){
22566'use strict';
22567
22568/* eslint no-unused-vars: [2, {"vars": "local"}] */
22569
22570module.exports = oldGlobals;
22571
22572// put old window.AlgoliaSearch.. into window. again so that
22573// users upgrading to V3 without changing their code, will be warned
22574function oldGlobals() {
22575  var message = '-- AlgoliaSearch V2 => V3 error --\n' +
22576    'You are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.\n' +
22577    'Please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\n' +
22578    '-- /AlgoliaSearch V2 => V3 error --';
22579
22580  window.AlgoliaSearch = function() {
22581    throw new Error(message);
22582  };
22583
22584  window.AlgoliaSearchHelper = function() {
22585    throw new Error(message);
22586  };
22587
22588  window.AlgoliaExplainResults = function() {
22589    throw new Error(message);
22590  };
22591}
22592
22593},{}],5:[function(require,module,exports){
22594'use strict';
22595
22596// This script will be browserified and prepended to the normal build
22597// directly in window, not wrapped in any module definition
22598// To avoid cases where we are loaded with /latest/ along with
22599migrationLayer("algoliasearch");
22600
22601// Now onto the V2 related code:
22602//  If the client is using /latest/$BUILDNAME.min.js, load V2 of the library
22603//
22604//  Otherwise, setup a migration layer that will throw on old constructors like
22605//  new AlgoliaSearch().
22606//  So that users upgrading from v2 to v3 will have a clear information
22607//  message on what to do if they did not read the migration guide
22608function migrationLayer(buildName) {
22609  var isUsingLatest = require(2);
22610  var loadV2 = require(3);
22611  var oldGlobals = require(4);
22612
22613  if (isUsingLatest(buildName)) {
22614    loadV2(buildName);
22615  } else {
22616    oldGlobals();
22617  }
22618}
22619
22620},{"2":2,"3":3,"4":4}]},{},[5])(5)
22621});(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.algoliasearch = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
22622(function (process){
22623/**
22624 * This is the web browser implementation of `debug()`.
22625 *
22626 * Expose `debug()` as the module.
22627 */
22628
22629exports = module.exports = require(2);
22630exports.log = log;
22631exports.formatArgs = formatArgs;
22632exports.save = save;
22633exports.load = load;
22634exports.useColors = useColors;
22635exports.storage = 'undefined' != typeof chrome
22636               && 'undefined' != typeof chrome.storage
22637                  ? chrome.storage.local
22638                  : localstorage();
22639
22640/**
22641 * Colors.
22642 */
22643
22644exports.colors = [
22645  'lightseagreen',
22646  'forestgreen',
22647  'goldenrod',
22648  'dodgerblue',
22649  'darkorchid',
22650  'crimson'
22651];
22652
22653/**
22654 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
22655 * and the Firebug extension (any Firefox version) are known
22656 * to support "%c" CSS customizations.
22657 *
22658 * TODO: add a `localStorage` variable to explicitly enable/disable colors
22659 */
22660
22661function useColors() {
22662  // NB: In an Electron preload script, document will be defined but not fully
vendor: 4,235 bytes, lines 22663-22824
22663  // initialized. Since we know we're in Chrome, we'll just detect this case
22664  // explicitly
22665  if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
22666    return true;
22667  }
22668
22669  // is webkit? http://stackoverflow.com/a/16459606/376773
22670  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
22671  return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
22672    // is firebug? http://stackoverflow.com/a/398120/376773
22673    (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
22674    // is firefox >= v31?
22675    // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
22676    (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
22677    // double check webkit in userAgent just in case we are in a worker
22678    (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
22679}
22680
22681/**
22682 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
22683 */
22684
22685exports.formatters.j = function(v) {
22686  try {
22687    return JSON.stringify(v);
22688  } catch (err) {
22689    return '[UnexpectedJSONParseError]: ' + err.message;
22690  }
22691};
22692
22693
22694/**
22695 * Colorize log arguments if enabled.
22696 *
22697 * @api public
22698 */
22699
22700function formatArgs(args) {
22701  var useColors = this.useColors;
22702
22703  args[0] = (useColors ? '%c' : '')
22704    + this.namespace
22705    + (useColors ? ' %c' : ' ')
22706    + args[0]
22707    + (useColors ? '%c ' : ' ')
22708    + '+' + exports.humanize(this.diff);
22709
22710  if (!useColors) return;
22711
22712  var c = 'color: ' + this.color;
22713  args.splice(1, 0, c, 'color: inherit')
22714
22715  // the final "%c" is somewhat tricky, because there could be other
22716  // arguments passed either before or after the %c, so we need to
22717  // figure out the correct index to insert the CSS into
22718  var index = 0;
22719  var lastC = 0;
22720  args[0].replace(/%[a-zA-Z%]/g, function(match) {
22721    if ('%%' === match) return;
22722    index++;
22723    if ('%c' === match) {
22724      // we only are interested in the *last* %c
22725      // (the user may have provided their own)
22726      lastC = index;
22727    }
22728  });
22729
22730  args.splice(lastC, 0, c);
22731}
22732
22733/**
22734 * Invokes `console.log()` when available.
22735 * No-op when `console.log` is not a "function".
22736 *
22737 * @api public
22738 */
22739
22740function log() {
22741  // this hackery is required for IE8/9, where
22742  // the `console.log` function doesn't have 'apply'
22743  return 'object' === typeof console
22744    && console.log
22745    && Function.prototype.apply.call(console.log, console, arguments);
22746}
22747
22748/**
22749 * Save `namespaces`.
22750 *
22751 * @param {String} namespaces
22752 * @api private
22753 */
22754
22755function save(namespaces) {
22756  try {
22757    if (null == namespaces) {
22758      exports.storage.removeItem('debug');
22759    } else {
22760      exports.storage.debug = namespaces;
22761    }
22762  } catch(e) {}
22763}
22764
22765/**
22766 * Load `namespaces`.
22767 *
22768 * @return {String} returns the previously persisted debug modes
22769 * @api private
22770 */
22771
22772function load() {
22773  var r;
22774  try {
22775    r = exports.storage.debug;
22776  } catch(e) {}
22777
22778  // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
22779  if (!r && typeof process !== 'undefined' && 'env' in process) {
22780    r = process.env.DEBUG;
22781  }
22782
22783  return r;
22784}
22785
22786/**
22787 * Enable namespaces listed in `localStorage.debug` initially.
22788 */
22789
22790exports.enable(load());
22791
22792/**
22793 * Localstorage attempts to return the localstorage.
22794 *
22795 * This is necessary because safari throws
22796 * when a user disables cookies/localstorage
22797 * and you attempt to access it.
22798 *
22799 * @return {LocalStorage}
22800 * @api private
22801 */
22802
22803function localstorage() {
22804  try {
22805    return window.localStorage;
22806  } catch (e) {}
22807}
22808
22809}).call(this,require(12))
22810},{"12":12,"2":2}],2:[function(require,module,exports){
22811
22812/**
22813 * This is the common logic for both the Node.js and web browser
22814 * implementations of `debug()`.
22815 *
22816 * Expose `debug()` as the module.
22817 */
22818
22819exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
22820exports.coerce = coerce;
22821exports.disable = disable;
22822exports.enable = enable;
22823exports.enabled = enabled;
22824exports.humanize = require(9
vendor: 4,029 bytes, lines 22824-23013
22824);
22825
22826/**
22827 * The currently active debug mode names, and names to skip.
22828 */
22829
22830exports.names = [];
22831exports.skips = [];
22832
22833/**
22834 * Map of special "%n" handling functions, for the debug "format" argument.
22835 *
22836 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
22837 */
22838
22839exports.formatters = {};
22840
22841/**
22842 * Previous log timestamp.
22843 */
22844
22845var prevTime;
22846
22847/**
22848 * Select a color.
22849 * @param {String} namespace
22850 * @return {Number}
22851 * @api private
22852 */
22853
22854function selectColor(namespace) {
22855  var hash = 0, i;
22856
22857  for (i in namespace) {
22858    hash  = ((hash << 5) - hash) + namespace.charCodeAt(i);
22859    hash |= 0; // Convert to 32bit integer
22860  }
22861
22862  return exports.colors[Math.abs(hash) % exports.colors.length];
22863}
22864
22865/**
22866 * Create a debugger with the given `namespace`.
22867 *
22868 * @param {String} namespace
22869 * @return {Function}
22870 * @api public
22871 */
22872
22873function createDebug(namespace) {
22874
22875  function debug() {
22876    // disabled?
22877    if (!debug.enabled) return;
22878
22879    var self = debug;
22880
22881    // set `diff` timestamp
22882    var curr = +new Date();
22883    var ms = curr - (prevTime || curr);
22884    self.diff = ms;
22885    self.prev = prevTime;
22886    self.curr = curr;
22887    prevTime = curr;
22888
22889    // turn the `arguments` into a proper Array
22890    var args = new Array(arguments.length);
22891    for (var i = 0; i < args.length; i++) {
22892      args[i] = arguments[i];
22893    }
22894
22895    args[0] = exports.coerce(args[0]);
22896
22897    if ('string' !== typeof args[0]) {
22898      // anything else let's inspect with %O
22899      args.unshift('%O');
22900    }
22901
22902    // apply any `formatters` transformations
22903    var index = 0;
22904    args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
22905      // if we encounter an escaped % then don't increase the array index
22906      if (match === '%%') return match;
22907      index++;
22908      var formatter = exports.formatters[format];
22909      if ('function' === typeof formatter) {
22910        var val = args[index];
22911        match = formatter.call(self, val);
22912
22913        // now we need to remove `args[index]` since it's inlined in the `format`
22914        args.splice(index, 1);
22915        index--;
22916      }
22917      return match;
22918    });
22919
22920    // apply env-specific formatting (colors, etc.)
22921    exports.formatArgs.call(self, args);
22922
22923    var logFn = debug.log || exports.log || console.log.bind(console);
22924    logFn.apply(self, args);
22925  }
22926
22927  debug.namespace = namespace;
22928  debug.enabled = exports.enabled(namespace);
22929  debug.useColors = exports.useColors();
22930  debug.color = selectColor(namespace);
22931
22932  // env-specific initialization logic for debug instances
22933  if ('function' === typeof exports.init) {
22934    exports.init(debug);
22935  }
22936
22937  return debug;
22938}
22939
22940/**
22941 * Enables a debug mode by namespaces. This can include modes
22942 * separated by a colon and wildcards.
22943 *
22944 * @param {String} namespaces
22945 * @api public
22946 */
22947
22948function enable(namespaces) {
22949  exports.save(namespaces);
22950
22951  exports.names = [];
22952  exports.skips = [];
22953
22954  var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
22955  var len = split.length;
22956
22957  for (var i = 0; i < len; i++) {
22958    if (!split[i]) continue; // ignore empty strings
22959    namespaces = split[i].replace(/\*/g, '.*?');
22960    if (namespaces[0] === '-') {
22961      exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
22962    } else {
22963      exports.names.push(new RegExp('^' + namespaces + '$'));
22964    }
22965  }
22966}
22967
22968/**
22969 * Disable debug output.
22970 *
22971 * @api public
22972 */
22973
22974function disable() {
22975  exports.enable('');
22976}
22977
22978/**
22979 * Returns true if the given mode name is enabled, false otherwise.
22980 *
22981 * @param {String} name
22982 * @return {Boolean}
22983 * @api public
22984 */
22985
22986function enabled(name) {
22987  var i, len;
22988  for (i = 0, len = exports.skips.length; i < len; i++) {
22989    if (exports.skips[i].test(name)) {
22990      return false;
22991    }
22992  }
22993  for (i = 0, len = exports.names.length; i < len; i++) {
22994    if (exports.names[i].test(name)) {
22995      return true;
22996    }
22997  }
22998  return false;
22999}
23000
23001/**
23002 * Coerce `val`.
23003 *
23004 * @param {Mixed} val
23005 * @return {Mixed}
23006 * @api private
23007 */
23008
23009function coerce(val) {
23010  if (val instanceof Error) return val.stack || val.message;
23011  return val;
23012}
23013
23014},{"9":9}],3:[function(require,module,exports){
23015(function (process,global){
23016/*!
23017 * @overview es6-promise - a tiny implementation of Promises/A+.
23018 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
23019 * @license   Licensed under MIT license
23020 *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
23021 * @version   4.1.1
23022 */
23023
23024(function (global, factory) {
23025	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
23026	typeof define === 'function' && define.amd ? define(factory) :
23027	(global.ES6Promise = factory());
23028}(this, (function () { 'use strict';
23029
23030function objectOrFunction(x) {
23031  var type = typeof x;
23032  return x !== null && (type === 'object' || type === 'function');
23033}
23034
23035function isFunction(x) {
23036  return typeof x === 'function';
23037}
23038
23039var _isArray = undefined;
23040if (Array.isArray) {
23041  _isArray = Array.isArray;
23042} else {
23043  _isArray = function (x) {
23044    return Object.prototype.toString.call(x) === '[object Array]';
23045  };
23046}
23047
23048var isArray = _isArray;
23049
23050var len = 0;
23051var vertxNext = undefined;
23052var customSchedulerFn = undefined;
23053
23054var asap = function asap(callback, arg) {
23055  queue[len] = callback;
23056  queue[len + 1] = arg;
23057  len += 2;
23058  if (len === 2) {
23059    // If len is 2, that means that we need to schedule an async flush.
23060    // If additional callbacks are queued before the queue is flushed, they
23061    // will be processed by this flush that we are scheduling.
23062    if (customSchedulerFn) {
23063      customSchedulerFn(flush);
23064    } else {
23065      scheduleFlush();
23066    }
23067  }
23068};
23069
23070function setScheduler(scheduleFn) {
23071  customSchedulerFn = scheduleFn;
23072}
23073
23074function setAsap(asapFn) {
23075  asap = asapFn;
23076}
23077
23078var browserWindow = typeof window !== 'undefined' ? window : undefined;
23079var browserGlobal = browserWindow || {};
23080var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
23081var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
23082
23083// test for web worker but not in IE10
23084var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
23085
23086// node
23087function useNextTick() {
23088  // node version 0.10.x displays a deprecation warning when nextTick is used recursively
23089  // see https://github.com/cujojs/when/issues/410 for details
23090  return function () {
23091    return process.nextTick(flush);
23092  };
23093}
23094
23095// vertx
23096function useVertxTimer() {
23097  if (typeof vertxNext !== 'undefined') {
23098    return function () {
23099      vertxNext(flush);
23100    };
23101  }
23102
23103  return useSetTimeout();
23104}
23105
23106function useMutationObserver() {
23107  var iterations = 0;
23108  var observer = new BrowserMutationObserver(flush);
23109  var node = document.createTextNode('');
23110  observer.observe(node, { characterData: true });
23111
23112  return function () {
23113    node.data = iterations = ++iterations % 2;
23114  };
23115}
23116
23117// web worker
23118function useMessageChannel() {
23119  var channel = new MessageChannel();
23120  channel.port1.onmessage = flush;
23121  return function () {
23122    return channel.port2.postMessage(0);
23123  };
23124}
23125
23126function useSetTimeout() {
23127  // Store setTimeout reference so es6-promise will be unaffected by
23128  // other code modifying setTimeout (like sinon.useFakeTimers())
23129  var globalSetTimeout = setTimeout;
23130  return function () {
23131    return globalSetTimeout(flush, 1);
23132  };
23133}
23134
23135var queue = new Array(1000);
23136function flush() {
23137  for (var i = 0; i < len; i += 2) {
23138    var callback = queue[i];
23139    var arg = queue[i + 1];
23140
23141    callback(arg);
23142
23143    queue[i] = undefined;
23144    queue[i + 1] = undefined;
23145  }
23146
23147  len = 0;
23148}
23149
23150function attemptVertx() {
23151  try {
23152    var r = require;
23153    var vertx = r('vertx');
23154    vertxNext = vertx.runOnLoop || vertx.runOnContext;
23155    return useVertxTimer();
23156  } catch (e) {
23157    return useSetTimeout();
23158  }
23159}
23160
23161var scheduleFlush = undefined;
23162// Decide what async method to use to triggering processing of queued callbacks:
23163if (isNode) {
23164  scheduleFlush = useNextTick();
23165} else if (BrowserMutationObserver) {
23166  scheduleFlush = useMutationObserver();
23167} else if (isWorker) {
vendor: 8,854 bytes, lines 23168-23556
23168  scheduleFlush = useMessageChannel();
23169} else if (browserWindow === undefined && typeof require === 'function') {
23170  scheduleFlush = attemptVertx();
23171} else {
23172  scheduleFlush = useSetTimeout();
23173}
23174
23175function then(onFulfillment, onRejection) {
23176  var _arguments = arguments;
23177
23178  var parent = this;
23179
23180  var child = new this.constructor(noop);
23181
23182  if (child[PROMISE_ID] === undefined) {
23183    makePromise(child);
23184  }
23185
23186  var _state = parent._state;
23187
23188  if (_state) {
23189    (function () {
23190      var callback = _arguments[_state - 1];
23191      asap(function () {
23192        return invokeCallback(_state, child, callback, parent._result);
23193      });
23194    })();
23195  } else {
23196    subscribe(parent, child, onFulfillment, onRejection);
23197  }
23198
23199  return child;
23200}
23201
23202/**
23203  `Promise.resolve` returns a promise that will become resolved with the
23204  passed `value`. It is shorthand for the following:
23205
23206  ```javascript
23207  let promise = new Promise(function(resolve, reject){
23208    resolve(1);
23209  });
23210
23211  promise.then(function(value){
23212    // value === 1
23213  });
23214  ```
23215
23216  Instead of writing the above, your code now simply becomes the following:
23217
23218  ```javascript
23219  let promise = Promise.resolve(1);
23220
23221  promise.then(function(value){
23222    // value === 1
23223  });
23224  ```
23225
23226  @method resolve
23227  @static
23228  @param {Any} value value that the returned promise will be resolved with
23229  Useful for tooling.
23230  @return {Promise} a promise that will become fulfilled with the given
23231  `value`
23232*/
23233function resolve$1(object) {
23234  /*jshint validthis:true */
23235  var Constructor = this;
23236
23237  if (object && typeof object === 'object' && object.constructor === Constructor) {
23238    return object;
23239  }
23240
23241  var promise = new Constructor(noop);
23242  resolve(promise, object);
23243  return promise;
23244}
23245
23246var PROMISE_ID = Math.random().toString(36).substring(16);
23247
23248function noop() {}
23249
23250var PENDING = void 0;
23251var FULFILLED = 1;
23252var REJECTED = 2;
23253
23254var GET_THEN_ERROR = new ErrorObject();
23255
23256function selfFulfillment() {
23257  return new TypeError("You cannot resolve a promise with itself");
23258}
23259
23260function cannotReturnOwn() {
23261  return new TypeError('A promises callback cannot return that same promise.');
23262}
23263
23264function getThen(promise) {
23265  try {
23266    return promise.then;
23267  } catch (error) {
23268    GET_THEN_ERROR.error = error;
23269    return GET_THEN_ERROR;
23270  }
23271}
23272
23273function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
23274  try {
23275    then$$1.call(value, fulfillmentHandler, rejectionHandler);
23276  } catch (e) {
23277    return e;
23278  }
23279}
23280
23281function handleForeignThenable(promise, thenable, then$$1) {
23282  asap(function (promise) {
23283    var sealed = false;
23284    var error = tryThen(then$$1, thenable, function (value) {
23285      if (sealed) {
23286        return;
23287      }
23288      sealed = true;
23289      if (thenable !== value) {
23290        resolve(promise, value);
23291      } else {
23292        fulfill(promise, value);
23293      }
23294    }, function (reason) {
23295      if (sealed) {
23296        return;
23297      }
23298      sealed = true;
23299
23300      reject(promise, reason);
23301    }, 'Settle: ' + (promise._label || ' unknown promise'));
23302
23303    if (!sealed && error) {
23304      sealed = true;
23305      reject(promise, error);
23306    }
23307  }, promise);
23308}
23309
23310function handleOwnThenable(promise, thenable) {
23311  if (thenable._state === FULFILLED) {
23312    fulfill(promise, thenable._result);
23313  } else if (thenable._state === REJECTED) {
23314    reject(promise, thenable._result);
23315  } else {
23316    subscribe(thenable, undefined, function (value) {
23317      return resolve(promise, value);
23318    }, function (reason) {
23319      return reject(promise, reason);
23320    });
23321  }
23322}
23323
23324function handleMaybeThenable(promise, maybeThenable, then$$1) {
23325  if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
23326    handleOwnThenable(promise, maybeThenable);
23327  } else {
23328    if (then$$1 === GET_THEN_ERROR) {
23329      reject(promise, GET_THEN_ERROR.error);
23330      GET_THEN_ERROR.error = null;
23331    } else if (then$$1 === undefined) {
23332      fulfill(promise, maybeThenable);
23333    } else if (isFunction(then$$1)) {
23334      handleForeignThenable(promise, maybeThenable, then$$1);
23335    } else {
23336      fulfill(promise, maybeThenable);
23337    }
23338  }
23339}
23340
23341function resolve(promise, value) {
23342  if (promise === value) {
23343    reject(promise, selfFulfillment());
23344  } else if (objectOrFunction(value)) {
23345    handleMaybeThenable(promise, value, getThen(value));
23346  } else {
23347    fulfill(promise, value);
23348  }
23349}
23350
23351function publishRejection(promise) {
23352  if (promise._onerror) {
23353    promise._onerror(promise._result);
23354  }
23355
23356  publish(promise);
23357}
23358
23359function fulfill(promise, value) {
23360  if (promise._state !== PENDING) {
23361    return;
23362  }
23363
23364  promise._result = value;
23365  promise._state = FULFILLED;
23366
23367  if (promise._subscribers.length !== 0) {
23368    asap(publish, promise);
23369  }
23370}
23371
23372function reject(promise, reason) {
23373  if (promise._state !== PENDING) {
23374    return;
23375  }
23376  promise._state = REJECTED;
23377  promise._result = reason;
23378
23379  asap(publishRejection, promise);
23380}
23381
23382function subscribe(parent, child, onFulfillment, onRejection) {
23383  var _subscribers = parent._subscribers;
23384  var length = _subscribers.length;
23385
23386  parent._onerror = null;
23387
23388  _subscribers[length] = child;
23389  _subscribers[length + FULFILLED] = onFulfillment;
23390  _subscribers[length + REJECTED] = onRejection;
23391
23392  if (length === 0 && parent._state) {
23393    asap(publish, parent);
23394  }
23395}
23396
23397function publish(promise) {
23398  var subscribers = promise._subscribers;
23399  var settled = promise._state;
23400
23401  if (subscribers.length === 0) {
23402    return;
23403  }
23404
23405  var child = undefined,
23406      callback = undefined,
23407      detail = promise._result;
23408
23409  for (var i = 0; i < subscribers.length; i += 3) {
23410    child = subscribers[i];
23411    callback = subscribers[i + settled];
23412
23413    if (child) {
23414      invokeCallback(settled, child, callback, detail);
23415    } else {
23416      callback(detail);
23417    }
23418  }
23419
23420  promise._subscribers.length = 0;
23421}
23422
23423function ErrorObject() {
23424  this.error = null;
23425}
23426
23427var TRY_CATCH_ERROR = new ErrorObject();
23428
23429function tryCatch(callback, detail) {
23430  try {
23431    return callback(detail);
23432  } catch (e) {
23433    TRY_CATCH_ERROR.error = e;
23434    return TRY_CATCH_ERROR;
23435  }
23436}
23437
23438function invokeCallback(settled, promise, callback, detail) {
23439  var hasCallback = isFunction(callback),
23440      value = undefined,
23441      error = undefined,
23442      succeeded = undefined,
23443      failed = undefined;
23444
23445  if (hasCallback) {
23446    value = tryCatch(callback, detail);
23447
23448    if (value === TRY_CATCH_ERROR) {
23449      failed = true;
23450      error = value.error;
23451      value.error = null;
23452    } else {
23453      succeeded = true;
23454    }
23455
23456    if (promise === value) {
23457      reject(promise, cannotReturnOwn());
23458      return;
23459    }
23460  } else {
23461    value = detail;
23462    succeeded = true;
23463  }
23464
23465  if (promise._state !== PENDING) {
23466    // noop
23467  } else if (hasCallback && succeeded) {
23468      resolve(promise, value);
23469    } else if (failed) {
23470      reject(promise, error);
23471    } else if (settled === FULFILLED) {
23472      fulfill(promise, value);
23473    } else if (settled === REJECTED) {
23474      reject(promise, value);
23475    }
23476}
23477
23478function initializePromise(promise, resolver) {
23479  try {
23480    resolver(function resolvePromise(value) {
23481      resolve(promise, value);
23482    }, function rejectPromise(reason) {
23483      reject(promise, reason);
23484    });
23485  } catch (e) {
23486    reject(promise, e);
23487  }
23488}
23489
23490var id = 0;
23491function nextId() {
23492  return id++;
23493}
23494
23495function makePromise(promise) {
23496  promise[PROMISE_ID] = id++;
23497  promise._state = undefined;
23498  promise._result = undefined;
23499  promise._subscribers = [];
23500}
23501
23502function Enumerator$1(Constructor, input) {
23503  this._instanceConstructor = Constructor;
23504  this.promise = new Constructor(noop);
23505
23506  if (!this.promise[PROMISE_ID]) {
23507    makePromise(this.promise);
23508  }
23509
23510  if (isArray(input)) {
23511    this.length = input.length;
23512    this._remaining = input.length;
23513
23514    this._result = new Array(this.length);
23515
23516    if (this.length === 0) {
23517      fulfill(this.promise, this._result);
23518    } else {
23519      this.length = this.length || 0;
23520      this._enumerate(input);
23521      if (this._remaining === 0) {
23522        fulfill(this.promise, this._result);
23523      }
23524    }
23525  } else {
23526    reject(this.promise, validationError());
23527  }
23528}
23529
23530function validationError() {
23531  return new Error('Array Methods must be provided an Array');
23532}
23533
23534Enumerator$1.prototype._enumerate = function (input) {
23535  for (var i = 0; this._state === PENDING && i < input.length; i++) {
23536    this._eachEntry(input[i], i);
23537  }
23538};
23539
23540Enumerator$1.prototype._eachEntry = function (entry, i) {
23541  var c = this._instanceConstructor;
23542  var resolve$$1 = c.resolve;
23543
23544  if (resolve$$1 === resolve$1) {
23545    var _then = getThen(entry);
23546
23547    if (_then === then && entry._state !== PENDING) {
23548      this._settledAt(entry._state, i, entry._result);
23549    } else if (typeof _then !== 'function') {
23550      this._remaining--;
23551      this._result[i] = entry;
23552    } else if (c === Promise$2) {
23553      var promise = new c(noop);
23554      handleMaybeThenable(promise, entry, _then);
23555      this._willSettleAt(promise, i);
23556    } else {
vendor: 3,626 bytes, lines 23557-23691
23557      this._willSettleAt(new c(function (resolve$$1) {
23558        return resolve$$1(entry);
23559      }), i);
23560    }
23561  } else {
23562    this._willSettleAt(resolve$$1(entry), i);
23563  }
23564};
23565
23566Enumerator$1.prototype._settledAt = function (state, i, value) {
23567  var promise = this.promise;
23568
23569  if (promise._state === PENDING) {
23570    this._remaining--;
23571
23572    if (state === REJECTED) {
23573      reject(promise, value);
23574    } else {
23575      this._result[i] = value;
23576    }
23577  }
23578
23579  if (this._remaining === 0) {
23580    fulfill(promise, this._result);
23581  }
23582};
23583
23584Enumerator$1.prototype._willSettleAt = function (promise, i) {
23585  var enumerator = this;
23586
23587  subscribe(promise, undefined, function (value) {
23588    return enumerator._settledAt(FULFILLED, i, value);
23589  }, function (reason) {
23590    return enumerator._settledAt(REJECTED, i, reason);
23591  });
23592};
23593
23594/**
23595  `Promise.all` accepts an array of promises, and returns a new promise which
23596  is fulfilled with an array of fulfillment values for the passed promises, or
23597  rejected with the reason of the first passed promise to be rejected. It casts all
23598  elements of the passed iterable to promises as it runs this algorithm.
23599
23600  Example:
23601
23602  ```javascript
23603  let promise1 = resolve(1);
23604  let promise2 = resolve(2);
23605  let promise3 = resolve(3);
23606  let promises = [ promise1, promise2, promise3 ];
23607
23608  Promise.all(promises).then(function(array){
23609    // The array here would be [ 1, 2, 3 ];
23610  });
23611  ```
23612
23613  If any of the `promises` given to `all` are rejected, the first promise
23614  that is rejected will be given as an argument to the returned promises's
23615  rejection handler. For example:
23616
23617  Example:
23618
23619  ```javascript
23620  let promise1 = resolve(1);
23621  let promise2 = reject(new Error("2"));
23622  let promise3 = reject(new Error("3"));
23623  let promises = [ promise1, promise2, promise3 ];
23624
23625  Promise.all(promises).then(function(array){
23626    // Code here never runs because there are rejected promises!
23627  }, function(error) {
23628    // error.message === "2"
23629  });
23630  ```
23631
23632  @method all
23633  @static
23634  @param {Array} entries array of promises
23635  @param {String} label optional string for labeling the promise.
23636  Useful for tooling.
23637  @return {Promise} promise that is fulfilled when all `promises` have been
23638  fulfilled, or rejected if any of them become rejected.
23639  @static
23640*/
23641function all$1(entries) {
23642  return new Enumerator$1(this, entries).promise;
23643}
23644
23645/**
23646  `Promise.race` returns a new promise which is settled in the same way as the
23647  first passed promise to settle.
23648
23649  Example:
23650
23651  ```javascript
23652  let promise1 = new Promise(function(resolve, reject){
23653    setTimeout(function(){
23654      resolve('promise 1');
23655    }, 200);
23656  });
23657
23658  let promise2 = new Promise(function(resolve, reject){
23659    setTimeout(function(){
23660      resolve('promise 2');
23661    }, 100);
23662  });
23663
23664  Promise.race([promise1, promise2]).then(function(result){
23665    // result === 'promise 2' because it was resolved before promise1
23666    // was resolved.
23667  });
23668  ```
23669
23670  `Promise.race` is deterministic in that only the state of the first
23671  settled promise matters. For example, even if other promises given to the
23672  `promises` array argument are resolved, but the first settled promise has
23673  become rejected before the other promises became fulfilled, the returned
23674  promise will become rejected:
23675
23676  ```javascript
23677  let promise1 = new Promise(function(resolve, reject){
23678    setTimeout(function(){
23679      resolve('promise 1');
23680    }, 200);
23681  });
23682
23683  let promise2 = new Promise(function(resolve, reject){
23684    setTimeout(function(){
23685      reject(new Error('promise 2'));
23686    }, 100);
23687  });
23688
23689  Promise.race([promise1, promise2]).then(function(result){
23690    // Code here never runs
23691  }, function(reason){
23692    // reason.message === 'promise 2' because promise 2 became rejected before
23693    // promise 1 became fulfilled
23694  });
23695  ```
23696
23697  An example real-world use case is implementing timeouts:
23698
23699  ```javascript
23700  Promise.race([ajax('foo.json'), timeout(5000)])
23701  ```
23702
23703  @method race
23704  @static
23705  @param {Array} promises array of promises to observe
23706  Useful for tooling.
23707  @return {Promise} a promise which settles in the same way as the first passed
23708  promise to settle.
23709*/
23710function race$1(entries) {
23711  /*jshint validthis:true */
23712  var Constructor = this;
23713
23714  if (!isArray(entries)) {
23715    return new Constructor(function (_, reject) {
23716      return reject(new TypeError('You must pass an array to race.'));
23717    });
23718  } else {
23719    return new Constructor(function (resolve, reject) {
23720      var length = entries.length;
23721      for (var i = 0; i < length; i++) {
23722        Constructor.resolve(entries[i]).then(resolve, reject);
23723      }
23724    });
23725  }
23726}
23727
23728/**
23729  `Promise.reject` returns a promise rejected with the passed `reason`.
23730  It is shorthand for the following:
23731
23732  ```javascript
23733  let promise = new Promise(function(resolve, reject){
23734    reject(new Error('WHOOPS'));
23735  });
23736
23737  promise.then(function(value){
23738    // Code here doesn't run because the promise is rejected!
23739  }, function(reason){
23740    // reason.message === 'WHOOPS'
23741  });
23742  ```
23743
23744  Instead of writing the above, your code now simply becomes the following:
23745
23746  ```javascript
23747  let promise = Promise.reject(new Error('WHOOPS'));
23748
23749  promise.then(function(value){
23750    // Code here doesn't run because the promise is rejected!
23751  }, function(reason){
23752    // reason.message === 'WHOOPS'
23753  });
23754  ```
23755
23756  @method reject
23757  @static
23758  @param {Any} reason value that the returned promise will be rejected with.
23759  Useful for tooling.
23760  @return {Promise} a promise rejected with the given `reason`.
23761*/
23762function reject$1(reason) {
23763  /*jshint validthis:true */
23764  var Constructor = this;
23765  var promise = new Constructor(noop);
23766  reject(promise, reason);
23767  return promise;
23768}
23769
23770function needsResolver() {
23771  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
23772}
23773
23774function needsNew() {
23775  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object c
23775onstructor cannot be called as a function.");
23776}
23777
23778/**
23779  Promise objects represent the eventual result of an asynchronous operation. The
23780  primary way of interacting with a promise is through its `then` method, which
23781  registers callbacks to receive either a promise's eventual value or the reason
23782  why the promise cannot be fulfilled.
23783
23784  Terminology
23785  -----------
23786
23787  - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
23788  - `thenable` is an object or function that defines a `then` method.
23789  - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
23790  - `exception` is a value that is thrown using the throw statement.
23791  - `reason` is a value that indicates why a promise was rejected.
23792  - `settled` the final resting state of a promise, fulfilled or rejected.
23793
23794  A promise can be in one of three states: pending, fulfilled, or rejected.
23795
23796  Promises that are fulfilled have a fulfillment value and are in the fulfilled
23797  state.  Promises that are rejected have a rejection reason and are in the
23798  rejected state.  A fulfillment value is never a thenable.
23799
23800  Promises can also be said to *resolve* a value.  If this value is also a
23801  promise, then the original promise's settled state will match the value's
23802  settled state.  So a promise that *resolves* a promise that rejects will
23803  itself reject, and a promise that *resolves* a promise that fulfills will
23804  itself fulfill.
23805
23806
23807  Basic Usage:
23808  ------------
23809
23810  ```js
23811  let promise = new Promise(function(resolve, reject) {
23812    // on success
23813    resolve(value);
23814
23815    // on failure
23816    reject(reason);
23817  });
23818
23819  promise.then(function(value) {
23820    // on fulfillment
23821  }, function(reason) {
23822    // on rejection
23823  });
23824  ```
23825
23826  Advanced Usage:
23827  ---------------
23828
23829  Promises shine when abstracting away asynchronous interactions such as
23830  `XMLHttpRequest`s.
23831
23832  ```js
23833  function getJSON(url) {
23834    return new Promise(function(resolve, reject){
23835      let xhr = new XMLHttpRequest();
23836
23837      xhr.open('GET', url);
23838      xhr.onreadystatechange = handler;
23839      xhr.responseType = 'json';
23840      xhr.setRequestHeader('Accept', 'application/json');
23841      xhr.send();
23842
23843      function handler() {
23844        if (this.readyState === this.DONE) {
23845          if (this.status === 200) {
23846            resolve(this.response);
23847          } else {
23848            reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
23849          }
23850        }
23851      };
23852    });
23853  }
23854
23855  getJSON('/posts.json').then(function(json) {
23856    // on fulfillment
23857  }, function(reason) {
23858    // on rejection
23859  });
23860  ```
23861
23862  Unlike callbacks, promises are great composable primitives.
23863
23864  ```js
23865  Promise.all([
23866    getJSON('/posts'),
23867    getJSON('/comments')
23868  ]).then(function(values){
23869    values[0] // => postsJSON
23870    values[1] // => commentsJSON
23871
23872    return values;
23873  });
23874  ```
23875
23876  @class Promise
23877  @param {function} resolver
23878  Useful for tooling.
23879  @constructor
23880*/
23881function Promise$2(resolver) {
23882  this[PROMISE_ID] = nextId();
23883  this._result = this._state = undefined;
23884  this._subscribers = [];
23885
23886  if (noop !== resolver) {
23887    typeof resolver !== 'function' && needsResolver();
23888    this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
23889  }
23890}
23891
23892Promise$2.all = all$1;
23893Promise$2.race = race$1;
23894Promise$2.resolve = resolve$1;
23895Promise$2.reject = reject$1;
23896Promise$2._setScheduler = setScheduler;
23897Promise$2._setAsap = setAsap;
23898Promise$2._asap = asap;
23899
23900Promise$2.prototype = {
23901  constructor: Promise$2,
23902
23903  /**
23904    The primary way of interacting with a promise is through its `then` method,
23905    which registers callbacks to receive either a promise's eventual value or the
23906    reason why the promise cannot be fulfilled.
23907  
23908    ```js
23909    findUser().then(function(user){
23910      // user is available
23911    }, function(reason){
23912      // user is unavailable, and you are given the reason why
23913    });
23914    ```
23915  
23916    Chaining
23917    --------
23918  
23919    The return value of `then` is itself a promise.  This second, 'downstream'
23920    promise is resolved with the return value of the first promise's fulfillment
23921    or rejection handler, or rejected if the handler throws an exception.
23922  
23923    ```js
23924    findUser().then(function (user) {
23925      return user.name;
23926    }, function (reason) {
23927      return 'default name';
23928    }).then(function (userName) {
23929      // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
23930      // will be `'default name'`
23931    });
23932  
23933    findUser().then(function (user) {
23934      throw new Error('Found user, but still unhappy');
23935    }, function (reason) {
23936      throw new Error('`findUser` rejected and we're unhappy');
23937    }).then(function (value) {
23938      // never reached
23939    }, function (reason) {
23940      // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
23941      // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
23942    });
23943    ```
23944    If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
23945  
23946    ```js
23947    findUser().then(function (user) {
23948      throw new PedagogicalException('Upstream error');
23949    }).then(function (value) {
23950      // never reached
23951    }).then(function (value) {
23952      // never reached
23953    }, function (reason) {
23954      // The `PedgagocialException` is propagated all the way down to here
23955    });
23956    ```
23957  
23958    Assimilation
23959    ------------
23960  
23961    Sometimes the value you want to propagate to a downstream promise can only be
23962    retrieved asynchronously. This can be achieved by returning a promise in the
23963    fulfillment or rejection handler. The downstream promise will then be pending
23964    until the returned promise is settled. This is called *assimilation*.
23965  
23966    ```js
23967    findUser().then(function (user) {
23968      return findCommentsByAuthor(user);
23969    }).then(function (comments) {
23970      // The user's comments are now available
23971    });
23972    ```
23973  
23974    If the assimliated promise rejects, then the downstream promise will also reject.
23975  
23976    ```js
23977    findUser().then(function (user) {
23978      return findCommentsByAuthor(user);
23979    }).then(function (comments) {
23980      // If `findCommentsByAuthor` fulfills, we'll have the value here
23981    }, function (reason) {
23982      // If `findCommentsByAuthor` rejects, we'll have the reason here
23983    });
23984    ```
23985  
23986    Simple Example
23987    --------------
23988  
23989    Synchronous Example
23990  
23991    ```javascript
23992    let result;
23993  
23994    try {
23995      result = findResult();
23996      // success
23997    } catch(reason) {
23998      // failure
23999    }
24000    ```
24001  
24002    Errback Example
24003  
24004    ```js
24005    findResult(function(result, err){
24006      if (err) {
24007        // failure
24008      } else {
24009        // success
24010      }
24011    });
24012    ```
24013  
24014    Promise Example;
24015  
24016    ```javascript
24017    findResult().then(function(result){
24018      // success
24019    }, function(reason){
24020      // failure
24021    });
24022    ```
24023  
24024    Advanced Example
24025    --------------
24026  
24027    Synchronous Example
24028  
24029    ```javascript
24030    let author, books;
24031  
24032    try {
24033      author = findAuthor();
24034      books  = findBooksByAuthor(author);
24035      // success
24036    } catch(reason) {
24037      // failure
24038    }
24039    ```
24040  
24041    Errback Example
24042  
24043    ```js
24044  
24045    function foundBooks(books) {
24046  
24047    }
24048  
24049    function failure(reason) {
24050  
24051    }
24052  
24053    findAuthor(function(author, err){
24054      if (err) {
24055        failure(err);
24056        // failure
24057      } else {
24058        try {
24059          findBoooksByAuthor(author, function(books, err) {
24060            if (err) {
24061              failure(err);
24062            } else {
24063              try {
24064                foundBooks(books);
24065              } catch(reason) {
24066                failure(reason);
24067              }
24068            }
24069          });
24070        } catch(error) {
24071          failure(err);
24072        }
24073        // success
24074      }
24075    });
24076    ```
24077  
24078    Promise Example;
24079  
24080    ```javascript
24081    findAuthor().
24082      then(findBooksByAuthor).
24083      then(function(books){
24084        // found books
24085    }).catch(function(reason){
24086      // something went wrong
24087    });
24088    ```
24089  
24090    @method then
24091    @param {Function} onFulfilled
24092    @param {Function} onRejected
24093    Useful for tooling.
24094    @return {Promise}
24095  */
24096  then: then,
24097
24098  /**
24099    `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
24100    as the catch block of a try/catch statement.
24101  
24102    ```js
24103    function findAuthor(){
24104      throw new Error('couldn't find that author');
24105    }
24106  
24107    // synchronous
24108    try {
24109      findAuthor();
24110    } catch(reason) {
24111      // something went wrong
24112    }
24113  
24114    // async with promises
24115    findAuthor().catch(function(reason){
24116      // something went wrong
24117    });
24118    ```
24119  
24120    @method catch
24121    @param {Function} onRejection
24122    Useful for tooling.
24123    @return {Promise}
24124  */
24125  'catch': function _catch(onRejection) {
24126    return this.then(null, onRejection);
24127  }
24128};
24129
24130/*global self*/
24131function polyfill$1() {
24132    var local = undefined;
24133
24134    if (typeof global !== 'undefined') {
24135        local = global;
24136    } else if (typeof self !== 'undefined') {
24137        local = self;
24138    } else {
24139        try {
24140            local = Function('return this')();
24141        } catch (e) {
24142            throw new Error('polyfill failed because global object is unavailable in this environment');
24143        }
24144    }
24145
24146    var P = local.Promise;
24147
24148    if (P) {
24149        var promiseToString = null;
24150        try {
24151            promiseToString = Object.prototype.toString.call(P.resolve());
24152        } catch (e) {
24153            // silently ignored
24154        }
24155
24156        if (promiseToString === '[object Promise]' && !P.cast) {
24157            return;
24158        }
24159    }
24160
24161    local.Promise = Promise$2;
24162}
24163
24164// Strange compat..
24165Promise$2.polyfill = polyfill$1;
24166Promise$2.Promise = Promise$2;
24167
24168return Promise$2;
24169
24170})));
24171
24172
24173
24174}).call(this,require(12),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
24175},{"12":12}],4:[function(require,module,exports){
24176// Copyright Joyent, Inc. and other Node contributors.
24177//
24178// Permission is hereby granted, free of charge, to any person obtaining a
24179// copy of this software and associated documentation files (the
24180// "Software"), to deal in the Software without restriction, including
24181// without limitation the rights to use, copy, modify, merge, publish,
24182// distribute, sublicense, and/or sell copies of the Software, and to permit
24183// persons to whom the Software is furnished to do so, subject to the
24184// following conditions:
24185//
24186// The above copyright notice and this permission notice shall be included
24187// in all copies or substantial portions of the Software.
24188//
24189// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24190// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24191// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
24192// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
24193// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24194// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
24195// USE OR OTHER DEALINGS IN THE SOFTWARE.
24196
24197function EventEmitter() {
24198  this._events = this._events || {};
24199  this._maxListeners = this._maxListeners || undefined;
24200}
24201module.exports = EventEmitter;
24202
24203// Backwards-compat with node 0.10.x
24204EventEmitter.EventEmitter = EventEmitter;
24205
24206EventEmitter.prototype._events = undefined;
24207EventEmitter.prototype._maxListeners = undefined;
24208
24209// By default EventEmitters will print a warning if more than 10 listeners are
24210// added to it. This is a useful default which helps finding memory leaks.
24211EventEmitter.defaultMaxListeners = 10;
24212
24213// Obviously not all Emitters should be limited to 10. This function allows
24214// that to be increased. Set to zero for unlimited.
24215EventEmitter.prototype.setMaxListeners = function(n) {
24216  if (!isNumber(n) || n < 0 || isNaN(n))
24217    throw TypeError('n must be a positive number');
24218  this._maxListeners = n;
24219  return this;
24220};
24221
24222EventEmitter.prototype.emit = function(type) {
24223  var er, handler, len, args, i, listeners;
24224
24225  if (!this._events)
24226    this._events = {};
24227
24228  // If there is no 'error' event listener then throw.
24229  if (type === 'error') {
24230    if (!this._events.error ||
24231        (isObject(this._events.error) && !this._events.error.length)) {
24232      er = arguments[1];
24233      if (er instanceof Error) {
24234        throw er; // Unhandled 'error' event
24235      } else {
24236        // At least give some kind of context to the user
24237        var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
24238        err.context = er;
24239        throw err;
24240      }
24241    }
24242  }
24243
24244  handler = this._events[type];
24245
24246  if (isUndefined(handler))
24247    return false;
24248
24249  if (isFunction(handler)) {
24250    switch (arguments.length) {
24251      // fast cases
24252      case 1:
24253        handler.call(this);
24254        break;
24255      case 2:
24256        handler.call(this, arguments[1]);
24257        break;
24258      case 3:
24259        handler.call(this, arguments[1], arguments[2]);
24260        break;
24261      // slower
24262      default:
24263        args = Array.prototype.slice.call(arguments, 1);
24264        handler.apply(this, args);
24265    }
24266  } else if (isObject(handler)) {
24267    args = Array.prototype.slice.call(arguments, 1);
24268    listeners = handler.slice();
24269    len = listeners.length;
24270    for (i = 0; i < len; i++)
24271      listeners[i].apply(this, args);
24272  }
24273
24274  return true;
24275};
24276
24277EventEmitter.prototype.addListener = function(type, listener) {
24278  var m;
24279
24280  if (!isFunction(listener))
24281    throw TypeError('listener must be a function');
24282
24283  if (!this._events)
24284    this._events = {};
24285
24286  // To avoid recursion in the case that type === "newListener"! Before
24287  // adding it to the listeners, first emit "newListener".
24288  if (this._events.newListener)
24289    this.emit('newListener', type,
24290              isFunction(listener.listener) ?
24291              listener.listener : listener);
24292
24293  if (!this._events[type])
24294    // Optimize the case of one listener. Don't need the extra array object.
24295    this._events[type] = listener;
24296  else if (isObject(this._events[type]))
24297    // If we've already got an array, just append.
24298    this._events[type].push(listener);
24299  else
24300    // Adding the second element, need to change to array.
24301    this._events[type] = [this._events[type], listener];
24302
24303  // Check for listener leak
24304  if (isObject(this._events[type]) && !this._events[type].warned) {
24305    if (!isUndefined(this._maxListeners)) {
24306      m = this._maxListeners;
24307    } else {
24308      m = EventEmitter.defaultMaxListeners;
24309    }
24310
24311    if (m && m > 0 && this._events[type].length > m) {
24312      this._events[type].warned = true;
24313      console.error('(node) warning: possible EventEmitter memory ' +
24314                    'leak detected. %d listeners added. ' +
24315                    'Use emitter.setMaxListeners() to increase limit.',
24316                    this._events[type].length);
24317      if (typeof console.trace === 'function') {
24318        // not supported in IE 10
24319        console.trace();
24320      }
24321    }
24322  }
24323
24324  return this;
24325};
24326
24327EventEmitter.prototype.on = EventEmitter.prototype.addListener;
24328
24329EventEmitter.prototype.once = function(type, listener) {
24330  if (!isFunction(listener))
24331    throw TypeError('listener must be a function');
24332
24333  var fired = false;
24334
24335  function g() {
24336    this.removeListener(type, g);
24337
24338    if (!fired) {
24339      fired = true;
24340      listener.apply(this, arguments);
24341    }
24342  }
24343
24344  g.listener = listener;
24345  this.on(type, g);
24346
24347  return this;
24348};
24349
24350// emits a 'removeListener' event iff the listener was removed
24351EventEmitter.prototype.removeListener = function(type, listener) {
24352  var list, position, length, i;
24353
24354  if (!isFunction(listener))
24355    throw TypeError('listener must be a function');
24356
24357  if (!this._events || !this._events[type])
24358    return this;
24359
24360  list = this._events[type];
24361  length = list.length;
24362  position = -1;
24363
24364  if (list === listener ||
24365      (isFunction(list.listener) && list.listener === listener)) {
24366    delete this._events[type];
24367    if (this._events.removeListener)
24368      this.emit('removeListener', type, listener);
24369
24370  } else if (isObject(list)) {
24371    for (i = length; i-- > 0;) {
24372      if (list[i] === listener ||
24373          (list[i].listener && list[i].listener === listener)) {
24374        position = i;
24375        break;
24376      }
24377    }
24378
24379    if (position < 0)
24380      return this;
24381
24382    if (list.length === 1) {
24383      list.length = 0;
24384      delete this._events[type];
24385    } else {
24386      list.splice(position, 1);
24387    }
24388
24389    if (this._events.removeListener)
24390      this.emit('removeListener', type, listener);
24391  }
24392
24393  return this;
24394};
24395
24396EventEmitter.prototype.removeAllListeners = function(type) {
24397  var key, listeners;
24398
24399  if (!this._events)
24400    return this;
24401
24402  // not listening for removeListener, no need to emit
24403  if (!this._events.removeListener) {
24404    if (arguments.length === 0)
24405      this._events = {};
24406    else if (this._events[type])
24407      delete this._events[type];
24408    return this;
24409  }
24410
24411  // emit removeListener for all listeners on all events
24412  if (arguments.length === 0) {
24413    for (key in this._events) {
24414      if (key === 'removeListener') continue;
24415      this.removeAllListeners(key);
24416    }
24417    this.removeAllListeners('removeListener');
24418    this._events = {};
24419    return this;
24420  }
24421
24422  listeners = this._events[type];
24423
24424  if (isFunction(listeners)) {
24425    this.removeListener(type, listeners);
24426  } else if (listeners) {
24427    // LIFO order
24428    while (listeners.length)
24429      this.removeListener(type, listeners[listeners.length - 1]);
24430  }
24431  delete this._events[type];
24432
24433  return this;
24434};
24435
24436EventEmitter.prototype.listeners = function(type) {
24437  var ret;
24438  if (!this._events || !this._events[type])
24439    ret = [];
24440  else if (isFunction(this._events[type]))
24441    ret = [this._events[type]];
24442  else
24443    ret = this._events[type].slice();
24444  return ret;
24445};
24446
24447EventEmitter.prototype.listenerCount = function(type) {
24448  if (this._events) {
24449    var evlistener = this._events[type];
24450
24451    if (isFunction(evlistener))
24452      return 1;
24453    else if (evlistener)
24454      return evlistener.length;
24455  }
24456  return 0;
24457};
24458
24459EventEmitter.listenerCount = function(emitter, type) {
24460  return emitter.listenerCount(type);
24461};
24462
24463function isFunction(arg) {
24464  return typeof arg === 'function';
24465}
24466
24467function isNumber(arg) {
24468  return typeof arg === 'number';
24469}
24470
24471function isObject(arg) {
24472  return typeof arg === 'object' && arg !== null;
24473}
24474
24475function isUndefined(arg) {
24476  return arg === void 0;
24477}
24478
24479},{}],5:[function(require,module,exports){
24480
24481var hasOwn = Object.prototype.hasOwnProperty;
24482var toString = Object.prototype.toString;
24483
24484module.exports = function forEach (obj, fn, ctx) {
24485    if (toString.call(fn) !== '[object Function]') {
24486        throw new TypeError('iterator must be a function');
24487    }
24488    var l = obj.length;
24489    if (l === +l) {
24490        for (var i = 0; i < l; i++) {
24491            fn.call(ctx, obj[i], i, obj);
24492        }
24493    } else {
24494        for (var k in obj) {
24495            if (hasOwn.call(obj, k)) {
24496                fn.call(ctx, obj[k], k, obj);
24497            }
24498        }
24499    }
24500};
24501
24502
24503},{}],6:[function(require,module,exports){
24504(function (global){
24505var win;
24506
24507if (typeof window !== "undefined") {
24508    win = window;
24509} else if (typeof global !== "undefined") {
24510    win = global;
24511} else if (typeof self !== "undefined"){
24512    win = self;
24513} else {
24514    win = {};
24515}
24516
24517module.exports = win;
24518
24519}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
24520},{}],7:[function(require,module,exports){
24521if (typeof Object.create === 'function') {
24522  // implementation from standard node.js 'util' module
24523  module.exports = function inherits(ctor, superCtor) {
24524    ctor.super_ = superCtor
24525    ctor.prototype = Object.create(superCtor.prototype, {
24526      constructor: {
24527        value: ctor,
24528        enumerable: false,
24529        writable: true,
24530        configurable: true
24531      }
24532    });
24533  };
24534} else {
24535  // old school shim for old browsers
24536  module.exports = function inherits(ctor, superCtor) {
24537    ctor.super_ = superCtor
24538    var TempCtor = function () {}
24539    TempCtor.prototype = superCtor.prototype
24540    ctor.prototype = new TempCtor()
24541    ctor.prototype.constructor = ctor
24542  }
24543}
24544
24545},{}],8:[function(require,module,exports){
24546var toString = {}.toString;
24547
24548module.exports = Array.isArray || function (arr) {
24549  return toString.call(arr) == '[object Array]';
24550};
24551
24552},{}],9:[function(require,module,exports){
24553/**
24554 * Helpers.
24555 */
24556
24557var s = 1000;
24558var m = s * 60;
24559var h = m * 60;
24560var d = h * 24;
24561var y = d * 365.25;
24562
24563/**
24564 * Parse or format the given `val`.
24565 *
24566 * Options:
24567 *
24568 *  - `long` verbose formatting [false]
24569 *
24570 * @param {String|Number} val
24571 * @param {Object} [options]
24572 * @throws {Error} throw an error if val is not a non-empty string or a number
24573 * @return {String|Number}
24574 * @api public
24575 */
24576
24577module.exports = function(val, options) {
24578  options = options || {};
24579  var type = typeof val;
24580  if (type === 'string' && val.length > 0) {
24581    return parse(val);
24582  } else if (type === 'number' && isNaN(val) === false) {
vendor: 6,209 bytes, lines 24583-24867
24583    return options.long ? fmtLong(val) : fmtShort(val);
24584  }
24585  throw new Error(
24586    'val is not a non-empty string or a valid number. val=' +
24587      JSON.stringify(val)
24588  );
24589};
24590
24591/**
24592 * Parse the given `str` and return milliseconds.
24593 *
24594 * @param {String} str
24595 * @return {Number}
24596 * @api private
24597 */
24598
24599function parse(str) {
24600  str = String(str);
24601  if (str.length > 100) {
24602    return;
24603  }
24604  var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
24605    str
24606  );
24607  if (!match) {
24608    return;
24609  }
24610  var n = parseFloat(match[1]);
24611  var type = (match[2] || 'ms').toLowerCase();
24612  switch (type) {
24613    case 'years':
24614    case 'year':
24615    case 'yrs':
24616    case 'yr':
24617    case 'y':
24618      return n * y;
24619    case 'days':
24620    case 'day':
24621    case 'd':
24622      return n * d;
24623    case 'hours':
24624    case 'hour':
24625    case 'hrs':
24626    case 'hr':
24627    case 'h':
24628      return n * h;
24629    case 'minutes':
24630    case 'minute':
24631    case 'mins':
24632    case 'min':
24633    case 'm':
24634      return n * m;
24635    case 'seconds':
24636    case 'second':
24637    case 'secs':
24638    case 'sec':
24639    case 's':
24640      return n * s;
24641    case 'milliseconds':
24642    case 'millisecond':
24643    case 'msecs':
24644    case 'msec':
24645    case 'ms':
24646      return n;
24647    default:
24648      return undefined;
24649  }
24650}
24651
24652/**
24653 * Short format for `ms`.
24654 *
24655 * @param {Number} ms
24656 * @return {String}
24657 * @api private
24658 */
24659
24660function fmtShort(ms) {
24661  if (ms >= d) {
24662    return Math.round(ms / d) + 'd';
24663  }
24664  if (ms >= h) {
24665    return Math.round(ms / h) + 'h';
24666  }
24667  if (ms >= m) {
24668    return Math.round(ms / m) + 'm';
24669  }
24670  if (ms >= s) {
24671    return Math.round(ms / s) + 's';
24672  }
24673  return ms + 'ms';
24674}
24675
24676/**
24677 * Long format for `ms`.
24678 *
24679 * @param {Number} ms
24680 * @return {String}
24681 * @api private
24682 */
24683
24684function fmtLong(ms) {
24685  return plural(ms, d, 'day') ||
24686    plural(ms, h, 'hour') ||
24687    plural(ms, m, 'minute') ||
24688    plural(ms, s, 'second') ||
24689    ms + ' ms';
24690}
24691
24692/**
24693 * Pluralization helper.
24694 */
24695
24696function plural(ms, n, name) {
24697  if (ms < n) {
24698    return;
24699  }
24700  if (ms < n * 1.5) {
24701    return Math.floor(ms / n) + ' ' + name;
24702  }
24703  return Math.ceil(ms / n) + ' ' + name + 's';
24704}
24705
24706},{}],10:[function(require,module,exports){
24707'use strict';
24708
24709// modified from https://github.com/es-shims/es5-shim
24710var has = Object.prototype.hasOwnProperty;
24711var toStr = Object.prototype.toString;
24712var slice = Array.prototype.slice;
24713var isArgs = require(11);
24714var isEnumerable = Object.prototype.propertyIsEnumerable;
24715var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
24716var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
24717var dontEnums = [
24718	'toString',
24719	'toLocaleString',
24720	'valueOf',
24721	'hasOwnProperty',
24722	'isPrototypeOf',
24723	'propertyIsEnumerable',
24724	'constructor'
24725];
24726var equalsConstructorPrototype = function (o) {
24727	var ctor = o.constructor;
24728	return ctor && ctor.prototype === o;
24729};
24730var excludedKeys = {
24731	$console: true,
24732	$external: true,
24733	$frame: true,
24734	$frameElement: true,
24735	$frames: true,
24736	$innerHeight: true,
24737	$innerWidth: true,
24738	$outerHeight: true,
24739	$outerWidth: true,
24740	$pageXOffset: true,
24741	$pageYOffset: true,
24742	$parent: true,
24743	$scrollLeft: true,
24744	$scrollTop: true,
24745	$scrollX: true,
24746	$scrollY: true,
24747	$self: true,
24748	$webkitIndexedDB: true,
24749	$webkitStorageInfo: true,
24750	$window: true
24751};
24752var hasAutomationEqualityBug = (function () {
24753	/* global window */
24754	if (typeof window === 'undefined') { return false; }
24755	for (var k in window) {
24756		try {
24757			if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
24758				try {
24759					equalsConstructorPrototype(window[k]);
24760				} catch (e) {
24761					return true;
24762				}
24763			}
24764		} catch (e) {
24765			return true;
24766		}
24767	}
24768	return false;
24769}());
24770var equalsConstructorPrototypeIfNotBuggy = function (o) {
24771	/* global window */
24772	if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
24773		return equalsConstructorPrototype(o);
24774	}
24775	try {
24776		return equalsConstructorPrototype(o);
24777	} catch (e) {
24778		return false;
24779	}
24780};
24781
24782var keysShim = function keys(object) {
24783	var isObject = object !== null && typeof object === 'object';
24784	var isFunction = toStr.call(object) === '[object Function]';
24785	var isArguments = isArgs(object);
24786	var isString = isObject && toStr.call(object) === '[object String]';
24787	var theKeys = [];
24788
24789	if (!isObject && !isFunction && !isArguments) {
24790		throw new TypeError('Object.keys called on a non-object');
24791	}
24792
24793	var skipProto = hasProtoEnumBug && isFunction;
24794	if (isString && object.length > 0 && !has.call(object, 0)) {
24795		for (var i = 0; i < object.length; ++i) {
24796			theKeys.push(String(i));
24797		}
24798	}
24799
24800	if (isArguments && object.length > 0) {
24801		for (var j = 0; j < object.length; ++j) {
24802			theKeys.push(String(j));
24803		}
24804	} else {
24805		for (var name in object) {
24806			if (!(skipProto && name === 'prototype') && has.call(object, name)) {
24807				theKeys.push(String(name));
24808			}
24809		}
24810	}
24811
24812	if (hasDontEnumBug) {
24813		var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
24814
24815		for (var k = 0; k < dontEnums.length; ++k) {
24816			if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
24817				theKeys.push(dontEnums[k]);
24818			}
24819		}
24820	}
24821	return theKeys;
24822};
24823
24824keysShim.shim = function shimObjectKeys() {
24825	if (Object.keys) {
24826		var keysWorksWithArguments = (function () {
24827			// Safari 5.0 bug
24828			return (Object.keys(arguments) || '').length === 2;
24829		}(1, 2));
24830		if (!keysWorksWithArguments) {
24831			var originalKeys = Object.keys;
24832			Object.keys = function keys(object) {
24833				if (isArgs(object)) {
24834					return originalKeys(slice.call(object));
24835				} else {
24836					return originalKeys(object);
24837				}
24838			};
24839		}
24840	} else {
24841		Object.keys = keysShim;
24842	}
24843	return Object.keys || keysShim;
24844};
24845
24846module.exports = keysShim;
24847
24848},{"11":11}],11:[function(require,module,exports){
24849'use strict';
24850
24851var toStr = Object.prototype.toString;
24852
24853module.exports = function isArguments(value) {
24854	var str = toStr.call(value);
24855	var isArgs = str === '[object Arguments]';
24856	if (!isArgs) {
24857		isArgs = str !== '[object Array]' &&
24858			value !== null &&
24859			typeof value === 'object' &&
24860			typeof value.length === 'number' &&
24861			value.length >= 0 &&
24862			toStr.call(value.callee) === '[object Function]';
24863	}
24864	return isArgs;
24865};
24866
24867},{}],12:[function(require,module,exports){
vendor: 5,027 bytes, lines 24867-25037
24867
24868// shim for using process in browser
24869var process = module.exports = {};
24870
24871// cached from whatever global is present so that test runners that stub it
24872// don't break things.  But we need to wrap it in a try catch in case it is
24873// wrapped in strict mode code which doesn't define any globals.  It's inside a
24874// function because try/catches deoptimize in certain engines.
24875
24876var cachedSetTimeout;
24877var cachedClearTimeout;
24878
24879function defaultSetTimout() {
24880    throw new Error('setTimeout has not been defined');
24881}
24882function defaultClearTimeout () {
24883    throw new Error('clearTimeout has not been defined');
24884}
24885(function () {
24886    try {
24887        if (typeof setTimeout === 'function') {
24888            cachedSetTimeout = setTimeout;
24889        } else {
24890            cachedSetTimeout = defaultSetTimout;
24891        }
24892    } catch (e) {
24893        cachedSetTimeout = defaultSetTimout;
24894    }
24895    try {
24896        if (typeof clearTimeout === 'function') {
24897            cachedClearTimeout = clearTimeout;
24898        } else {
24899            cachedClearTimeout = defaultClearTimeout;
24900        }
24901    } catch (e) {
24902        cachedClearTimeout = defaultClearTimeout;
24903    }
24904} ())
24905function runTimeout(fun) {
24906    if (cachedSetTimeout === setTimeout) {
24907        //normal enviroments in sane situations
24908        return setTimeout(fun, 0);
24909    }
24910    // if setTimeout wasn't available but was latter defined
24911    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
24912        cachedSetTimeout = setTimeout;
24913        return setTimeout(fun, 0);
24914    }
24915    try {
24916        // when when somebody has screwed with setTimeout but no I.E. maddness
24917        return cachedSetTimeout(fun, 0);
24918    } catch(e){
24919        try {
24920            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
24921            return cachedSetTimeout.call(null, fun, 0);
24922        } catch(e){
24923            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
24924            return cachedSetTimeout.call(this, fun, 0);
24925        }
24926    }
24927
24928
24929}
24930function runClearTimeout(marker) {
24931    if (cachedClearTimeout === clearTimeout) {
24932        //normal enviroments in sane situations
24933        return clearTimeout(marker);
24934    }
24935    // if clearTimeout wasn't available but was latter defined
24936    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
24937        cachedClearTimeout = clearTimeout;
24938        return clearTimeout(marker);
24939    }
24940    try {
24941        // when when somebody has screwed with setTimeout but no I.E. maddness
24942        return cachedClearTimeout(marker);
24943    } catch (e){
24944        try {
24945            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
24946            return cachedClearTimeout.call(null, marker);
24947        } catch (e){
24948            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
24949            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
24950            return cachedClearTimeout.call(this, marker);
24951        }
24952    }
24953
24954
24955
24956}
24957var queue = [];
24958var draining = false;
24959var currentQueue;
24960var queueIndex = -1;
24961
24962function cleanUpNextTick() {
24963    if (!draining || !currentQueue) {
24964        return;
24965    }
24966    draining = false;
24967    if (currentQueue.length) {
24968        queue = currentQueue.concat(queue);
24969    } else {
24970        queueIndex = -1;
24971    }
24972    if (queue.length) {
24973        drainQueue();
24974    }
24975}
24976
24977function drainQueue() {
24978    if (draining) {
24979        return;
24980    }
24981    var timeout = runTimeout(cleanUpNextTick);
24982    draining = true;
24983
24984    var len = queue.length;
24985    while(len) {
24986        currentQueue = queue;
24987        queue = [];
24988        while (++queueIndex < len) {
24989            if (currentQueue) {
24990                currentQueue[queueIndex].run();
24991            }
24992        }
24993        queueIndex = -1;
24994        len = queue.length;
24995    }
24996    currentQueue = null;
24997    draining = false;
24998    runClearTimeout(timeout);
24999}
25000
25001process.nextTick = function (fun) {
25002    var args = new Array(arguments.length - 1);
25003    if (arguments.length > 1) {
25004        for (var i = 1; i < arguments.length; i++) {
25005            args[i - 1] = arguments[i];
25006        }
25007    }
25008    queue.push(new Item(fun, args));
25009    if (queue.length === 1 && !draining) {
25010        runTimeout(drainQueue);
25011    }
25012};
25013
25014// v8 likes predictible objects
25015function Item(fun, array) {
25016    this.fun = fun;
25017    this.array = array;
25018}
25019Item.prototype.run = function () {
25020    this.fun.apply(null, this.array);
25021};
25022process.title = 'browser';
25023process.browser = true;
25024process.env = {};
25025process.argv = [];
25026process.version = ''; // empty string to avoid regexp issues
25027process.versions = {};
25028
25029function noop() {}
25030
25031process.on = noop;
25032process.addListener = noop;
25033process.once = noop;
25034process.off = noop;
25035process.removeListener = noop;
25036process.removeAllListeners = noop;
25037process.emit = noop;
vendor: 6,040 bytes, lines 25038-25247
25038
25039process.binding = function (name) {
25040    throw new Error('process.binding is not supported');
25041};
25042
25043process.cwd = function () { return '/' };
25044process.chdir = function (dir) {
25045    throw new Error('process.chdir is not supported');
25046};
25047process.umask = function() { return 0; };
25048
25049},{}],13:[function(require,module,exports){
25050// Copyright Joyent, Inc. and other Node contributors.
25051//
25052// Permission is hereby granted, free of charge, to any person obtaining a
25053// copy of this software and associated documentation files (the
25054// "Software"), to deal in the Software without restriction, including
25055// without limitation the rights to use, copy, modify, merge, publish,
25056// distribute, sublicense, and/or sell copies of the Software, and to permit
25057// persons to whom the Software is furnished to do so, subject to the
25058// following conditions:
25059//
25060// The above copyright notice and this permission notice shall be included
25061// in all copies or substantial portions of the Software.
25062//
25063// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
25064// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25065// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
25066// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
25067// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
25068// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
25069// USE OR OTHER DEALINGS IN THE SOFTWARE.
25070
25071'use strict';
25072
25073// If obj.hasOwnProperty has been overridden, then calling
25074// obj.hasOwnProperty(prop) will break.
25075// See: https://github.com/joyent/node/issues/1707
25076function hasOwnProperty(obj, prop) {
25077  return Object.prototype.hasOwnProperty.call(obj, prop);
25078}
25079
25080module.exports = function(qs, sep, eq, options) {
25081  sep = sep || '&';
25082  eq = eq || '=';
25083  var obj = {};
25084
25085  if (typeof qs !== 'string' || qs.length === 0) {
25086    return obj;
25087  }
25088
25089  var regexp = /\+/g;
25090  qs = qs.split(sep);
25091
25092  var maxKeys = 1000;
25093  if (options && typeof options.maxKeys === 'number') {
25094    maxKeys = options.maxKeys;
25095  }
25096
25097  var len = qs.length;
25098  // maxKeys <= 0 means that we should not limit keys count
25099  if (maxKeys > 0 && len > maxKeys) {
25100    len = maxKeys;
25101  }
25102
25103  for (var i = 0; i < len; ++i) {
25104    var x = qs[i].replace(regexp, '%20'),
25105        idx = x.indexOf(eq),
25106        kstr, vstr, k, v;
25107
25108    if (idx >= 0) {
25109      kstr = x.substr(0, idx);
25110      vstr = x.substr(idx + 1);
25111    } else {
25112      kstr = x;
25113      vstr = '';
25114    }
25115
25116    k = decodeURIComponent(kstr);
25117    v = decodeURIComponent(vstr);
25118
25119    if (!hasOwnProperty(obj, k)) {
25120      obj[k] = v;
25121    } else if (isArray(obj[k])) {
25122      obj[k].push(v);
25123    } else {
25124      obj[k] = [obj[k], v];
25125    }
25126  }
25127
25128  return obj;
25129};
25130
25131var isArray = Array.isArray || function (xs) {
25132  return Object.prototype.toString.call(xs) === '[object Array]';
25133};
25134
25135},{}],14:[function(require,module,exports){
25136// Copyright Joyent, Inc. and other Node contributors.
25137//
25138// Permission is hereby granted, free of charge, to any person obtaining a
25139// copy of this software and associated documentation files (the
25140// "Software"), to deal in the Software without restriction, including
25141// without limitation the rights to use, copy, modify, merge, publish,
25142// distribute, sublicense, and/or sell copies of the Software, and to permit
25143// persons to whom the Software is furnished to do so, subject to the
25144// following conditions:
25145//
25146// The above copyright notice and this permission notice shall be included
25147// in all copies or substantial portions of the Software.
25148//
25149// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
25150// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25151// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
25152// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
25153// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
25154// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
25155// USE OR OTHER DEALINGS IN THE SOFTWARE.
25156
25157'use strict';
25158
25159var stringifyPrimitive = function(v) {
25160  switch (typeof v) {
25161    case 'string':
25162      return v;
25163
25164    case 'boolean':
25165      return v ? 'true' : 'false';
25166
25167    case 'number':
25168      return isFinite(v) ? v : '';
25169
25170    default:
25171      return '';
25172  }
25173};
25174
25175module.exports = function(obj, sep, eq, name) {
25176  sep = sep || '&';
25177  eq = eq || '=';
25178  if (obj === null) {
25179    obj = undefined;
25180  }
25181
25182  if (typeof obj === 'object') {
25183    return map(objectKeys(obj), function(k) {
25184      var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
25185      if (isArray(obj[k])) {
25186        return map(obj[k], function(v) {
25187          return ks + encodeURIComponent(stringifyPrimitive(v));
25188        }).join(sep);
25189      } else {
25190        return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
25191      }
25192    }).join(sep);
25193
25194  }
25195
25196  if (!name) return '';
25197  return encodeURIComponent(stringifyPrimitive(name)) + eq +
25198         encodeURIComponent(stringifyPrimitive(obj));
25199};
25200
25201var isArray = Array.isArray || function (xs) {
25202  return Object.prototype.toString.call(xs) === '[object Array]';
25203};
25204
25205function map (xs, f) {
25206  if (xs.map) return xs.map(f);
25207  var res = [];
25208  for (var i = 0; i < xs.length; i++) {
25209    res.push(f(xs[i], i));
25210  }
25211  return res;
25212}
25213
25214var objectKeys = Object.keys || function (obj) {
25215  var res = [];
25216  for (var key in obj) {
25217    if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
25218  }
25219  return res;
25220};
25221
25222},{}],15:[function(require,module,exports){
25223'use strict';
25224
25225exports.decode = exports.parse = require(13);
25226exports.encode = exports.stringify = require(14);
25227
25228},{"13":13,"14":14}],16:[function(require,module,exports){
25229module.exports = AlgoliaSearch;
25230
25231var Index = require(18);
25232var deprecate = require(28);
25233var deprecatedMessage = require(29);
25234var AlgoliaSearchCore = require(17);
25235var inherits = require(7);
25236var errors = require(30);
25237
25238function AlgoliaSearch() {
25239  AlgoliaSearchCore.apply(this, arguments);
25240}
25241
25242inherits(AlgoliaSearch, AlgoliaSearchCore);
25243
25244/*
25245 * Delete an index
25246 *
25247 * @param indexName the name of index to delete
25248 * @param callback the result callback called with two arguments
25249 *  error: null or Error('message')
25250 *  content: the server answer that contains the task ID
25251 */
25252AlgoliaSearch.prototype.deleteIndex = function(indexName, callback) {
25253  return this._jsonRequest({
25254    method: 'DELETE',
25255    url: '/1/indexes/' + encodeURIComponent(indexName),
25256    hostType: 'write',
25257    callback: callback
25258  });
25259};
25260
25261/**
25262 * Move an existing index.
25263 * @param srcIndexName the name of index to copy.
25264 * @param dstIndexName the new index name that will contains a copy of
25265 * srcIndexName (destination will be overriten if it already exist).
25266 * @param callback the result callback called with two arguments
25267 *  error: null or Error('message')
25268 *  content: the server answer that contains the task ID
25269 */
25270AlgoliaSearch.prototype.moveIndex = function(srcIndexName, dstIndexName, callback) {
25271  var postObj = {
25272    operation: 'move', destination: dstIndexName
25273  };
25274  return this._jsonRequest({
25275    method: 'POST',
25276    url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
25277    body: postObj,
25278    hostType: 'write',
25279    callback: callback
25280  });
25281};
25282
25283/**
25284 * Copy an existing index.
25285 * @param srcIndexName the name of index to copy.
25286 * @param dstIndexName the new index name that will contains a copy
25287 * of srcIndexName (destination will be overriten if it already exist).
25288 * @param scope an array of scopes to copy: ['settings', 'synonyms', 'rules']
25289 * @param callback the result callback called with two arguments
25290 *  error: null or Error('message')
25291 *  content: the server answer that contains the task ID
25292 */
25293AlgoliaSearch.prototype.copyIndex = function(srcIndexName, dstIndexName, scopeOrCallback, _callback) {
25294  var postObj = {
25295    operation: 'copy',
25296    destination: dstIndexName
25297  };
25298  var callback = _callback;
25299  if (typeof scopeOrCallback === 'function') {
25300    // oops, old behaviour of third argument being a function
25301    callback = scopeOrCallback;
25302  } else if (Array.isArray(scopeOrCallback) && scopeOrCallback.length > 0) {
25303    postObj.scope = scopeOrCallback;
25304  } else if (typeof scopeOrCallback !== 'undefined') {
25305    throw new Error('the scope given to `copyIndex` was not an array with settings, synonyms or rules');
25306  }
25307  return this._jsonRequest({
25308    method: 'POST',
25309    url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
25310    body: postObj,
25311    hostType: 'write',
25312    callback: callback
25313  });
25314};
25315
25316/**
25317 * Return last log entries.
25318 * @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
25319 * @param length Specify the maximum number of entries to retrieve starting
25320 * at offset. Maximum allowed value: 1000.
25321 * @param type Specify the maximum number of entries to retrieve starting
25322 * at offset. Maximum allowed value: 1000.
25323 * @param callback the result callback called with two arguments
25324 *  error: null or Error('message')
25325 *  content: the server answer that contains the task ID
25326 */
25327AlgoliaSearch.prototype.getLogs = function(offset, length, callback) {
25328  var clone = require(26);
25329  var params = {};
25330  if (typeof offset === 'object') {
25331    // getLogs(params)
25332    params = clone(offset);
25333    callback = length;
25334  } else if (arguments.length === 0 || typeof offset === 'function') {
25335    // getLogs([cb])
25336    callback = offset;
25337  } else if (arguments.length === 1 || typeof length === 'function') {
25338    // getLogs(1, [cb)]
25339    callback = length;
25340    params.offset = offset;
25341  } else {
25342    // getLogs(1, 2, [cb])
25343    params.offset = offset;
25344    params.length = length;
25345  }
25346
25347  if (params.offset === undefined) params.offset = 0;
25348  if (params.length === undefined) params.length = 10;
25349
25350  return this._jsonRequest({
25351    method: 'GET',
25352    url: '/1/logs?' + this._getSearchParams(params, ''),
25353    hostType: 'read',
25354    callback: callback
25355  });
25356};
25357
25358/*
25359 * List all existing indexes (paginated)
25360 *
25361 * @param page The page to retrieve, starting at 0.
25362 * @param callback the result callback called with two arguments
25363 *  error: null or Error('message')
25364 *  content: the server answer with index list
25365 */
25366AlgoliaSearch.prototype.listIndexes = function(page, callback) {
25367  var params = '';
25368
25369  if (page === undefined || typeof page === 'function') {
25370    callback = page;
25371  } else {
25372    params = '?page=' + page;
25373  }
25374
25375  return this._jsonRequest({
25376    method: 'GET',
25377    url: '/1/indexes' + params,
25378    hostType: 'read',
25379    callback: callback
25380  });
25381};
25382
25383/*
25384 * Get the index object initialized
25385 *
25386 * @param indexName the name of index
25387 * @param callback the result callback with one argument (the Index instance)
25388 */
25389AlgoliaSearch.prototype.initIndex = function(indexName) {
25390  return new Index(this, indexName);
25391};
25392
25393AlgoliaSearch.prototype.initAnalytics = function(opts) {
25394  // the actual require must be inside the function, when put outside then you have a cyclic dependency
25395  // not well resolved that ends up making the main "./index.js" (main module, the agloliasearch function)
25396  // export an object instead of a function
25397  // Other workarounds:
25398  // - rewrite the lib in ES6, cyclic dependencies may be better supported
25399  // - move initAnalytics to a property on the main module (algoliasearch.initAnalytics),
25400  // same as places.
25401  // The current API was made mostly to mimic the one made in PHP
25402  var createAnalyticsClient = require(27);
25403  return createAnalyticsClient(this.applicationID, this.apiKey, opts);
25404};
25405
25406/*
25407 * @deprecated use client.listApiKeys
25408 */
25409AlgoliaSearch.prototype.listUserKeys = deprecate(function(callback) {
25410  return this.listApiKeys(callback);
25411}, deprecatedMessage('client.listUserKeys()', 'client.listApiKeys()'));
25412
25413/*
25414 * List all existing api keys with their associated ACLs
25415 *
25416 * @param callback the result callback called with two arguments
25417 *  error: null or Error('message')
25418 *  content: the server answer with api keys list
25419 */
25420AlgoliaSearch.prototype.listApiKeys = function(callback) {
25421  return this._jsonRequest({
25422    method: 'GET',
25423    url: '/1/keys',
25424    hostType: 'read',
25425    callback: callback
25426  });
25427};
25428
25429/*
25430 * @deprecated see client.getApiKey
25431 */
25432AlgoliaSearch.prototype.getUserKeyACL = deprecate(function(key, callback) {
25433  return this.getApiKey(key, callback);
25434}, deprecatedMessage('client.getUserKeyACL()', 'client.getApiKey()'));
25435
25436/*
25437 * Get an API key
25438 *
25439 * @param key
25440 * @param callback the result callback called with two arguments
25441 *  error: null or Error('message')
25442 *  content: the server answer with the right API key
25443 */
25444AlgoliaSearch.prototype.getApiKey = function(key, callback) {
25445  return this._jsonRequest({
25446    method: 'GET',
25447    url: '/1/keys/' + key,
25448    hostType: 'read',
25449    callback: callback
25450  });
25451};
25452
25453/*
25454 * @deprecated see client.deleteApiKey
25455 */
25456AlgoliaSearch.prototype.deleteUserKey = deprecate(function(key, callback) {
25457  return this.deleteApiKey(key, callback);
25458}, deprecatedMessage('client.deleteUserKey()', 'client.deleteApiKey()'));
25459
25460/*
25461 * Delete an existing API key
25462 * @param key
25463 * @param callback the result callback called with two arguments
25464 *  error: null or Error('message')
25465 *  content: the server answer with the date of deletion
25466 */
25467AlgoliaSearch.prototype.deleteApiKey = function(key, callback) {
25468  return this._jsonRequest({
25469    method: 'DELETE',
25470    url: '/1/keys/' + key,
25471    hostType: 'write',
25472    callback: callback
25473  });
25474};
25475
25476/**
25477 * Restore a deleted API key
25478 *
25479 * @param {String} key - The key to restore
25480 * @param {Function} callback - The result callback called with two arguments
25481 *   error: null or Error('message')
25482 *   content: the server answer with the restored API key
25483 * @return {Promise|undefined} Returns a promise if no callback given
25484 * @example
25485 * client.restoreApiKey('APIKEY')
25486 * @see {@link https://www.algolia.com/doc/rest-api/search/#restore-api-key|Algolia REST API Documentation}
25487 */
25488AlgoliaSearch.prototype.restoreApiKey = function(key, callback) {
25489  return this._jsonRequest({
25490    method: 'POST',
25491    url: '/1/keys/' + key + '/restore',
25492    hostType: 'write',
25493    callback: callback
25494  });
25495};
25496
25497/*
25498 @deprecated see client.addApiKey
25499 */
25500AlgoliaSearch.prototype.addUserKey = deprecate(function(acls, params, callback) {
25501  return this.addApiKey(acls, params, callback);
25502}, deprecatedMessage('client.addUserKey()', 'client.addApiKey()'));
25503
25504/*
25505 * Add a new global API key
25506 *
25507 * @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
25508 *   can contains the following values:
25509 *     - search: allow to search (https and http)
25510 *     - addObject: allows to add/update an object in the index (https only)
25511 *     - deleteObject : allows to delete an existing object (https only)
25512 *     - deleteIndex : allows to delete index content (https only)
25513 *     - settings : allows to get index settings (https only)
25514 *     - editSettings : allows to change index settings (https only)
25515 * @param {Object} [params] - Optionnal parameters to set for the key
25516 * @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key)
25517 * @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
25518 * @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
25519 * @param {string[]} params.indexes - Allowed targeted indexes for this key
25520 * @param {string} params.description - A description for your key
25521 * @param {string[]} params.referers - A list of authorized referers
25522 * @param {Object} params.queryParameters - Force the key to use specific query parameters
25523 * @param {Function} callback - The result callback called with two arguments
25524 *   error: null or Error('message')
25525 *   content: the server answer with the added API key
25526 * @return {Promise|undefined} Returns a promise if no callback given
25527 * @example
25528 * client.addApiKey(['search'], {
25529 *   validity: 300,
25530 *   maxQueriesPerIPPerHour: 2000,
25531 *   maxHitsPerQuery: 3,
25532 *   indexes: ['fruits'],
25533 *   description: 'Eat three fruits',
25534 *   referers: ['*.algolia.com'],
25535 *   queryParameters: {
25536 *     tagFilters: ['public'],
25537 *   }
25538 * })
25539 * @see {@link https://www.algolia.com/doc/rest_api#AddKey|Algolia REST API Documentation}
25540 */
25541AlgoliaSearch.prototype.addApiKey = function(acls, params, callback) {
25542  var isArray = require(8);
25543  var usage = 'Usage: client.addApiKey(arrayOfAcls[, params, callback])';
25544
25545  if (!isArray(acls)) {
25546    throw new Error(usage);
25547  }
25548
25549  if (arguments.length === 1 || typeof params === 'function') {
25550    callback = params;
25551    params = null;
25552  }
25553
25554  var postObj = {
25555    acl: acls
25556  };
25557
25558  if (params) {
25559    postObj.validity = params.validity;
25560    postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
25561    postObj.maxHitsPerQuery = params.maxHitsPerQuery;
25562    postObj.indexes = params.indexes;
25563    postObj.description = params.description;
25564
25565    if (params.queryParameters) {
25566      postObj.queryParameters = this._getSearchParams(params.queryParameters, '');
25567    }
25568
25569    postObj.referers = params.referers;
25570  }
25571
25572  return this._jsonRequest({
25573    method: 'POST',
25574    url: '/1/keys',
25575    body: postObj,
25576    hostType: 'write',
25577    callback: callback
25578  });
25579};
25580
25581/**
25582 * @deprecated Please use client.addApiKey()
25583 */
25584AlgoliaSearch.prototype.addUserKeyWithValidity = deprecate(function(acls, params, callback) {
25585  return this.addApiKey(acls, params, callback);
25586}, deprecatedMessage('client.addUserKeyWithValidity()', 'client.addApiKey()'));
25587
25588/**
25589 * @deprecated Please use client.updateApiKey()
25590 */
25591AlgoliaSearch.prototype.updateUserKey = deprecate(function(key, acls, params, callback) {
25592  return this.updateApiKey(key, acls, params, callback);
25593}, deprecatedMessage('client.updateUserKey()', 'client.updateApiKey()'));
25594
25595/**
25596 * Update an existing API key
25597 * @param {string} key - The key to update
25598 * @param {string[]} acls - The list of ACL for this key. Defined by an array of str
25598ings that
25599 *   can contains the following values:
25600 *     - search: allow to search (https and http)
25601 *     - addObject: allows to add/update an object in the index (https only)
25602 *     - deleteObject : allows to delete an existing object (https only)
25603 *     - deleteIndex : allows to delete index content (https only)
25604 *     - settings : allows to get index settings (https only)
25605 *     - editSettings : allows to change index settings (https only)
25606 * @param {Object} [params] - Optionnal parameters to set for the key
25607 * @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key)
25608 * @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
25609 * @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
25610 * @param {string[]} params.indexes - Allowed targeted indexes for this key
25611 * @param {string} params.description - A description for your key
25612 * @param {string[]} params.referers - A list of authorized referers
25613 * @param {Object} params.queryParameters - Force the key to use specific query parameters
25614 * @param {Function} callback - The result callback called with two arguments
25615 *   error: null or Error('message')
25616 *   content: the server answer with the modified API key
25617 * @return {Promise|undefined} Returns a promise if no callback given
25618 * @example
25619 * client.updateApiKey('APIKEY', ['search'], {
25620 *   validity: 300,
25621 *   maxQueriesPerIPPerHour: 2000,
25622 *   maxHitsPerQuery: 3,
25623 *   indexes: ['fruits'],
25624 *   description: 'Eat three fruits',
25625 *   referers: ['*.algolia.com'],
25626 *   queryParameters: {
25627 *     tagFilters: ['public'],
25628 *   }
25629 * })
25630 * @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation}
25631 */
25632AlgoliaSearch.prototype.updateApiKey = function(key, acls, params, callback) {
25633  var isArray = require(8);
25634  var usage = 'Usage: client.updateApiKey(key, arrayOfAcls[, params, callback])';
25635
25636  if (!isArray(acls)) {
25637    throw new Error(usage);
25638  }
25639
25640  if (arguments.length === 2 || typeof params === 'function') {
25641    callback = params;
25642    params = null;
25643  }
25644
25645  var putObj = {
25646    acl: acls
25647  };
25648
25649  if (params) {
25650    putObj.validity = params.validity;
25651    putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
25652    putObj.maxHitsPerQuery = params.maxHitsPerQuery;
25653    putObj.indexes = params.indexes;
25654    putObj.description = params.description;
25655
25656    if (params.queryParameters) {
25657      putObj.queryParameters = this._getSearchParams(params.queryParameters, '');
25658    }
25659
25660    putObj.referers = params.referers;
25661  }
25662
25663  return this._jsonRequest({
25664    method: 'PUT',
25665    url: '/1/keys/' + key,
25666    body: putObj,
25667    hostType: 'write',
25668    callback: callback
25669  });
25670};
25671
25672/**
25673 * Initialize a new batch of search queries
25674 * @deprecated use client.search()
25675 */
25676AlgoliaSearch.prototype.startQueriesBatch = deprecate(function startQueriesBatchDeprecated() {
25677  this._batch = [];
25678}, deprecatedMessage('client.startQueriesBatch()', 'client.search()'));
25679
25680/**
25681 * Add a search query in the batch
25682 * @deprecated use client.search()
25683 */
25684AlgoliaSearch.prototype.addQueryInBatch = deprecate(function addQueryInBatchDeprecated(indexName, query, args) {
25685  this._batch.push({
25686    indexName: indexName,
25687    query: query,
25688    params: args
25689  });
25690}, deprecatedMessage('client.addQueryInBatch()', 'client.search()'));
25691
25692/**
25693 * Launch the batch of queries using XMLHttpRequest.
25694 * @deprecated use client.search()
25695 */
25696AlgoliaSearch.prototype.sendQueriesBatch = deprecate(function sendQueriesBatchDeprecated(callback) {
25697  return this.search(this._batch, callback);
25698}, deprecatedMessage('client.sendQueriesBatch()', 'client.search()'));
25699
25700/**
25701 * Perform write operations across multiple indexes.
25702 *
25703 * To reduce the amount of time spent on network round trips,
25704 * you can create, update, or delete several objects in one call,
25705 * using the batch endpoint (all operations are done in the given order).
25706 *
25707 * Available actions:
25708 *   - addObject
25709 *   - updateObject
25710 *   - partialUpdateObject
25711 *   - partialUpdateObjectNoCreate
25712 *   - deleteObject
25713 *
25714 * https://www.algolia.com/doc/rest_api#Indexes
25715 * @param  {Object[]} operations An array of operations to perform
25716 * @return {Promise|undefined} Returns a promise if no callback given
25717 * @example
25718 * client.batch([{
25719 *   action: 'addObject',
25720 *   indexName: 'clients',
25721 *   body: {
25722 *     name: 'Bill'
25723 *   }
25724 * }, {
25725 *   action: 'udpateObject',
25726 *   indexName: 'fruits',
25727 *   body: {
25728 *     objectID: '29138',
25729 *     name: 'banana'
25730 *   }
25731 * }], cb)
25732 */
25733AlgoliaSearch.prototype.batch = function(operations, callback) {
25734  var isArray = require(8);
25735  var usage = 'Usage: client.batch(operations[, callback])';
25736
25737  if (!isArray(operations)) {
25738    throw new Error(usage);
25739  }
25740
25741  return this._jsonRequest({
25742    method: 'POST',
25743    url: '/1/indexes/*/batch',
25744    body: {
25745      requests: operations
25746    },
25747    hostType: 'write',
25748    callback: callback
25749  });
25750};
25751
25752/**
25753 * Assign or Move a userID to a cluster
25754 *
25755 * @param {string} data.userID The userID to assign to a new cluster
25756 * @param {string} data.cluster The cluster to assign the user to
25757 * @return {Promise|undefined} Returns a promise if no callback given
25758 * @example
25759 * client.assignUserID({ cluster: 'c1-test', userID: 'some-user' });
25760 */
25761AlgoliaSearch.prototype.assignUserID = function(data, callback) {
25762  if (!data.userID || !data.cluster) {
25763    throw new errors.AlgoliaSearchError('You have to provide both a userID and cluster', data);
25764  }
25765  return this._jsonRequest({
25766    method: 'POST',
25767    url: '/1/clusters/mapping',
25768    hostType: 'write',
25769    body: {cluster: data.cluster},
25770    callback: callback,
25771    headers: {
25772      'x-algolia-user-id': data.userID
25773    }
25774  });
25775};
25776
25777/**
25778 * Assign a array of userIDs to a cluster.
25779 *
25780 * @param {Array} data.userIDs The array of userIDs to assign to a new cluster
25781 * @param {string} data.cluster The cluster to assign the user to
25782 * @return {Promise|undefined} Returns a promise if no callback given
25783 * @example
25784 * client.assignUserIDs({ cluster: 'c1-test', userIDs: ['some-user-1', 'some-user-2'] });
25785 */
25786AlgoliaSearch.prototype.assignUserIDs = function(data, callback) {
25787  if (!data.userIDs || !data.cluster) {
25788    throw new errors.AlgoliaSearchError('You have to provide both an array of userIDs and cluster', data);
25789  }
25790  return this._jsonRequest({
25791    method: 'POST',
25792    url: '/1/clusters/mapping/batch',
25793    hostType: 'write',
25794    body: {
25795      cluster: data.cluster,
25796      users: data.userIDs
25797    },
25798    callback: callback
25799  });
25800};
25801
25802/**
25803 * Get the top userIDs
25804 *
25805 * (the callback is the second argument)
25806 *
25807 * @return {Promise|undefined} Returns a promise if no callback given
25808 * @example
25809 * client.getTopUserID();
25810 */
25811AlgoliaSearch.prototype.getTopUserID = function(callback) {
25812  return this._jsonRequest({
25813    method: 'GET',
25814    url: '/1/clusters/mapping/top',
25815    hostType: 'read',
25816    callback: callback
25817  });
25818};
25819
25820/**
25821 * Get userID
25822 *
25823 * @param {string} data.userID The userID to get info about
25824 * @return {Promise|undefined} Returns a promise if no callback given
25825 * @example
25826 * client.getUserID({ userID: 'some-user' });
25827 */
25828AlgoliaSearch.prototype.getUserID = function(data, callback) {
25829  if (!data.userID) {
25830    throw new errors.AlgoliaSearchError('You have to provide a userID', {debugData: data});
25831  }
25832  return this._jsonRequest({
25833    method: 'GET',
25834    url: '/1/clusters/mapping/' + data.userID,
25835    hostType: 'read',
25836    callback: callback
25837  });
25838};
25839
25840/**
25841 * List all the clusters
25842 *
25843 * (the callback is the second argument)
25844 *
25845 * @return {Promise|undefined} Returns a promise if no callback given
25846 * @example
25847 * client.listClusters();
25848 */
25849AlgoliaSearch.prototype.listClusters = function(callback) {
25850  return this._jsonRequest({
25851    method: 'GET',
25852    url: '/1/clusters',
25853    hostType: 'read',
25854    callback: callback
25855  });
25856};
25857
25858/**
25859 * List the userIDs
25860 *
25861 * (the callback is the second argument)
25862 *
25863 * @param {string} data.hitsPerPage How many hits on every page
25864 * @param {string} data.page The page to retrieve
25865 * @return {Promise|undefined} Returns a promise if no callback given
25866 * @example
25867 * client.listClusters();
25868 * client.listClusters({ page: 3, hitsPerPage: 30});
25869 */
25870AlgoliaSearch.prototype.listUserIDs = function(data, callback) {
25871  return this._jsonRequest({
25872    method: 'GET',
25873    url: '/1/clusters/mapping',
25874    body: data,
25875    hostType: 'read',
25876    callback: callback
25877  });
25878};
25879
25880/**
25881 * Remove an userID
25882 *
25883 * @param {string} data.userID The userID to assign to a new cluster
25884 * @return {Promise|undefined} Returns a promise if no callback given
25885 * @example
25886 * client.removeUserID({ userID: 'some-user' });
25887 */
25888AlgoliaSearch.prototype.removeUserID = function(data, callback) {
25889  if (!data.userID) {
25890    throw new errors.AlgoliaSearchError('You have to provide a userID', {debugData: data});
25891  }
25892  return this._jsonRequest({
25893    method: 'DELETE',
25894    url: '/1/clusters/mapping',
25895    hostType: 'write',
25896    callback: callback,
25897    headers: {
25898      'x-algolia-user-id': data.userID
25899    }
25900  });
25901};
25902
25903/**
25904 * Search for userIDs
25905 *
25906 * @param {string} data.cluster The cluster to target
25907 * @param {string} data.query The query to execute
25908 * @param {string} data.hitsPerPage How many hits on every page
25909 * @param {string} data.page The page to retrieve
25910 * @return {Promise|undefined} Returns a promise if no callback given
25911 * @example
25912 * client.searchUserIDs({ cluster: 'c1-test', query: 'some-user' });
25913 * client.searchUserIDs({
25914 *   cluster: "c1-test",
25915 *   query: "some-user",
25916 *   page: 3,
25917 *   hitsPerPage: 2
25918 * });
25919 */
25920AlgoliaSearch.prototype.searchUserIDs = function(data, callback) {
25921  return this._jsonRequest({
25922    method: 'POST',
25923    url: '/1/clusters/mapping/search',
25924    body: data,
25925    hostType: 'read',
25926    callback: callback
25927  });
25928};
25929
25930/**
25931 * Set strategy for personalization
25932 *
25933 * @param {Object} data
25934 * @param {Object} data.eventsScoring Associate a score to an event
25935 * @param {Object} data.eventsScoring.<eventName> The name of the event
25936 * @param {Number} data.eventsScoring.<eventName>.score The score to associate to <eventName>
25937 * @param {String} data.eventsScoring.<eventName>.type Either "click", "conversion" or "view"
25938 * @param {Object} data.facetsScoring Associate a score to a facet
25939 * @param {Object} data.facetsScoring.<facetName> The name of the facet
25940 * @param {Number} data.facetsScoring.<facetName>.score The score to associate to <facetName>
25941 * @return {Promise|undefined} Returns a promise if no callback given
25942 * @example
25943 * client.setPersonalizationStrategy({
25944 *   eventsScoring: {
25945 *      "Add to cart": { score: 50, type: "conversion" },
25946 *      Purchase: { score: 100, type: "conversion" }
25947 *   },
25948 *   facetsScoring: {
25949 *      brand: { score: 100 },
25950 *      categories: { score: 10 }
25951 *   }
25952 * });
25953 */
25954AlgoliaSearch.prototype.setPersonalizationStrategy = function(data, callback) {
25955  return this._jsonRequest({
25956    method: 'POST',
25957    url: '/1/recommendation/personalization/strategy',
25958    body: data,
25959    hostType: 'write',
25960    callback: callback
25961  });
25962};
25963
25964/**
25965 * Get strategy for personalization
25966 *
25967 * @return {Promise|undefined} Returns a promise if no callback given
25968 * @example
25969 * client.getPersonalizationStrategy();
25970 */
25971
25972AlgoliaSearch.prototype.getPersonalizationStrategy = function(callback) {
25973  return this._jsonRequest({
25974    method: 'GET',
25975    url: '/1/recommendation/personalization/strategy',
25976    hostType: 'read',
25977    callback: callback
25978  });
25979};
25980
25981// environment specific methods
25982AlgoliaSearch.prototype.destroy = notImplemented;
25983AlgoliaSearch.prototype.enableRateLimitForward = notImplemented;
25984AlgoliaSearch.prototype.disableRateLimitForward = notImplemented;
25985AlgoliaSearch.prototype.useSecuredAPIKey = notImplemented;
25986AlgoliaSearch.prototype.disableSecuredAPIKey = notImplemented;
25987AlgoliaSearch.prototype.generateSecuredApiKey = notImplemented;
25988AlgoliaSearch.prototype.getSecuredApiKeyRemainingValidity = notImplemented;
25989
25990function notImplemented() {
25991  var message = 'Not implemented in this environment.\n' +
vendor: 19,084 bytes, lines 25992-26567
25992    'If you feel this is a mistake, write to [email protected]';
25993
25994  throw new errors.AlgoliaSearchError(message);
25995}
25996
25997},{"17":17,"18":18,"26":26,"27":27,"28":28,"29":29,"30":30,"7":7,"8":8}],17:[function(require,module,exports){
25998(function (process){
25999module.exports = AlgoliaSearchCore;
26000
26001var errors = require(30);
26002var exitPromise = require(31);
26003var IndexCore = require(20);
26004var store = require(36);
26005
26006// We will always put the API KEY in the JSON body in case of too long API KEY,
26007// to avoid query string being too long and failing in various conditions (our server limit, browser limit,
26008// proxies limit)
26009var MAX_API_KEY_LENGTH = 500;
26010var RESET_APP_DATA_TIMER =
26011  process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) ||
26012  60 * 2 * 1000; // after 2 minutes reset to first host
26013
26014/*
26015 * Algolia Search library initialization
26016 * https://www.algolia.com/
26017 *
26018 * @param {string} applicationID - Your applicationID, found in your dashboard
26019 * @param {string} apiKey - Your API key, found in your dashboard
26020 * @param {Object} [opts]
26021 * @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
26022 * another request will be issued after this timeout
26023 * @param {string} [opts.protocol='https:'] - The protocol used to query Algolia Search API.
26024 *                                        Set to 'http:' to force using http.
26025 * @param {Object|Array} [opts.hosts={
26026 *           read: [this.applicationID + '-dsn.algolia.net'].concat([
26027 *             this.applicationID + '-1.algolianet.com',
26028 *             this.applicationID + '-2.algolianet.com',
26029 *             this.applicationID + '-3.algolianet.com']
26030 *           ]),
26031 *           write: [this.applicationID + '.algolia.net'].concat([
26032 *             this.applicationID + '-1.algolianet.com',
26033 *             this.applicationID + '-2.algolianet.com',
26034 *             this.applicationID + '-3.algolianet.com']
26035 *           ]) - The hosts to use for Algolia Search API.
26036 *           If you provide them, you will less benefit from our HA implementation
26037 */
26038function AlgoliaSearchCore(applicationID, apiKey, opts) {
26039  var debug = require(1)('algoliasearch');
26040
26041  var clone = require(26);
26042  var isArray = require(8);
26043  var map = require(32);
26044
26045  var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
26046
26047  if (opts._allowEmptyCredentials !== true && !applicationID) {
26048    throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
26049  }
26050
26051  if (opts._allowEmptyCredentials !== true && !apiKey) {
26052    throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
26053  }
26054
26055  this.applicationID = applicationID;
26056  this.apiKey = apiKey;
26057
26058  this.hosts = {
26059    read: [],
26060    write: []
26061  };
26062
26063  opts = opts || {};
26064
26065  this._timeouts = opts.timeouts || {
26066    connect: 1 * 1000, // 500ms connect is GPRS latency
26067    read: 2 * 1000,
26068    write: 30 * 1000
26069  };
26070
26071  // backward compat, if opts.timeout is passed, we use it to configure all timeouts like before
26072  if (opts.timeout) {
26073    this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout;
26074  }
26075
26076  var protocol = opts.protocol || 'https:';
26077  // while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
26078  // we also accept `http` and `https`. It's a common error.
26079  if (!/:$/.test(protocol)) {
26080    protocol = protocol + ':';
26081  }
26082
26083  if (protocol !== 'http:' && protocol !== 'https:') {
26084    throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
26085  }
26086
26087  this._checkAppIdData();
26088
26089  if (!opts.hosts) {
26090    var defaultHosts = map(this._shuffleResult, function(hostNumber) {
26091      return applicationID + '-' + hostNumber + '.algolianet.com';
26092    });
26093
26094    // no hosts given, compute defaults
26095    var mainSuffix = (opts.dsn === false ? '' : '-dsn') + '.algolia.net';
26096    this.hosts.read = [this.applicationID + mainSuffix].concat(defaultHosts);
26097    this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
26098  } else if (isArray(opts.hosts)) {
26099    // when passing custom hosts, we need to have a different host index if the number
26100    // of write/read hosts are different.
26101    this.hosts.read = clone(opts.hosts);
26102    this.hosts.write = clone(opts.hosts);
26103  } else {
26104    this.hosts.read = clone(opts.hosts.read);
26105    this.hosts.write = clone(opts.hosts.write);
26106  }
26107
26108  // add protocol and lowercase hosts
26109  this.hosts.read = map(this.hosts.read, prepareHost(protocol));
26110  this.hosts.write = map(this.hosts.write, prepareHost(protocol));
26111
26112  this.extraHeaders = {};
26113
26114  // In some situations you might want to warm the cache
26115  this.cache = opts._cache || {};
26116
26117  this._ua = opts._ua;
26118  this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
26119  this._useRequestCache = this._useCache && opts._useRequestCache;
26120  this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
26121
26122  this._setTimeout = opts._setTimeout;
26123
26124  debug('init done, %j', this);
26125}
26126
26127/*
26128 * Get the index object initialized
26129 *
26130 * @param indexName the name of index
26131 * @param callback the result callback with one argument (the Index instance)
26132 */
26133AlgoliaSearchCore.prototype.initIndex = function(indexName) {
26134  return new IndexCore(this, indexName);
26135};
26136
26137/**
26138* Add an extra field to the HTTP request
26139*
26140* @param name the header field name
26141* @param value the header field value
26142*/
26143AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
26144  this.extraHeaders[name.toLowerCase()] = value;
26145};
26146
26147/**
26148* Get the value of an extra HTTP header
26149*
26150* @param name the header field name
26151*/
26152AlgoliaSearchCore.prototype.getExtraHeader = function(name) {
26153  return this.extraHeaders[name.toLowerCase()];
26154};
26155
26156/**
26157* Remove an extra field from the HTTP request
26158*
26159* @param name the header field name
26160*/
26161AlgoliaSearchCore.prototype.unsetExtraHeader = function(name) {
26162  delete this.extraHeaders[name.toLowerCase()];
26163};
26164
26165/**
26166* Augment sent x-algolia-agent with more data, each agent part
26167* is automatically separated from the others by a semicolon;
26168*
26169* @param algoliaAgent the agent to add
26170*/
26171AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
26172  var algoliaAgentWithDelimiter = '; ' + algoliaAgent;
26173
26174  if (this._ua.indexOf(algoliaAgentWithDelimiter) === -1) {
26175    this._ua += algoliaAgentWithDelimiter;
26176  }
26177};
26178
26179/*
26180 * Wrapper that try all hosts to maximize the quality of service
26181 */
26182AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
26183  this._checkAppIdData();
26184
26185  var requestDebug = require(1)('algoliasearch:' + initialOpts.url);
26186
26187
26188  var body;
26189  var cacheID;
26190  var additionalUA = initialOpts.additionalUA || '';
26191  var cache = initialOpts.cache;
26192  var client = this;
26193  var tries = 0;
26194  var usingFallback = false;
26195  var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
26196  var headers;
26197
26198  if (
26199    this.apiKey.length > MAX_API_KEY_LENGTH &&
26200    initialOpts.body !== undefined &&
26201    (initialOpts.body.params !== undefined || // index.search()
26202    initialOpts.body.requests !== undefined) // client.search()
26203  ) {
26204    initialOpts.body.apiKey = this.apiKey;
26205    headers = this._computeRequestHeaders({
26206      additionalUA: additionalUA,
26207      withApiKey: false,
26208      headers: initialOpts.headers
26209    });
26210  } else {
26211    headers = this._computeRequestHeaders({
26212      additionalUA: additionalUA,
26213      headers: initialOpts.headers
26214    });
26215  }
26216
26217  if (initialOpts.body !== undefined) {
26218    body = safeJSONStringify(initialOpts.body);
26219  }
26220
26221  requestDebug('request start');
26222  var debugData = [];
26223
26224
26225  function doRequest(requester, reqOpts) {
26226    client._checkAppIdData();
26227
26228    var startTime = new Date();
26229
26230    if (client._useCache && !client._useRequestCache) {
26231      cacheID = initialOpts.url;
26232    }
26233
26234    // as we sometime use POST requests to pass parameters (like query='aa'),
26235    // the cacheID must also include the body to be different between calls
26236    if (client._useCache && !client._useRequestCache && body) {
26237      cacheID += '_body_' + reqOpts.body;
26238    }
26239
26240    // handle cache existence
26241    if (isCacheValidWithCurrentID(!client._useRequestCache, cache, cacheID)) {
26242      requestDebug('serving response from cache');
26243
26244      var responseText = cache[cacheID];
26245
26246      // Cache response must match the type of the original one
26247      return client._promise.resolve({
26248        body: JSON.parse(responseText),
26249        responseText: responseText
26250      });
26251    }
26252
26253    // if we reached max tries
26254    if (tries >= client.hosts[initialOpts.hostType].length) {
26255      if (!hasFallback || usingFallback) {
26256        requestDebug('could not get any response');
26257        // then stop
26258        return client._promise.reject(new errors.AlgoliaSearchError(
26259          'Cannot connect to the AlgoliaSearch API.' +
26260          ' Send an email to [email protected] to report and resolve the issue.' +
26261          ' Application id was: ' + client.applicationID, {debugData: debugData}
26262        ));
26263      }
26264
26265      requestDebug('switching to fallback');
26266
26267      // let's try the fallback starting from here
26268      tries = 0;
26269
26270      // method, url and body are fallback dependent
26271      reqOpts.method = initialOpts.fallback.method;
26272      reqOpts.url = initialOpts.fallback.url;
26273      reqOpts.jsonBody = initialOpts.fallback.body;
26274      if (reqOpts.jsonBody) {
26275        reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
26276      }
26277      // re-compute headers, they could be omitting the API KEY
26278      headers = client._computeRequestHeaders({
26279        additionalUA: additionalUA,
26280        headers: initialOpts.headers
26281      });
26282
26283      reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
26284      client._setHostIndexByType(0, initialOpts.hostType);
26285      usingFallback = true; // the current request is now using fallback
26286      return doRequest(client._request.fallback, reqOpts);
26287    }
26288
26289    var currentHost = client._getHostByType(initialOpts.hostType);
26290
26291    var url = currentHost + reqOpts.url;
26292    var options = {
26293      body: reqOpts.body,
26294      jsonBody: reqOpts.jsonBody,
26295      method: reqOpts.method,
26296      headers: headers,
26297      timeouts: reqOpts.timeouts,
26298      debug: requestDebug,
26299      forceAuthHeaders: reqOpts.forceAuthHeaders
26300    };
26301
26302    requestDebug('method: %s, url: %s, headers: %j, timeouts: %d',
26303      options.method, url, options.headers, options.timeouts);
26304
26305    if (requester === client._request.fallback) {
26306      requestDebug('using fallback');
26307    }
26308
26309    // `requester` is any of this._request or this._request.fallback
26310    // thus it needs to be called using the client as context
26311    return requester.call(client, url, options).then(success, tryFallback);
26312
26313    function success(httpResponse) {
26314      // compute the status of the response,
26315      //
26316      // When in browser mode, using XDR or JSONP, we have no statusCode available
26317      // So we rely on our API response `status` property.
26318      // But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
26319      // So we check if there's a `message` along `status` and it means it's an error
26320      //
26321      // That's the only case where we have a response.status that's not the http statusCode
26322      var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
26323
26324        // this is important to check the request statusCode AFTER the body eventual
26325        // statusCode because some implementations (jQuery XDomainRequest transport) may
26326        // send statusCode 200 while we had an error
26327        httpResponse.statusCode ||
26328
26329        // When in browser mode, using XDR or JSONP
26330        // we default to success when no error (no response.status && response.message)
26331        // If there was a JSON.parse() error then body is null and it fails
26332        httpResponse && httpResponse.body && 200;
26333
26334      requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
26335        httpResponse.statusCode, status, httpResponse.headers);
26336
26337      var httpResponseOk = Math.floor(status / 100) === 2;
26338
26339      var endTime = new Date();
26340      debugData.push({
26341        currentHost: currentHost,
26342        headers: removeCredentials(headers),
26343        content: body || null,
26344        contentLength: body !== undefined ? body.length : null,
26345        method: reqOpts.method,
26346        timeouts: reqOpts.timeouts,
26347        url: reqOpts.url,
26348        startTime: startTime,
26349        endTime: endTime,
26350        duration: endTime - startTime,
26351        statusCode: status
26352      });
26353
26354      if (httpResponseOk) {
26355        if (client._useCache && !client._useRequestCache && cache) {
26356          cache[cacheID] = httpResponse.responseText;
26357        }
26358
26359        return {
26360          responseText: httpResponse.responseText,
26361          body: httpResponse.body
26362        };
26363      }
26364
26365      var shouldRetry = Math.floor(status / 100) !== 4;
26366
26367      if (shouldRetry) {
26368        tries += 1;
26369        return retryRequest();
26370      }
26371
26372      requestDebug('unrecoverable error');
26373
26374      // no success and no retry => fail
26375      var unrecoverableError = new errors.AlgoliaSearchError(
26376        httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
26377      );
26378
26379      return client._promise.reject(unrecoverableError);
26380    }
26381
26382    function tryFallback(err) {
26383      // error cases:
26384      //  While not in fallback mode:
26385      //    - CORS not supported
26386      //    - network error
26387      //  While in fallback mode:
26388      //    - timeout
26389      //    - network error
26390      //    - badly formatted JSONP (script loaded, did not call our callback)
26391      //  In both cases:
26392      //    - uncaught exception occurs (TypeError)
26393      requestDebug('error: %s, stack: %s', err.message, err.stack);
26394
26395      var endTime = new Date();
26396      debugData.push({
26397        currentHost: currentHost,
26398        headers: removeCredentials(headers),
26399        content: body || null,
26400        contentLength: body !== undefined ? body.length : null,
26401        method: reqOpts.method,
26402        timeouts: reqOpts.timeouts,
26403        url: reqOpts.url,
26404        startTime: startTime,
26405        endTime: endTime,
26406        duration: endTime - startTime
26407      });
26408
26409      if (!(err instanceof errors.AlgoliaSearchError)) {
26410        err = new errors.Unknown(err && err.message, err);
26411      }
26412
26413      tries += 1;
26414
26415      // stop the request implementation when:
26416      if (
26417        // we did not generate this error,
26418        // it comes from a throw in some other piece of code
26419        err instanceof errors.Unknown ||
26420
26421        // server sent unparsable JSON
26422        err instanceof errors.UnparsableJSON ||
26423
26424        // max tries and already using fallback or no fallback
26425        tries >= client.hosts[initialOpts.hostType].length &&
26426        (usingFallback || !hasFallback)) {
26427        // stop request implementation for this command
26428        err.debugData = debugData;
26429        return client._promise.reject(err);
26430      }
26431
26432      // When a timeout occurred, retry by raising timeout
26433      if (err instanceof errors.RequestTimeout) {
26434        return retryRequestWithHigherTimeout();
26435      }
26436
26437      return retryRequest();
26438    }
26439
26440    function retryRequest() {
26441      requestDebug('retrying request');
26442      client._incrementHostIndex(initialOpts.hostType);
26443      return doRequest(requester, reqOpts);
26444    }
26445
26446    function retryRequestWithHigherTimeout() {
26447      requestDebug('retrying request with higher timeout');
26448      client._incrementHostIndex(initialOpts.hostType);
26449      client._incrementTimeoutMultipler();
26450      reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
26451      return doRequest(requester, reqOpts);
26452    }
26453  }
26454
26455  function isCacheValidWithCurrentID(
26456    useRequestCache,
26457    currentCache,
26458    currentCacheID
26459  ) {
26460    return (
26461      client._useCache &&
26462      useRequestCache &&
26463      currentCache &&
26464      currentCache[currentCacheID] !== undefined
26465    );
26466  }
26467
26468
26469  function interopCallbackReturn(request, callback) {
26470    if (isCacheValidWithCurrentID(client._useRequestCache, cache, cacheID)) {
26471      request.catch(function() {
26472        // Release the cache on error
26473        delete cache[cacheID];
26474      });
26475    }
26476
26477    if (typeof initialOpts.callback === 'function') {
26478      // either we have a callback
26479      request.then(function okCb(content) {
26480        exitPromise(function() {
26481          initialOpts.callback(null, callback(content));
26482        }, client._setTimeout || setTimeout);
26483      }, function nookCb(err) {
26484        exitPromise(function() {
26485          initialOpts.callback(err);
26486        }, client._setTimeout || setTimeout);
26487      });
26488    } else {
26489      // either we are using promises
26490      return request.then(callback);
26491    }
26492  }
26493
26494  if (client._useCache && client._useRequestCache) {
26495    cacheID = initialOpts.url;
26496  }
26497
26498  // as we sometime use POST requests to pass parameters (like query='aa'),
26499  // the cacheID must also include the body to be different between calls
26500  if (client._useCache && client._useRequestCache && body) {
26501    cacheID += '_body_' + body;
26502  }
26503
26504  if (isCacheValidWithCurrentID(client._useRequestCache, cache, cacheID)) {
26505    requestDebug('serving request from cache');
26506
26507    var maybePromiseForCache = cache[cacheID];
26508
26509    // In case the cache is warmup with value that is not a promise
26510    var promiseForCache = typeof maybePromiseForCache.then !== 'function'
26511      ? client._promise.resolve({responseText: maybePromiseForCache})
26512      : maybePromiseForCache;
26513
26514    return interopCallbackReturn(promiseForCache, function(content) {
26515      // In case of the cache request, return the original value
26516      return JSON.parse(content.responseText);
26517    });
26518  }
26519
26520  var request = doRequest(
26521    client._request, {
26522      url: initialOpts.url,
26523      method: initialOpts.method,
26524      body: body,
26525      jsonBody: initialOpts.body,
26526      timeouts: client._getTimeoutsForRequest(initialOpts.hostType),
26527      forceAuthHeaders: initialOpts.forceAuthHeaders
26528    }
26529  );
26530
26531  if (client._useCache && client._useRequestCache && cache) {
26532    cache[cacheID] = request;
26533  }
26534
26535  return interopCallbackReturn(request, function(content) {
26536    // In case of the first request, return the JSON value
26537    return content.body;
26538  });
26539};
26540
26541/*
26542* Transform search param object in query string
26543* @param {object} args arguments to add to the current query string
26544* @param {string} params current query string
26545* @return {string} the final query string
26546*/
26547AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
26548  if (args === undefined || args === null) {
26549    return params;
26550  }
26551  for (var key in args) {
26552    if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
26553      params += params === '' ? '' : '&';
26554      params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
26555    }
26556  }
26557  return params;
26558};
26559
26560/**
26561 * Compute the headers for a request
26562 *
26563 * @param [string] options.additionalUA semi-colon separated string with other user agents to add
26564 * @param [boolean=true] options.withApiKey Send the api key as a header
26565 * @param [Object] options.headers Extra headers to send
26566 */
26567AlgoliaSearchCore.prototype._computeRequestHeaders = function(options) {
vendor: 11,502 bytes, lines 26568-26968
26568  var forEach = require(5);
26569
26570  var ua = options.additionalUA ?
26571    this._ua + '; ' + options.additionalUA :
26572    this._ua;
26573
26574  var requestHeaders = {
26575    'x-algolia-agent': ua,
26576    'x-algolia-application-id': this.applicationID
26577  };
26578
26579  // browser will inline headers in the url, node.js will use http headers
26580  // but in some situations, the API KEY will be too long (big secured API keys)
26581  // so if the request is a POST and the KEY is very long, we will be asked to not put
26582  // it into headers but in the JSON body
26583  if (options.withApiKey !== false) {
26584    requestHeaders['x-algolia-api-key'] = this.apiKey;
26585  }
26586
26587  if (this.userToken) {
26588    requestHeaders['x-algolia-usertoken'] = this.userToken;
26589  }
26590
26591  if (this.securityTags) {
26592    requestHeaders['x-algolia-tagfilters'] = this.securityTags;
26593  }
26594
26595  forEach(this.extraHeaders, function addToRequestHeaders(value, key) {
26596    requestHeaders[key] = value;
26597  });
26598
26599  if (options.headers) {
26600    forEach(options.headers, function addToRequestHeaders(value, key) {
26601      requestHeaders[key] = value;
26602    });
26603  }
26604
26605  return requestHeaders;
26606};
26607
26608/**
26609 * Search through multiple indices at the same time
26610 * @param  {Object[]}   queries  An array of queries you want to run.
26611 * @param {string} queries[].indexName The index name you want to target
26612 * @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
26613 * @param {Object} queries[].params Any search param like hitsPerPage, ..
26614 * @param  {Function} callback Callback to be called
26615 * @return {Promise|undefined} Returns a promise if no callback given
26616 */
26617AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
26618  var isArray = require(8);
26619  var map = require(32);
26620
26621  var usage = 'Usage: client.search(arrayOfQueries[, callback])';
26622
26623  if (!isArray(queries)) {
26624    throw new Error(usage);
26625  }
26626
26627  if (typeof opts === 'function') {
26628    callback = opts;
26629    opts = {};
26630  } else if (opts === undefined) {
26631    opts = {};
26632  }
26633
26634  var client = this;
26635
26636  var postObj = {
26637    requests: map(queries, function prepareRequest(query) {
26638      var params = '';
26639
26640      // allow query.query
26641      // so we are mimicing the index.search(query, params) method
26642      // {indexName:, query:, params:}
26643      if (query.query !== undefined) {
26644        params += 'query=' + encodeURIComponent(query.query);
26645      }
26646
26647      return {
26648        indexName: query.indexName,
26649        params: client._getSearchParams(query.params, params)
26650      };
26651    })
26652  };
26653
26654  var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
26655    return requestId + '=' +
26656      encodeURIComponent(
26657        '/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
26658        request.params
26659      );
26660  }).join('&');
26661
26662  var url = '/1/indexes/*/queries';
26663
26664  if (opts.strategy !== undefined) {
26665    postObj.strategy = opts.strategy;
26666  }
26667
26668  return this._jsonRequest({
26669    cache: this.cache,
26670    method: 'POST',
26671    url: url,
26672    body: postObj,
26673    hostType: 'read',
26674    fallback: {
26675      method: 'GET',
26676      url: '/1/indexes/*',
26677      body: {
26678        params: JSONPParams
26679      }
26680    },
26681    callback: callback
26682  });
26683};
26684
26685/**
26686* Search for facet values
26687* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
26688* This is the top-level API for SFFV.
26689*
26690* @param {object[]} queries An array of queries to run.
26691* @param {string} queries[].indexName Index name, name of the index to search.
26692* @param {object} queries[].params Query parameters.
26693* @param {string} queries[].params.facetName Facet name, name of the attribute to search for values in.
26694* Must be declared as a facet
26695* @param {string} queries[].params.facetQuery Query for the facet search
26696* @param {string} [queries[].params.*] Any search parameter of Algolia,
26697* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
26698* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
26699*/
26700AlgoliaSearchCore.prototype.searchForFacetValues = function(queries) {
26701  var isArray = require(8);
26702  var map = require(32);
26703
26704  var usage = 'Usage: client.searchForFacetValues([{indexName, params: {facetName, facetQuery, ...params}}, ...queries])'; // eslint-disable-line max-len
26705
26706  if (!isArray(queries)) {
26707    throw new Error(usage);
26708  }
26709
26710  var client = this;
26711
26712  return client._promise.all(map(queries, function performQuery(query) {
26713    if (
26714      !query ||
26715      query.indexName === undefined ||
26716      query.params.facetName === undefined ||
26717      query.params.facetQuery === undefined
26718    ) {
26719      throw new Error(usage);
26720    }
26721
26722    var clone = require(26);
26723    var omit = require(34);
26724
26725    var indexName = query.indexName;
26726    var params = query.params;
26727
26728    var facetName = params.facetName;
26729    var filteredParams = omit(clone(params), function(keyName) {
26730      return keyName === 'facetName';
26731    });
26732    var searchParameters = client._getSearchParams(filteredParams, '');
26733
26734    return client._jsonRequest({
26735      cache: client.cache,
26736      method: 'POST',
26737      url:
26738        '/1/indexes/' +
26739        encodeURIComponent(indexName) +
26740        '/facets/' +
26741        encodeURIComponent(facetName) +
26742        '/query',
26743      hostType: 'read',
26744      body: {params: searchParameters}
26745    });
26746  }));
26747};
26748
26749/**
26750 * Set the extra security tagFilters header
26751 * @param {string|array} tags The list of tags defining the current security filters
26752 */
26753AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
26754  if (Object.prototype.toString.call(tags) === '[object Array]') {
26755    var strTags = [];
26756    for (var i = 0; i < tags.length; ++i) {
26757      if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
26758        var oredTags = [];
26759        for (var j = 0; j < tags[i].length; ++j) {
26760          oredTags.push(tags[i][j]);
26761        }
26762        strTags.push('(' + oredTags.join(',') + ')');
26763      } else {
26764        strTags.push(tags[i]);
26765      }
26766    }
26767    tags = strTags.join(',');
26768  }
26769
26770  this.securityTags = tags;
26771};
26772
26773/**
26774 * Set the extra user token header
26775 * @param {string} userToken The token identifying a uniq user (used to apply rate limits)
26776 */
26777AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
26778  this.userToken = userToken;
26779};
26780
26781/**
26782 * Clear all queries in client's cache
26783 * @return undefined
26784 */
26785AlgoliaSearchCore.prototype.clearCache = function() {
26786  this.cache = {};
26787};
26788
26789/**
26790* Set the number of milliseconds a request can take before automatically being terminated.
26791* @deprecated
26792* @param {Number} milliseconds
26793*/
26794AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
26795  if (milliseconds) {
26796    this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds;
26797  }
26798};
26799
26800/**
26801* Set the three different (connect, read, write) timeouts to be used when requesting
26802* @param {Object} timeouts
26803*/
26804AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) {
26805  this._timeouts = timeouts;
26806};
26807
26808/**
26809* Get the three different (connect, read, write) timeouts to be used when requesting
26810* @param {Object} timeouts
26811*/
26812AlgoliaSearchCore.prototype.getTimeouts = function() {
26813  return this._timeouts;
26814};
26815
26816AlgoliaSearchCore.prototype._getAppIdData = function() {
26817  var data = store.get(this.applicationID);
26818  if (data !== null) this._cacheAppIdData(data);
26819  return data;
26820};
26821
26822AlgoliaSearchCore.prototype._setAppIdData = function(data) {
26823  data.lastChange = (new Date()).getTime();
26824  this._cacheAppIdData(data);
26825  return store.set(this.applicationID, data);
26826};
26827
26828AlgoliaSearchCore.prototype._checkAppIdData = function() {
26829  var data = this._getAppIdData();
26830  var now = (new Date()).getTime();
26831  if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) {
26832    return this._resetInitialAppIdData(data);
26833  }
26834
26835  return data;
26836};
26837
26838AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) {
26839  var newData = data || {};
26840  newData.hostIndexes = {read: 0, write: 0};
26841  newData.timeoutMultiplier = 1;
26842  newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]);
26843  return this._setAppIdData(newData);
26844};
26845
26846AlgoliaSearchCore.prototype._cacheAppIdData = function(data) {
26847  this._hostIndexes = data.hostIndexes;
26848  this._timeoutMultiplier = data.timeoutMultiplier;
26849  this._shuffleResult = data.shuffleResult;
26850};
26851
26852AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) {
26853  var foreach = require(5);
26854  var currentData = this._getAppIdData();
26855  foreach(newData, function(value, key) {
26856    currentData[key] = value;
26857  });
26858
26859  return this._setAppIdData(currentData);
26860};
26861
26862AlgoliaSearchCore.prototype._getHostByType = function(hostType) {
26863  return this.hosts[hostType][this._getHostIndexByType(hostType)];
26864};
26865
26866AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() {
26867  return this._timeoutMultiplier;
26868};
26869
26870AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) {
26871  return this._hostIndexes[hostType];
26872};
26873
26874AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) {
26875  var clone = require(26);
26876  var newHostIndexes = clone(this._hostIndexes);
26877  newHostIndexes[hostType] = hostIndex;
26878  this._partialAppIdDataUpdate({hostIndexes: newHostIndexes});
26879  return hostIndex;
26880};
26881
26882AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) {
26883  return this._setHostIndexByType(
26884    (this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType
26885  );
26886};
26887
26888AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() {
26889  var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4);
26890  return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier});
26891};
26892
26893AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) {
26894  return {
26895    connect: this._timeouts.connect * this._timeoutMultiplier,
26896    complete: this._timeouts[hostType] * this._timeoutMultiplier
26897  };
26898};
26899
26900function prepareHost(protocol) {
26901  return function prepare(host) {
26902    return protocol + '//' + host.toLowerCase();
26903  };
26904}
26905
26906// Prototype.js < 1.7, a widely used library, defines a weird
26907// Array.prototype.toJSON function that will fail to stringify our content
26908// appropriately
26909// refs:
26910//   - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
26911//   - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
26912//   - http://stackoverflow.com/a/3148441/147079
26913function safeJSONStringify(obj) {
26914  /* eslint no-extend-native:0 */
26915
26916  if (Array.prototype.toJSON === undefined) {
26917    return JSON.stringify(obj);
26918  }
26919
26920  var toJSON = Array.prototype.toJSON;
26921  delete Array.prototype.toJSON;
26922  var out = JSON.stringify(obj);
26923  Array.prototype.toJSON = toJSON;
26924
26925  return out;
26926}
26927
26928function shuffle(array) {
26929  var currentIndex = array.length;
26930  var temporaryValue;
26931  var randomIndex;
26932
26933  // While there remain elements to shuffle...
26934  while (currentIndex !== 0) {
26935    // Pick a remaining element...
26936    randomIndex = Math.floor(Math.random() * currentIndex);
26937    currentIndex -= 1;
26938
26939    // And swap it with the current element.
26940    temporaryValue = array[currentIndex];
26941    array[currentIndex] = array[randomIndex];
26942    array[randomIndex] = temporaryValue;
26943  }
26944
26945  return array;
26946}
26947
26948function removeCredentials(headers) {
26949  var newHeaders = {};
26950
26951  for (var headerName in headers) {
26952    if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
26953      var value;
26954
26955      if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
26956        value = '**hidden for security purposes**';
26957      } else {
26958        value = headers[headerName];
26959      }
26960
26961      newHeaders[headerName] = value;
26962    }
26963  }
26964
26965  return newHeaders;
26966}
26967
26968}
26968).call(this,require(12))
26969},{"1":1,"12":12,"20":20,"26":26,"30":30,"31":31,"32":32,"34":34,"36":36,"5":5,"8":8}],18:[function(require,module,exports){
26970var inherits = require(7);
26971var IndexCore = require(20);
26972var deprecate = require(28);
26973var deprecatedMessage = require(29);
26974var exitPromise = require(31);
26975var errors = require(30);
26976
26977var deprecateForwardToSlaves = deprecate(
26978  function() {},
26979  deprecatedMessage('forwardToSlaves', 'forwardToReplicas')
26980);
26981
26982module.exports = Index;
26983
26984function Index() {
26985  IndexCore.apply(this, arguments);
26986}
26987
26988inherits(Index, IndexCore);
26989
26990/*
26991* Add an object in this index
26992*
26993* @param content contains the javascript object to add inside the index
26994* @param objectID (optional) an objectID you want to attribute to this object
26995* (if the attribute already exist the old object will be overwrite)
26996* @param callback (optional) the result callback called with two arguments:
26997*  error: null or Error('message')
26998*  content: the server answer that contains 3 elements: createAt, taskId and objectID
26999*/
27000Index.prototype.addObject = function(content, objectID, callback) {
27001  var indexObj = this;
27002
27003  if (arguments.length === 1 || typeof objectID === 'function') {
27004    callback = objectID;
27005    objectID = undefined;
27006  }
27007
27008  return this.as._jsonRequest({
27009    method: objectID !== undefined ?
27010    'PUT' : // update or create
27011    'POST', // create (API generates an objectID)
27012    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + // create
27013    (objectID !== undefined ? '/' + encodeURIComponent(objectID) : ''), // update or create
27014    body: content,
27015    hostType: 'write',
27016    callback: callback
27017  });
27018};
27019
27020/*
27021* Add several objects
27022*
27023* @param objects contains an array of objects to add
27024* @param callback (optional) the result callback called with two arguments:
27025*  error: null or Error('message')
27026*  content: the server answer that updateAt and taskID
27027*/
27028Index.prototype.addObjects = function(objects, callback) {
27029  var isArray = require(8);
27030  var usage = 'Usage: index.addObjects(arrayOfObjects[, callback])';
27031
27032  if (!isArray(objects)) {
27033    throw new Error(usage);
27034  }
27035
27036  var indexObj = this;
27037  var postObj = {
27038    requests: []
27039  };
27040  for (var i = 0; i < objects.length; ++i) {
27041    var request = {
27042      action: 'addObject',
27043      body: objects[i]
27044    };
27045    postObj.requests.push(request);
27046  }
27047  return this.as._jsonRequest({
27048    method: 'POST',
27049    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
27050    body: postObj,
27051    hostType: 'write',
27052    callback: callback
27053  });
27054};
27055
27056/*
27057* Update partially an object (only update attributes passed in argument)
27058*
27059* @param partialObject contains the javascript attributes to override, the
27060*  object must contains an objectID attribute
27061* @param createIfNotExists (optional) if false, avoid an automatic creation of the object
27062* @param callback (optional) the result callback called with two arguments:
27063*  error: null or Error('message')
27064*  content: the server answer that contains 3 elements: createAt, taskId and objectID
27065*/
27066Index.prototype.partialUpdateObject = function(partialObject, createIfNotExists, callback) {
27067  if (arguments.length === 1 || typeof createIfNotExists === 'function') {
27068    callback = createIfNotExists;
27069    createIfNotExists = undefined;
27070  }
27071
27072  var indexObj = this;
27073  var url = '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(partialObject.objectID) + '/partial';
27074  if (createIfNotExists === false) {
27075    url += '?createIfNotExists=false';
27076  }
27077
27078  return this.as._jsonRequest({
27079    method: 'POST',
27080    url: url,
27081    body: partialObject,
27082    hostType: 'write',
27083    callback: callback
27084  });
27085};
27086
27087/*
27088* Partially Override the content of several objects
27089*
27090* @param objects contains an array of objects to update (each object must contains a objectID attribute)
27091* @param callback (optional) the result callback called with two arguments:
27092*  error: null or Error('message')
27093*  content: the server answer that updateAt and taskID
27094*/
27095Index.prototype.partialUpdateObjects = function(objects, createIfNotExists, callback) {
27096  if (arguments.length === 1 || typeof createIfNotExists === 'function') {
27097    callback = createIfNotExists;
27098    createIfNotExists = true;
27099  }
27100
27101  var isArray = require(8);
27102  var usage = 'Usage: index.partialUpdateObjects(arrayOfObjects[, callback])';
27103
27104  if (!isArray(objects)) {
27105    throw new Error(usage);
27106  }
27107
27108  var indexObj = this;
27109  var postObj = {
27110    requests: []
27111  };
27112  for (var i = 0; i < objects.length; ++i) {
27113    var request = {
27114      action: createIfNotExists === true ? 'partialUpdateObject' : 'partialUpdateObjectNoCreate',
27115      objectID: objects[i].objectID,
27116      body: objects[i]
27117    };
27118    postObj.requests.push(request);
27119  }
27120  return this.as._jsonRequest({
27121    method: 'POST',
27122    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
27123    body: postObj,
27124    hostType: 'write',
27125    callback: callback
27126  });
27127};
27128
27129/*
27130* Override the content of object
27131*
27132* @param object contains the javascript object to save, the object must contains an objectID attribute
27133* @param callback (optional) the result callback called with two arguments:
27134*  error: null or Error('message')
27135*  content: the server answer that updateAt and taskID
27136*/
27137Index.prototype.saveObject = function(object, callback) {
27138  var indexObj = this;
27139  return this.as._jsonRequest({
27140    method: 'PUT',
27141    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(object.objectID),
27142    body: object,
27143    hostType: 'write',
27144    callback: callback
27145  });
27146};
27147
27148/*
27149* Override the content of several objects
27150*
27151* @param objects contains an array of objects to update (each object must contains a objectID attribute)
27152* @param callback (optional) the result callback called with two arguments:
27153*  error: null or Error('message')
27154*  content: the server answer that updateAt and taskID
27155*/
27156Index.prototype.saveObjects = function(objects, callback) {
27157  var isArray = require(8);
27158  var usage = 'Usage: index.saveObjects(arrayOfObjects[, callback])';
27159
27160  if (!isArray(objects)) {
27161    throw new Error(usage);
27162  }
27163
27164  var indexObj = this;
27165  var postObj = {
27166    requests: []
27167  };
27168  for (var i = 0; i < objects.length; ++i) {
27169    var request = {
27170      action: 'updateObject',
27171      objectID: objects[i].objectID,
27172      body: objects[i]
27173    };
27174    postObj.requests.push(request);
27175  }
27176  return this.as._jsonRequest({
27177    method: 'POST',
27178    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
27179    body: postObj,
27180    hostType: 'write',
27181    callback: callback
27182  });
27183};
27184
27185/*
27186* Delete an object from the index
27187*
27188* @param objectID the unique identifier of object to delete
27189* @param callback (optional) the result callback called with two arguments:
27190*  error: null or Error('message')
27191*  content: the server answer that contains 3 elements: createAt, taskId and objectID
27192*/
27193Index.prototype.deleteObject = function(objectID, callback) {
27194  if (typeof objectID === 'function' || typeof objectID !== 'string' && typeof objectID !== 'number') {
27195    var err = new errors.AlgoliaSearchError(
27196      objectID && typeof objectID !== 'function'
27197      ? 'ObjectID must be a string'
27198      : 'Cannot delete an object without an objectID'
27199    );
27200    callback = objectID;
27201    if (typeof callback === 'function') {
27202      return callback(err);
27203    }
27204
27205    return this.as._promise.reject(err);
27206  }
27207
27208  var indexObj = this;
27209  return this.as._jsonRequest({
27210    method: 'DELETE',
27211    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID),
27212    hostType: 'write',
27213    callback: callback
27214  });
27215};
27216
27217/*
27218* Delete several objects from an index
27219*
27220* @param objectIDs contains an array of objectID to delete
27221* @param callback (optional) the result callback called with two arguments:
27222*  error: null or Error('message')
27223*  content: the server answer that contains 3 elements: createAt, taskId and objectID
27224*/
27225Index.prototype.deleteObjects = function(objectIDs, callback) {
27226  var isArray = require(8);
27227  var map = require(32);
27228
27229  var usage = 'Usage: index.deleteObjects(arrayOfObjectIDs[, callback])';
27230
27231  if (!isArray(objectIDs)) {
27232    throw new Error(usage);
27233  }
27234
27235  var indexObj = this;
27236  var postObj = {
27237    requests: map(objectIDs, function prepareRequest(objectID) {
27238      return {
27239        action: 'deleteObject',
27240        objectID: objectID,
27241        body: {
27242          objectID: objectID
27243        }
27244      };
27245    })
27246  };
27247
27248  return this.as._jsonRequest({
27249    method: 'POST',
27250    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch',
27251    body: postObj,
27252    hostType: 'write',
27253    callback: callback
27254  });
27255};
27256
27257/*
27258* Delete all objects matching a query
27259*
27260* @param query the query string
27261* @param params the optional query parameters
27262* @param callback (optional) the result callback called with one argument
27263*  error: null or Error('message')
27264* @deprecated see index.deleteBy
27265*/
27266Index.prototype.deleteByQuery = deprecate(function(query, params, callback) {
27267  var clone = require(26);
27268  var map = require(32);
27269
27270  var indexObj = this;
27271  var client = indexObj.as;
27272
27273  if (arguments.length === 1 || typeof params === 'function') {
27274    callback = params;
27275    params = {};
27276  } else {
27277    params = clone(params);
27278  }
27279
27280  params.attributesToRetrieve = 'objectID';
27281  params.hitsPerPage = 1000;
27282  params.distinct = false;
27283
27284  // when deleting, we should never use cache to get the
27285  // search results
27286  this.clearCache();
27287
27288  // there's a problem in how we use the promise chain,
27289  // see how waitTask is done
27290  var promise = this
27291  .search(query, params)
27292  .then(stopOrDelete);
27293
27294  function stopOrDelete(searchContent) {
27295    // stop here
27296    if (searchContent.nbHits === 0) {
27297      // return indexObj.as._request.resolve();
27298      return searchContent;
27299    }
27300
27301    // continue and do a recursive call
27302    var objectIDs = map(searchContent.hits, function getObjectID(object) {
27303      return object.objectID;
27304    });
27305
27306    return indexObj
27307    .deleteObjects(objectIDs)
27308    .then(waitTask)
27309    .then(doDeleteByQuery);
27310  }
27311
27312  function waitTask(deleteObjectsContent) {
27313    return indexObj.waitTask(deleteObjectsContent.taskID);
27314  }
27315
27316  function doDeleteByQuery() {
27317    return indexObj.deleteByQuery(query, params);
27318  }
27319
27320  if (!callback) {
27321    return promise;
27322  }
27323
27324  promise.then(success, failure);
27325
27326  function success() {
27327    exitPromise(function exit() {
27328      callback(null);
27329    }, client._setTimeout || setTimeout);
27330  }
27331
27332  function failure(err) {
27333    exitPromise(function exit() {
27334      callback(err);
27335    }, client._setTimeout || setTimeout);
27336  }
27337}, deprecatedMessage('index.deleteByQuery()', 'index.deleteBy()'));
27338
27339/**
27340* Delete all objects matching a query
27341*
27342* the query parameters that can be used are:
27343* - filters (numeric, facet, tag)
27344* - geo
27345*
27346* you can not send an empty query or filters
27347*
27348* @param params the optional query parameters
27349* @param callback (optional) the result callback called with one argument
27350*  error: null or Error('message')
27351*/
27352Index.prototype.deleteBy = function(params, callback) {
27353  var indexObj = this;
27354  return this.as._jsonRequest({
27355    method: 'POST',
27356    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/deleteByQuery',
27357    body: {params: indexObj.as._getSearchParams(params, '')},
27358    hostType: 'write',
27359    callback: callback
27360  });
27361};
27362
27363/*
27364* Browse all content from an index using events. Basically this will do
27365* .browse() -> .browseFrom -> .browseFrom -> .. until all the results are returned
27366*
27367* @param {string} query - The full text query
27368* @param {Object} [queryParameters] - Any search query parameter
27369* @return {EventEmitter}
27370* @example
27371* var browser = index.browseAll('cool songs', {
27372*   tagFilters: 'public,comments',
27373*   hitsPerPage: 500
27374* });
27375*
27376* browser.on('result', function resultCallback(content) {
27377*   console.log(content.hits);
27378* });
27379*
27380* // if any error occurs, you get it
27381* browser.on('error', function(err) {
27382*   throw err;
27383* });
27384*
27385* // when you have browsed the whole index, you get this event
27386* browser.on('end', function() {
27387*   console.log('finished');
27388* });
27389*
27390* // at any point if you want to stop the browsing process, you can stop it manually
27391* // otherwise it will go on and on
27392* browser.stop();
27393*
27394* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
27395*/
27396Index.prototype.browseAll = function(query, queryParameters) {
27397  if (typeof query === 'object') {
27398    queryParameters = query;
27399    query = undefined;
27400  }
27401
27402  var merge = require(33);
27403
27404  var IndexBrowser = require(19);
27405
27406  var browser = new IndexBrowser();
27407  var client = this.as;
27408  var index = this;
27409  var params = client._getSearchParams(
27410    merge({}, queryParameters || {}, {
27411      query: query
27412    }), ''
27413  );
27414
27415  // start browsing
27416  browseLoop();
27417
27418  function browseLoop(cursor) {
27419    if (browser._stopped) {
27420      return;
27421    }
27422
27423    var body;
27424
27425    if (cursor !== undefined) {
27426      body = {
27427        cursor: cursor
27428      };
27429    } else {
27430      body = {
27431        params: params
27432      };
27433    }
27434
27435    client._jsonRequest({
27436      method: 'POST',
27437      url: '/1/indexes/' + encodeURIComponent(index.indexName) + '/browse',
27438      hostType: 'read',
27439      body: body,
27440      callback: browseCallback
27441    });
27442  }
27443
27444  function browseCallback(err, content) {
27445    if (browser._stopped) {
27446      return;
27447    }
27448
27449    if (err) {
27450      browser._error(err);
27451      return;
27452    }
27453
27454    browser._result(content);
27455
27456    // no cursor means we are finished browsing
27457    if (content.cursor === undefined) {
27458      browser._end();
27459      return;
27460    }
27461
27462    browseLoop(content.cursor);
27463  }
27464
27465  return browser;
27466};
27467
27468/*
27469* Get a Typeahead.js adapter
27470* @param searchParams contains an object with query parameters (see search for details)
27471*/
27472Index.prototype.ttAdapter = deprecate(function(params) {
27473  var self = this;
27474  return function ttAdapter(query, syncCb, asyncCb) {
27475    var cb;
27476
27477    if (typeof asyncCb === 'function') {
27478      // typeahead 0.11
27479      cb = asyncCb;
27480    } else {
27481      // pre typeahead 0.11
27482      cb = syncCb;
27483    }
27484
27485    self.search(query, params, function searchDone(err, content) {
27486      if (err) {
27487        cb(err);
27488        return;
27489      }
27490
27491      cb(content.hits);
27492    });
27493  };
27494},
27495'ttAdapter is not necessary anymore and will be removed in the next version,\n' +
27496'have a look at autocomplete.js (https://github.com/algolia/autocomplete.js)');
27497
27498/*
27499* Wait the publication of a task on the server.
27500* All server task are asynchronous and you can check with this method that the task is published.
27501*
27502* @param taskID the id of the task returned by server
27503* @param callback the result callback with with two arguments:
27504*  error: null or Error('message')
27505*  content: the server answer that contains the list of results
27506*/
27507Index.prototype.waitTask = function(taskID, callback) {
27508  // wait minimum 100ms before retrying
27509  var baseDelay = 100;
27510  // wait maximum 5s before retrying
27511  var maxDelay = 5000;
27512  var loop = 0;
27513
27514  // waitTask() must be handled differently from other methods,
27515  // it's a recursive method using a timeout
27516  var indexObj = this;
27517  var client = indexObj.as;
27518
27519  var promise = retryLoop();
27520
27521  function retryLoop() {
27522    return client._jsonRequest({
27523      method: 'GET',
27524      hostType: 'read',
27525      url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/task/' + taskID
27526    }).then(function success(content) {
27527      loop++;
27528      var delay = baseDelay * loop * loop;
27529      if (delay > maxDelay) {
27530        delay = maxDelay;
27531      }
27532
27533      if (content.status !== 'published') {
27534        return client._promise.delay(delay).then(retryLoop);
27535      }
27536
27537      return content;
27538    });
27539  }
27540
27541  if (!callback) {
27542    return promise;
27543  }
27544
27545  promise.then(successCb, failureCb);
27546
27547  function successCb(content) {
27548    exitPromise(function exit() {
27549      callback(null, content);
27550    }, client._setTimeout || setTimeout);
27551  }
27552
27553  function failureCb(err) {
27554    exitPromise(function exit() {
27555      callback(err);
27556    }, client._setTimeout || setTimeout);
27557  }
27558};
27559
27560/*
27561* This function deletes the index content. Settings and index specific API keys are kept untouched.
27562*
27563* @param callback (optional) the result callback called with two arguments
27564*  error: null or Error('message')
27565*  content: the settings object or the error message if a failure occurred
27566*/
27567Index.prototype.clearIndex = function(callback) {
27568  var indexObj = this;
27569  return this.as._jsonRequest({
27570    method: 'POST',
27571    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/clear',
27572    hostType: 'write',
27573    callback: callback
27574  });
27575};
27576
27577/*
27578* Get settings of this index
27579*
27580* @param opts an object of options to add
27581* @param opts.advanced get more settings like nbShards (useful for Enterprise)
27582* @param callback (optional) the result callback called with two arguments
27583*  error: null or Error('message')
27584*  content: the settings object or the error message if a failure occurred
27585*/
27586Index.prototype.getSettings = function(opts, callback) {
27587  if (arguments.length === 1 && typeof opts === 'function') {
27588    callback = opts;
27589    opts = {};
27590  }
27591  opts = opts || {};
27592
27593  var indexName = encodeURIComponent(this.indexName);
27594  return this.as._jsonRequest({
27595    method: 'GET',
27596    url:
27597      '/1/indexes/' +
27598      indexName +
27599      '/settings?getVersion=2' +
27600      (opts.advanced ? '&advanced=' + opts.advanced : ''),
27601    hostType: 'read',
27602    callback: callback
27603  });
27604};
27605
27606Index.prototype.searchSynonyms = function(params, callback) {
27607  if (typeof params === 'function') {
27608    callback = params;
27609    params = {};
27610  } else if (params === undefined) {
27611    params = {};
27612  }
27613
27614  return this.as._jsonRequest({
27615    method: 'POST',
27616    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/search',
27617    body: params,
27618    hostType: 'read',
27619    callback: callback
27620  });
27621};
27622
27623function exportData(method, _hitsPerPage, callback) {
27624  function search(page, _previous) {
27625    var options = {
27626      page: page || 0,
27627      hitsPerPage: _hitsPerPage || 100
27628    };
27629    var previous = _previous || [];
27630
27631    return method(options).then(function(result) {
27632      var hits = result.hits;
27633      var nbHits = result.nbHits;
27634      var current = hits.map(function(s) {
27635        delete s._highlightResult;
27636        return s;
27637      });
27638      var synonyms = previous.concat(current);
27639      if (synonyms.length < nbHits) {
27640        return search(options.page + 1, synonyms);
27641      }
27642      return synonyms;
27643    });
27644  }
27645  return search().then(function(data) {
27646    if (typeof callback === 'function') {
27647      callback(data);
27648      return undefined;
27649    }
27650    return data;
27651  });
27652}
27653
27654/**
27655 * Retrieve all the synonyms in an index
27656 * @param [number=100] hitsPerPage The amount of synonyms to retrieve per batch
27657 * @param [function] callback will be called after all synonyms are retrieved
27658 */
27659Index.prototype.exportSynonyms = function(hitsPerPage, callback) {
27660  return exportData(this.searchSynonyms.bind(this), hitsPerPage, callback);
27661};
27662
27663Index.prototype.saveSynonym = function(synonym, opts, callback) {
27664  if (typeof opts === 'function') {
27665    callback = opts;
27666    opts = {};
27667  } else if (opts === undefined) {
27668    opts = {};
27669  }
27670
27671  if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
27672  var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
27673
27674  return this.as._jsonRequest({
27675    method: 'PUT',
27676    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(synonym.objectID) +
27677      '?forwardToReplicas=' + forwardToReplicas,
27678    body: synonym,
27679    hostType: 'write',
27680    callback: callback
27681  });
27682};
27683
27684Index.prototype.getSynonym = function(objectID, callback) {
27685  return this.as._jsonRequest({
27686    method: 'GET',
27687    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID),
27688    hostType: 'read',
27689    callback: callback
27690  });
27691};
27692
27693Index.prototype.deleteSynonym = function(objectID, opts, callback) {
27694  if (typeof opts === 'function') {
27695    callback = opts;
27696    opts = {};
27697  } else if (opts === undefined) {
27698    opts = {};
27699  }
27700
27701  if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
27702  var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
27703
27704  return this.as._jsonRequest({
27705    method: 'DELETE',
27706    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID) +
27707      '?forwardToReplicas=' + forwardToReplicas,
27708    hostType: 'write',
27709    callback: callback
27710  });
27711};
27712
27713Index.prototype.clearSynonyms = function(opts, callback) {
27714  if (typeof opts === 'function') {
27715    callback = opts;
27716    opts = {};
27717  } else if (opts === undefined) {
27718    opts = {};
27719  }
27720
27721  if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
27722  var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
27723
27724  return this.as._jsonRequest({
27725    method: 'POST',
27726    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/clear' +
27727      '?forwardToReplicas=' + forwardToReplicas,
27728    hostType: 'write',
27729    callback: callback
27730  });
27731};
27732
27733Index.prototype.batchSynonyms = function(synonyms, opts, callback) {
27734  if (typeof opts === 'function') {
27735    callback = opts;
27736    opts = {};
27737  } else if (opts === undefined) {
27738    opts = {};
27739  }
27740
27741  if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
27742  var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
27743
27744  return this.as._jsonRequest({
27745    method: 'POST',
27746    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/batch' +
27747      '?forwardToReplicas=' + forwardToReplicas +
27748      '&replaceExistingSynonyms=' + (opts.replaceExistingSynonyms ? 'true' : 'false'),
27749    hostType: 'write',
27750    body: synonyms,
27751    callback: callback
27752  });
27753};
27754
27755Index.prototype.searchRules = function(params, callback) {
27756  if (typeof params === 'function') {
27757    callback = params;
27758    params = {};
27759  } else if (params === undefined) {
27760    params = {};
27761  }
27762
27763  return this.as._jsonRequest({
27764    method: 'POST',
27765    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/search',
27766    body: params,
27767    hostType: 'read',
27768    callback: callback
27769  });
27770};
27771/**
27772 * Retrieve all the query rules in an index
27773 * @param [number=100] hitsPerPage The amount of query rules to retrieve per batch
27774 * @param [function] callback will be called after all query rules are retrieved
27775 *  error: null or Error('message')
27776 */
27777Index.prototype.exportRules = function(hitsPerPage, callback) {
27778  return exportData(this.searchRules.bind(this), hitsPerPage, callback);
27779};
27780
27781Index.prototype.saveRule = function(rule, opts, callback) {
27782  if (typeof opts === 'function') {
27783    callback = opts;
27784    opts = {};
27785  } else if (opts === undefined) {
27786    opts = {};
27787  }
27788
27789  if (!rule.objectID) {
27790    throw new errors.AlgoliaSearchError('Missing or empty objectID field for rule');
27791  }
27792
27793  var forwardToReplicas = opts.forwardToReplicas === true ? 'true' : 'false';
27794
27795  return this.as._jsonRequest({
27796    method: 'PUT',
27797    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/' + encodeURIComponent(rule.objectID) +
27798      '?forwardToReplicas=' + forwardToReplicas,
27799    body: rule,
27800    hostType: 'write',
27801    callback: callback
27802  });
27803};
27804
27805Index.prototype.getRule = function(objectID, callback) {
27806  return this.as._jsonRequest({
27807    method: 'GET',
27808    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/' + encodeURIComponent(objectID),
27809    hostType: 'read',
27810    callback: callback
27811  });
27812};
27813
27814Index.prototype.deleteRule = function(objectID, opts, callback) {
27815  if (typeof opts === 'function') {
27816    callback = opts;
27817    opts = {};
27818  } else if (opts === undefined) {
27819    opts = {};
27820  }
27821
27822  var forwardToReplicas = opts.forwardToReplicas === true ? 'true' : 'false';
27823
27824  return this.as._jsonRequest({
27825    method: 'DELETE',
27826    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/' + encodeURIComponent(objectID) +
27827      '?forwardToReplicas=' + forwardToReplicas,
27828    hostType: 'write',
27829    callback: callback
27830  });
27831};
27832
27833Index.prototype.clearRules = function(opts, callback) {
27834  if (typeof opts === 'function') {
27835    callback = opts;
27836    opts = {};
27837  } else if (opts === undefined) {
27838    opts = {};
27839  }
27840
27841  var forwardToReplicas = opts.forwardToReplicas === true ? 'true' : 'false';
27842
27843  return this.as._jsonRequest({
27844    method: 'POST',
27845    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/clear' +
27846      '?forwardToReplicas=' + forwardToReplicas,
27847    hostType: 'write',
27848    callback: callback
27849  });
27850};
27851
27852Index.prototype.batchRules = function(rules, opts, callback) {
27853  if (typeof opts === 'function') {
27854    callback = opts;
27855    opts = {};
27856  } else if (opts === undefined) {
27857    opts = {};
27858  }
27859
27860  var forwardToReplicas = opts.forwardToReplicas === true ? 'true' : 'false';
27861
27862  return this.as._jsonRequest({
27863    method: 'POST',
27864    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/rules/batch' +
27865      '?forwardToReplicas=' + forwardToReplicas +
27866      '&clearExistingRules=' + (opts.clearExistingRules === true ? 'true' : 'false'),
27867    hostType: 'write',
27868    body: rules,
27869    callback: callback
27870  });
27871};
27872
27873Index.prototype.exists = function(callback) {
27874  var result = this.getSettings().then(function() {
27875    return true;
27876  }).catch(function(err) {
27877    if (err instanceof errors.AlgoliaSearchError && err.statusCode === 404) {
27878      return false;
27879    }
27880
27881    throw err;
27882  });
27883
27884  if (typeof callback !== 'function') {
27885    return result;
27886  }
27887
27888  result.then(function(res) {
27889    callback(null, res);
27890  }).catch(function(err) {
27891    callback(err);
27892  });
27893};
27894
27895Index.prototype.findObject = function(findCallback, requestOptions, callback) {
27896  requestOptions = requestOptions === undefined ? {} : requestOptions;
27897  var paginate = requestOptions.paginate !== undefined ? requestOptions.paginate : true;
27898  var query = requestOptions.query !== undefined ? requestOptions.query : '';
27899
27900  var that = this;
27901  var page = 0;
27902
27903  var paginateLoop = function() {
27904    requestOptions.page = page;
27905
27906    return that.search(query, requestOptions).then(function(result) {
27907      var hits = result.hits;
27908
27909      for (var position = 0; position < hits.length; position++) {
27910        var hit = hits[position];
27911        if (findCallback(hit)) {
27912          return {
27913            object: hit,
27914            position: position,
27915            page: page
27916          };
27917        }
27918      }
27919
27920      page += 1;
27921
27922      // paginate if option was set and has next page
27923      if (!paginate || page >= result.nbPages) {
27924        throw new errors.ObjectNotFound('Object not found');
27925      }
27926
27927      return paginateLoop();
27928    });
27929  };
27930
27931  var promise = paginateLoop(page);
27932
27933  if (callback === undefined) {
27934    return promise;
27935  }
27936
27937  promise
27938    .then(function(res) {
27939      callback(null, res);
27940    })
27941    .catch(function(err) {
27942      callback(err);
27943    });
27944};
27945
27946Index.prototype.getObjectPosition = function(result, objectID) {
27947  var hits = result.hits;
27948
27949  for (var position = 0; position < hits.length; position++) {
27950    if (hits[position].objectID === objectID) {
27951      return position;
27952    }
27953  }
27954
27955  return -1;
27956};
27957
27958/*
27959* Set settings for this index
27960*
27961* @param settings the settings object that can contains :
27962* - minWordSizefor1Typo: (integer) the minimum number of characters to accept one typo (default = 3).
27963* - minWordSizefor2Typos: (integer) the minimum number of characters to accept two typos (default = 7).
27964* - hitsPerPage: (integer) the number of hits per page (default = 10).
27965* - attributesToRetrieve: (array of strings) default list of attributes to retrieve in objects.
27966*   If set to null, all attributes are retrieved.
27967* - attributesToHighlight: (array of strings) default list of attributes to highlight.
27968*   If set to null, all indexed attributes are highlighted.
27969* - attributesToSnippet**: (array of strings) default list of attributes to snippet alongside the number
27970* of words to return (syntax is attributeName:nbWords).
27971*   By default no snippet is computed. If set to null, no snippet is computed.
27972* - attributesToIndex: (array of strings) the list of fields you want to index.
27973*   If set to null, all textual and numerical attributes of your objects are indexed,
27974*   but you should update it to get optimal results.
27975*   This parameter has two important uses:
27976*     - Limit the attributes to index: For example if you store a binary image in base64,
27977*     you want to store it and be able to
27978*       retrieve it but you don't want to search in the base64 string.
27979*     - Control part of the ranking*: (see the ranking parameter for full explanation)
27980*     Matches in attributes at the beginning of
27981*       the list will be considered more important than matches in attributes further down the list.
27982*       In one attribute, matching text at the beginning of the attribute will be
27983*       considered more important than text after, you can disable
27984*       this behavior if you add your attribute inside `unordered(AttributeName)`,
27985*       for example attributesToIndex: ["title", "unordered(text)"].
27986* - attributesForFaceting: (array of strings) The list of fields you want to use for faceting.
27987*   All strings in the attribute selected for faceting are extracted and added as a facet.
27988*   If set to null, no attribute is used for faceting.
27989* - attributeForDistinct: (string) The attribute name used for the Distinct feature.
27990* This feature is similar to the SQL "distinct" keyword: when enabled
27991*   in query with the distinct=1 parameter, all hits containing a duplicate
27992*   value for this attribute are removed from results.
27993*   For example, if the chosen attribute is show_name and several hits have
27994*   the same value for show_name, then only the best one is kept and others are removed.
27995* - ranking: (array of strings) controls the way results are sorted.
27996*   We have six available criteria:
27997*    - typo: sort according to number of typos,
27998*    - geo: sort according to decreassing distance when performing a geo-location based search,
27999*    - proximity: sort according to the proximity of query words in hits,
28000*    - attribute: sort according to the order of attributes defined by attributesToIndex,
28001*    - exact:
28002*        - if the user query contains one word: sort objects having an attribute
28003*        that is exactly the query word before others.
28004*          For example if you search for the "V" TV show, you want to find it
28005*          with the "V" query and avoid to have all popular TV
28006*          show starting by the v letter before it.
28007*        - if the user query contains multiple words: sort according to the
28008*        number of words that matched exactly (and not as a prefix).
28009*    - custom: sort according to a user defined formula set in **customRanking** attribute.
28010*   The standard order is ["typo", "geo", "proximity", "attribute", "exact", "custom"]
28011* - customRanking: (array of strings) lets you specify part of the ranking.
28012*   The syntax of this condition is an array of strings containing attributes
28013*   prefixed by asc (ascending order) or desc (descending order) operator.
28014*   For example `"customRanking" => ["desc(population)", "asc(name)"]`
28015* - queryType: Select how the query words are interpreted, it can be one of the following value:
28016*   - prefixAll: all query words are interpreted as prefixes,
28017*   - prefixLast: only the last word is interpreted as a prefix (default behavior),
28018*   - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
28019* - highlightPreTag: (string) Specify the string that is inserted before
28020* the highlighted parts in the query result (default to "<em>").
28021* - highlightPostTag: (string) Specify the string that is inserted after
28022* the highlighted parts in the query result (default to "</em>").
28023* - optionalWords: (array of strings) Specify a list of words that should
28024* be considered as optional when found in the query.
28025* @param callback (optional) the result callback called with two arguments
28026*  error: null or Error('message')
28027*  content: the server answer or the error message if a failure occurred
28028*/
28029Index.prototype.setSettings = function(settings, opts, callback) {
28030  if (arguments.length === 1 || typeof opts === 'function') {
28031    callback = opts;
28032    opts = {};
28033  }
28034
28035  if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves();
28036  var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false';
28037
28038  var indexObj = this;
28039  return this.as._jsonRequest({
28040    method: 'PUT',
28041    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings?forwardToReplicas='
28042      + forwardToReplicas,
28043    hostType: 'write',
28044    body: settings,
28045    callback: callback
28046  });
28047};
28048
28049/*
28050* @deprecated see client.listApiKeys()
28051*/
28052Index.prototype.listUserKeys = deprecate(function(callback) {
28053  return this.listApiKeys(callback);
28054}, deprecatedMessage('index.listUserKeys()', 'client.listApiKeys()'));
28055
28056/*
28057* List all existing API keys to this index
28058*
28059* @param callback the result callback called with two arguments
28060*  error: null or Error('message')
28061*  content: the server answer with API keys belonging to the index
28062*
28063* @deprecated see client.listApiKeys()
28064*/
28065Index.prototype.listApiKeys = deprecate(function(callback) {
28066  var indexObj = this;
28067  return this.as._jsonRequest({
28068    method: 'GET',
28069    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys',
28070    hostType: 'read',
28071    callback: callback
28072  });
28073}, deprecatedMessage('index.listApiKeys()', 'client.listApiKeys()'));
28074
28075/*
28076* @deprecated see client.getApiKey()
28077*/
28078Index.prototype.getUserKeyACL = deprecate(function(key, callback) {
28079  return this.getApiKey(key, callback);
28080}, deprecatedMessage('index.getUserKeyACL()', 'client.getApiKey()'));
28081
28082
28083/*
28084* Get an API key from this index
28085*
28086* @param key
28087* @param callback the result callback called with two arguments
28088*  error: null or Error('message')
28089*  content: the server answer with the right API key
28090*
28091* @deprecated see client.getApiKey()
28092*/
28093Index.prototype.getApiKey = deprecate(function(key, callback) {
28094  var indexObj = this;
28095  return this.as._jsonRequest({
28096    method: 'GET',
28097    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key,
28098    hostType: 'read',
28099    callback: callback
28100  });
28101}, deprecatedMessage('index.getApiKey()', 'client.getApiKey()'));
28102
28103/*
28104* @deprecated see client.deleteApiKey()
28105*/
28106Index.prototype.deleteUserKey = deprecate(function(key, callback) {
28107  return this.deleteApiKey(key, callback);
28108}, deprecatedMessage('index.deleteUserKey()', 'client.deleteApiKey()'));
28109
28110/*
28111* Delete an existing API key associated to this index
28112*
28113* @param key
28114* @param callback the result callback called with two arguments
28115*  error: null or Error('message')
28116*  content: the server answer with the deletion date
28117*
28118* @deprecated see client.deleteApiKey()
28119*/
28120Index.prototype.deleteApiKey = deprecate(function(key, callback) {
28121  var indexObj = this;
28122  return this.as._jsonRequest({
28123    method: 'DELETE',
28124    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key,
28125    hostType: 'write',
28126    callback: callback
28127  });
28128}, deprecatedMessage('index.deleteApiKey()', 'client.deleteApiKey()'));
28129
28130/*
28131* @deprecated see client.addApiKey()
28132*/
28133Index.prototype.addUserKey = deprecate(function(acls, params, callback) {
28134  return this.addApiKey(acls, params, callback);
28135}, deprecatedMessage('index.addUserKey()', 'client.addApiKey()'));
28136
28137/*
28138* Add a new API key to this index
28139*
28140* @param {string[]} acls - The list of ACL for this key. Defined by an array of str
28140ings that
28141*   can contains the following values:
28142*     - search: allow to search (https and http)
28143*     - addObject: allows to add/update an object in the index (https only)
28144*     - deleteObject : allows to delete an existing object (https only)
28145*     - deleteIndex : allows to delete index content (https only)
28146*     - settings : allows to get index settings (https only)
28147*     - editSettings : allows to change index settings (https only)
28148* @param {Object} [params] - Optionnal parameters to set for the key
28149* @param {number} params.validity - Number of seconds after which the key will
28150* be automatically removed (0 means no time limit for this key)
28151* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
28152* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
28153* @param {string} params.description - A description for your key
28154* @param {string[]} params.referers - A list of authorized referers
28155* @param {Object} params.queryParameters - Force the key to use specific query parameters
28156* @param {Function} callback - The result callback called with two arguments
28157*   error: null or Error('message')
28158*   content: the server answer with the added API key
28159* @return {Promise|undefined} Returns a promise if no callback given
28160* @example
28161* index.addUserKey(['search'], {
28162*   validity: 300,
28163*   maxQueriesPerIPPerHour: 2000,
28164*   maxHitsPerQuery: 3,
28165*   description: 'Eat three fruits',
28166*   referers: ['*.algolia.com'],
28167*   queryParameters: {
28168*     tagFilters: ['public'],
28169*   }
28170* })
28171* @see {@link https://www.algolia.com/doc/rest_api#AddIndexKey|Algolia REST API Documentation}
28172*
28173* @deprecated see client.addApiKey()
28174*/
28175Index.prototype.addApiKey = deprecate(function(acls, params, callback) {
28176  var isArray = require(8);
28177  var usage = 'Usage: index.addApiKey(arrayOfAcls[, params, callback])';
28178
28179  if (!isArray(acls)) {
28180    throw new Error(usage);
28181  }
28182
28183  if (arguments.length === 1 || typeof params === 'function') {
28184    callback = params;
28185    params = null;
28186  }
28187
28188  var postObj = {
28189    acl: acls
28190  };
28191
28192  if (params) {
28193    postObj.validity = params.validity;
28194    postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
28195    postObj.maxHitsPerQuery = params.maxHitsPerQuery;
28196    postObj.description = params.description;
28197
28198    if (params.queryParameters) {
28199      postObj.queryParameters = this.as._getSearchParams(params.queryParameters, '');
28200    }
28201
28202    postObj.referers = params.referers;
28203  }
28204
28205  return this.as._jsonRequest({
28206    method: 'POST',
28207    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys',
28208    body: postObj,
28209    hostType: 'write',
28210    callback: callback
28211  });
28212}, deprecatedMessage('index.addApiKey()', 'client.addApiKey()'));
28213
28214/**
28215* @deprecated use client.addApiKey()
28216*/
28217Index.prototype.addUserKeyWithValidity = deprecate(function deprecatedAddUserKeyWithValidity(acls, params, callback) {
28218  return this.addApiKey(acls, params, callback);
28219}, deprecatedMessage('index.addUserKeyWithValidity()', 'client.addApiKey()'));
28220
28221/*
28222* @deprecated see client.updateApiKey()
28223*/
28224Index.prototype.updateUserKey = deprecate(function(key, acls, params, callback) {
28225  return this.updateApiKey(key, acls, params, callback);
28226}, deprecatedMessage('index.updateUserKey()', 'client.updateApiKey()'));
28227
28228/**
28229* Update an existing API key of this index
28230* @param {string} key - The key to update
28231* @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that
28232*   can contains the following values:
28233*     - search: allow to search (https and http)
28234*     - addObject: allows to add/update an object in the index (https only)
28235*     - deleteObject : allows to delete an existing object (https only)
28236*     - deleteIndex : allows to delete index content (https only)
28237*     - settings : allows to get index settings (https only)
28238*     - editSettings : allows to change index settings (https only)
28239* @param {Object} [params] - Optionnal parameters to set for the key
28240* @param {number} params.validity - Number of seconds after which the key will
28241* be automatically removed (0 means no time limit for this key)
28242* @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour
28243* @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call
28244* @param {string} params.description - A description for your key
28245* @param {string[]} params.referers - A list of authorized referers
28246* @param {Object} params.queryParameters - Force the key to use specific query parameters
28247* @param {Function} callback - The result callback called with two arguments
28248*   error: null or Error('message')
28249*   content: the server answer with user keys list
28250* @return {Promise|undefined} Returns a promise if no callback given
28251* @example
28252* index.updateApiKey('APIKEY', ['search'], {
28253*   validity: 300,
28254*   maxQueriesPerIPPerHour: 2000,
28255*   maxHitsPerQuery: 3,
28256*   description: 'Eat three fruits',
28257*   referers: ['*.algolia.com'],
28258*   queryParameters: {
28259*     tagFilters: ['public'],
28260*   }
28261* })
28262* @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation}
28263*
28264* @deprecated see client.updateApiKey()
28265*/
28266Index.prototype.updateApiKey = deprecate(function(key, acls, params, callback) {
28267  var isArray = require(8);
28268  var usage = 'Usage: index.updateApiKey(key, arrayOfAcls[, params, callback])';
28269
28270  if (!isArray(acls)) {
28271    throw new Error(usage);
28272  }
28273
28274  if (arguments.length === 2 || typeof params === 'function') {
28275    callback = params;
28276    params = null;
28277  }
28278
28279  var putObj = {
28280    acl: acls
28281  };
28282
28283  if (params) {
28284    putObj.validity = params.validity;
28285    putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour;
28286    putObj.maxHitsPerQuery = params.maxHitsPerQuery;
28287    putObj.description = params.description;
28288
28289    if (params.queryParameters) {
28290      putObj.queryParameters = this.as._getSearchParams(params.queryParameters, '');
28291    }
28292
28293    putObj.referers = params.referers;
28294  }
28295
28296  return this.as._jsonRequest({
28297    method: 'PUT',
28298    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys/' + key,
28299    body: putObj,
28300    hostType: 'write',
28301    callback: callback
28302  });
28303}, deprecatedMessage('index.updateApiKey()', 'client.updateApiKey()'));
28304
28305},{"19":19,"20":20,"26":26,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"7":7,"8":8}],19:[function(require,module,exports){
28306'use strict';
28307
28308// This is the object returned by the `index.browseAll()` method
28309
28310module.exports = IndexBrowser;
28311
28312var inherits = require(7);
28313var EventEmitter = require(4).EventEmitter;
28314
28315function IndexBrowser() {
28316}
28317
28318inherits(IndexBrowser, EventEmitter);
28319
28320IndexBrowser.prototype.stop = function() {
28321  this._stopped = true;
28322  this._clean();
28323};
28324
28325IndexBrowser.prototype._end = function() {
28326  this.emit('end');
28327  this._clean();
28328};
28329
28330IndexBrowser.prototype._error = function(err) {
28331  this.emit('error', err);
28332  this._clean();
28333};
28334
28335IndexBrowser.prototype._result = function(content) {
28336  this.emit('result', content);
28337};
28338
28339IndexBrowser.prototype._clean = function() {
28340  this.removeAllListeners('stop');
28341  this.removeAllListeners('end');
28342  this.removeAllListeners('error');
28343  this.removeAllListeners('result');
28344};
28345
28346},{"4":4,"7":7}],20:[function(require,module,exports){
28347var buildSearchMethod = require(25);
28348var deprecate = require(28);
28349var deprecatedMessage = require(29);
28350
28351module.exports = IndexCore;
28352
28353/*
28354* Index class constructor.
28355* You should not use this method directly but use initIndex() function
28356*/
28357function IndexCore(algoliasearch, indexName) {
28358  this.indexName = indexName;
28359  this.as = algoliasearch;
28360  this.typeAheadArgs = null;
28361  this.typeAheadValueOption = null;
28362
28363  // make sure every index instance has it's own cache
28364  this.cache = {};
28365}
28366
28367/*
28368* Clear all queries in cache
28369*/
28370IndexCore.prototype.clearCache = function() {
28371  this.cache = {};
28372};
28373
28374/*
28375* Search inside the index using XMLHttpRequest request (Using a POST query to
28376* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
28377*
28378* @param {string} [query] the full text query
28379* @param {object} [args] (optional) if set, contains an object with query parameters:
28380* - page: (integer) Pagination parameter used to select the page to retrieve.
28381*                   Page is zero-based and defaults to 0. Thus,
28382*                   to retrieve the 10th page you need to set page=9
28383* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
28384* - attributesToRetrieve: a string that contains the list of object attributes
28385* you want to retrieve (let you minimize the answer size).
28386*   Attributes are separated with a comma (for example "name,address").
28387*   You can also use an array (for example ["name","address"]).
28388*   By default, all attributes are retrieved. You can also use '*' to retrieve all
28389*   values when an attributesToRetrieve setting is specified for your index.
28390* - attributesToHighlight: a string that contains the list of attributes you
28391*   want to highlight according to the query.
28392*   Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
28393*   If an attribute has no match for the query, the raw value is returned.
28394*   By default all indexed text attributes are highlighted.
28395*   You can use `*` if you want to highlight all textual attributes.
28396*   Numerical attributes are not highlighted.
28397*   A matchLevel is returned for each highlighted attribute and can contain:
28398*      - full: if all the query terms were found in the attribute,
28399*      - partial: if only some of the query terms were found,
28400*      - none: if none of the query terms were found.
28401* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
28402* the number of words to return (syntax is `attributeName:nbWords`).
28403*    Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
28404*    You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
28405*    By default no snippet is computed.
28406* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
28407* Defaults to 3.
28408* - minWordSizefor2Typos: the minimum number of characters in a query word
28409* to accept two typos in this word. Defaults to 7.
28410* - getRankingInfo: if set to 1, the result hits will contain ranking
28411* information in _rankingInfo attribute.
28412* - aroundLatLng: search for entries around a given
28413* latitude/longitude (specified as two floats separated by a comma).
28414*   For example aroundLatLng=47.316669,5.016670).
28415*   You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
28416*   and the precision for ranking with aroundPrecision
28417*   (for example if you set aroundPrecision=100, two objects that are distant of
28418*   less than 100m will be considered as identical for "geo" ranking parameter).
28419*   At indexing, you should specify geoloc of an object with the _geoloc attribute
28420*   (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
28421* - insideBoundingBox: search entries inside a given area defined by the two extreme points
28422* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
28423*   For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
28424*   At indexing, you should specify geoloc of an object with the _geoloc attribute
28425*   (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
28426* - numericFilters: a string that contains the list of numeric filters you want to
28427* apply separated by a comma.
28428*   The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
28429*   Supported operands are `<`, `<=`, `=`, `>` and `>=`.
28430*   You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
28431*   You can also use an array (for example numericFilters: ["price>100","price<1000"]).
28432* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
28433*   To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
28434*   You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
28435*   means tag1 AND (tag2 OR tag3).
28436*   At indexing, tags should be added in the _tags** attribute
28437*   of objects (for example {"_tags":["tag1","tag2"]}).
28438* - facetFilters: filter the query by a list of facets.
28439*   Facets are separated by commas and each facet is encoded as `attributeName:value`.
28440*   For example: `facetFilters=category:Book,author:John%20Doe`.
28441*   You can also use an array (for example `["category:Book","author:John%20Doe"]`).
28442* - facets: List of object attributes that you want to use for faceting.
28443*   Comma separated list: `"category,author"` or array `['category','author']`
28444*   Only attributes that have been added in **attributesForFaceting** index setting
28445*   can be used in this parameter.
28446*   You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
28447* - queryType: select how the query words are interpreted, it can be one of the following value:
28448*    - prefixAll: all query words are interpreted as prefixes,
28449*    - prefixLast: only the last word is interpreted as a prefix (default behavior),
28450*    - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
28451* - optionalWords: a string that contains the list of words that should
28452* be considered as optional when found in the query.
28453*   Comma separated and array are accepted.
28454* - distinct: If set to 1, enable the distinct feature (disabled by default)
28455* if the attributeForDistinct index setting is set.
28456*   This feature is similar to the SQL "distinct" keyword: when enabled
28457*   in a query with the distinct=1 parameter,
28458*   all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
28459*   For example, if the chosen attribute is show_name and several hits have
28460*   the same value for show_name, then only the best
28461*   one is kept and others are removed.
28462* - restrictSearchableAttributes: List of attributes you want to use for
28463* textual search (must be a subset of the attributesToIndex index setting)
28464* either comma separated or as an array
28465* @param {function} [callback] the result callback called with two arguments:
28466*  error: null or Error('message'). If false, the content contains the error.
28467*  content: the server answer that contains the list of results.
28468*/
28469IndexCore.prototype.search = buildSearchMethod('query');
28470
28471/*
28472* -- BETA --
28473* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
28474* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
28475*
28476* @param {string} [query] the similar query
28477* @param {object} [args] (optional) if set, contains an object with query parameters.
28478*   All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
28479*   are the two most useful to restrict the similar results and get more relevant content
28480*/
28481IndexCore.prototype.similarSearch = deprecate(
28482  buildSearchMethod('similarQuery'),
28483  deprecatedMessage(
28484    'index.similarSearch(query[, callback])',
28485    'index.search({ similarQuery: query }[, callback])'
28486  )
28487);
28488
28489/*
28490* Browse index content. The response content will have a `cursor` property that you can use
28491* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
28492*
28493* @param {string} query - The full text query
28494* @param {Object} [queryParameters] - Any search query parameter
28495* @param {Function} [callback] - The result callback called with two arguments
28496*   error: null or Error('message')
28497*   content: the server answer with the browse result
28498* @return {Promise|undefined} Returns a promise if no callback given
28499* @example
28500* index.browse('cool songs', {
28501*   tagFilters: 'public,comments',
28502*   hitsPerPage: 500
28503* }, callback);
28504* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
28505*/
28506IndexCore.prototype.browse = function(query, queryParameters, callback) {
28507  var merge = require(33);
28508
28509  var indexObj = this;
28510
28511  var page;
28512  var hitsPerPage;
28513
28514  // we check variadic calls that are not the one defined
28515  // .browse()/.browse(fn)
28516  // => page = 0
28517  if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
28518    page = 0;
28519    callback = arguments[0];
28520    query = undefined;
28521  } else if (typeof arguments[0] === 'number') {
vendor: 8,837 bytes, lines 28522-28811
28522    // .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
28523    page = arguments[0];
28524    if (typeof arguments[1] === 'number') {
28525      hitsPerPage = arguments[1];
28526    } else if (typeof arguments[1] === 'function') {
28527      callback = arguments[1];
28528      hitsPerPage = undefined;
28529    }
28530    query = undefined;
28531    queryParameters = undefined;
28532  } else if (typeof arguments[0] === 'object') {
28533    // .browse(queryParameters)/.browse(queryParameters, cb)
28534    if (typeof arguments[1] === 'function') {
28535      callback = arguments[1];
28536    }
28537    queryParameters = arguments[0];
28538    query = undefined;
28539  } else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
28540    // .browse(query, cb)
28541    callback = arguments[1];
28542    queryParameters = undefined;
28543  }
28544
28545  // otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
28546
28547  // get search query parameters combining various possible calls
28548  // to .browse();
28549  queryParameters = merge({}, queryParameters || {}, {
28550    page: page,
28551    hitsPerPage: hitsPerPage,
28552    query: query
28553  });
28554
28555  var params = this.as._getSearchParams(queryParameters, '');
28556
28557  return this.as._jsonRequest({
28558    method: 'POST',
28559    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse',
28560    body: {params: params},
28561    hostType: 'read',
28562    callback: callback
28563  });
28564};
28565
28566/*
28567* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
28568*
28569* @param {string} query - The full text query
28570* @param {Object} [queryParameters] - Any search query parameter
28571* @param {Function} [callback] - The result callback called with two arguments
28572*   error: null or Error('message')
28573*   content: the server answer with the browse result
28574* @return {Promise|undefined} Returns a promise if no callback given
28575* @example
28576* index.browseFrom('14lkfsakl32', callback);
28577* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
28578*/
28579IndexCore.prototype.browseFrom = function(cursor, callback) {
28580  return this.as._jsonRequest({
28581    method: 'POST',
28582    url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse',
28583    body: {cursor: cursor},
28584    hostType: 'read',
28585    callback: callback
28586  });
28587};
28588
28589/*
28590* Search for facet values
28591* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
28592*
28593* @param {string} params.facetName Facet name, name of the attribute to search for values in.
28594* Must be declared as a facet
28595* @param {string} params.facetQuery Query for the facet search
28596* @param {string} [params.*] Any search parameter of Algolia,
28597* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
28598* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
28599* @param callback (optional)
28600*/
28601IndexCore.prototype.searchForFacetValues = function(params, callback) {
28602  var clone = require(26);
28603  var omit = require(34);
28604  var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])';
28605
28606  if (params.facetName === undefined || params.facetQuery === undefined) {
28607    throw new Error(usage);
28608  }
28609
28610  var facetName = params.facetName;
28611  var filteredParams = omit(clone(params), function(keyName) {
28612    return keyName === 'facetName';
28613  });
28614  var searchParameters = this.as._getSearchParams(filteredParams, '');
28615
28616  return this.as._jsonRequest({
28617    method: 'POST',
28618    url: '/1/indexes/' +
28619      encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query',
28620    hostType: 'read',
28621    body: {params: searchParameters},
28622    callback: callback
28623  });
28624};
28625
28626IndexCore.prototype.searchFacet = deprecate(function(params, callback) {
28627  return this.searchForFacetValues(params, callback);
28628}, deprecatedMessage(
28629  'index.searchFacet(params[, callback])',
28630  'index.searchForFacetValues(params[, callback])'
28631));
28632
28633IndexCore.prototype._search = function(params, url, callback, additionalUA) {
28634  return this.as._jsonRequest({
28635    cache: this.cache,
28636    method: 'POST',
28637    url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
28638    body: {params: params},
28639    hostType: 'read',
28640    fallback: {
28641      method: 'GET',
28642      url: '/1/indexes/' + encodeURIComponent(this.indexName),
28643      body: {params: params}
28644    },
28645    callback: callback,
28646    additionalUA: additionalUA
28647  });
28648};
28649
28650/*
28651* Get an object from this index
28652*
28653* @param objectID the unique identifier of the object to retrieve
28654* @param attrs (optional) if set, contains the array of attribute names to retrieve
28655* @param callback (optional) the result callback called with two arguments
28656*  error: null or Error('message')
28657*  content: the object to retrieve or the error message if a failure occurred
28658*/
28659IndexCore.prototype.getObject = function(objectID, attrs, callback) {
28660  var indexObj = this;
28661
28662  if (arguments.length === 1 || typeof attrs === 'function') {
28663    callback = attrs;
28664    attrs = undefined;
28665  }
28666
28667  var params = '';
28668  if (attrs !== undefined) {
28669    params = '?attributes=';
28670    for (var i = 0; i < attrs.length; ++i) {
28671      if (i !== 0) {
28672        params += ',';
28673      }
28674      params += attrs[i];
28675    }
28676  }
28677
28678  return this.as._jsonRequest({
28679    method: 'GET',
28680    url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
28681    hostType: 'read',
28682    callback: callback
28683  });
28684};
28685
28686/*
28687* Get several objects from this index
28688*
28689* @param objectIDs the array of unique identifier of objects to retrieve
28690*/
28691IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
28692  var isArray = require(8);
28693  var map = require(32);
28694
28695  var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
28696
28697  if (!isArray(objectIDs)) {
28698    throw new Error(usage);
28699  }
28700
28701  var indexObj = this;
28702
28703  if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
28704    callback = attributesToRetrieve;
28705    attributesToRetrieve = undefined;
28706  }
28707
28708  var body = {
28709    requests: map(objectIDs, function prepareRequest(objectID) {
28710      var request = {
28711        indexName: indexObj.indexName,
28712        objectID: objectID
28713      };
28714
28715      if (attributesToRetrieve) {
28716        request.attributesToRetrieve = attributesToRetrieve.join(',');
28717      }
28718
28719      return request;
28720    })
28721  };
28722
28723  return this.as._jsonRequest({
28724    method: 'POST',
28725    url: '/1/indexes/*/objects',
28726    hostType: 'read',
28727    body: body,
28728    callback: callback
28729  });
28730};
28731
28732IndexCore.prototype.as = null;
28733IndexCore.prototype.indexName = null;
28734IndexCore.prototype.typeAheadArgs = null;
28735IndexCore.prototype.typeAheadValueOption = null;
28736
28737},{"25":25,"26":26,"28":28,"29":29,"32":32,"33":33,"34":34,"8":8}],21:[function(require,module,exports){
28738'use strict';
28739
28740var AlgoliaSearch = require(16);
28741var createAlgoliasearch = require(22);
28742
28743module.exports = createAlgoliasearch(AlgoliaSearch, 'Browser');
28744
28745},{"16":16,"22":22}],22:[function(require,module,exports){
28746(function (process){
28747'use strict';
28748
28749var global = require(6);
28750var Promise = global.Promise || require(3).Promise;
28751
28752// This is the standalone browser build entry point
28753// Browser implementation of the Algolia Search JavaScript client,
28754// using XMLHttpRequest, XDomainRequest and JSONP as fallback
28755module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
28756  var inherits = require(7);
28757  var errors = require(30);
28758  var inlineHeaders = require(23);
28759  var jsonpRequest = require(24);
28760  var places = require(35);
28761  uaSuffix = uaSuffix || '';
28762
28763  if (process.env.NODE_ENV === 'debug') {
28764    require(1).enable('algoliasearch*');
28765  }
28766
28767  function algoliasearch(applicationID, apiKey, opts) {
28768    var cloneDeep = require(26);
28769
28770    opts = cloneDeep(opts || {});
28771
28772    opts._ua = opts._ua || algoliasearch.ua;
28773
28774    return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
28775  }
28776
28777  algoliasearch.version = require(37);
28778
28779  algoliasearch.ua =
28780    'Algolia for JavaScript (' + algoliasearch.version + '); ' + uaSuffix;
28781
28782  algoliasearch.initPlaces = places(algoliasearch);
28783
28784  // we expose into window no matter how we are used, this will allow
28785  // us to easily debug any website running algolia
28786  global.__algolia = {
28787    debug: require(1),
28788    algoliasearch: algoliasearch
28789  };
28790
28791  var support = {
28792    hasXMLHttpRequest: 'XMLHttpRequest' in global,
28793    hasXDomainRequest: 'XDomainRequest' in global
28794  };
28795
28796  if (support.hasXMLHttpRequest) {
28797    support.cors = 'withCredentials' in new XMLHttpRequest();
28798  }
28799
28800  function AlgoliaSearchBrowser() {
28801    // call AlgoliaSearch constructor
28802    AlgoliaSearch.apply(this, arguments);
28803  }
28804
28805  inherits(AlgoliaSearchBrowser, AlgoliaSearch);
28806
28807  AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
28808    return new Promise(function wrapRequest(resolve, reject) {
28809      // no cors or XDomainRequest, no request
28810      if (!support.cors && !support.hasXDomainRequest) {
28811        // very old browser, not supported
vendor: 5,698 bytes, lines 28812-29019
28812        reject(new errors.Network('CORS not supported'));
28813        return;
28814      }
28815
28816      url = inlineHeaders(url, opts.headers);
28817
28818      var body = opts.body;
28819      var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
28820      var reqTimeout;
28821      var timedOut;
28822      var connected = false;
28823
28824      reqTimeout = setTimeout(onTimeout, opts.timeouts.connect);
28825      // we set an empty onprogress listener
28826      // so that XDomainRequest on IE9 is not aborted
28827      // refs:
28828      //  - https://github.com/algolia/algoliasearch-client-js/issues/76
28829      //  - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
28830      req.onprogress = onProgress;
28831      if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange;
28832      req.onload = onLoad;
28833      req.onerror = onError;
28834
28835      // do not rely on default XHR async flag, as some analytics code like hotjar
28836      // breaks it and set it to false by default
28837      if (req instanceof XMLHttpRequest) {
28838        req.open(opts.method, url, true);
28839
28840        // The Analytics API never accepts Auth headers as query string
28841        // this option exists specifically for them.
28842        if (opts.forceAuthHeaders) {
28843          req.setRequestHeader(
28844            'x-algolia-application-id',
28845            opts.headers['x-algolia-application-id']
28846          );
28847          req.setRequestHeader(
28848            'x-algolia-api-key',
28849            opts.headers['x-algolia-api-key']
28850          );
28851        }
28852      } else {
28853        req.open(opts.method, url);
28854      }
28855
28856      // headers are meant to be sent after open
28857      if (support.cors) {
28858        if (body) {
28859          if (opts.method === 'POST') {
28860            // https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
28861            req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
28862          } else {
28863            req.setRequestHeader('content-type', 'application/json');
28864          }
28865        }
28866        req.setRequestHeader('accept', 'application/json');
28867      }
28868
28869      if (body) {
28870        req.send(body);
28871      } else {
28872        req.send();
28873      }
28874
28875      // event object not received in IE8, at least
28876      // but we do not use it, still important to note
28877      function onLoad(/* event */) {
28878        // When browser does not supports req.timeout, we can
28879        // have both a load and timeout event, since handled by a dumb setTimeout
28880        if (timedOut) {
28881          return;
28882        }
28883
28884        clearTimeout(reqTimeout);
28885
28886        var out;
28887
28888        try {
28889          out = {
28890            body: JSON.parse(req.responseText),
28891            responseText: req.responseText,
28892            statusCode: req.status,
28893            // XDomainRequest does not have any response headers
28894            headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
28895          };
28896        } catch (e) {
28897          out = new errors.UnparsableJSON({
28898            more: req.responseText
28899          });
28900        }
28901
28902        if (out instanceof errors.UnparsableJSON) {
28903          reject(out);
28904        } else {
28905          resolve(out);
28906        }
28907      }
28908
28909      function onError(event) {
28910        if (timedOut) {
28911          return;
28912        }
28913
28914        clearTimeout(reqTimeout);
28915
28916        // error event is trigerred both with XDR/XHR on:
28917        //   - DNS error
28918        //   - unallowed cross domain request
28919        reject(
28920          new errors.Network({
28921            more: event
28922          })
28923        );
28924      }
28925
28926      function onTimeout() {
28927        timedOut = true;
28928        req.abort();
28929
28930        reject(new errors.RequestTimeout());
28931      }
28932
28933      function onConnect() {
28934        connected = true;
28935        clearTimeout(reqTimeout);
28936        reqTimeout = setTimeout(onTimeout, opts.timeouts.complete);
28937      }
28938
28939      function onProgress() {
28940        if (!connected) onConnect();
28941      }
28942
28943      function onReadyStateChange() {
28944        if (!connected && req.readyState > 1) onConnect();
28945      }
28946    });
28947  };
28948
28949  AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
28950    url = inlineHeaders(url, opts.headers);
28951
28952    return new Promise(function wrapJsonpRequest(resolve, reject) {
28953      jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
28954        if (err) {
28955          reject(err);
28956          return;
28957        }
28958
28959        resolve(content);
28960      });
28961    });
28962  };
28963
28964  AlgoliaSearchBrowser.prototype._promise = {
28965    reject: function rejectPromise(val) {
28966      return Promise.reject(val);
28967    },
28968    resolve: function resolvePromise(val) {
28969      return Promise.resolve(val);
28970    },
28971    delay: function delayPromise(ms) {
28972      return new Promise(function resolveOnTimeout(resolve/* , reject*/) {
28973        setTimeout(resolve, ms);
28974      });
28975    },
28976    all: function all(promises) {
28977      return Promise.all(promises);
28978    }
28979  };
28980
28981  return algoliasearch;
28982};
28983
28984}).call(this,require(12))
28985},{"1":1,"12":12,"23":23,"24":24,"26":26,"3":3,"30":30,"35":35,"37":37,"6":6,"7":7}],23:[function(require,module,exports){
28986'use strict';
28987
28988module.exports = inlineHeaders;
28989
28990var encode = require(14);
28991
28992function inlineHeaders(url, headers) {
28993  if (/\?/.test(url)) {
28994    url += '&';
28995  } else {
28996    url += '?';
28997  }
28998
28999  return url + encode(headers);
29000}
29001
29002},{"14":14}],24:[function(require,module,exports){
29003'use strict';
29004
29005module.exports = jsonpRequest;
29006
29007var errors = require(30);
29008
29009var JSONPCounter = 0;
29010
29011function jsonpRequest(url, opts, cb) {
29012  if (opts.method !== 'GET') {
29013    cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
29014    return;
29015  }
29016
29017  opts.debug('JSONP: start');
29018
29019  var cbCalled = false;
vendor: 5,397 bytes, lines 29020-29216
29020  var timedOut = false;
29021
29022  JSONPCounter += 1;
29023  var head = document.getElementsByTagName('head')[0];
29024  var script = document.createElement('script');
29025  var cbName = 'algoliaJSONP_' + JSONPCounter;
29026  var done = false;
29027
29028  window[cbName] = function(data) {
29029    removeGlobals();
29030
29031    if (timedOut) {
29032      opts.debug('JSONP: Late answer, ignoring');
29033      return;
29034    }
29035
29036    cbCalled = true;
29037
29038    clean();
29039
29040    cb(null, {
29041      body: data,
29042      responseText: JSON.stringify(data)/* ,
29043      // We do not send the statusCode, there's no statusCode in JSONP, it will be
29044      // computed using data.status && data.message like with XDR
29045      statusCode*/
29046    });
29047  };
29048
29049  // add callback by hand
29050  url += '&callback=' + cbName;
29051
29052  // add body params manually
29053  if (opts.jsonBody && opts.jsonBody.params) {
29054    url += '&' + opts.jsonBody.params;
29055  }
29056
29057  var ontimeout = setTimeout(timeout, opts.timeouts.complete);
29058
29059  // script onreadystatechange needed only for
29060  // <= IE8
29061  // https://github.com/angular/angular.js/issues/4523
29062  script.onreadystatechange = readystatechange;
29063  script.onload = success;
29064  script.onerror = error;
29065
29066  script.async = true;
29067  script.defer = true;
29068  script.src = url;
29069  head.appendChild(script);
29070
29071  function success() {
29072    opts.debug('JSONP: success');
29073
29074    if (done || timedOut) {
29075      return;
29076    }
29077
29078    done = true;
29079
29080    // script loaded but did not call the fn => script loading error
29081    if (!cbCalled) {
29082      opts.debug('JSONP: Fail. Script loaded but did not call the callback');
29083      clean();
29084      cb(new errors.JSONPScriptFail());
29085    }
29086  }
29087
29088  function readystatechange() {
29089    if (this.readyState === 'loaded' || this.readyState === 'complete') {
29090      success();
29091    }
29092  }
29093
29094  function clean() {
29095    clearTimeout(ontimeout);
29096    script.onload = null;
29097    script.onreadystatechange = null;
29098    script.onerror = null;
29099    head.removeChild(script);
29100  }
29101
29102  function removeGlobals() {
29103    try {
29104      delete window[cbName];
29105      delete window[cbName + '_loaded'];
29106    } catch (e) {
29107      window[cbName] = window[cbName + '_loaded'] = undefined;
29108    }
29109  }
29110
29111  function timeout() {
29112    opts.debug('JSONP: Script timeout');
29113    timedOut = true;
29114    clean();
29115    cb(new errors.RequestTimeout());
29116  }
29117
29118  function error() {
29119    opts.debug('JSONP: Script error');
29120
29121    if (done || timedOut) {
29122      return;
29123    }
29124
29125    clean();
29126    cb(new errors.JSONPScriptError());
29127  }
29128}
29129
29130},{"30":30}],25:[function(require,module,exports){
29131module.exports = buildSearchMethod;
29132
29133var errors = require(30);
29134
29135/**
29136 * Creates a search method to be used in clients
29137 * @param {string} queryParam the name of the attribute used for the query
29138 * @param {string} url the url
29139 * @return {function} the search method
29140 */
29141function buildSearchMethod(queryParam, url) {
29142  /**
29143   * The search method. Prepares the data and send the query to Algolia.
29144   * @param {string} query the string used for query search
29145   * @param {object} args additional parameters to send with the search
29146   * @param {function} [callback] the callback to be called with the client gets the answer
29147   * @return {undefined|Promise} If the callback is not provided then this methods returns a Promise
29148   */
29149  return function search(query, args, callback) {
29150    // warn V2 users on how to search
29151    if (typeof query === 'function' && typeof args === 'object' ||
29152      typeof callback === 'object') {
29153      // .search(query, params, cb)
29154      // .search(cb, params)
29155      throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
29156    }
29157
29158    // Normalizing the function signature
29159    if (arguments.length === 0 || typeof query === 'function') {
29160      // Usage : .search(), .search(cb)
29161      callback = query;
29162      query = '';
29163    } else if (arguments.length === 1 || typeof args === 'function') {
29164      // Usage : .search(query/args), .search(query, cb)
29165      callback = args;
29166      args = undefined;
29167    }
29168    // At this point we have 3 arguments with values
29169
29170    // Usage : .search(args) // careful: typeof null === 'object'
29171    if (typeof query === 'object' && query !== null) {
29172      args = query;
29173      query = undefined;
29174    } else if (query === undefined || query === null) { // .search(undefined/null)
29175      query = '';
29176    }
29177
29178    var params = '';
29179
29180    if (query !== undefined) {
29181      params += queryParam + '=' + encodeURIComponent(query);
29182    }
29183
29184    var additionalUA;
29185    if (args !== undefined) {
29186      if (args.additionalUA) {
29187        additionalUA = args.additionalUA;
29188        delete args.additionalUA;
29189      }
29190      // `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
29191      params = this.as._getSearchParams(args, params);
29192    }
29193
29194
29195    return this._search(params, url, callback, additionalUA);
29196  };
29197}
29198
29199},{"30":30}],26:[function(require,module,exports){
29200module.exports = function clone(obj) {
29201  return JSON.parse(JSON.stringify(obj));
29202};
29203
29204},{}],27:[function(require,module,exports){
29205module.exports = createAnalyticsClient;
29206
29207var algoliasearch = require(21);
29208
29209function createAnalyticsClient(appId, apiKey, opts) {
29210  var analytics = {};
29211
29212  opts = opts || {};
29213  // there need to be 4 hosts, like on the client, since if requests fail,
29214  // the counter goes up by 1, so we need to have the same amount of hosts
29215  // 4 because: -dsn, -1, -2, -3
29216  // This is done because the APPID used for search will be the same for the analytics client created,
29217  // and since the state of available hosts is shared by APPID globally for the module, we had issues
29218  // where the hostIndex would be 1 while the array was only one entry (you got an empty host)
29219  opts.hosts = opts.hosts || [
29220    'analytics.algolia.com',
29221    'analytics.algolia.com',
29222    'analytics.algolia.com',
29223    'analytics.algolia.com'
29224  ];
29225  opts.protocol = opts.protocol || 'https:';
29226
29227  analytics.as = algoliasearch(appId, apiKey, opts);
29228
29229  analytics.getABTests = function(_params, callback) {
29230    var params = params || {};
29231    var offset = params.offset || 0;
29232    var limit = params.limit || 10;
29233
29234    return this.as._jsonRequest({
29235      method: 'GET',
29236      url: '/2/abtests?offset=' + encodeURIComponent(offset) + '&limit=' + encodeURIComponent(limit),
29237      hostType: 'read',
29238      forceAuthHeaders: true,
29239      callback: callback
29240    });
29241  };
29242
29243  analytics.getABTest = function(abTestID, callback) {
29244    return this.as._jsonRequest({
29245      method: 'GET',
29246      url: '/2/abtests/' + encodeURIComponent(abTestID),
29247      hostType: 'read',
29248      forceAuthHeaders: true,
29249      callback: callback
29250    });
29251  };
29252
29253  analytics.addABTest = function(abTest, callback) {
29254    return this.as._jsonRequest({
29255      method: 'POST',
29256      url: '/2/abtests',
29257      body: abTest,
29258      hostType: 'read',
29259      forceAuthHeaders: true,
29260      callback: callback
29261    });
29262  };
29263
29264  analytics.stopABTest = function(abTestID, callback) {
29265    return this.as._jsonRequest({
29266      method: 'POST',
29267      url: '/2/abtests/' + encodeURIComponent(abTestID) + '/stop',
29268      hostType: 'read',
29269      forceAuthHeaders: true,
29270      callback: callback
29271    });
29272  };
29273
29274  analytics.deleteABTest = function(abTestID, callback) {
29275    return this.as._jsonRequest({
29276      method: 'DELETE',
29277      url: '/2/abtests/' + encodeURIComponent(abTestID),
29278      hostType: 'write',
29279      forceAuthHeaders: true,
29280      callback: callback
29281    });
29282  };
29283
29284  analytics.waitTask = function(indexName, taskID, callback) {
29285    return this.as.initIndex(indexName).waitTask(taskID, callback);
29286  };
29287
29288  return analytics;
29289}
29290
29291},{"21":21}],28:[function(require,module,exports){
29292module.exports = function deprecate(fn, message) {
29293  var warned = false;
29294
29295  function deprecated() {
29296    if (!warned) {
29297      /* eslint no-console:0 */
29298      console.warn(message);
29299      warned = true;
29300    }
29301
29302    return fn.apply(this, arguments);
29303  }
29304
29305  return deprecated;
29306};
29307
29308},{}],29:[function(require,module,exports){
29309module.exports = function deprecatedMessage(previousUsage, newUsage) {
29310  var githubAnchorLink = previousUsage.toLowerCase()
29311    .replace(/[\.\(\)]/g, '');
29312
29313  return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage +
29314    '`. Please see https://github.com/algolia/algoliasearch-client-javascript/wiki/Deprecated#' + githubAnchorLink;
29315};
29316
29317},{}],30:[function(require,module,exports){
29318'use strict';
29319
29320// This file hosts our error definitions
29321// We use custom error "types" so that we can act on them when we need it
29322// e.g.: if error instanceof errors.UnparsableJSON then..
29323
29324var inherits = require(7);
29325
29326function AlgoliaSearchError(message, extraProperties) {
29327  var forEach = require(5);
29328
29329  var error = this;
29330
29331  // try to get a stacktrace
29332  if (typeof Error.captureStackTrace === 'function') {
29333    Error.captureStackTrace(this, this.constructor);
29334  } else {
29335    error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
29336  }
29337
29338  this.name = 'AlgoliaSearchError';
29339  this.message = message || 'Unknown error';
29340
29341  if (extraProperties) {
29342    forEach(extraProperties, function addToErrorObject(value, key) {
29343      error[key] = value;
29344    });
29345  }
29346}
29347
29348inherits(AlgoliaSearchError, Error);
29349
29350function createCustomError(name, message) {
29351  function AlgoliaSearchCustomError() {
29352    var args = Array.prototype.slice.call(arguments, 0);
29353
29354    // custom message not set, use default
29355    if (typeof args[0] !== 'string') {
29356      args.unshift(message);
29357    }
29358
29359    AlgoliaSearchError.apply(this, args);
29360    this.name = 'AlgoliaSearch' + name + 'Error';
29361  }
29362
29363  inherits(AlgoliaSearchCustomError, AlgoliaSearchError);
29364
29365  return AlgoliaSearchCustomError;
29366}
29367
29368// late exports to let various fn defs and inherits take place
29369module.exports = {
29370  AlgoliaSearchError: AlgoliaSearchError,
29371  UnparsableJSON: createCustomError(
29372    'UnparsableJSON',
29373    'Could not parse the incoming response as JSON, see err.more for details'
29374  ),
29375  RequestTimeout: createCustomError(
29376    'RequestTimeout',
29377    'Request timed out before getting a response'
29378  ),
29379  Network: createCustomError(
29380    'Network',
29381    'Network issue, see err.more for details'
29382  ),
29383  JSONPScriptFail: createCustomError(
29384    'JSONPScriptFail',
29385    '<script> was loaded but did not call our provided callback'
29386  ),
29387  ValidUntilNotFound: createCustomError(
29388    'ValidUntilNotFound',
29389    'The SecuredAPIKey does not have a validUntil parameter.'
29390  ),
29391  JSONPScriptError: createCustomError(
29392    'JSONPScriptError',
29393    '<script> unable to load due to an `error` event on it'
29394  ),
29395  ObjectNotFound: createCustomError(
29396    'ObjectNotFound',
29397    'Object not found'
29398  ),
29399  Unknown: createCustomError(
29400    'Unknown',
29401    'Unknown error occured'
29402  )
29403};
29404
29405},{"5":5,"7":7}],31:[function(require,module,exports){
29406// Parse cloud does not supports setTimeout
29407// We do not store a setTimeout reference in the client everytime
29408// We only fallback to a fake setTimeout when not available
29409// setTimeout cannot be override globally sadly
29410module.exports = function exitPromise(fn, _setTimeout) {
29411  _setTimeout(fn, 0);
29412};
29413
29414},{}],32:[function(require,module,exports){
29415var foreach = require(5);
29416
29417module.exports = function map(arr, fn) {
29418  var newArr = [];
29419  foreach(arr, function(item, itemIndex) {
vendor: 4,317 bytes, lines 29420-29586
29420    newArr.push(fn(item, itemIndex, arr));
29421  });
29422  return newArr;
29423};
29424
29425},{"5":5}],33:[function(require,module,exports){
29426var foreach = require(5);
29427
29428module.exports = function merge(destination/* , sources */) {
29429  var sources = Array.prototype.slice.call(arguments);
29430
29431  foreach(sources, function(source) {
29432    for (var keyName in source) {
29433      if (source.hasOwnProperty(keyName)) {
29434        if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
29435          destination[keyName] = merge({}, destination[keyName], source[keyName]);
29436        } else if (source[keyName] !== undefined) {
29437          destination[keyName] = source[keyName];
29438        }
29439      }
29440    }
29441  });
29442
29443  return destination;
29444};
29445
29446},{"5":5}],34:[function(require,module,exports){
29447module.exports = function omit(obj, test) {
29448  var keys = require(10);
29449  var foreach = require(5);
29450
29451  var filtered = {};
29452
29453  foreach(keys(obj), function doFilter(keyName) {
29454    if (test(keyName) !== true) {
29455      filtered[keyName] = obj[keyName];
29456    }
29457  });
29458
29459  return filtered;
29460};
29461
29462},{"10":10,"5":5}],35:[function(require,module,exports){
29463module.exports = createPlacesClient;
29464
29465var qs3 = require(15);
29466var buildSearchMethod = require(25);
29467
29468function createPlacesClient(algoliasearch) {
29469  return function places(appID, apiKey, opts) {
29470    var cloneDeep = require(26);
29471
29472    opts = opts && cloneDeep(opts) || {};
29473    opts.hosts = opts.hosts || [
29474      'places-dsn.algolia.net',
29475      'places-1.algolianet.com',
29476      'places-2.algolianet.com',
29477      'places-3.algolianet.com'
29478    ];
29479
29480    // allow initPlaces() no arguments => community rate limited
29481    if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
29482      appID = '';
29483      apiKey = '';
29484      opts._allowEmptyCredentials = true;
29485    }
29486
29487    var client = algoliasearch(appID, apiKey, opts);
29488    var index = client.initIndex('places');
29489    index.search = buildSearchMethod('query', '/1/places/query');
29490    index.reverse = function(options, callback) {
29491      var encoded = qs3.encode(options);
29492
29493      return this.as._jsonRequest({
29494        method: 'GET',
29495        url: '/1/places/reverse?' + encoded,
29496        hostType: 'read',
29497        callback: callback
29498      });
29499    };
29500
29501    index.getObject = function(objectID, callback) {
29502      return this.as._jsonRequest({
29503        method: 'GET',
29504        url: '/1/places/' + encodeURIComponent(objectID),
29505        hostType: 'read',
29506        callback: callback
29507      });
29508    };
29509    return index;
29510  };
29511}
29512
29513},{"15":15,"25":25,"26":26}],36:[function(require,module,exports){
29514(function (global){
29515var debug = require(1)('algoliasearch:src/hostIndexState.js');
29516var localStorageNamespace = 'algoliasearch-client-js';
29517
29518var store;
29519var moduleStore = {
29520  state: {},
29521  set: function(key, data) {
29522    this.state[key] = data;
29523    return this.state[key];
29524  },
29525  get: function(key) {
29526    return this.state[key] || null;
29527  }
29528};
29529
29530var localStorageStore = {
29531  set: function(key, data) {
29532    moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure
29533
29534    try {
29535      var namespace = JSON.parse(global.localStorage[localStorageNamespace]);
29536      namespace[key] = data;
29537      global.localStorage[localStorageNamespace] = JSON.stringify(namespace);
29538      return namespace[key];
29539    } catch (e) {
29540      return localStorageFailure(key, e);
29541    }
29542  },
29543  get: function(key) {
29544    try {
29545      return JSON.parse(global.localStorage[localStorageNamespace])[key] || null;
29546    } catch (e) {
29547      return localStorageFailure(key, e);
29548    }
29549  }
29550};
29551
29552function localStorageFailure(key, e) {
29553  debug('localStorage failed with', e);
29554  cleanup();
29555  store = moduleStore;
29556  return store.get(key);
29557}
29558
29559store = supportsLocalStorage() ? localStorageStore : moduleStore;
29560
29561module.exports = {
29562  get: getOrSet,
29563  set: getOrSet,
29564  supportsLocalStorage: supportsLocalStorage
29565};
29566
29567function getOrSet(key, data) {
29568  if (arguments.length === 1) {
29569    return store.get(key);
29570  }
29571
29572  return store.set(key, data);
29573}
29574
29575function supportsLocalStorage() {
29576  try {
29577    if ('localStorage' in global &&
29578      global.localStorage !== null) {
29579      if (!global.localStorage[localStorageNamespace]) {
29580        // actual creation of the namespace
29581        global.localStorage.setItem(localStorageNamespace, JSON.stringify({}));
29582      }
29583      return true;
29584    }
29585
29586    return false;
29587  } catch (_) {
29588    return false;
29589  }
29590}
29591
29592// In case of any error on localStorage, we clean our own namespace, this should handle
29593// quota errors when a lot of keys + data are used
29594function cleanup() {
29595  try {
29596    global.localStorage.removeItem(localStorageNamespace);
29597  } catch (_) {
29598    // nothing to do
29599  }
29600}
29601
29602}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
29603},{"1":1}],37:[function(require,module,exports){
29604'use strict';
29605
29606module.exports = '3.35.1';
29607
29608},{}]},{},[21])(21)
29609});
29610/**
29611 * html2pdf.js v0.9.3
29612 * Copyright (c) 2021 Erik Koopmans
29613 * Released under the MIT License.
29614 */
29615(function (global, factory) {
29616	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
29617	typeof define === 'function' && define.amd ? define(factory) :
29618	(global.html2pdf = factory());
29619}(this, (function () { 'use strict';
29620
29621var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
29622
29623function commonjsRequire () {
29624	throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
29625}
29626
29627function unwrapExports (x) {
29628	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
29629}
29630
29631function createCommonjsModule(fn, module) {
29632	return module = { exports: {} }, fn(module, module.exports), module.exports;
29633}
29634
29635var jspdf_min = createCommonjsModule(function (module, exports) {
29636!function(t,e){module.exports=e();}(commonjsGlobal,function(){var t,y,e,I,i,o,a,h,C,T,d,p,F,n,r,s,c,P,E,q,g,m,w,l,v,b,x,S,u,k,_,f,A,O,B,R,j,D,M,U,N,z,L,H,W,G,V,Y,X,J,K,Q,Z,vt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$=function(pt){var gt="1.3",mt={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};function wt(o){var a={};this.subscribe=function(t,e,n){if("function"!=typeof e)return!1;a.hasOwnProperty(t)||(a[t]={});var r=Math.random().toString(35);return a[t][r]=[e,!!n], r}, this.unsubscribe=function(t){for(var e in a)if(a[e][t])return delete a[e][t], !0;return!1}, this.publish=function(t){if(a.hasOwnProperty(t)){var e=Array.prototype.slice.call(arguments,1),n=[];for(var r in a[t]){var i=a[t][r];try{i[0].apply(o,e);}catch(t){pt.console&&console.error("jsPDF PubSub Error",t.message,t);}i[1]&&n.push(r);}n.length&&n.forEach(this.unsubscribe);}};}function yt(t,e,n,r){var i={};"object"===(void 0===t?"undefined":vt(t))&&(t=(i=t).orientation, e=i.unit||e, n=i.format||n, r=i.compress||i.compressPdf||r), e=e||"mm", n=n||"a4", t=(""+(t||"P")).toLowerCase();(""+n).toLowerCase();var K,w,y,o,u,v,a,s,h,c,l,f=!!r&&"function"==typeof Uint8Array,Q=i.textColor||"0 g",d=i.drawColor||"0 G",Z=i.fontSize||16,$=i.charSpace||0,tt=i.R2L||!1,et=i.lineHeight||1.15,p=i.lineWidth||.200025,g="00000000000000000000000000000000",m=2,b=!1,x=[],nt={},S={},k=0,_=[],A=[],I=[],C=[],T=[],F=0,P=0,E=0,q={title:"",subject:"",author:"",keywords:"",creator:""},O={},rt=new wt(O),B=i.hotfixes||[],R=function(t){var e,n=t.ch1,r=t.ch2,i=t.ch3,o=t.ch4,a=(t.precision, "draw"===t.pdfColorType?["G","RG","K"]:["g","rg","k"]);if("string"==typeof n&&"#"!==n.charAt(0)){var s=new RGBColor(n);s.ok&&(n=s.toHex());}if("string"==typeof n&&/^#[0-9A-Fa-f]{3}$/.test(n)&&(n="#"+n[1]+n[1]+n[2]+n[2]+n[3]+n[3]), "string"==typeof n&&/^#[0-9A-Fa-f]{6}$/.test(n)){var h=parseInt(n.substr(1),16);n=h>>16&255, r=h>>8&255, i=255&h;}if(void 0===r||void 0===o&&n===r&&r===i)if("string"==typeof n)e=n+" "+a[0];
29636else switch(t.precision){case 2:e=N(n/255)+" "+a[0];break;case 3:default:e=z(n/255)+" "+a[0];}else if(void 0===o||"object"===(void 0===o?"undefined":vt(o))){if("string"==typeof n)e=[n,r,i,a[1]].join(" ");else switch(t.precision){case 2:e=[N(n/255),N(r/255),N(i/255),a[1]].join(" ");break;default:case 3:e=[z(n/255),z(r/255),z(i/255),a[1]].join(" ");}o&&0===o.a&&(e=["255","255","255",a[1]].join(" "));}else if("string"==typeof n)e=[n,r,i,o,a[2]].join(" ");else switch(t.precision){case 2:e=[N(n),N(r),N(i),N(o),a[2]].join(" ");break;case 3:default:e=[z(n),z(r),z(i),z(o),a[2]].join(" ");}return e},j=function(t){var e=function(t){return("0"+parseInt(t)).slice(-2)},n=t.getTimezoneOffset(),r=n<0?"+":"-",i=Math.floor(Math.abs(n/60)),o=Math.abs(n%60),a=[r,e(i),"'",e(o),"'"].join("");return["D:",t.getFullYear(),e(t.getMonth()+1),e(t.getDate()),e(t.getHours()),e(t.getMinutes()),e(t.getSeconds()),a].join("")},D=function(t){var e;return void 0===(void 0===t?"undefined":vt(t))&&(t=new Date), e="object"===(void 0===t?"undefined":vt(t))&&"[object Date]"===Object.prototype.toString.call(t)?j(t):/^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|\-0[0-9]|\-1[0-1])\'(0[0-9]|[1-5][0-9])\'?$/.test(t)?t:j(new Date), c=e},M=function(t){var e=c;return"jsDate"===t&&(e=function(t){var e=parseInt(t.substr(2,4),10),n=parseInt(t.substr(6,2),10)-1,r=parseInt(t.substr(8,2),10),i=parseInt(t.substr(10,2),10),o=parseInt(t.substr(12,2),10),a=parseInt(t.substr(14,2),10);parseInt(t.substr(16,2),10), parseInt(t.substr(20,2),10);return new Date(e,n,r,i,o,a,0)}(c)), e},U=function(t){return t=t||"12345678901234567890123456789012".split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""), g=t},N=function(t){return t.toFixed(2)},z=function(t){return t.toFixed(3)},it=function(t){t="string"==typeof t?t:t.toString(), b?_[o].push(t):(E+=t.length+1, C.push(t));},L=function(){return x[++m]=E, it(m+" 0 obj"), m},H=function(t){it("stream"), it(t), it("endstream");},W=function(){for(var t in it("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"), it("/Font <<"), nt)nt.hasOwnProperty(t)&&it("/"+t+" "+nt[t].objectNumber+" 0 R");it(">>"), it("/XObject <<"), rt.publish("putXobjectDict"), it(">>");},G=function(){!function(){for(var t in nt)nt.hasOwnProperty(t)&&(e=nt[t], rt.publish("putFont",{font:e,out:it,newObject:L}), !0!==e.isAlreadyPutted&&(e.objectNumber=L(), it("<<"), it("/Type /Font"), it("/BaseFont /"+e.postScriptName), it("/Subtype /Type1"), "string"==typeof e.encoding&&it("/Encoding /"+e.encoding), it("/FirstChar 32"), it("/LastChar 255"), it(">>"), it("endobj")));var e;}(), rt.publish("putResources"), x[2]=E, it("2 0 obj"), it("<<"), W(), it(">>"), it("endobj"), rt.publish("postPutResources");},V=function(t,e,n){S.hasOwnProperty(e)||(S[e]={}), S[e][n]=t;},Y=function(t,e,n,r){var i="F"+(Object.keys(nt).length+1).toString(10),o=nt[i]={id:i,postScriptName:t,fontName:e,fontStyle:n,encoding:r,metadata:{}};return V(i,e,n), rt.publish("addFont",o), i},ot=function(t,e){return function(t,e){var n,r,i,o,a,s,h,c,l;if(i=(e=e||{}).sourceEncoding||"Unicode", a=e.outputEncoding, (e.autoencode||a)&&nt[K].metadata&&nt[K].metadata[i]&&nt[K].metadata[i].encoding&&(o=nt[K].metadata[i].encoding, !a&&nt[K].encoding&&(a=nt[K].encoding), !a&&o.codePages&&(a=o.c
29636odePages[0]), "string"==typeof a&&(a=o[a]), a)){for(h=!1, s=[], n=0, r=t.length;n<r;n++)(c=a[t.charCodeAt(n)])?s.push(String.fromCharCode(c)):s.push(t[n]), s[n].charCodeAt(0)>>8&&(h=!0);t=s.join("");}for(n=t.length;void 0===h&&0!==n;)t.charCodeAt(n-1)>>8&&(h=!0), n--;if(!h)return t;for(s=e.noBOM?[]:[254,255], n=0, r=t.length;n<r;n++){if((l=(c=t.charCodeAt(n))>>8)>>8)throw new Error("Character at position "+n+" of string '"+t+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");s.push(l), s.push(c-(l<<8));}return String.fromCharCode.apply(void 0,s)}(t,e).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},X=function(){(function(t,e){var n="string"==typeof e&&e.toLowerCase();if("string"==typeof t){var r=t.toLowerCase();mt.hasOwnProperty(r)&&(t=mt[r][0]/w, e=mt[r][1]/w);}if(Array.isArray(t)&&(e=t[1], t=t[0]), n){switch(n.substr(0,1)){case"l":t<e&&(n="s");break;case"p":e<t&&(n="s");}"s"===n&&(y=t, t=e, e=y);}b=!0, _[++k]=[], I[k]={width:Number(t)||u,height:Number(e)||v}, A[k]={}, J(k);}).apply(this,arguments), it(N(p*w)+" w"), it(d), 0!==F&&it(F+" J"), 0!==P&&it(P+" j"), rt.publish("addPage",{pageNumber:k});},J=function(t){0<t&&t<=k&&(u=I[o=t].width, v=I[t].height);},at=function(t,e,n){var r,i=void 0;return n=n||{}, t=void 0!==t?t:nt[K].fontName, e=void 0!==e?e:nt[K].fontStyle, r=t.toLowerCase(), void 0!==S[r]&&void 0!==S[r][e]?i=S[r][e]:void 0!==S[t]&&void 0!==S[t][e]?i=S[t][e]:!1===n.disableWarning&&console.warn("Unable to look up font label for font '"+t+"', '"+e+"'. Refer to getFontList() for available fonts."), i||n.noFallback||null==(i=S.times[e])&&(i=S.times.normal), i},st=function(){b=!1, m=2, E=0, C=[], x=[], T=[], rt.publish("buildDocument"), it("%PDF-"+gt), it("%ºß¬à"), function(){var t,e,n,r,i,o,a,s,h,c=[];for(a=pt.adler32cs||yt.API.adler32cs, f&&void 0===a&&(f=!1), t=1;t<=k;t++){if(c.push(L()), s=(u=I[t].width)*w, h=(v=I[t].height)*w, it("<</Type /Page"), it("/Parent 1 0 R"), it("/Resources 2 0 R"), it("/MediaBox [0 0 "+N(s)+" "+N(h)+"]"), rt.publish("putPage",{pageNumber:t,page:_[t]}), it("/Contents "+(m+1)+" 0 R"), it(">>"), it("endobj"), e=_[t].join("\n"), L(), f){for(n=[], r=e.length;r--;)n[r]=e.charCodeAt(r);o=a.from(e), (i=new Deflater(6)).append(new Uint8Array(n)), e=i.flush(), (n=new Uint8Array(e.length+6)).set(new Uint8Array([120,156])), n.set(e,2), n.set(new Uint8Array([255&o,o>>8&255,o>>16&255,o>>24&255]),e.length+2), e=String.fromCharCode.apply(null,n), it("<</Length "+e.length+" /Filter [/FlateDecode]>>");}else it("<</Length "+e.length+">>");H(e), it("endobj");}x[1]=E, it("1 0 obj"), it("<</Type /Pages");var l="/Kids [";for(r=0;r<k;r++)l+=c[r]+" 0 R ";it(l+"]"), it("/Count "+k), it(">>"), it("endobj"), rt.publish("postPutPages");}(), function(){rt.publish("putAdditionalObjects");for(var t=0;t<T.length;t++){var e=T[t];x[e.objId]=E, it(e.objId+" 0 obj"), it(e.content), it("endobj");}m+=T.length, rt.publish("postPutAdditionalObjects");}(), G(), L(), it("<<"), function(){for(var t in it("/Producer (jsPDF "+yt.version+")"), q)q.hasOwnProperty(t)&&q[t]&&it("/"+t.substr(0,1).toUpperCase()+t.substr(1)+" ("+ot(q[t])+")");it("/CreationDate ("+c+")");}(), it(">>"), it("endobj"), L(), it("<<"), function(){switch(it("/Type /Catalog"), it("/Pages 1 0 R"), s||(s="fullwidth"), s){case"fullwidth":it("/OpenAction [3 0 R /FitH null]");break;case"fullheight":it("/OpenAction [3 0 R /FitV null]");break;case"fullpage":it("/OpenAction [3 0 R /Fit]");break;case"original":it("/OpenAction [3 0 R /XYZ null null 1]");break;default:var t=""+s;"%"===t.substr(t.length-1)&&(s=parseInt(s)/100), "number"==typeof s&&it("/OpenAction [3 0 R /XYZ null null "+N(s)+"]");}switch(h||(h="continuous"), h){case"continuous":it("/PageLayout /OneColumn");break;case"single":it("/PageLayout /SinglePage");break;case"two":case"twoleft":it("/PageLayout /TwoColumnLeft");break;case"tworight":it("/PageLayout /TwoColumnRight");}a&&it("/PageMode /"+a), rt.publish("putCatalog");}(), it(">>"), it("endobj");var t,e=E,n="0000000000";for(it("xref"), it("0 "+(m+1)), it(n+" 65535 f "), t=1;t<=m;t++){var r=x[t];it("function"==typeof r?(n+x[t]()).slice(-10)+" 00000 n ":(n+x[t]).slice(-10)+" 00000 n ");}return it("trailer"), it("<<"), it("/Size "+(m+1)), it("/Root "+m+" 0 R"), it("/Info "+(m-1)+" 0 R"), it("/ID [ <"+g+"> <"+g+"> ]"), it(">>
29636"), it("startxref"), it(""+e), it("%%EOF"), b=!0, C.join("\n")},ht=function(t){var e="S";return"F"===t?e="f":"FD"===t||"DF"===t?e="B":"f"!==t&&"f*"!==t&&"B"!==t&&"B*"!==t||(e=t), e},ct=function(){for(var t=st(),e=t.length,n=new ArrayBuffer(e),r=new Uint8Array(n);e--;)r[e]=t.charCodeAt(e);return n},lt=function(){return new Blob([ct()],{type:"application/pdf"})},ut=((l=function(t,e){var n="dataur"===(""+t).substr(0,6)?"data:application/pdf;base64,"+btoa(st()):0;switch(t){case void 0:return st();case"save":if("object"===("undefined"==typeof navigator?"undefined":vt(navigator))&&navigator.getUserMedia&&(void 0===pt.URL||void 0===pt.URL.createObjectURL))return O.output("dataurlnewwindow");bt(lt(),e), "function"==typeof bt.unload&&pt.setTimeout&&setTimeout(bt.unload,911);break;case"arraybuffer":return ct();case"blob":return lt();case"bloburi":case"bloburl":return pt.URL&&pt.URL.createObjectURL(lt())||void 0;case"datauristring":case"dataurlstring":return n;case"dataurlnewwindow":var r=pt.open(n);if(r||"undefined"==typeof safari)return r;case"datauri":case"dataurl":return pt.document.location.href=n;default:throw new Error('Output type "'+t+'" is not supported.')}}).foo=function(){try{return l.apply(this,arguments)}catch(t){var e=t.stack||"";~e.indexOf(" at ")&&(e=e.split(" at ")[1]);var n="Error in function "+e.split("\n")[0].split("<")[0]+": "+t.message;if(!pt.console)throw new Error(n);pt.console.error(n,t), pt.alert&&alert(n);}}, (l.foo.bar=l).foo),ft=function(t){return!0===Array.isArray(B)&&-1<B.indexOf(t)};switch(e){case"pt":w=1;break;case"mm":w=72/25.4;break;case"cm":w=72/2.54;break;case"in":w=72;break;case"px":w=1==ft("px_scaling")?.75:96/72;break;case"pc":case"em":w=12;break;case"ex":w=6;break;default:throw"Invalid unit: "+e}for(var dt in D(), U(), O.internal={pdfEscape:ot,getStyle:ht,getFont:function(){return nt[at.apply(O,arguments)]},getFontSize:function(){return Z},getCharSpace:function(){return $},getTextColor:function(){var t=Q.split(" ");if(2===t.length&&"g"===t[1]){var e=parseFloat(t[0]);t=[e,e,e,"r"];}for(var n="#",r=0;r<3;r++)n+=("0"+Math.floor(255*parseFloat(t[r])).toString(16)).slice(-2);return n},getLineHeight:function(){return Z*et},write:function(t){it(1===arguments.length?t:Array.prototype.join.call(arguments," "));},getCoordinateString:function(t){return N(t*w)},getVerticalCoordinateString:function(t){return N((v-t)*w)},collections:{},newObject:L,newAdditionalObject:function(){var t=2*_.length+1,e={objId:t+=T.length,content:""};return T.push(e), e},newObjectDeferred:function(){return x[++m]=function(){return E}, m},newObjectDeferredBegin:function(t){x[t]=E;},putStream:H,events:rt,scaleFactor:w,pageSize:{getWidth:function(){return u},getHeight:function(){return v}},output:function(t,e){return ut(t,e)},getNumberOfPages:function(){return _.length-1},pages:_,out:it,f2:N,getPageInfo:function(t){return{objId:2*(t-1)+3,pageNumber:t,pageContext:A[t]}},getCurrentPageInfo:function(){return{objId:2*(o-1)+3,pageNumber:o,pageContext:A[o]}},getPDFVersion:function(){return gt},hasHotfix:ft}, O.addPage=function(){return X.apply(this,arguments), this}, O.setPage=function(){return J.apply(this,arguments), this}, O.insertPage=function(t){return this.addPage(), this.movePage(o,t), this}, O.movePage=function(t,e){if(e<t){for(var n=_[t],r=I[t],i=A[t],o=t;e<o;o--)_[o]=_[o-1], I[o]=I[o-1], A[o]=A[o-1];_[e]=n, I[e]=r, A[e]=i, this.setPage(e);}else if(t<e){for(n=_[t], r=I[t], i=A[t], o=t;o<e;o++)_[o]=_[o+1], I[o]=I[o+1], A[o]=A[o+1];_[e]=n, I[e]=r, A[e]=i, this.setPage(e);}return this}, O.deletePage=function(){return function(t){0<t&&t<=k&&(_.splice(t,1), I.splice(t,1), --k<o&&(o=k), this.setPage(o));}.apply(this,arguments), this}, O.setCreationDate=function(t){return D(t), this}, O.getCreationDate=function(t){return M(t)}, O.setFileId=function(t){return U(t), this}, O.getFileId=function(){return g}, O.setDisplayMode=function(t,e,n){if(s=t, h=e, -1==[void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(a=n))throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+n+'" is not recognized.');return this}, O.text=function(t,e,n,i){var r,o,a="",s=et,h=this;function c(t){for(var e,n=t.concat(),r=[],i=n.length;i--;
29636)"string"==typeof(e=n.shift())?r.push(e):"[object Array]"===Object.prototype.toString.call(t)&&1===e.length?r.push(e[0]):r.push([e[0],e[1],e[2]]);return r}function l(t,e){var n;if("string"==typeof t)n=e(t)[0];else if("[object Array]"===Object.prototype.toString.call(t)){for(var r,i,o=t.concat(),a=[],s=o.length;s--;)"string"==typeof(r=o.shift())?a.push(e(r)[0]):"[object Array]"===Object.prototype.toString.call(r)&&"string"===r[0]&&(i=e(r[0],r[1],r[2]), a.push([i[0],i[1],i[2]]));n=a;}return n}"number"==typeof t&&(o=n, n=e, e=t, t=o);var u=i,f=arguments[4],d=arguments[5];"object"===(void 0===u?"undefined":vt(u))&&null!==u||("string"==typeof f&&(d=f, f=null), "string"==typeof u&&(d=u, u=null), "number"==typeof u&&(f=u, u=null), i={flags:u,angle:f,align:d});var p=!1,g=!0;if("string"==typeof t)p=!0;else if("[object Array]"===Object.prototype.toString.call(t)){for(var m,w=t.concat(),y=[],v=w.length;v--;)("string"!=typeof(m=w.shift())||"[object Array]"===Object.prototype.toString.call(m)&&"string"!=typeof m[0])&&(g=!1);p=g;}if(!1===p)throw new Error('Type of text must be string or Array. "'+t+'" is not recognized.');var b=nt[K].encoding;"WinAnsiEncoding"!==b&&"StandardEncoding"!==b||(t=l(t,function(t,e,n){return[(r=t, r=r.split("\t").join(Array(i.TabLen||9).join(" ")), ot(r,u)),e,n];var r;})), "string"==typeof t&&(t=t.match(/[\r?\n]/)?t.split(/\r\n|\r|\n/g):[t]), 0<(j=i.maxWidth||0)&&("string"==typeof t?t=h.splitTextToSize(t,j):"[object Array]"===Object.prototype.toString.call(t)&&(t=h.splitTextToSize(t.join(" "),j)));var x={text:t,x:e,y:n,options:i,mutex:{pdfEscape:ot,activeFontKey:K,fonts:nt,activeFontSize:Z}};rt.publish("preProcessText",x), t=x.text;f=(i=x.options).angle;var S=h.internal.scaleFactor,k=(h.internal.pageSize.getHeight(), []);if(f){f*=Math.PI/180;var _=Math.cos(f),A=Math.sin(f),I=function(t){return t.toFixed(2)};k=[I(_),I(A),I(-1*A),I(_)];}void 0!==(R=i.charSpace)&&(a+=R+" Tc\n");i.lang;var C=-1,T=i.renderingMode||i.stroke,F=h.internal.getCurrentPageInfo().pageContext;switch(T){case 0:case!1:case"fill":C=0;break;case 1:case!0:case"stroke":C=1;break;case 2:case"fillThenStroke":C=2;break;case 3:case"invisible":C=3;break;case 4:case"fillAndAddForClipping":C=4;break;case 5:case"strokeAndAddPathForClipping":C=5;break;case 6:case"fillThenStrokeAndAddToPathForClipping":C=6;break;case 7:case"addToPathForClipping":C=7;}var P=F.usedRenderingMode||-1;-1!==C?a+=C+" Tr\n":-1!==P&&(a+="0 Tr\n"), -1!==C&&(F.usedRenderingMode=C);d=i.align||"left";var E=Z*s,q=h.internal.pageSize.getHeight(),O=h.internal.pageSize.getWidth(),B=(S=h.internal.scaleFactor, nt[K]),R=i.charSpace||$,j=i.maxWidth||0,D=(u={}, []);if("[object Array]"===Object.prototype.toString.call(t)){var M,U;y=c(t);"left"!==d&&(U=y.map(function(t){return h.getStringUnitWidth(t,{font:B,charSpace:R,fontSize:Z})*Z/S}));var N,z=Math.max.apply(Math,U),L=0;if("right"===d){e-=U[0], t=[];var H=0;for(v=y.length;H<v;H++)z-U[H], 0===H?(N=e*S, M=(q-n)*S):(N=(L-U[H])*S, M=-E), t.push([y[H],N,M]), L=U[H];}else if("center"===d){e-=U[0]/2, t=[];for(H=0, v=y.length;H<v;H++)(z-U[H])/2, 0===H?(N=e*S, M=(q-n)*S):(N=(L-U[H])/2*S, M=-E), t.push([y[H],N,M]), L=U[H];}else if("left"===d){t=[];for(H=0, v=y.length;H<v;H++)M=0===H?(q-n)*S:-E, N=0===H?e*S:0, t.push(y[H]);}else{if("justify"!==d)throw new Error('Unrecognized alignment option, use "left", "center", "right" or "justify".');t=[];for(j=0!==j?j:O, H=0, v=y.length;H<v;H++)M=0===H?(q-n)*S:-E, N=0===H?e*S:0, H<v-1&&D.push(((j-U[H])/(y[H].split(" ").length-1)*S).toFixed(2)), t.push([y[H],N,M]);}}!0===("boolean"==typeof i.R2L?i.R2L:tt)&&(t=l(t,function(t,e,n){return[t.split("").reverse().join(""),e,n]}));x={text:t,x:e,y:n,options:i,mutex:{pdfEscape:ot,activeFontKey:K,fonts:nt,activeFontSize:Z}};rt.publish("postProcessText",x), t=x.text, r=x.mutex.isHex;y=c(t);t=[];var W,G,V,Y=0,X=(v=y.length, "");for(H=0;H<v;H++)X="", "[object Array]"!==Object.prototype.toString.call(y[H])?(W=parseFloat(e*S).toFixed(2), G=parseFloat((q-n)*S).toFixed(2), V=(r?"<":"(")+y[H]+(r?">":")")):"[object Array]"===Object.prototype.toString.call(y[H])&&(W=parseFloat(y[H][1]).toFixed(2), G=parseFloat(y[H][2]).toFixed(2), V=(r?"<":"(")+y[H][0]+(r?">":")"), Y=1), void 0!==D&&void 0!==D[H]&&(X=D[H]+" Tw\n"), 0!==k.length&&0===H?t.push(X+k.join(" ")+" "+W+" "+G+" Tm\n"+V):1===Y||0===Y&&0===H?t.push(X+W+" "+G+" Td\n"+V):t.push(X+V);t=0===Y?t.join(" Tj\nT* "):t.join(" Tj\n"), t+=" Tj\n";var J="BT\n/"+K+" "+Z+" Tf\n"+(Z*s).toFixed(2)+" TL\n"+Q+"\n";return J+=a, J+=t, it(J+="ET"), h}, O.lstext=function(t,e,n,r){console.warn("jsPDF.lstext is deprecated");for(var i=0,o=t.length;i<o;i++, e+=r)this.text(t[i],e,n);return this}, O.line=function(t,e,n,r){return this.lines([[n-t,r-e]],t,e)}
29636, O.clip=function(){it("W"), it("S");}, O.clip_fixed=function(t){it("evenodd"===t?"W*":"W"), it("n");}, O.lines=function(t,e,n,r,i,o){var a,s,h,c,l,u,f,d,p,g,m;for("number"==typeof t&&(y=n, n=e, e=t, t=y), r=r||[1,1], it(z(e*w)+" "+z((v-n)*w)+" m "), a=r[0], s=r[1], c=t.length, g=e, m=n, h=0;h<c;h++)2===(l=t[h]).length?(g=l[0]*a+g, m=l[1]*s+m, it(z(g*w)+" "+z((v-m)*w)+" l")):(u=l[0]*a+g, f=l[1]*s+m, d=l[2]*a+g, p=l[3]*s+m, g=l[4]*a+g, m=l[5]*s+m, it(z(u*w)+" "+z((v-f)*w)+" "+z(d*w)+" "+z((v-p)*w)+" "+z(g*w)+" "+z((v-m)*w)+" c"));return o&&it(" h"), null!==i&&it(ht(i)), this}, O.rect=function(t,e,n,r,i){ht(i);return it([N(t*w),N((v-e)*w),N(n*w),N(-r*w),"re"].join(" ")), null!==i&&it(ht(i)), this}, O.triangle=function(t,e,n,r,i,o,a){return this.lines([[n-t,r-e],[i-n,o-r],[t-i,e-o]],t,e,[1,1],a,!0), this}, O.roundedRect=function(t,e,n,r,i,o,a){var s=4/3*(Math.SQRT2-1);return this.lines([[n-2*i,0],[i*s,0,i,o-o*s,i,o],[0,r-2*o],[0,o*s,-i*s,o,-i,o],[2*i-n,0],[-i*s,0,-i,-o*s,-i,-o],[0,2*o-r],[0,-o*s,i*s,-o,i,-o]],t+i,e,[1,1],a), this}, O.ellipse=function(t,e,n,r,i){var o=4/3*(Math.SQRT2-1)*n,a=4/3*(Math.SQRT2-1)*r;return it([N((t+n)*w),N((v-e)*w),"m",N((t+n)*w),N((v-(e-a))*w),N((t+o)*w),N((v-(e-r))*w),N(t*w),N((v-(e-r))*w),"c"].join(" ")), it([N((t-o)*w),N((v-(e-r))*w),N((t-n)*w),N((v-(e-a))*w),N((t-n)*w),N((v-e)*w),"c"].join(" ")), it([N((t-n)*w),N((v-(e+a))*w),N((t-o)*w),N((v-(e+r))*w),N(t*w),N((v-(e+r))*w),"c"].join(" ")), it([N((t+o)*w),N((v-(e+r))*w),N((t+n)*w),N((v-(e+a))*w),N((t+n)*w),N((v-e)*w),"c"].join(" ")), null!==i&&it(ht(i)), this}, O.circle=function(t,e,n,r){return this.ellipse(t,e,n,n,r)}, O.setProperties=function(t){for(var e in q)q.hasOwnProperty(e)&&t[e]&&(q[e]=t[e]);return this}, O.setFontSize=function(t){return Z=t, this}, O.setFont=function(t,e){return K=at(t,e), this}, O.setFontStyle=O.setFontType=function(t){return K=at(void 0,t), this}, O.getFontList=function(){var t,e,n,r={};for(t in S)if(S.hasOwnProperty(t))for(e in r[t]=n=[], S[t])S[t].hasOwnProperty(e)&&n.push(e);return r}, O.addFont=function(t,e,n,r){Y(t,e,n,r=r||"Identity-H");}, O.setLineWidth=function(t){return it((t*w).toFixed(2)+" w"), this}, O.setDrawColor=function(t,e,n,r){return it(R({ch1:t,ch2:e,ch3:n,ch4:r,pdfColorType:"draw",precision:2})), this}, O.setFillColor=function(t,e,n,r){return it(R({ch1:t,ch2:e,ch3:n,ch4:r,pdfColorType:"fill",precision:2})), this}, O.setTextColor=function(t,e,n,r){return Q=R({ch1:t,ch2:e,ch3:n,ch4:r,pdfColorType:"text",precision:3}), this}, O.setCharSpace=function(t){return $=t, this}, O.setR2L=function(t){return tt=t, this}, O.CapJoinStyles={0:0,butt:0,but:0,miter:0,1:1,round:1,rounded:1,circle:1,2:2,projecting:2,project:2,square:2,bevel:2}, O.setLineCap=function(t){var e=this.CapJoinStyles[t];if(void 0===e)throw new Error("Line cap style of '"+t+"' is not recognized. See or extend .CapJoinStyles property for valid styles");return it((F=e)+" J"), this}, O.setLineJoin=function(t){var e=this.CapJoinStyles[t];if(void 0===e)throw new Error("Line join style of '"+t+"' is not recognized. See or extend .CapJoinStyles property for valid styles");return it((P=e)+" j"), this}, O.output=ut, O.save=function(t){O.output("save",t);}, yt.API)yt.API.hasOwnProperty(dt)&&("events"===dt&&yt.API.events.length?function(t,e){var n,r,i;for(i=e.length-1;-1!==i;i--)n=e[i][0], r=e[i][1], t.subscribe.apply(t,[n].concat("function"==typeof r?[r]:r));}(rt,yt.API.events):O[dt]=yt.API[dt]);return function(){for(var t="helvetica",e="times",n="courier",r="normal",i="bold",o="italic",a="bolditalic",s=[["Helvetica",t,r,"WinAnsiEncoding"],["Helvetica-Bold",t,i,"WinAnsiEncoding"],["Helvetica-Oblique",t,o,"WinAnsiEncoding"],["Helvetica-BoldOblique",t,a,"WinAnsiEncoding"],["Courier",n,r,"WinAnsiEncoding"],["Courier-Bold",n,i,"WinAnsiEncoding"],["Courier-Oblique",n,o,"WinAnsiEncoding"],["Courier-BoldOblique",n,a,"WinAnsiEncoding"],["Times-Roman",e,r,"WinAnsiEncoding"],["Times-Bold",e,i,"WinAnsiEncoding"],["Times-Italic",e,o,"WinAnsiEncoding"],["Times-BoldItalic",e,a,"WinAnsiEncoding"],["ZapfDingbats","zapfdingbats",r,null],["Symbol","symbol",r,null]],h=0,c=s.length;h<c;h++){var l=Y(s[h][0],s[h][1],s[h][2],s[h][3]),u=s[h][0].split("-");V(l,u[0],u[1]||"");}rt.publish("addFonts",{fonts:nt,dictionary:S});}(), K="F1", X(n,t), rt.publish("initialized"), O}return yt.API={events:[]}, yt.version="0.0.0", "function"==typeof undefined&&undefined.amd?undefined("jsPDF",function(){return yt}):"undefined"!='object'&&module.exports?(module.exports=yt, module.exports.jsPDF=yt):pt.jsPDF=yt, yt}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||"undefined"!=typeof commonjsGlobal&&commonjsGlobal||Function('return typeof this === "object" && this.content')()||Function("return this")());
29637/** @preserve
29638   * jsPDF - PDF Document creation from JavaScript
29639   * Version 1.4.1 Built on 2018-06-06T07:49:34.040Z
29640   *                           CommitID 3233f44044
29641   *
29642   * Copyright (c) 2010-2016 James Hall <[email protected]>, https://github.com/MrRio/jsPDF
29643   *               2010 Aaron Spike, https://github.com/acspike
29644   *               2012 Willow Systems Corporation, willow-systems.com
29645   *               2012 Pablo Hess, https://github.com/pablohess
29646   *               2012 Florian Jenett, https://github.com/fjenett
29647   *               2013 Warren Weckesser, https://github.com/warrenweckesser
29648   *               2013 Youssef Beddad, https://github.com/lifof
29649   *               2013 Lee Driscoll, https://github.com/lsdriscoll
29650   *               2013 Stefan Slonevskiy, https://github.com/stefslon
29651   *               2013 Jeremy Morel, https://github.com/jmorel
29652   *               2013 Christoph Hartmann, https://github.com/chris-rock
29653   *               2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
29654   *               2014 James Makes, https://github.com/dollaruw
29655   *               2014 Diego Casorran, https://github.com/diegocr
29656   *               2014 Steven Spungin, https://github.com/Flamenco
29657   *               2014 Kenneth Glassey, https://github.com/Gavver
29657s
29658   *
29659   * Licensed under the MIT License
29660   *
29661   * Contributor(s):
29662   *    siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
29663   *    kim3er, mfo, alnorth, Flamenco
29664   */
29665/**
29666   * jsPDF AcroForm Plugin Copyright (c) 2016 Alexander Weidt,
29667   * https://github.com/BiggA94
29668   * 
29669   * Licensed under the MIT License. http://opensource.org/licenses/mit-license
29670   */
29671!function(n,t){var l,a,e=1,r=function(t,e){t.prototype=Object.create(e.prototype), t.prototype.constructor=t;},s=function(t){return t*(e/1)},h=function(t){var e=new I,n=N.internal.getHeight(t)||0,r=N.internal.getWidth(t)||0;return e.BBox=[0,0,r.toFixed(2),n.toFixed(2)], e},i=function(t,e,n){t=t||0;var r=1;if(r<<=e-1, 1==(n=n||1))t=t|r;else t=t&~r;return t},o=function(t,e,n){n=n||1.3, t=t||0;return 1==e.readOnly&&(t=i(t,1)), 1==e.required&&(t=i(t,2)), 1==e.noExport&&(t=i(t,3)), 1==e.multiline&&(t=i(t,13)), e.password&&(t=i(t,14)), e.noToggleToOff&&(t=i(t,15)), e.radio&&(t=i(t,16)), e.pushbutton&&(t=i(t,17)), e.combo&&(t=i(t,18)), e.edit&&(t=i(t,19)), e.sort&&(t=i(t,20)), e.fileSelect&&1.4<=n&&(t=i(t,21)), e.multiSelect&&1.4<=n&&(t=i(t,22)), e.doNotSpellCheck&&1.4<=n&&(t=i(t,23)), 1==e.doNotScroll&&1.4<=n&&(t=i(t,24)), e.richText&&1.4<=n&&(t=i(t,25)), t},u=function(t){var e=t[0],n=t[1],r=t[2],i=t[3],o={};return Array.isArray(e)?(e[0]=s(e[0]), e[1]=s(e[1]), e[2]=s(e[2]), e[3]=s(e[3])):(e=s(e), n=s(n), r=s(r), i=s(i)), o.lowerLeft_X=e||0, o.lowerLeft_Y=s(a)-n-i||0, o.upperRight_X=e+r||0, o.upperRight_Y=s(a)-n||0, [o.lowerLeft_X.toFixed(2),o.lowerLeft_Y.toFixed(2),o.upperRight_X.toFixed(2),o.upperRight_Y.toFixed(2)]},f=function(t){if(t.appearanceStreamContent)return t.appearanceStreamContent;if(t.V||t.DV){var e=[],n=t.V||t.DV,r=c(t,n);e.push("/Tx BMC"), e.push("q"), e.push("/F1 "+r.fontSize.toFixed(2)+" Tf"), e.push("1 0 0 1 0 0 Tm"), e.push("BT"), e.push(r.text), e.push("ET"), e.push("Q"), e.push("EMC");var i=new h(t);return i.stream=e.join("\n"), i}},c=function(t,e,i,n){n=n||12, i=i||"helvetica";var r={text:"",fontSize:""},o=(e=")"==(e="("==e.substr(0,1)?e.substr(1):e).substr(e.length-1)?e.substr(0,e.length-1):e).split(" "),a=n,s=N.internal.getHeight(t)||0;s=s<0?-s:s;var h=N.internal.getWidth(t)||0;h=h<0?-h:h;var c=function(t,e,n){if(t+1<o.length){var r=e+" "+o[t+1];return A(r,n+"px",i).width<=h-4}return!1};a++;t:for(;;){e="";var l=A("3",--a+"px",i).height,u=t.multiline?s-a:(s-l)/2,f=-2,d=u+=2,p=0,g=0,m=0;if(a<=0){a=12, e="(...) Tj\n", e+="% Width of Text: "+A(e,"1px").width+", FieldWidth:"+h+"\n";break}m=A(o[0]+" ",a+"px",i).width;var w="",y=0;for(var v in o){w=" "==(w+=o[v]+" ").substr(w.length-1)?w.substr(0,w.length-1):w;var b=parseInt(v);m=A(w+" ",a+"px",i).width;var x=c(b,w,a),S=v>=o.length-1;if(!x||S){if(x||S){if(S)g=b;else if(t.multiline&&s<(l+2)*(y+2)+2)continue t}else{if(!t.multiline)continue t;if(s<(l+2)*(y+2)+2)continue t;g=b;}for(var k="",_=p;_<=g;_++)k+=o[_]+" ";switch(k=" "==k.substr(k.length-1)?k.substr(0,k.length-1):k, m=A(k,a+"px",i).width, t.Q){case 2:f=h-m-2;break;case 1:f=(h-m)/2;break;case 0:default:f=2;}e+=f.toFixed(2)+" "+d.toFixed(2)+" Td\n", e+="("+k+") Tj\n", e+=-f.toFixed(2)+" 0 Td\n", d=-(a+2), m=0, p=g+1, y++, w="";}else w+=" ";}break}return r.text=e, r.fontSize=a, r},A=function(t,e,n){n=n||"helvetica";var r=l.internal.getFont(n),i=l.getStringUnitWidth(t,{font:r,fontSize:parseFloat(e),charSpace:0})*parseFloat(e);return{height:l.getStringUnitWidth("3",{font:r,fontSize:parseFloat(e),charSpace:0})*parseFloat(e)*1.5,width:i}},d={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},p=function(){for(var t in l.internal.acroformPlugin.acroFormDictionaryRoot.Fields){var e=l.internal.acroformPlugin.acroFormDictionaryRoot.Fields[t];e.hasAnnotation&&m.call(l,e);}},g=function(t){l.internal.acroformPlugin.printedOut&&(l.internal.acroformPlugin.printedOut=!1, l.internal.acroformPlugin.acroFormDictionaryRoot=null), l.internal.acroformPlugin.acroFormDictionaryRoot||x.call(l), l.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(t);},m=function(t){var e={type:"reference",object:t};l.annotationPlugin.annotations[l.internal.getPageInfo(t.page).pageNumber].push(e);},w=function(){void 0!==l.internal.acroformPlugin.acroFormDictionaryRoot?l.internal.write("/AcroForm "+l.internal.acroformPlugin.acroFormDictionaryRoot.objId+" 0 R"):console.log("Root missing...");},y=function(){l.internal.events.unsubscribe(l.internal.acroformPlugin.acroFormDictionaryRoot._eventID), delete l.internal.acroformPlugin.acroFormDictionaryRoot._eventID, l.internal.acroformPlugin.printedOut=!0;},v=function(t){var e=!t;t||(l.internal.newObjectDeferredBegin(l.internal.acroformPlugin.acroFormDictionaryRoot.objId), l.internal.out(l.internal.acroformPlugin.acroFormDictionaryRoot.getString()));t=t||l.internal.acroformPlugin.acroFormDictionaryRoot.Kids;for(var n in t){var r=t[n],i=r.Rect;r.Rect&&(r.Rect=u.call(this,r.Rect)), l.internal.newObjectDeferredBegin(r.objId);var o=r.objId+" 0 obj\n<<\n";if("object"===(void 0===r?"undefined":vt(r))&&"function"==typeof r.getContent&&(o+=r.getContent()), r.Rect=i, r.hasAppearanceStream&&!r.appearanceStreamContent){var a=f.call(this,r);o+="/AP << /N "+a+" >>\n", l.internal.acroformPlugin.xForms.push(a);}if(r.appearanceStreamContent){for(var s in o+="/AP << ", r.appearanceStreamContent){var h=r.appearanceStreamContent[s];if(o+="/"+s+" ", o+="<< ", 1<=Object.keys(h).length||Array.isArray(h))for(var n in h){var c;"function"==typeof(c=h[n])&&(c=c.call(this,r)), o+="/"+n+" "+c+" ", 0<=l.internal.acroformPlugin.xForms.indexOf(c)||l.internal.acroformPlugin.xForms.push(c);}
29671else"function"==typeof(c=h)&&(c=c.call(this,r)), o+="/"+n+" "+c+" \n", 0<=l.internal.acroformPlugin.xForms.indexOf(c)||l.internal.acroformPlugin.xForms.push(c);o+=" >>\n";}o+=">>\n";}o+=">>\nendobj\n", l.internal.out(o);}e&&b.call(this,l.internal.acroformPlugin.xForms);},b=function(t){for(var e in t){var n=e,r=t[e];l.internal.newObjectDeferredBegin(r&&r.objId);var i="";"object"===(void 0===r?"undefined":vt(r))&&"function"==typeof r.getString&&(i=r.getString()), l.internal.out(i), delete t[n];}},x=function(){if(void 0!==this.internal&&(void 0===this.internal.acroformPlugin||!1===this.internal.acroformPlugin.isInitialized)){if(l=this, T.FieldNum=0, this.internal.acroformPlugin=JSON.parse(JSON.stringify(d)), this.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");e=l.internal.scaleFactor, a=l.internal.pageSize.getHeight(), l.internal.acroformPlugin.acroFormDictionaryRoot=new C, l.internal.acroformPlugin.acroFormDictionaryRoot._eventID=l.internal.events.subscribe("postPutResources",y), l.internal.events.subscribe("buildDocument",p), l.internal.events.subscribe("putCatalog",w), l.internal.events.subscribe("postPutPages",v), l.internal.acroformPlugin.isInitialized=!0;}},S=function(t){if(Array.isArray(t)){var e=" [";for(var n in t){e+=t[n].toString(), e+=n<t.length-1?" ":"";}return e+="]"}},k=function(t){return 0!==(t=t||"").indexOf("(")&&(t="("+t), ")"!=t.substring(t.length-1)&&(t+=")"), t},_=function(){var t;Object.defineProperty(this,"objId",{get:function(){return t||(t=l.internal.newObjectDeferred()), t||console.log("Couldn't create Object ID"), t},configurable:!1});};_.prototype.toString=function(){return this.objId+" 0 R"}, _.prototype.getString=function(){var t=this.objId+" 0 obj\n<<";return t+=this.getContent()+">>\n", this.stream&&(t+="stream\n", t+=this.stream, t+="\nendstream\n"), t+="endobj\n"}, _.prototype.getContent=function(){var t="";return t+=function(t){var e="",n=Object.keys(t).filter(function(t){return"content"!=t&&"appearanceStreamContent"!=t&&"_"!=t.substring(0,1)});for(var r in n){var i=n[r],o=t[i];o&&(Array.isArray(o)?e+="/"+i+" "+S(o)+"\n":e+=o instanceof _?"/"+i+" "+o.objId+" 0 R\n":"/"+i+" "+o+"\n");}return e}(this)};var I=function(){var e;_.call(this), this.Type="/XObject", this.Subtype="/Form", this.FormType=1, this.BBox, this.Matrix, this.Resources="2 0 R", this.PieceInfo, Object.defineProperty(this,"Length",{enumerable:!0,get:function(){return void 0!==e?e.length:0}}), Object.defineProperty(this,"stream",{enumerable:!1,set:function(t){e=t.trim();},get:function(){return e||null}});};r(I,_);var C=function(){_.call(this);var t=[];Object.defineProperty(this,"Kids",{enumerable:!1,configurable:!0,get:function(){return 0<t.length?t:void 0}}), Object.defineProperty(this,"Fields",{enumerable:!0,configurable:!0,get:function(){return t}}), this.DA;};r(C,_);var T=function t(){var e;_.call(this), Object.defineProperty(this,"Rect",{enumerable:!0,configurable:!1,get:function(){if(e)return e},set:function(t){e=t;}});var n,r,i,o,a="";Object.defineProperty(this,"FT",{enumerable:!0,set:function(t){a=t;},get:function(){return a}}), Object.defineProperty(this,"T",{enumerable:!0,configurable:!1,set:function(t){n=t;},get:function(){if(!n||n.length<1){if(this instanceof j)return;return"(FieldObject"+t.FieldNum+++")"}return"("==n.substring(0,1)&&n.substring(n.length-1)?n:"("+n+")"}}), Object.defineProperty(this,"DA",{enumerable:!0,get:function(){if(r)return"("+r+")"},set:function(t){r=t;}}), Object.defineProperty(this,"DV",{enumerable:!0,configurable:!0,get:function(){if(i)return i},set:function(t){i=t;}}), Object.defineProperty(this,"V",{enumerable:!0,configurable:!0,get:function(){if(o)return o},set:function(t){o=t;}}), Object.defineProperty(this,"Type",{enumerable:!0,get:function(){return this.hasAnnotation?"/Annot":null}}), Object.defineProperty(this,"Subtype",{enumerable:!0,get:function(){return this.hasAnnotation?"/Widget":null}}), this.BG, Object.defineProperty(this,"hasAnnotation",{enumerable:!1,get:function(){return!!(this.Rect||this.BC||this.BG)}}), Object.defineProperty(this,"hasAppearanceStream",{enumerable:!1,
29671configurable:!0,writable:!0}), Object.defineProperty(this,"page",{enumerable:!1,configurable:!0,writable:!0});};r(T,_);var F=function(){T.call(this), this.FT="/Ch", this.Opt=[], this.V="()", this.TI=0;var e=!1;Object.defineProperty(this,"combo",{enumerable:!1,get:function(){return e},set:function(t){e=t;}}), Object.defineProperty(this,"edit",{enumerable:!0,set:function(t){1==t?(this._edit=!0, this.combo=!0):this._edit=!1;},get:function(){return!!this._edit&&this._edit},configurable:!1}), this.hasAppearanceStream=!0;};r(F,T);var P=function(){F.call(this), this.combo=!1;};r(P,F);var E=function(){P.call(this), this.combo=!0;};r(E,P);var q=function(){E.call(this), this.edit=!0;};r(q,E);var O=function(){T.call(this), this.FT="/Btn";};r(O,T);var B=function(){O.call(this);var e=!0;Object.defineProperty(this,"pushbutton",{enumerable:!1,get:function(){return e},set:function(t){e=t;}});};r(B,O);var R=function(){O.call(this);var e=!0;Object.defineProperty(this,"radio",{enumerable:!1,get:function(){return e},set:function(t){e=t;}});var n,t=[];Object.defineProperty(this,"Kids",{enumerable:!0,get:function(){if(0<t.length)return t}}), Object.defineProperty(this,"__Kids",{get:function(){return t}}), Object.defineProperty(this,"noToggleToOff",{enumerable:!1,get:function(){return n},set:function(t){n=t;}});};r(R,O);var j=function(t,e){T.call(this), this.Parent=t, this._AppearanceType=N.RadioButton.Circle, this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(e), this.F=i(this.F,3,1), this.MK=this._AppearanceType.createMK(), this.AS="/Off", this._Name=e;};r(j,T), R.prototype.setAppearance=function(t){if("createAppearanceStream"in t&&"createMK"in t)for(var e in this.__Kids){var n=this.__Kids[e];n.appearanceStreamContent=t.createAppearanceStream(n._Name), n.MK=t.createMK();}else console.log("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");}, R.prototype.createOption=function(t){this.__Kids.length;var e=new j(this,t);return this.__Kids.push(e), n.addField(e), e};var D=function(){O.call(this), this.appearanceStreamContent=N.CheckBox.createAppearanceStream(), this.MK=N.CheckBox.createMK(), this.AS="/On", this.V="/On";};r(D,O);var M=function(){var e,n;T.call(this), this.DA=N.createDefaultAppearanceStream(), this.F=4, Object.defineProperty(this,"V",{get:function(){return e?k(e):e},enumerable:!0,set:function(t){e=t;}}), Object.defineProperty(this,"DV",{get:function(){return n?k(n):n},enumerable:!0,set:function(t){n=t;}});var r=!1;Object.defineProperty(this,"multiline",{enumerable:!1,get:function(){return r},set:function(t){r=t;}});var i=!1;Object.defineProperty(this,"fileSelect",{enumerable:!1,get:function(){return i},set:function(t){i=t;}});var o=!1;Object.defineProperty(this,"doNotSpellCheck",{enumerable:!1,get:function(){return o},set:function(t){o=t;}});var a=!1;Object.defineProperty(this,"doNotScroll",{enumerable:!1,get:function(){return a}
29671,set:function(t){a=t;}});var s=!1;Object.defineProperty(this,"MaxLen",{enumerable:!0,get:function(){return s},set:function(t){s=t;}}), Object.defineProperty(this,"hasAppearanceStream",{enumerable:!1,get:function(){return this.V||this.DV}});};r(M,T);var U=function(){M.call(this);var e=!0;Object.defineProperty(this,"password",{enumerable:!1,get:function(){return e},set:function(t){e=t;}});};r(U,M);var N={CheckBox:{createAppearanceStream:function(){return{N:{On:N.CheckBox.YesNormal},D:{On:N.CheckBox.YesPushDown,Off:N.CheckBox.OffPushDown}}},createMK:function(){return"<< /CA (3)>>"},YesPushDown:function(t){var e=h(t),n=[],r=l.internal.getFont("zapfdingbats","normal").id;t.Q=1;var i=c(t,"3","ZapfDingbats",50);return n.push("0.749023 g"), n.push("0 0 "+N.internal.getWidth(t).toFixed(2)+" "+N.internal.getHeight(t).toFixed(2)+" re"), n.push("f"), n.push("BMC"), n.push("q"), n.push("0 0 1 rg"), n.push("/"+r+" "+i.fontSize.toFixed(2)+" Tf 0 g"), n.push("BT"), n.push(i.text), n.push("ET"), n.push("Q"), n.push("EMC"), e.stream=n.join("\n"), e},YesNormal:function(t){var e=h(t),n=l.internal.getFont("zapfdingbats","normal").id,r=[];t.Q=1;var i=N.internal.getHeight(t),o=N.internal.getWidth(t),a=c(t,"3","ZapfDingbats",.9*i);return r.push("1 g"), r.push("0 0 "+o.toFixed(2)+" "+i.toFixed(2)+" re"), r.push("f"), r.push("q"), r.push("0 0 1 rg"), r.push("0 0 "+(o-1).toFixed(2)+" "+(i-1).toFixed(2)+" re"), r.push("W"), r.push("n"), r.push("0 g"), r.push("BT"), r.push("/"+n+" "+a.fontSize.toFixed(2)+" Tf 0 g"), r.push(a.text), r.push("ET"), r.push("Q"), e.stream=r.join("\n"), e},OffPushDown:function(t){var e=h(t),n=[];return n.push("0.749023 g"), n.push("0 0 "+N.internal.getWidth(t).toFixed(2)+" "+N.internal.getHeight(t).toFixed(2)+" re"), n.push("f"), e.stream=n.join("\n"), e}},RadioButton:{Circle:{createAppearanceStream:function(t){var e={D:{Off:N.RadioButton.Circle.OffPushDown},N:{}};return e.N[t]=N.RadioButton.Circle.YesNormal, e.D[t]=N.RadioButton.Circle.YesPushDown, e},createMK:function(){return"<< /CA (l)>>"},YesNormal:function(t){var e=h(t),n=[],r=N.internal.getWidth(t)<=N.internal.getHeight(t)?N.internal.getWidth(t)/4:N.internal.getHeight(t)/4;r*=.9;var i=N.internal.Bezier_C;return n.push("q"), n.push("1 0 0 1 "+N.internal.getWidth(t)/2+" "+N.internal.getHeight(t)/2+" cm"), n.push(r+" 0 m"), n.push(r+" "+r*i+" "+r*i+" "+r+" 0 "+r+" c"), n.push("-"+r*i+" "+r+" -"+r+" "+r*i+" -"+r+" 0 c"), n.push("-"+r+" -"+r*i+" -"+r*i+" -"+r+" 0 -"+r+" c"), n.push(r*i+" -"+r+" "+r+" -"+r*i+" "+r+" 0 c"), n.push("f"), n.push("Q"), e.stream=n.join("\n"), e},YesPushDown:function(t){var e=h(t),n=[],r=N.internal.getWidth(t)<=N.internal.getHeight(t)?N.internal.getWidth(t)/4:N.internal.getHeight(t)/4,i=2*(r*=.9),o=i*N.internal.Bezier_C,a=r*N.internal.Bezier_C;return n.push("0.749023 g"), n.push("q"), n.push("1 0 0 1 "+(N.internal.getWidth(t)/2).toFixed(2)+" "+(N.internal.getHeight(t)/2).toFixed(2)+" cm"), n.push(i+" 0 m"), n.push(i+" "+o+" "+o+" "+i+" 0 "+i+" c"), n.push("-"+o+" "+i+" -"+i+" "+o+" -"+i+" 0 c"), n.push("-"+i+" -"+o+" -"+o+" -"+i+" 0 -"+i+" c"), n.push(o+" -"+i+" "+i+" -"+o+" "+i+" 0 c"), n.push("f"), n.push("Q"), n.push("0 g"), n.push("q"), n.push("1 0 0 1 "+(N.internal.getWidth(t)/2).toFixed(2)+" "+(N.internal.getHeight(t)/2).toFixed(2)+" cm"), n.push(r+" 0 m"), n.push(r+" "+a+" "+a+" "+r+" 0 "+r+" c"), n.push("-"+a+" "+r+" -"+r+" "+a+" -"+r+" 0 c"), n.push("-"+r+" -"+a+" -"+a+" -"+r+" 0 -"+r+" c"), n.push(a+" -"+r+" "+r+" -"+a+" "+r+" 0 c"), n.push("f"), n.push("Q"), e.stream=n.join("\n"), e},OffPushDown:function(t){var e=h(t),n=[],r=N.internal.getWidth(t)<=N.internal.getHeight(t)?N.internal.getWidth(t)/4:N.internal.getHeight(t)/4,i=2*(r*=.9),o=i*N.internal.Bezier_C;return n.push("0.749023 g"), n.push("q"), n.push("1 0 0 1 "+(N.internal.getWidth(t)/2).toFixed(2)+" "+(N.internal.getHeight(t)/2).toFixed(2)+" cm"), n.push(i+" 0 m"), n.push(i+" "+o+" "+o+" "+i+" 0 "+i+" c"), n.push("-"+o+" "+i+" -"+i+" "+o+" -"+i+" 0 c"), n.push("-"+i+" -"+o+" -"+o+" -"+i+" 0 -"+i+" c"), n.push(o+" -"+i+" "+i+" -"+o+" "+i+" 0 c"), n.push("f"), n.push("Q"), e.stream=n.join("\n"), e}},Cross:{createAppearanceStream:function(t){var e={D:{Off:N.RadioButton.Cross.OffPushDown},N:{}}
29671;return e.N[t]=N.RadioButton.Cross.YesNormal, e.D[t]=N.RadioButton.Cross.YesPushDown, e},createMK:function(){return"<< /CA (8)>>"},YesNormal:function(t){var e=h(t),n=[],r=N.internal.calculateCross(t);return n.push("q"), n.push("1 1 "+(N.internal.getWidth(t)-2).toFixed(2)+" "+(N.internal.getHeight(t)-2).toFixed(2)+" re"), n.push("W"), n.push("n"), n.push(r.x1.x.toFixed(2)+" "+r.x1.y.toFixed(2)+" m"), n.push(r.x2.x.toFixed(2)+" "+r.x2.y.toFixed(2)+" l"), n.push(r.x4.x.toFixed(2)+" "+r.x4.y.toFixed(2)+" m"), n.push(r.x3.x.toFixed(2)+" "+r.x3.y.toFixed(2)+" l"), n.push("s"), n.push("Q"), e.stream=n.join("\n"), e},YesPushDown:function(t){var e=h(t),n=N.internal.calculateCross(t),r=[];return r.push("0.749023 g"), r.push("0 0 "+N.internal.getWidth(t).toFixed(2)+" "+N.internal.getHeight(t).toFixed(2)+" re"), r.push("f"), r.push("q"), r.push("1 1 "+(N.internal.getWidth(t)-2).toFixed(2)+" "+(N.internal.getHeight(t)-2).toFixed(2)+" re"), r.push("W"), r.push("n"), r.push(n.x1.x.toFixed(2)+" "+n.x1.y.toFixed(2)+" m"), r.push(n.x2.x.toFixed(2)+" "+n.x2.y.toFixed(2)+" l"), r.push(n.x4.x.toFixed(2)+" "+n.x4.y.toFixed(2)+" m"), r.push(n.x3.x.toFixed(2)+" "+n.x3.y.toFixed(2)+" l"), r.push("s"), r.push("Q"), e.stream=r.join("\n"), e},OffPushDown:function(t){var e=h(t),n=[];return n.push("0.749023 g"), n.push("0 0 "+N.internal.getWidth(t).toFixed(2)+" "+N.internal.getHeight(t).toFixed(2)+" re"), n.push("f"), e.stream=n.join("\n"), e}}},createDefaultAppearanceStream:function(t){return"/F1 0 Tf 0 g"}};N.internal={Bezier_C:.551915024494,calculateCross:function(t){var e,n,r=N.internal.getWidth(t),i=N.internal.getHeight(t),o=(n=i)<(e=r)?n:e;return{x1:{x:(r-o)/2,y:(i-o)/2+o},x2:{x:(r-o)/2+o,y:(i-o)/2},x3:{x:(r-o)/2,y:(i-o)/2},x4:{x:(r-o)/2+o,y:(i-o)/2+o}}}}, N.internal.getWidth=function(t){var e=0;return"object"===(void 0===t?"undefined":vt(t))&&(e=s(t.Rect[2])), e}, N.internal.getHeight=function(t){var e=0;return"object"===(void 0===t?"undefined":vt(t))&&(e=s(t.Rect[3])), e}, n.addField=function(t){return x.call(this), t instanceof M?this.addTextField.call(this,t):t instanceof F?this.addChoiceField.call(this,t):t instanceof O?this.addButton.call(this,t):t instanceof j?g.call(this,t):t&&g.call(this,t), t.page=l.internal.getCurrentPageInfo().pageNumber, this}, n.addButton=function(t){x.call(this);var e=t||new T;e.FT="/Btn", e.Ff=o(e.Ff,t,l.internal.getPDFVersion()), g.call(this,e);}, n.addTextField=function(t){x.call(this);var e=t||new T;e.FT="/Tx", e.Ff=o(e.Ff,t,l.internal.getPDFVersion()), g.call(this,e);}, n.addChoiceField=function(t){x.call(this);var e=t||new T;e.FT="/Ch", e.Ff=o(e.Ff,t,l.internal.getPDFVersion()), g.call(this,e);}, "object"==(void 0===t?"undefined":vt(t))&&(t.ChoiceField=F, t.ListBox=P, t.ComboBox=E, t.EditBox=q, t.Button=O, t.PushButton=B, t.RadioButton=R, t.CheckBox=D, t.TextField=M, t.PasswordField=U, t.AcroForm={Appearance:N}), n.AcroFormChoiceField=F, n.AcroFormListBox=P, n.AcroFormComboBox=E, n.AcroFormEditBox=q, n.AcroFormButton=O, n.AcroFormPushButton=B, n.AcroFormRadioButton=R, n.AcroFormCheckBox=D, n.AcroFormTextField=M, n.AcroFormPasswordField=U, n.AcroForm={ChoiceField:F,ListBox:P,ComboBox:E,EditBox:q,Button:O,PushButton:B,RadioButton:R,CheckBox:D,TextField:M,PasswordField:U};}($.API,"undefined"!=typeof window&&window||"undefined"!=typeof commonjsGlobal&&commonjsGlobal), $.API.addHTML=function(t,p,g,s,m){if("undefined"==typeof html2canvas&&"undefined"==typeof rasterizeHTML)throw new Error("You need either https://github.com/niklasvh/html2canvas or https://github.com/cburgmer/rasterizeHTML.js");"number"!=typeof p&&(s=p, m=g), "function"==typeof s&&(m=s, s=null), "function"!=typeof m&&(m=function(){});var e=this.internal,w=e.scaleFactor,y=e.pageSize.getWidth(),v=e.pageSize.getHeight();if((s=s||{}).onrendered=function(h){p=parseInt(p)||0, g=parseInt(g)||0;var t=s.dim||{},c=Object.assign({top:0,right:0,bottom:0,left:0,useFor:"content"},s.margin),e=t.h||Math.min(v,h.height/w),l=t.w||Math.min(y,h.width/w)-p,u=s.format||"JPEG",f=s.imageCompression||"SLOW";if(h.height>v-c.top-c.bottom&&s.pagesplit){var d=function(t,e,n,r,i){var o=document.createElement("canvas");o.height=i, o.width=r;var a=o.getContext("2d");return a.mozImageSmoothingEnabled=!1, a.webkitImageSmoothingEnabled=!1, a.msImageSmoothingEnabled=!1, a.imageSmoothingEnabled=!1, a.fillStyle=s.backgroundColor||"#ffffff", a.fillRect(0,0,r,i), a.drawImage(t,e,n,r,i,0,0,r,i), o},n=function(){for(var t,e,n=0,r=0,i={},o=!1;;){var a;
29671if(r=0, i.top=0!==n?c.top:g, i.left=0!==n?c.left:p, o=(y-c.left-c.right)*w<h.width, "content"===c.useFor?0===n?(t=Math.min((y-c.left)*w,h.width), e=Math.min((v-c.top)*w,h.height-n)):(t=Math.min(y*w,h.width), e=Math.min(v*w,h.height-n), i.top=0):(t=Math.min((y-c.left-c.right)*w,h.width), e=Math.min((v-c.bottom-c.top)*w,h.height-n)), o)for(;;){"content"===c.useFor&&(0===r?t=Math.min((y-c.left)*w,h.width):(t=Math.min(y*w,h.width-r), i.left=0));var s=[a=d(h,r,n,t,e),i.left,i.top,a.width/w,a.height/w,u,null,f];if(this.addImage.apply(this,s), (r+=t)>=h.width)break;this.addPage();}else s=[a=d(h,0,n,t,e),i.left,i.top,a.width/w,a.height/w,u,null,f], this.addImage.apply(this,s);if((n+=e)>=h.height)break;this.addPage();}m(l,n,null,s);}.bind(this);if("CANVAS"===h.nodeName){var r=new Image;r.onload=n, r.src=h.toDataURL("image/png"), h=r;}else n();}else{var i=Math.random().toString(35),o=[h,p,g,l,e,u,i,f];this.addImage.apply(this,o), m(l,e,i,o);}}.bind(this), "undefined"!=typeof html2canvas&&!s.rstz)return html2canvas(t,s);if("undefined"!=typeof rasterizeHTML){var n="drawDocument";return"string"==typeof t&&(n=/^http/.test(t)?"drawURL":"drawHTML"), s.width=s.width||y*w, rasterizeHTML[n](t,void 0,s).then(function(t){s.onrendered(t.image);},function(t){m(null,t);})}return null}, function(b){var x="addImage_",h={PNG:[[137,80,78,71]],TIFF:[[77,77,0,42],[73,73,42,0]],JPEG:[[255,216,255,224,void 0,void 0,74,70,73,70,0],[255,216,255,225,void 0,void 0,69,120,105,102,0,0]],JPEG2000:[[0,0,0,12,106,80,32,32]],GIF87a:[[71,73,70,56,55,97]],GIF89a:[[71,73,70,56,57,97]],BMP:[[66,77],[66,65],[67,73],[67,80],[73,67],[80,84]]};b.getImageFileTypeByImageData=function(t,e){var n,r;e=e||"UNKNOWN";var i,o,a,s="UNKNOWN";for(a in h)for(i=h[a], n=0;n<i.length;n+=1){for(o=!0, r=0;r<i[n].length;r+=1)if(void 0!==i[n][r]&&i[n][r]!==t.charCodeAt(r)){o=!1;break}if(!0===o){s=a;break}}return"UNKOWN"===s&&"UNKNOWN"!==e&&(console.warn('FileType of Image not recognized. Processing image as "'+e+'".'), s=e), s};var n=function t(e){var n=this.internal.newObject(),r=this.internal.write,i=this.internal.putStream;if(e.n=n, r("<</Type /XObject"), r("/Subtype /Image"), r("/Width "+e.w), r("/Height "+e.h), e.cs===this.color_spaces.INDEXED?r("/ColorSpace [/Indexed /DeviceRGB "+(e.pal.length/3-1)+" "+("smask"in e?n+2:n+1)+" 0 R]"):(r("/ColorSpace /"+e.cs), e.cs===this.color_spaces.DEVICE_CMYK&&r("/Decode [1 0 1 0 1 0 1 0]")), r("/BitsPerComponent "+e.bpc), "f"in e&&r("/Filter /"+e.f), "dp"in e&&r("/DecodeParms <<"+e.dp+">>"), "trns"in e&&e.trns.constructor==Array){for(var o="",a=0,s=e.trns.length;a<s;a++)o+=e.trns[a]+" "+e.trns[a]+" ";r("/Mask ["+o+"]");}if("smask"in e&&r("/SMask "+(n+1)+" 0 R"), r("/Length "+e.data.length+">>"), i(e.data), r("endobj"), "smask"in e){var h="/Predictor "+e.p+" /Colors 1 /BitsPerComponent "+e.bpc+" /Columns "+e.w,c={w:e.w,h:e.h,cs:"DeviceGray",bpc:e.bpc,dp:h,data:e.smask};"f"in e&&(c.f=e.f), t.call(this,c);}e.cs===this.color_spaces.INDEXED&&(this.internal.newObject(), r("<< /Length "+e.pal.length+">>"), i(this.arrayBufferToBinaryString(new Uint8Array(e.pal))), r("endobj"));},S=function(){var t=this.internal.collections[x+"images"];for(var e in t)n.call(this,t[e]);},k=function(){var t,e=this.internal.collections[x+"images"],n=this.internal.write;for(var r in e)n("/I"+(t=e[r]).i,t.n,"0","R");},_=function(t){return"function"==typeof b["process"+t.toUpperCase()]},A=function(t){return"object"===(void 0===t?"undefined":vt(t))&&1===t.nodeType},I=function(t,e){if("IMG"===t.nodeName&&t.hasAttribute("src")){var n=""+t.getAttribute("src");if(0===n.indexOf("data:image/"))return n;!e&&/\.png(?:[?#].*)?$/i.test(n)&&(e="png");}if("CANVAS"===t.nodeName)var r=t;else{(r=document.createElement("canvas")).width=t.clientWidth||t.width, r.height=t.clientHeight||t.height;var i=r.getContext("2d");if(!i)throw"addImage requires canvas to be supported by browser.";i.drawImage(t,0,0,r.width,r.height);}return r.toDataURL("png"==(""+e).toLowerCase()?"image/png":"image/jpeg")},C=function(t,e){var n;if(e)for(var r in e)if(t===e[r].alias){n=e[r];break}return n};b.color_spaces={DEVICE_RGB:"DeviceRGB",DEVICE_GRAY:"DeviceGray",DEVICE_CMYK:"DeviceCMYK",CAL_GREY:"CalGray",CAL_RGB:"CalRGB",LAB:"Lab",ICC_BASED:"ICCBased",INDEXED:"Indexed",PATTERN:"Pattern",SEPARATION:"Separation",DEVICE_N:"DeviceN"}, b.decode={DCT_DECODE:"DCTDecode",FLATE_DECODE:"FlateDecode",LZW_DECODE:"LZWDecode",JPX_DECODE:"JPXDecode",JBIG2_DECODE:"JBIG2Decode",ASCII85_DECODE:"ASCII85Decode",ASCII_HEX_DECODE:"ASCIIHexDecode",RUN_LENGTH_DECODE:"RunLengthDecode",CCITT_FAX_DECODE:"CCITTFaxDecode"}, b.image_compression={NONE:"NONE",FAST:"FAST",MEDIUM:"MEDIUM",SLOW:"SLOW"}, b.sHashCode=function(t){return t=t||"", Array.prototype.reduce&&t.split("").reduce(function(t,e){return(t=(t<<5)-t+e.charCodeAt(0))&t},0)}, b.isString=function(t){return"string"==typeof t}
29671, b.validateStringAsBase64=function(t){var e=!0;return(t=t||"").length%4!=0&&(e=!1), !1===/[A-Za-z0-9\/]+/.test(t.substr(0,t.length-2))&&(e=!1), !1===/[A-Za-z0-9\/][A-Za-z0-9+\/]|[A-Za-z0-9+\/]=|==/.test(t.substr(-2))&&(e=!1), e}, b.extractInfoFromBase64DataURI=function(t){return/^data:([\w]+?\/([\w]+?));base64,(.+)$/g.exec(t)}, b.supportsArrayBuffer=function(){return"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array}, b.isArrayBuffer=function(t){return!!this.supportsArrayBuffer()&&t instanceof ArrayBuffer}, b.isArrayBufferView=function(t){return!!this.supportsArrayBuffer()&&("undefined"!=typeof Uint32Array&&(t instanceof Int8Array||t instanceof Uint8Array||"undefined"!=typeof Uint8ClampedArray&&t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array))}, b.binaryStringToUint8Array=function(t){for(var e=t.length,n=new Uint8Array(e),r=0;r<e;r++)n[r]=t.charCodeAt(r);return n}, b.arrayBufferToBinaryString=function(t){if("function"==typeof atob)return atob(this.arrayBufferToBase64(t));if("function"==typeof TextDecoder){var e=new TextDecoder("ascii");if("ascii"===e.encoding)return e.decode(t)}for(var n=this.isArrayBuffer(t)?t:new Uint8Array(t),r=20480,i="",o=Math.ceil(n.byteLength/r),a=0;a<o;a++)i+=String.fromCharCode.apply(null,n.slice(a*r,a*r+r));return i}, b.arrayBufferToBase64=function(t){for(var e,n="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=new Uint8Array(t),o=i.byteLength,a=o%3,s=o-a,h=0;h<s;h+=3)n+=r[(16515072&(e=i[h]<<16|i[h+1]<<8|i[h+2]))>>18]+r[(258048&e)>>12]+r[(4032&e)>>6]+r[63&e];return 1==a?n+=r[(252&(e=i[s]))>>2]+r[(3&e)<<4]+"==":2==a&&(n+=r[(64512&(e=i[s]<<8|i[s+1]))>>10]+r[(1008&e)>>4]+r[(15&e)<<2]+"="), n}, b.createImageInfo=function(t,e,n,r,i,o,a,s,h,c,l,u,f){var d={alias:s,w:e,h:n,cs:r,bpc:i,i:a,data:t};return o&&(d.f=o), h&&(d.dp=h), c&&(d.trns=c), l&&(d.pal=l), u&&(d.smask=u), f&&(d.p=f), d}, b.addImage=function(t,e,n,r,i,o,a,s,h){var c="";if("string"!=typeof e){var l=o;o=i, i=r, r=n, n=e, e=l;}if("object"===(void 0===t?"undefined":vt(t))&&!A(t)&&"imageData"in t){var u=t;t=u.imageData, e=u.format||e, n=u.x||n||0, r=u.y||r||0, i=u.w||i, o=u.h||o, a=u.alias||a, s=u.compression||s, h=u.rotation||u.angle||h;}if(isNaN(n)||isNaN(r))throw console.error("jsPDF.addImage: Invalid coordinates",arguments), new Error("Invalid coordinates passed to jsPDF.addImage");var f,d,p,g,m,w,y,v=function(){var t=this.internal.collections[x+"images"];return t||(this.internal.collections[x+"images"]=t={}, this.internal.events.subscribe("putResources",S), this.internal.events.subscribe("putXobjectDict",k)), t}.call(this);if(!(f=C(t,v))&&(A(t)&&(t=I(t,e)), (null==(y=a)||0===y.length)&&(a="string"==typeof(w=t)&&b.sHashCode(w)), !(f=C(a,v)))){if(this.isString(t)&&(""!==(c=this.convertStringToImageData(t))?t=c:void 0!==(c=this.loadImageFile(t))&&(t=c)), e=this.getImageFileTypeByImageData(t,e), !_(e))throw new Error("addImage does not support files of type '"+e+"', please ensure that a plugin for '"+e+"' support is added.");if(this.supportsArrayBuffer()&&(t instanceof Uint8Array||(d=t, t=this.binaryStringToUint8Array(t))), !(f=this["process"+e.toUpperCase()](t,(m=0, (g=v)&&(m=Object.keys?Object.keys(g).length:function(t){var e=0;for(var n in t)t.hasOwnProperty(n)&&e++;return e}(g)), m),a,((p=s)&&"string"==typeof p&&(p=p.toUpperCase()), p in b.image_compression?p:b.image_compression.NONE),d)))throw new Error("An unkwown error occurred whilst processing the image")}return function(t,e,n,r,i,o,a,s){var h=function(t,e,n){return t||e||(e=t=-96), t<0&&(t=-1*n.w*72/t/this.internal.scaleFactor), e<0&&(e=-1*n.h*72/e/this.internal.scaleFactor), 0===t&&(t=e*n.w/n.h), 0===e&&(e=t*n.h/n.w), [t,e]}.call(this,n,r,i),c=this.internal.getCoordinateString,l=this.internal.getVerticalCoordinateString;if(n=h[0], r=h[1], a[o]=i, s){s*=Math.PI/180;var u=Math.cos(s),f=Math.sin(s),d=function(t){return t.toFixed(4)},p=[d(u),d(f),d(-1*f),d(u),0,0,"cm"];}this.internal.write("q"), s?(this.internal.write([1,"0","0",1,c(t),l(e+r),"cm"].join(" ")), this.internal.write(p.join(" ")), this.internal.write([c(n),"0","0",c(r),"0","0","cm"].join(" "))):this.internal.write([c(n),"0","0",c(r),c(t),l(e+r),"cm"].join(" ")), this.internal.write("/I"+i.i+" Do"), this.internal.write("Q");}.call(this,n,r,i,o,f,f.i,v,h), this}, b.convertStringToImageData=function(t){var e,n="";this.isString(t)&&(null!==(e=this.extractInfoFromBase64DataURI(t))?b.validateStringAs
29671Base64(e[3])&&(n=atob(e[3])):b.validateStringAsBase64(t)&&(n=atob(t)));return n};var c=function(t,e){return t.subarray(e,e+5)};b.processJPEG=function(t,e,n,r,i,o){var a,s=this.decode.DCT_DECODE;if(!this.isString(t)&&!this.isArrayBuffer(t)&&!this.isArrayBufferView(t))return null;if(this.isString(t)&&(a=function(t){var e;if(255===!t.charCodeAt(0)||216===!t.charCodeAt(1)||255===!t.charCodeAt(2)||224===!t.charCodeAt(3)||!t.charCodeAt(6)==="J".charCodeAt(0)||!t.charCodeAt(7)==="F".charCodeAt(0)||!t.charCodeAt(8)==="I".charCodeAt(0)||!t.charCodeAt(9)==="F".charCodeAt(0)||0===!t.charCodeAt(10))throw new Error("getJpegSize requires a binary string jpeg file");for(var n=256*t.charCodeAt(4)+t.charCodeAt(5),r=4,i=t.length;r<i;){if(r+=n, 255!==t.charCodeAt(r))throw new Error("getJpegSize could not find the size of the image");if(192===t.charCodeAt(r+1)||193===t.charCodeAt(r+1)||194===t.charCodeAt(r+1)||195===t.charCodeAt(r+1)||196===t.charCodeAt(r+1)||197===t.charCodeAt(r+1)||198===t.charCodeAt(r+1)||199===t.charCodeAt(r+1))return e=256*t.charCodeAt(r+5)+t.charCodeAt(r+6), [256*t.charCodeAt(r+7)+t.charCodeAt(r+8),e,t.charCodeAt(r+9)];r+=2, n=256*t.charCodeAt(r)+t.charCodeAt(r+1);}}(t)), this.isArrayBuffer(t)&&(t=new Uint8Array(t)), this.isArrayBufferView(t)&&(a=function(t){if(65496!=(t[0]<<8|t[1]))throw new Error("Supplied data is not a JPEG");for(var e,n=t.length,r=(t[4]<<8)+t[5],i=4;i<n;){if(r=((e=c(t,i+=r))[2]<<8)+e[3], (192===e[1]||194===e[1])&&255===e[0]&&7<r)return{width:((e=c(t,i+5))[2]<<8)+e[3],height:(e[0]<<8)+e[1],numcomponents:e[4]};i+=2;}throw new Error("getJpegSizeFromBytes could not find the size of the image")}(t), t=i||this.arrayBufferToBinaryString(t)), void 0===o)switch(a.numcomponents){case 1:o=this.color_spaces.DEVICE_GRAY;break;case 4:o=this.color_spaces.DEVICE_CMYK;break;default:case 3:o=this.color_spaces.DEVICE_RGB;}return this.createImageInfo(t,a.width,a.height,o,8,s,e,n)}, b.processJPG=function(){return this.processJPEG.apply(this,arguments)}, b.loadImageFile=function(t,e,n){e=e||!0, n=n||function(){};Object.prototype.toString.call("undefined"!=typeof process?process:0);if(void 0!==("undefined"==typeof window?"undefined":vt(window))&&"object"===("undefined"==typeof location?"undefined":vt(location))&&"http"===location.protocol.substr(0,4))return function(t,e,n){var r=new XMLHttpRequest,i=[],o=0,a=function(t){var e=t.length,n=String.fromCharCode;for(o=0;o<e;o+=1)i.push(n(255&t.charCodeAt(o)));return i.join("")};if(r.open("GET",t,!e), r.overrideMimeType("text/plain; charset=x-user-defined"), !1===e&&(r.onload=function(){return a(this.responseText)}), r.send(null), 200===r.status)return e?a(r.responseText):void 0;console.warn('Unable to load file "'+t+'"');}(t,e)}, b.getImageProperties=function(t){var e,n,r="";if(A(t)&&(t=I(t)), this.isString(t)&&(""!==(r=this.convertStringToImageData(t))?t=r:void 0!==(r=this.loadImageFile(t))&&(t=r)), n=this.getImageFileTypeByImageData(t), !_(n))throw new Error("addImage does not support files of type '"+n+"', please ensure that a plugin for '"+n+"' support is added.");if(this.supportsArrayBuffer()&&(t instanceof Uint8Array||(t=this.binaryStringToUint8Array(t))), !(e=this["process"+n.toUpperCase()](t)))throw new Error("An unkwown error occurred whilst processing the image");return{fileType:n,width:e.w,height:e.h,colorSpace:e.cs,compressionMode:e.f,bitsPerComponent:e.bpc}};}($.API), t=$.API, y={annotations:[],f2:function(t){return t.toFixed(2)},notEmpty:function(t){if(void 0!==t&&""!=t)return!0}}, $.API.annotationPlugin=y, $.API.events.push(["addPage",function(t){this.annotationPlugin.annotations[t.pageNumber]=[];}]), t.events.push(["putPage",function(t){for(var e=this.annotationPlugin.annotations[t.pageNumber],n=!1,r=0;r<e.length&&!n;r++)switch((h=e[r]).type){case"link":if(y.notEmpty(h.options.url)||y.notEmpty(h.options.pageNumber)){n=!0;break}case"reference":case"text":case"freetext":n=!0;}if(0!=n){this.internal.write("/Annots [");var i=this.annotationPlugin.f2,o=this.internal.scaleFactor,a=this.internal.pageSize.getHeight(),s=this.internal.getPageInfo(t.pageNumber);for(r=0;r<e.length;r++){var h;
29671switch((h=e[r]).type){case"reference":this.internal.write(" "+h.object.objId+" 0 R ");break;case"text":var c=this.internal.newAdditionalObject(),l=this.internal.newAdditionalObject(),u=h.title||"Note";m="<</Type /Annot /Subtype /Text "+(d="/Rect ["+i(h.bounds.x*o)+" "+i(a-(h.bounds.y+h.bounds.h)*o)+" "+i((h.bounds.x+h.bounds.w)*o)+" "+i((a-h.bounds.y)*o)+"] ")+"/Contents ("+h.contents+")", m+=" /Popup "+l.objId+" 0 R", m+=" /P "+s.objId+" 0 R", m+=" /T ("+u+") >>", c.content=m;var f=c.objId+" 0 R";m="<</Type /Annot /Subtype /Popup "+(d="/Rect ["+i((h.bounds.x+30)*o)+" "+i(a-(h.bounds.y+h.bounds.h)*o)+" "+i((h.bounds.x+h.bounds.w+30)*o)+" "+i((a-h.bounds.y)*o)+"] ")+" /Parent "+f, h.open&&(m+=" /Open true"), m+=" >>", l.content=m, this.internal.write(c.objId,"0 R",l.objId,"0 R");break;case"freetext":var d="/Rect ["+i(h.bounds.x*o)+" "+i((a-h.bounds.y)*o)+" "+i(h.bounds.x+h.bounds.w*o)+" "+i(a-(h.bounds.y+h.bounds.h)*o)+"] ",p=h.color||"#000000";m="<</Type /Annot /Subtype /FreeText "+d+"/Contents ("+h.contents+")", m+=" /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#"+p+")", m+=" /Border [0 0 0]", m+=" >>", this.internal.write(m);break;case"link":if(h.options.name){var g=this.annotations._nameMap[h.options.name];h.options.pageNumber=g.page, h.options.top=g.y;}else h.options.top||(h.options.top=0);d="/Rect ["+i(h.x*o)+" "+i((a-h.y)*o)+" "+i((h.x+h.w)*o)+" "+i((a-(h.y+h.h))*o)+"] ";var m="";if(h.options.url)m="<</Type /Annot /Subtype /Link "+d+"/Border [0 0 0] /A <</S /URI /URI ("+h.options.url+") >>";else if(h.options.pageNumber)switch(m="<</Type /Annot /Subtype /Link "+d+"/Border [0 0 0] /Dest ["+(t=this.internal.getPageInfo(h.options.pageNumber)).objId+" 0 R", h.options.magFactor=h.options.magFactor||"XYZ", h.options.magFactor){case"Fit":m+=" /Fit]";break;case"FitH":m+=" /FitH "+h.options.top+"]";break;case"FitV":h.options.left=h.options.left||0, m+=" /FitV "+h.options.left+"]";break;case"XYZ":default:var w=i((a-h.options.top)*o);h.options.left=h.options.left||0, void 0===h.options.zoom&&(h.options.zoom=0), m+=" /XYZ "+h.options.left+" "+w+" "+h.options.zoom+"]";}""!=m&&(m+=" >>", this.internal.write(m));}}this.internal.write("]");}}]), t.createAnnotation=function(t){switch(t.type){case"link":this.link(t.bounds.x,t.bounds.y,t.bounds.w,t.bounds.h,t);break;case"text":case"freetext":this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(t);}}, t.link=function(t,e,n,r,i){this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push({x:t,y:e,w:n,h:r,options:i,type:"link"});}, t.textWithLink=function(t,e,n,r){var i=this.getTextWidth(t),o=this.internal.getLineHeight()/this.internal.scaleFactor;return this.text(t,e,n), n+=.2*o, this.link(e,n-o,i,o,r), i}, t.getTextWidth=function(t){var e=this.internal.getFontSize();return this.getStringUnitWidth(t)*e/this.internal.scaleFactor}, t.getLineHeight=function(){return this.internal.getLineHeight()}, function(t){var a=Object.keys({ar:"Arabic (Standard)","ar-DZ":"Arabic (Algeria)","ar-BH":"Arabic (Bahrain)","ar-EG":"Arabic (Egypt)","ar-IQ":"Arabic (Iraq)","ar-JO":"Arabic (Jordan)","ar-KW":"Arabic (Kuwait)","ar-LB":"Arabic (Lebanon)","ar-LY":"Arabic (Libya)","ar-MA":"Arabic (Morocco)","ar-OM":"Arabic (Oman)","ar-QA":"Arabic (Qatar)","ar-SA":"Arabic (Saudi Arabia)","ar-SY":"Arabic (Syria)","ar-TN":"Arabic (Tunisia)","ar-AE":"Arabic (U.A.E.)","ar-YE":"Arabic (Yemen)",fa:"Persian","fa-IR":"Persian/Iran",ur:"Urdu"}),u={1569:[65152],1570:[65153,65154,65153,65154],1571:[65155,65156,65155,65156],1572:[65157,65158],1573:[65159,65160,65159,65160],1574:[65161,65162,65163,65164],1575:[65165,65166,65165,65166],1576:[65167,65168,65169,65170],1577:[65171,65172],1578:[65173,65174,65175,65176],1579:[65177,65178,65179,65180],1580:[65181,65182,65183,65184],1581:[65185,65186,65187,65188],1582:[65189,65190,65191,65192],1583:[65193,65194,65193],1584:[65195,65196,65195],1585:[65197,65198,65197],1586:[65199,65200,65199],1587:[65201,65202,65203,65204],1588:[65205,65206,65207,65208],1589:[65209,65210,65211,65212],1590:[65213,65214,65215,65216],1591:[65217,65218,65219,65220],1592:[65221,65222,65223,65224],1593:[65225,65226,65227,65228],1594:[65229,65230,65231,65232],1601:[65233,65234,65235,65236],1602:[65237,65238,65239,65240],1603:[65241,65242,65243,65244],1604:[65245,65246,65247,65248],1605:[65249,65250,65251,65252],1606:[65253,65254,65255,65256],1607:[65257,65258,65259,65260],1608:[65261,65262,65261],1609:[65263,65264,64488,64489],1610:[65265,652
2967166,65267,65268],1649:[64336,64337],1655:[64477],1657:[64358,64359,64360,64361],1658:[64350,64351,64352,64353],1659:[64338,64339,64340,64341],1662:[64342,64343,64344,64345],1663:[64354,64355,64356,64357],1664:[64346,64347,64348,64349],1667:[64374,64375,64376,64377],1668:[64370,64371,64372,64373],1670:[64378,64379,64380,64381],1671:[64382,64383,64384,64385],1672:[64392,64393],1676:[64388,64389],1677:[64386,64387],1678:[64390,64391],1681:[64396,64397],1688:[64394,64395,64394],1700:[64362,64363,64364,64365],1702:[64366,64367,64368,64369],1705:[64398,64399,64400,64401],1709:[64467,64468,64469,64470],1711:[64402,64403,64404,64405],1713:[64410,64411,64412,64413],1715:[64406,64407,64408,64409],1722:[64414,64415],1723:[64416,64417,64418,64419],1726:[64426,64427,64428,64429],1728:[64420,64421],1729:[64422,64423,64424,64425],1733:[64480,64481],1734:[64473,64474],1735:[64471,64472],1736:[64475,64476],1737:[64482,64483],1739:[64478,64479],1740:[64508,64509,64510,64511],1744:[64484,64485,64486,64487],1746:[64430,64431],1747:[64432,64433]},f={1570:[65269,65270,65269,65270],1571:[65271,65272,65271,65272],1573:[65273,65274,65273,65274],1575:[65275,65276,65275,65276]},d={1570:[65153,65154,65153,65154],1571:[65155,65156,65155,65156],1573:[65159,65160,65159,65160],1575:[65165,65166,65165,65166]},p={1612:64606,1613:64607,1614:64608,1615:64609,1616:64610},e=[1570,1571,1573,1575],n=[1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688],o=0,s=1,h=2,c=3;function g(t){return void 0!==t&&void 0!==u[t.charCodeAt(0)]}function l(t){return void 0!==t&&0<=n.indexOf(t.charCodeAt(0))}function m(t){return void 0!==t&&0<=e.indexOf(t.charCodeAt(0))}function w(t){return g(t)&&2<=u[t.charCodeAt(0)].length}function y(t,e,n,r){return g(t)?(r=r||{}, u=Object.assign(u,r), !w(t)||!g(e)&&!g(n)||!g(n)&&l(e)||l(t)&&!g(e)||l(t)&&m(e)||l(t)&&l(e)?(u=Object.assign(u,d), o):g(i=t)&&4==u[i.charCodeAt(0)].length&&g(e)&&!l(e)&&g(n)&&w(n)?(u=Object.assign(u,d), c):l(t)||!g(n)?(u=Object.assign(u,d), s):(u=Object.assign(u,d), h)):-1;var i;}var v=t.processArabic=function(t,e){t=t||"", e=e||!1;var n,r,i,o="",a=0,s=0,h="",c="",l="";for(a=0;a<t.length;a+=1)h=t[a], c=t[a-1], l=t[a+1], g(h)?void 0!==c&&1604===c.charCodeAt(0)&&m(h)?(s=y(h,t[a-2],t[a+1],f), n=String.fromCharCode(f[h.charCodeAt(0)][s]), o=o.substr(0,o.length-1)+n):void 0!==c&&1617===c.charCodeAt(0)&&(void 0!==(r=h)&&void 0!==p[r.charCodeAt(0)])?(s=y(h,t[a-2],t[a+1],d), n=String.fromCharCode(p[h.charCodeAt(0)][s]), o=o.substr(0,o.length-1)+n):(s=y(h,c,l,d), o+=String.fromCharCode(u[h.charCodeAt(0)][s])):o+=e?{"(":")",")":"("}[i=h]||i:h;return e?o.split("").reverse().join(""):o};t.events.push(["preProcessText",function(t){var e=t.text,n=(t.x, t.y, t.options||{}),r=(t.mutex, n.lang),i=[];if(0<=a.indexOf(r)){if("[object Array]"===Object.prototype.toString.call(e)){var o=0;for(i=[], o=0;o<e.length;o+=1)"[object Array]"===Object.prototype.toString.call(e[o])?i.push([v(e[o][0],!0),e[o][1],e[o][2]]):i.push([v(e[o],!0)]);t.text=i;}else t.text=v(e,!0);void 0===n.charSpace&&(t.options.charSpace=0), !0===n.R2L&&(t.options.R2L=!1);}}]);}($.API), $.API.autoPrint=function(t){var e;switch((t=t||{}).variant=t.variant||"non-conform", t.variant){case"javascript":this.addJS("print({});");break;case"non-conform":default:this.internal.events.subscribe("postPutResources",function(){e=this.internal.newObject(), this.internal.out("<<"), this.internal.out("/S /Named"), this.internal.out("/Type /Action"), this.internal.out("/N /Print"), this.internal.out(">>"), this.internal.out("endobj");}), this.internal.events.subscribe("putCatalog",function(){this.internal.out("/OpenAction "+e+" 0 R");});}return this}, (
29672/**
29673   * jsPDF Canvas PlugIn
29674   * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  [email protected]
29675   *
29676   * Licensed under the MIT License.
29677   * http://opensource.org/licenses/mit-license
29678   */
29679e=$.API).events.push(["initialized",function(){this.canvas.pdf=this;}]), e.canvas={getContext:function(t){return(this.pdf.context2d._canvas=this).pdf.context2d},childNodes:[]}, Object.defineProperty(e.canvas,"width",{get:function(){return this._width}
29679,set:function(t){this._width=t, this.getContext("2d").pageWrapX=t+1;}}), Object.defineProperty(e.canvas,"height",{get:function(){return this._height},set:function(t){this._height=t, this.getContext("2d").pageWrapY=t+1;}}), I=$.API, C={x:void 0,y:void 0,w:void 0,h:void 0,ln:void 0}, T=1, d=function(t,e,n,r,i){C={x:t,y:e,w:n,h:r,ln:i};}, p=function(){return C}, F={left:0,top:0,bottom:0}, I.setHeaderFunction=function(t){h=t;}, I.getTextDimensions=function(e){i=this.internal.getFont().fontName, o=this.table_font_size||this.internal.getFontSize(), a=this.internal.getFont().fontStyle;var t,n,r=19.049976/25.4;(n=document.createElement("font")).id="jsPDFCell";try{n.style.fontStyle=a;}catch(t){n.style.fontWeight=a;}n.style.fontSize=o+"pt", n.style.fontFamily=i;try{n.textContent=e;}catch(t){n.innerText=e;}return document.body.appendChild(n), t={w:(n.offsetWidth+1)*r,h:(n.offsetHeight+1)*r}, document.body.removeChild(n), t}, I.cellAddPage=function(){var t=this.margins||F;this.addPage(), d(t.left,t.top,void 0,void 0), T+=1;}, I.cellInitialize=function(){C={x:void 0,y:void 0,w:void 0,h:void 0,ln:void 0}, T=1;}, I.cell=function(t,e,n,r,i,o,a){var s=p(),h=!1;if(void 0!==s.ln)if(s.ln===o)t=s.x+s.w, e=s.y;else{var c=this.margins||F;s.y+s.h+r+13>=this.internal.pageSize.getHeight()-c.bottom&&(this.cellAddPage(), h=!0, this.printHeaders&&this.tableHeaderRow&&this.printHeaderRow(o,!0)), e=p().y+p().h, h&&(e=23);}if(void 0!==i[0])if(this.printingHeaderRow?this.rect(t,e,n,r,"FD"):this.rect(t,e,n,r), "right"===a){i instanceof Array||(i=[i]);for(var l=0;l<i.length;l++){var u=i[l],f=this.getStringUnitWidth(u)*this.internal.getFontSize();this.text(u,t+n-f-3,e+this.internal.getLineHeight()*(l+1));}}else this.text(i,t+3,e+this.internal.getLineHeight());return d(t,e,n,r,o), this}, I.arrayMax=function(t,e){var n,r,i,o=t[0];for(n=0, r=t.length;n<r;n+=1)i=t[n], e?-1===e(o,i)&&(o=i):o<i&&(o=i);return o}, I.table=function(t,e,n,r,i){if(!n)throw"No data for PDF table";var o,a,s,h,c,l,u,f,d,p,g=[],m=[],w={},y={},v=[],b=[],x=!1,S=!0,k=12,_=F;if(_.width=this.internal.pageSize.getWidth(), i&&(!0===i.autoSize&&(x=!0), !1===i.printHeaders&&(S=!1), i.fontSize&&(k=i.fontSize), i.css&&void 0!==i.css["font-size"]&&(k=16*i.css["font-size"]), i.margins&&(_=i.margins)), this.lnMod=0, C={x:void 0,y:void 0,w:void 0,h:void 0,ln:void 0}, T=1, this.printHeaders=S, this.margins=_, this.setFontSize(k), this.table_font_size=k, null==r)g=Object.keys(n[0]);else if(r[0]&&"string"!=typeof r[0])for(a=0, s=r.length;a<s;a+=1)o=r[a], g.push(o.name), m.push(o.prompt), y[o.name]=o.width*(19.049976/25.4);else g=r;if(x)for(p=function(t){return t[o]}, a=0, s=g.length;a<s;a+=1){for(w[o=g[a]]=n.map(p), v.push(this.getTextDimensions(m[a]||o).w), u=0, h=(l=w[o]).length;u<h;u+=1)c=l[u], v.push(this.getTextDimensions(c).w);y[o]=I.arrayMax(v), v=[];}if(S){var A=this.calculateLineHeight(g,y,m.length?m:g);for(a=0, s=g.length;a<s;a+=1)o=g[a], b.push([t,e,y[o],A,String(m.length?m[a]:o)]);this.setTableHeaderRow(b), this.printHeaderRow(1,!1);}for(a=0, s=n.length;a<s;a+=1)for(f=n[a], A=this.calculateLineHeight(g,y,f), u=0, d=g.length;u<d;u+=1)o=g[u], this.cell(t,e,y[o],A,f[o],a+2,o.align);return this.lastCellPos=C, this.table_x=t, this.table_y=e, this}, I.calculateLineHeight=function(t,e,n){for(var r,i=0,o=0;o<t.length;o++){n[r=t[o]]=this.splitTextToSize(String(n[r]),e[r]-3);var a=this.internal.getLineHeight()*n[r].length+3;i<a&&(i=a);}return i}, I.setTableHeaderRow=function(t){this.tableHeaderRow=t;}, I.printHeaderRow=function(t,e){if(!this.tableHeaderRow)throw"Property tableHeaderRow does not exist.";var n,r,i,o;if(this.printingHeaderRow=!0, void 0!==h){var a=h(this,T);d(a[0],a[1],a[2],a[3],-1);}this.setFontStyle("bold");var s=[];for(i=0, o=this.tableHeaderRow.length;i<o;i+=1)this.setFillColor(200,200,200), n=this.tableHeaderRow[i], e&&(this.margins.top=13, n[1]=this.margins&&this.margins.top||0, s.push(n)), r=[].concat(n), this.cell.apply(this,r.concat(t));0<s.length&&this.setTableHeaderRow(s), this.setFontStyle("normal"), this.printingHeaderRow=!1;}, function(t){t.events.push(["initialized",function(){((this.context2d.pdf=this).context2d.internal.pdf=this).context2d.ctx=new e, this.context2d.ctxStack=[], this.context2d.path=[];}]), t.context2d={pageWrapXEnabled:!1,pageWrapYEnabled:!1,pageWrapX:9999999,pageWrapY:9999999,ctx:new e,f2:function(t){return t.toFixed(2)}
29679,fillRect:function(t,e,n,r){if(!this._isFillTransparent()){t=this._wrapX(t), e=this._wrapY(e);var i=this._matrix_map_rect(this.ctx._transform,{x:t,y:e,w:n,h:r});this.pdf.rect(i.x,i.y,i.w,i.h,"f");}},strokeRect:function(t,e,n,r){if(!this._isStrokeTransparent()){t=this._wrapX(t), e=this._wrapY(e);var i=this._matrix_map_rect(this.ctx._transform,{x:t,y:e,w:n,h:r});this.pdf.rect(i.x,i.y,i.w,i.h,"s");}},clearRect:function(t,e,n,r){if(!this.ctx.ignoreClearRect){t=this._wrapX(t), e=this._wrapY(e);var i=this._matrix_map_rect(this.ctx._transform,{x:t,y:e,w:n,h:r});this.save(), this.setFillStyle("#ffffff"), this.pdf.rect(i.x,i.y,i.w,i.h,"f"), this.restore();}},save:function(){this.ctx._fontSize=this.pdf.internal.getFontSize();var t=new e;t.copy(this.ctx), this.ctxStack.push(this.ctx), this.ctx=t;},restore:function(){this.ctx=this.ctxStack.pop(), this.setFillStyle(this.ctx.fillStyle), this.setStrokeStyle(this.ctx.strokeStyle), this.setFont(this.ctx.font), this.pdf.setFontSize(this.ctx._fontSize), this.setLineCap(this.ctx.lineCap), this.setLineWidth(this.ctx.lineWidth), this.setLineJoin(this.ctx.lineJoin);},rect:function(t,e,n,r){this.moveTo(t,e), this.lineTo(t+n,e), this.lineTo(t+n,e+r), this.lineTo(t,e+r), this.lineTo(t,e), this.closePath();},beginPath:function(){this.path=[];},closePath:function(){this.path.push({type:"close"});},_getRGBA:function(t){var e,n,r,i,o=new RGBColor(t);if(!t)return{r:0,g:0,b:0,a:0,style:t};if(this.internal.rxTransparent.test(t))i=r=n=e=0;else{var a=this.internal.rxRgb.exec(t);null!=a?(e=parseInt(a[1]), n=parseInt(a[2]), r=parseInt(a[3]), i=1):null!=(a=this.internal.rxRgba.exec(t))?(e=parseInt(a[1]), n=parseInt(a[2]), r=parseInt(a[3]), i=parseFloat(a[4])):(i=1, "#"!=t.charAt(0)&&(t=o.ok?o.toHex():"#000000"), 4===t.length?(e=t.substring(1,2), e+=e, n=t.substring(2,3), n+=n, r=t.substring(3,4), r+=r):(e=t.substring(1,3), n=t.substring(3,5), r=t.substring(5,7)), e=parseInt(e,16), n=parseInt(n,16), r=parseInt(r,16));}return{r:e,g:n,b:r,a:i,style:t}},setFillStyle:function(t){var e=this._getRGBA(t);this.ctx.fillStyle=t, this.ctx._isFillTransparent=0===e.a, this.ctx._fillOpacity=e.a, this.pdf.setFillColor(e.r,e.g,e.b,{a:e.a}), this.pdf.setTextColor(e.r,e.g,e.b,{a:e.a});},setStrokeStyle:function(t){var e=this._getRGBA(t);this.ctx.strokeStyle=e.style, this.ctx._isStrokeTransparent=0===e.a, this.ctx._strokeOpacity=e.a, 0===e.a?this.pdf.setDrawColor(255,255,255):(e.a, this.pdf.setDrawColor(e.r,e.g,e.b));},fillText:function(t,e,n,r){if(!this._isFillTransparent()){e=this._wrapX(e), n=this._wrapY(n);var i=this._matrix_map_point(this.ctx._transform,[e,n]);e=i[0], n=i[1];var o=57.2958*this._matrix_rotation(this.ctx._transform);if(0<this.ctx._clip_path.length){var a;(a=window.outIntercept?"group"===window.outIntercept.type?window.outIntercept.stream:window.outIntercept:this.internal.getCurrentPage()).push("q");var s=this.path;this.path=this.ctx._clip_path, this.ctx._clip_path=[], this._fill(null,!0), this.ctx._clip_path=this.path, this.path=s;}var h=1;try{h=this._matrix_decompose(this._getTransform()).scale[0];}catch(t){console.warn(t);}if(h<.01)this.pdf.text(t,e,this._getBaseline(n),null,o);else{var c=this.pdf.internal.getFontSize();this.pdf.setFontSize(c*h), this.pdf.text(t,e,this._getBaseline(n),null,o), this.pdf.setFontSize(c);}0<this.ctx._clip_path.length&&a.push("Q");}}
29679,strokeText:function(t,e,n,r){if(!this._isStrokeTransparent()){e=this._wrapX(e), n=this._wrapY(n);var i=this._matrix_map_point(this.ctx._transform,[e,n]);e=i[0], n=i[1];var o=57.2958*this._matrix_rotation(this.ctx._transform);if(0<this.ctx._clip_path.length){var a;(a=window.outIntercept?"group"===window.outIntercept.type?window.outIntercept.stream:window.outIntercept:this.internal.getCurrentPage()).push("q");var s=this.path;this.path=this.ctx._clip_path, this.ctx._clip_path=[], this._fill(null,!0), this.ctx._clip_path=this.path, this.path=s;}var h=1;try{h=this._matrix_decompose(this._getTransform()).scale[0];}catch(t){console.warn(t);}if(1===h)this.pdf.text(t,e,this._getBaseline(n),{stroke:!0},o);else{var c=this.pdf.internal.getFontSize();this.pdf.setFontSize(c*h), this.pdf.text(t,e,this._getBaseline(n),{stroke:!0},o), this.pdf.setFontSize(c);}0<this.ctx._clip_path.length&&a.push("Q");}},setFont:function(t){if(this.ctx.font=t, null!=(c=/\s*(\w+)\s+(\w+)\s+(\w+)\s+([\d\.]+)(px|pt|em)\s+(.*)?/.exec(t))){var e=c[1],n=(c[2], c[3]),r=c[4],i=c[5],o=c[6];r="px"===i?Math.floor(parseFloat(r)):"em"===i?Math.floor(parseFloat(r)*this.pdf.getFontSize()):Math.floor(parseFloat(r)), this.pdf.setFontSize(r), "bold"===n||"700"===n?this.pdf.setFontStyle("bold"):"italic"===e?this.pdf.setFontStyle("italic"):this.pdf.setFontStyle("normal"), l="bold"===n||"700"===n?"italic"===e?"bolditalic":"bold":"italic"===e?"italic":"normal";for(var a=o.toLowerCase().split(/\s*,\s*/),s="Times",h=0;h<a.length;h++){if(void 0!==this.pdf.internal.getFont(a[h],l,{noFallback:!0,disableWarning:!0})){s=a[h];break}if("bolditalic"===l&&void 0!==this.pdf.internal.getFont(a[h],"bold",{noFallback:!0,disableWarning:!0}))s=a[h], l="bold";else if(void 0!==this.pdf.internal.getFont(a[h],"normal",{noFallback:!0,disableWarning:!0})){s=a[h], l="normal";break}}this.pdf.setFont(s,l);}else{var c=/\s*(\d+)(pt|px|em)\s+([\w "]+)\s*([\w "]+)?/.exec(t);if(null!=c){var l,u=c[1],f=(c[2], c[3]);(l=c[4])||(l="normal"), u="em"===i?Math.floor(parseFloat(r)*this.pdf.getFontSize()):Math.floor(parseFloat(u)), this.pdf.setFontSize(u), this.pdf.setFont(f,l);}}},setTextBaseline:function(t){this.ctx.textBaseline=t;},getTextBaseline:function(){return this.ctx.textBaseline},setTextAlign:function(t){this.ctx.textAlign=t;},getTextAlign:function(){return this.ctx.textAlign},setLineWidth:function(t){this.ctx.lineWidth=t, this.pdf.setLineWidth(t);},setLineCap:function(t){this.ctx.lineCap=t, this.pdf.setLineCap(t);},setLineJoin:function(t){this.ctx.lineJoin=t, this.pdf.setLineJoin(t);},moveTo:function(t,e){t=this._wrapX(t), e=this._wrapY(e);var n=this._matrix_map_point(this.ctx._transform,[t,e]),r={type:"mt",x:t=n[0],y:e=n[1]};this.path.push(r);},_wrapX:function(t){return this.pageWrapXEnabled?t%this.pageWrapX:t},_wrapY:function(t){return this.pageWrapYEnabled?(this._gotoPage(this._page(t)), (t-this.lastBreak)%this.pageWrapY):t},transform:function(t,e,n,r,i,o){this.ctx._transform=this._matrix_multiply(this.ctx._transform,[t,e,n,r,i,o]);},setTransform:function(t,e,n,r,i,o){this.ctx._transform=[t,e,n,r,i,o];},_getTransform:function(){return this.ctx._transform},lastBreak:0,pageBreaks:[],_page:function(t){if(this.pageWrapYEnabled){for(var e=this.lastBreak=0,n=0,r=0;r<this.pageBreaks.length;r++)if(t>=this.pageBreaks[r]){e++, 0===this.lastBreak&&n++;var i=this.pageBreaks[r]-this.lastBreak;this.lastBreak=this.pageBreaks[r], n+=Math.floor(i/this.pageWrapY);}if(0===this.lastBreak)n+=Math.floor(t/this.pageWrapY)+1;return n+e}return this.pdf.internal.getCurrentPageInfo().pageNumber},_gotoPage:function(t){},lineTo:function(t,e){t=this._wrapX(t), e=this._wrapY(e);var n=this._matrix_map_point(this.ctx._transform,[t,e]),r={type:"lt",x:t=n[0],y:e=n[1]};this.path.push(r);},bezierCurveTo:function(t,e,n,r,i,o){var a;t=this._wrapX(t), e=this._wrapY(e), n=this._wrapX(n), r=this._wrapY(r), i=this._wrapX(i), o=this._wrapY(o), i=(a=this._matrix_map_point(this.ctx._transform,[i,o]))[0], o=a[1];var s={type:"bct",x1:t=(a=this._matrix_map_point(this.ctx._transform,[t,e]))[0],y1:e=a[1],x2:n=(a=this._matrix_map_point(this.ctx._transform,[n,r]))[0],y2:r=a[1],x:i,y:o};this.path.push(s);},quadraticCurveTo:function(t,e,n,r){var i;t=this._wrapX(t), e=this._wrapY(e), n=this._wrapX(n), r=this._wrapY(r), n=(i=this._matrix_map_point(this.ctx._transform,[n,r]))[0], r=i[1];var o={type:"qct",x1:t=(i=this._matrix_map_point(this.ctx._transform,[t,e]))[0],y1:e=i[1],x:n,y:r};this.path.push(o);},arc:function(t,e,n,r,i,o){if(t=this._wrapX(t), e=this._wrapY(e), !this._matrix_is_identity(this.ctx._transform)){var a=this._matrix_map_point(this.ctx._transform,[t,e]);t=a[0], e=a[1];var s=this._matrix_map_point(this.ctx._transform,[0,0]),h=this._matrix_map_point(this.ctx._transform,[0,n]);n=Math.sqrt(Math.pow(h[0]-s[0],2)+Math.pow(h[1]-s[1],2));}
29679var c={type:"arc",x:t,y:e,radius:n,startAngle:r,endAngle:i,anticlockwise:o};this.path.push(c);},drawImage:function(t,e,n,r,i,o,a,s,h){void 0!==o&&(e=o, n=a, r=s, i=h), e=this._wrapX(e), n=this._wrapY(n);var c,l=this._matrix_map_rect(this.ctx._transform,{x:e,y:n,w:r,h:i}),u=(this._matrix_map_rect(this.ctx._transform,{x:o,y:a,w:s,h:h}), /data:image\/(\w+).*/i.exec(t));c=null!=u?u[1]:"png", this.pdf.addImage(t,c,l.x,l.y,l.w,l.h);},_matrix_multiply:function(t,e){var n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],s=e[5],h=n*t[0]+r*t[2],c=i*t[0]+o*t[2],l=a*t[0]+s*t[2]+t[4];return r=n*t[1]+r*t[3], o=i*t[1]+o*t[3], s=a*t[1]+s*t[3]+t[5], [n=h,r,i=c,o,a=l,s]},_matrix_rotation:function(t){return Math.atan2(t[2],t[0])},_matrix_decompose:function(t){var e=t[0],n=t[1],r=t[2],i=t[3],o=Math.sqrt(e*e+n*n),a=(e/=o)*r+(n/=o)*i;r-=e*a, i-=n*a;var s=Math.sqrt(r*r+i*i);return a/=s, e*(i/=s)<n*(r/=s)&&(e=-e, n=-n, a=-a, o=-o), {scale:[o,0,0,s,0,0],translate:[1,0,0,1,t[4],t[5]],rotate:[e,n,-n,e,0,0],skew:[1,0,a,1,0,0]}},_matrix_map_point:function(t,e){var n=t[0],r=t[1],i=t[2],o=t[3],a=t[4],s=t[5],h=e[0],c=e[1];return[h*n+c*i+a,h*r+c*o+s]},_matrix_map_point_obj:function(t,e){var n=this._matrix_map_point(t,[e.x,e.y]);return{x:n[0],y:n[1]}},_matrix_map_rect:function(t,e){var n=this._matrix_map_point(t,[e.x,e.y]),r=this._matrix_map_point(t,[e.x+e.w,e.y+e.h]);return{x:n[0],y:n[1],w:r[0]-n[0],h:r[1]-n[1]}},_matrix_is_identity:function(t){return 1==t[0]&&(0==t[1]&&(0==t[2]&&(1==t[3]&&(0==t[4]&&0==t[5]))))},rotate:function(t){var e=[Math.cos(t),Math.sin(t),-Math.sin(t),Math.cos(t),0,0];this.ctx._transform=this._matrix_multiply(this.ctx._transform,e);},scale:function(t,e){var n=[t,0,0,e,0,0];this.ctx._transform=this._matrix_multiply(this.ctx._transform,n);},translate:function(t,e){var n=[1,0,0,1,t,e];this.ctx._transform=this._matrix_multiply(this.ctx._transform,n);},stroke:function(){if(0<this.ctx._clip_path.length){var t;(t=window.outIntercept?"group"===window.outIntercept.type?window.outIntercept.stream:window.outIntercept:this.internal.getCurrentPage()).push("q");var e=this.path;this.path=this.ctx._clip_path, this.ctx._clip_path=[], this._stroke(!0), this.ctx._clip_path=this.path, this.path=e, this._stroke(!1), t.push("Q");}else this._stroke(!1);}
29679,_stroke:function(t){if(t||!this._isStrokeTransparent()){for(var e=[],n=this.path,r=0;r<n.length;r++){var i=n[r];switch(i.type){case"mt":e.push({start:i,deltas:[],abs:[]});break;case"lt":var o=[i.x-n[r-1].x,i.y-n[r-1].y];e[e.length-1].deltas.push(o), e[e.length-1].abs.push(i);break;case"bct":o=[i.x1-n[r-1].x,i.y1-n[r-1].y,i.x2-n[r-1].x,i.y2-n[r-1].y,i.x-n[r-1].x,i.y-n[r-1].y];e[e.length-1].deltas.push(o);break;case"qct":var a=n[r-1].x+2/3*(i.x1-n[r-1].x),s=n[r-1].y+2/3*(i.y1-n[r-1].y),h=i.x+2/3*(i.x1-i.x),c=i.y+2/3*(i.y1-i.y),l=i.x,u=i.y;o=[a-n[r-1].x,s-n[r-1].y,h-n[r-1].x,c-n[r-1].y,l-n[r-1].x,u-n[r-1].y];e[e.length-1].deltas.push(o);break;case"arc":0==e.length&&e.push({start:{x:0,y:0},deltas:[],abs:[]}), e[e.length-1].arc=!0, Array.isArray(e[e.length-1].abs)&&e[e.length-1].abs.push(i);}}for(r=0;r<e.length;r++){var f;if(f=r==e.length-1?"s":null, e[r].arc)for(var d=e[r].abs,p=0;p<d.length;p++){var g=d[p],m=360*g.startAngle/(2*Math.PI),w=360*g.endAngle/(2*Math.PI),y=g.x,v=g.y;this.internal.arc2(this,y,v,g.radius,m,w,g.anticlockwise,f,t);}else{y=e[r].start.x, v=e[r].start.y;t?(this.pdf.lines(e[r].deltas,y,v,null,null), this.pdf.clip_fixed()):this.pdf.lines(e[r].deltas,y,v,null,f);}}}},_isFillTransparent:function(){return this.ctx._isFillTransparent||0==this.globalAlpha},_isStrokeTransparent:function(){return this.ctx._isStrokeTransparent||0==this.globalAlpha},fill:function(t){if(0<this.ctx._clip_path.length){var e;(e=window.outIntercept?"group"===window.outIntercept.type?window.outIntercept.stream:window.outIntercept:this.internal.getCurrentPage()).push("q");var n=this.path;this.path=this.ctx._clip_path, this.ctx._clip_path=[], this._fill(t,!0), this.ctx._clip_path=this.path, this.path=n, this._fill(t,!1), e.push("Q");}else this._fill(t,!1);},_fill:function(t,e){if(!this._isFillTransparent()){var n,r="function"==typeof this.pdf.internal.newObject2;n=window.outIntercept?"group"===window.outIntercept.type?window.outIntercept.stream:window.outIntercept:this.internal.getCurrentPage();var i=[],o=window.outIntercept;if(r)switch(this.ctx.globalCompositeOperation){case"normal":case"source-over":break;case"destination-in":case"destination-out":var a=this.pdf.internal.newStreamObject(),s=this.pdf.internal.newObject2();s.push("<</Type /ExtGState"), s.push("/SMask <</S /Alpha /G "+a.objId+" 0 R>>"), s.push(">>");var h="MASK"+s.objId;this.pdf.internal.addGraphicsState(h,s.objId);var c="/"+h+" gs";n.splice(0,0,"q"), n.splice(1,0,c), n.push("Q"), window.outIntercept=a;break;default:var l="/"+this.pdf.internal.blendModeMap[this.ctx.globalCompositeOperation.toUpperCase()];l&&this.pdf.internal.out(l+" gs");}var u=this.ctx.globalAlpha;if(this.ctx._fillOpacity<1&&(u=this.ctx._fillOpacity), r){var f=this.pdf.internal.newObject2();f.push("<</Type /ExtGState"), f.push("/CA "+u), f.push("/ca "+u), f.push(">>");h="GS_O_"+f.objId;this.pdf.internal.addGraphicsState(h,f.objId), this.pdf.internal.out("/"+h+" gs");}for(var d=this.path,p=0;p<d.length;p++){var g=d[p];switch(g.type){case"mt":i.push({start:g,deltas:[],abs:[]});break;case"lt":var m=[g.x-d[p-1].x,g.y-d[p-1].y];i[i.length-1].deltas.push(m), i[i.length-1].abs.push(g);break;case"bct":m=[g.x1-d[p-1].x,g.y1-d[p-1].y,g.x2-d[p-1].x,g.y2-d[p-1].y,g.x-d[p-1].x,g.y-d[p-1].y];i[i.length-1].deltas.push(m);break;case"qct":var w=d[p-1].x+2/3*(g.x1-d[p-1].x),y=d[p-1].y+2/3*(g.y1-d[p-1].y),v=g.x+2/3*(g.x1-g.x),b=g.y+2/3*(g.y1-g.y),x=g.x,S=g.y;m=[w-d[p-1].x,y-d[p-1].y,v-d[p-1].x,b-d[p-1].y,x-d[p-1].x,S-d[p-1].y];i[i.length-1].deltas.push(m);break;case"arc":0===i.length&&i.push({deltas:[],abs:[]}), i[i.length-1].arc=!0, Array.isArray(i[i.length-1].abs)&&i[i.length-1].abs.push(g);break;case"close":i.push({close:!0});}}for(p=0;p<i.length;p++){var k;if(p==i.length-1?(k="f", "evenodd"===t&&(k+="*")):k=null, i[p].close)this.pdf.internal.out("h"), k&&this.pdf.internal.out(k);else if(i[p].arc){i[p].start&&this.internal.move2(this,i[p].start.x,i[p].start.y);for(var _=i[p].abs,A=0;A<_.length;A++){var I=_[A];if(void 0!==I.startAngle){var C=360*I.startAngle/(2*Math.PI),T=360*I.endAngle/(2*Math.PI),F=I.x,P=I.y;if(0===A&&this.internal.move2(this,F,P), this.internal.arc2(this,F,P,I.radius,C,T,I.anticlockwise,null,e), A===_.length-1&&i[p].start){F=i[p].start.x, P=i[p].start.y;this.internal.line2(E,F,P);}}else this.internal.line2(E,I.x,I.y);}}else{F=i[p].start.x, P=i[p].start.y;
29679e?(this.pdf.lines(i[p].deltas,F,P,null,null), this.pdf.clip_fixed()):this.pdf.lines(i[p].deltas,F,P,null,k);}}window.outIntercept=o;}},pushMask:function(){if("function"==typeof this.pdf.internal.newObject2){var t=this.pdf.internal.newStreamObject(),e=this.pdf.internal.newObject2();e.push("<</Type /ExtGState"), e.push("/SMask <</S /Alpha /G "+t.objId+" 0 R>>"), e.push(">>");var n="MASK"+e.objId;this.pdf.internal.addGraphicsState(n,e.objId);var r="/"+n+" gs";this.pdf.internal.out(r);}else console.log("jsPDF v2 not enabled");},clip:function(){if(0<this.ctx._clip_path.length)for(var t=0;t<this.path.length;t++)this.ctx._clip_path.push(this.path[t]);else this.ctx._clip_path=this.path;this.path=[];},measureText:function(n){var r=this.pdf;return{getWidth:function(){var t=r.internal.getFontSize(),e=r.getStringUnitWidth(n)*t/r.internal.scaleFactor;return e*=1.3333},get width(){return this.getWidth(n)}}},_getBaseline:function(t){var e=parseInt(this.pdf.internal.getFontSize()),n=.25*e;switch(this.ctx.textBaseline){case"bottom":return t-n;case"top":return t+e;case"hanging":return t+e-n;case"middle":return t+e/2-n;case"ideographic":return t;case"alphabetic":default:return t}}};var E=t.context2d;function e(){this._isStrokeTransparent=!1, this._strokeOpacity=1, this.strokeStyle="#000000", this.fillStyle="#000000", this._isFillTransparent=!1, this._fillOpacity=1, this.font="12pt times", this.textBaseline="alphabetic", this.textAlign="start", this.lineWidth=1, this.lineJoin="miter", this.lineCap="butt", this._transform=[1,0,0,1,0,0], this.globalCompositeOperation="normal", this.globalAlpha=1, this._clip_path=[], this.ignoreClearRect=!1, this.copy=function(t){this._isStrokeTransparent=t._isStrokeTransparent, this._strokeOpacity=t._strokeOpacity, this.strokeStyle=t.strokeStyle, this._isFillTransparent=t._isFillTransparent, this._fillOpacity=t._fillOpacity, this.fillStyle=t.fillStyle, this.font=t.font, this.lineWidth=t.lineWidth, this.lineJoin=t.lineJoin, this.lineCap=t.lineCap, this.textBaseline=t.textBaseline, this.textAlign=t.textAlign, this._fontSize=t._fontSize, this._transform=t._transform.slice(0), this.globalCompositeOperation=t.globalCompositeOperation, this.globalAlpha=t.globalAlpha, this._clip_path=t._clip_path.slice(0), this.ignoreClearRect=t.ignoreClearRect;};}Object.defineProperty(E,"fillStyle",{set:function(t){this.setFillStyle(t);},get:function(){return this.ctx.fillStyle}}), Object.defineProperty(E,"strokeStyle",{set:function(t){this.setStrokeStyle(t);},get:function(){return this.ctx.strokeStyle}}), Object.defineProperty(E,"lineWidth",{set:function(t){this.setLineWidth(t);},get:function(){return this.ctx.lineWidth}}), Object.defineProperty(E,"lineCap",{set:function(t){this.setLineCap(t);},get:function(){return this.ctx.lineCap}}), Object.defineProperty(E,"lineJoin",{set:function(t){this.setLineJoin(t);},get:function(){return this.ctx.lineJoin}}), Object.defineProperty(E,"miterLimit",{set:function(t){this.ctx.miterLimit=t;},get:function(){return this.ctx.miterLimit}}), Object.defineProperty(E,"textBaseline",{set:function(t){this.setTextBaseline(t);},get:function(){return this.getTextBaseline()}}), Object.defineProperty(E,"textAlign",{set:function(t){this.setTextAlign(t);},get:function(){return this.getTextAlign()}}), Object.defineProperty(E,"font",{set:function(t){this.setFont(t);},get:function(){return this.ctx.font}}), Object.defineProperty(E,"globalCompositeOperation",{set:function(t){this.ctx.globalCompositeOperation=t;},get:function(){return this.ctx.globalCompositeOperation}}), Object.defineProperty(E,"globalAlpha",{set:function(t){this.ctx.globalAlpha=t;},get:function(){return this.ctx.globalAlpha}}), Object.defineProperty(E,"canvas",{get:function(){return{parentNode:!1,style:!1}}}), Object.defineProperty(E,"ignoreClearRect",{set:function(t){this.ctx.ignoreClearRect=t;},get:function(){return this.ctx.ignoreClearRect}}), E.internal={}, E.internal.rxRgb=/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/, E.internal.rxRgba=/rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/, E.internal.rxTransparent=/transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/, E.internal.arc=function(t,e,n,r,i,o,a,s){for(var h=this.pdf.internal.scaleFactor,c=this.pdf.internal.pageSize.getHeight(),l=this.pdf.internal.f2,u=i*(Math.PI/180),f=o*(Math.PI/180),d=this.createArc(r,u,f,a),p=0;p<d.length;p++){var g=d[p];0===p?this.pdf.internal.out([l((g.x1+e)*h),l((c-(g.y1+n))*h),"m",l((g.x2+e)*h),l((c-(g.y2+n))*h),l((g.x3+e)*h),l((c-(g.y3+n))*h),l((g.x4+e)*h),l((c-(g.y4
29679+n))*h),"c"].join(" ")):this.pdf.internal.out([l((g.x2+e)*h),l((c-(g.y2+n))*h),l((g.x3+e)*h),l((c-(g.y3+n))*h),l((g.x4+e)*h),l((c-(g.y4+n))*h),"c"].join(" ")), t._lastPoint={x:e,y:n};}null!==s&&this.pdf.internal.out(this.pdf.internal.getStyle(s));}, E.internal.arc2=function(t,e,n,r,i,o,a,s,h){var c=e,l=n;h?(this.arc(t,c,l,r,i,o,a,null), this.pdf.clip_fixed()):this.arc(t,c,l,r,i,o,a,s);}, E.internal.move2=function(t,e,n){var r=this.pdf.internal.scaleFactor,i=this.pdf.internal.pageSize.getHeight(),o=this.pdf.internal.f2;this.pdf.internal.out([o(e*r),o((i-n)*r),"m"].join(" ")), t._lastPoint={x:e,y:n};}, E.internal.line2=function(t,e,n){var r=this.pdf.internal.scaleFactor,i=this.pdf.internal.pageSize.getHeight(),o=this.pdf.internal.f2,a={x:e,y:n};this.pdf.internal.out([o(a.x*r),o((i-a.y)*r),"l"].join(" ")), t._lastPoint=a;}, E.internal.createArc=function(t,e,n,r){var i=2*Math.PI,o=Math.PI/2,a=e;for((a<i||i<a)&&(a%=i), a<0&&(a=i+a);n<e;)e-=i;var s=Math.abs(n-e);s<i&&r&&(s=i-s);for(var h=[],c=r?-1:1,l=a;1e-5<s;){var u=l+c*Math.min(s,o);h.push(this.createSmallArc(t,l,u)), s-=Math.abs(u-l), l=u;}return h}, E.internal.getCurrentPage=function(){return this.pdf.internal.pages[this.pdf.internal.getCurrentPageInfo().pageNumber]}, E.internal.createSmallArc=function(t,e,n){var r=(n-e)/2,i=t*Math.cos(r),o=t*Math.sin(r),a=i,s=-o,h=a*a+s*s,c=h+a*i+s*o,l=4/3*(Math.sqrt(2*h*c)-c)/(a*o-s*i),u=a-l*s,f=s+l*a,d=u,p=-f,g=r+e,m=Math.cos(g),w=Math.sin(g);return{x1:t*Math.cos(e),y1:t*Math.sin(e),x2:u*m-f*w,y2:u*w+f*m,x3:d*m-p*w,y3:d*w+p*m,x4:t*Math.cos(n),y4:t*Math.sin(n)}};}($.API,"undefined"!=typeof self&&self||"undefined"!=typeof window&&window||"undefined"!=typeof commonjsGlobal&&commonjsGlobal||Function('return typeof this === "object" && this.content')()||Function("return this")()), function(t){var T,F,i,a,s,h,c,l,P,v,f,u,d,n,E,q,p,g,m,O;T=function(){return function(t){return e.prototype=t, new e};function e(){}}(), v=function(t){var e,n,r,i,o,a,s;for(n=0, r=t.length, e=void 0, a=i=!1;!i&&n!==r;)(e=t[n]=t[n].trimLeft())&&(i=!0), n++;for(n=r-1;r&&!a&&-1!==n;)(e=t[n]=t[n].trimRight())&&(a=!0), n--;for(o=/\s+$/g, s=!0, n=0;n!==r;)"\u2028"!=t[n]&&(e=t[n].replace(/\s+/g," "), s&&(e=e.trimLeft()), e&&(s=o.test(e)), t[n]=e), n++;return t}, u=function(t){var e,n,r;for(e=void 0, n=(r=t.split(",")).shift();!e&&n;)e=i[n.trim().toLowerCase()], n=r.shift();return e}, d=function(t){var e;return-1<(t="auto"===t?"0px":t).indexOf("em")&&!isNaN(Number(t.replace("em","")))&&(t=18.719*Number(t.replace("em",""))+"px"), -1<t.indexOf("pt")&&!isNaN(Number(t.replace("pt","")))&&(t=1.333*Number(t.replace("pt",""))+"px"), (e=n[t])?e:void 0!==(e={"xx-small":9,"x-small":11,small:13,medium:16,large:19,"x-large":23,"xx-large":28,auto:0}[t])?n[t]=e/16:(e=parseFloat(t))?n[t]=e/16:(e=t.match(/([\d\.]+)(px)/), Array.isArray(e)&&3===e.length?n[t]=parseFloat(e[1])/16:n[t]=1)}, P=function(t){var e,n,r,i,o;return o=t, i=document.defaultView&&document.defaultView.getComputedStyle?document.defaultView.getComputedStyle(o,null):o.currentStyle?o.currentStyle:o.style, n=void 0, (e={})["font-family"]=u((r=function(t){return t=t.replace(/-\D/g,function(t){return t.charAt(1).toUpperCase()}), i[t]})("font-family"))||"times", e["font-style"]=a[r("font-style")]||"normal", e["text-align"]=s[r("text-align")]||"left", "bold"===(n=h[r("font-weight")]||"normal")&&("normal"===e["font-style"]?e["font-style"]=n:e["font-style"]=n+e["font-style"]), e["font-size"]=d(r("font-size"))||1, e["line-height"]=d(r("line-height"))||1, e.display="inline"===r("display")?"inline":"block", n="block"===e.display, e["margin-top"]=n&&d(r("margin-top"))||0, e["margin-bottom"]=n&&d(r("margin-bottom"))||0, e["padding-top"]=n&&d(r("padding-top"))||0, e["padding-bottom"]=n&&d(r("padding-bottom"))||0, e["margin-left"]=n&&d(r("margin-left"))||0, e["margin-right"]=n&&d(r("margin-right"))||0, e["padding-left"]=n&&d(r("padding-left"))||0, e["padding-right"]=n&&d(r("padding-right"))||0, e["page-break-before"]=r("page-break-before")||"auto", e.float=c[r("cssFloat")]||"none", e.clear=l[r("clear")]||"none", e.color=r("color"), e}, E=function(t,e,n){var r,i,o,a,s;if(o=!1, a=i=void 0, r=n["#"+t.id])if("function"==typeof r)o=r(t,e);else for(i=0, a=r.length;!o&&i!==a;)o=r[i](t,e), i++;if(r=n[t.nodeName], !o&&r)if("function"==typeof r)o=r(t,e);else for(i=0, a=r.length;!o&&i!==a;)o=r[i](t,e), i++;for(s="string"==typeof t.className?t.className.split(" "):[], i=0;i<s.length;i++)if(r=n["."+s[i]], !o&&r)if("function"==typeof r)o=r(t,e);else for(i=0, a=r.length;!o&&i!==a;)o=r[i](t,e), i++;return o}, O=function(t,e){var n,r,i,o,a,s,h,c,l;
29679for(n=[], r=[], i=0, l=t.rows[0].cells.length, h=t.clientWidth;i<l;)c=t.rows[0].cells[i], r[i]={name:c.textContent.toLowerCase().replace(/\s+/g,""),prompt:c.textContent.replace(/\r?\n/g,""),width:c.clientWidth/h*e.pdf.internal.pageSize.getWidth()}, i++;for(i=1;i<t.rows.length;){for(s=t.rows[i], a={}, o=0;o<s.cells.length;)a[r[o].name]=s.cells[o].textContent.replace(/\r?\n/g,""), o++;n.push(a), i++;}return{rows:n,headers:r}};var B={SCRIPT:1,STYLE:1,NOSCRIPT:1,OBJECT:1,EMBED:1,SELECT:1},R=1;F=function(t,i,e){var n,r,o,a,s,h,c,l;for(r=t.childNodes, n=void 0, (s="block"===(o=P(t)).display)&&(i.setBlockBoundary(), i.setBlockStyle(o)), a=0, h=r.length;a<h;){if("object"===(void 0===(n=r[a])?"undefined":vt(n))){if(i.executeWatchFunctions(n), 1===n.nodeType&&"HEADER"===n.nodeName){var u=n,f=i.pdf.margins_doc.top;i.pdf.internal.events.subscribe("addPage",function(t){i.y=f, F(u,i,e), i.pdf.margins_doc.top=i.y+10, i.y+=10;},!1);}if(8===n.nodeType&&"#comment"===n.nodeName)~n.textContent.indexOf("ADD_PAGE")&&(i.pdf.addPage(), i.y=i.pdf.margins_doc.top);else if(1!==n.nodeType||B[n.nodeName])if(3===n.nodeType){var d=n.nodeValue;if(n.nodeValue&&"LI"===n.parentNode.nodeName)if("OL"===n.parentNode.parentNode.nodeName)d=R+++". "+d;else{var p=o["font-size"],g=(3-.75*p)*i.pdf.internal.scaleFactor,m=.75*p*i.pdf.internal.scaleFactor,w=1.74*p/i.pdf.internal.scaleFactor;l=function(t,e){this.pdf.circle(t+g,e+m,w,"FD");};}16&n.ownerDocument.body.compareDocumentPosition(n)&&i.addText(d,o);}else"string"==typeof n&&i.addText(n,o);else{var y;if("IMG"===n.nodeName){var v=n.getAttribute("src");y=q[i.pdf.sHashCode(v)||v];}if(y){i.pdf.internal.pageSize.getHeight()-i.pdf.margins_doc.bottom<i.y+n.height&&i.y>i.pdf.margins_doc.top&&(i.pdf.addPage(), i.y=i.pdf.margins_doc.top, i.executeWatchFunctions(n));var b=P(n),x=i.x,S=12/i.pdf.internal.scaleFactor,k=(b["margin-left"]+b["padding-left"])*S,_=(b["margin-right"]+b["padding-right"])*S,A=(b["margin-top"]+b["padding-top"])*S,I=(b["margin-bottom"]+b["padding-bottom"])*S;void 0!==b.float&&"right"===b.float?x+=i.settings.width-n.width-_:x+=k, i.pdf.addImage(y,x,i.y+A,n.width,n.height), y=void 0, "right"===b.float||"left"===b.float?(i.watchFunctions.push(function(t,e,n,r){return i.y>=e?(i.x+=t, i.settings.width+=n, !0):!!(r&&1===r.nodeType&&!B[r.nodeName]&&i.x+r.width>i.pdf.margins_doc.left+i.pdf.margins_doc.width)&&(i.x+=t, i.y=e, i.settings.width+=n, !0)}.bind(this,"left"===b.float?-n.width-k-_:0,i.y+n.height+A+I,n.width)), i.watchFunctions.push(function(t,e,n){return!(i.y<t&&e===i.pdf.internal.getNumberOfPages())||1===n.nodeType&&"both"===P(n).clear&&(i.y=t, !0)}.bind(this,i.y+n.height,i.pdf.internal.getNumberOfPages())), i.settings.width-=n.width+k+_, "left"===b.float&&(i.x+=n.width+k+_)):i.y+=n.height+A+I;}else if("TABLE"===n.nodeName)c=O(n,i), i.y+=10, i.pdf.table(i.x,i.y,c.rows,c.headers,{autoSize:!1,printHeaders:e.printHeaders,margins:i.pdf.margins_doc,css:P(n)}), i.y=i.pdf.lastCellPos.y+i.pdf.lastCellPos.h+20;else if("OL"===n.nodeName||"UL"===n.nodeName)R=1, E(n,i,e)||F(n,i,e), i.y+=10;else if("LI"===n.nodeName){var C=i.x;i.x+=20/i.pdf.internal.scaleFactor, i.y+=3, E(n,i,e)||F(n,i,e), i.x=C;}else"BR"===n.nodeName?(i.y+=o["font-size"]*i.pdf.internal.scaleFactor, i.addText("\u2028",T(o))):E(n,i,e)||F(n,i,e);}}a++;}if(e.outY=i.y, s)return i.setBlockBoundary(l)}, q={}, p=function(t,o,e,n){var a,r=t.getElementsByTagName("img"),i=r.length,s=0;function h(){o.pdf.internal.events.publish("imagesLoaded"), n(a);}function c(e,n,r){if(e){var i=new Image;a=++s, i.crossOrigin="", i.onerror=i.onload=function(){if(i.complete&&(0===i.src.indexOf("data:image/")&&(i.width=n||i.width||0, i.height=r||i.height||0), i.width+i.height)){var t=o.pdf.sHashCode(e)||e;q[t]=q[t]||i;}--s||h();}, i.src=e;}}for(;i--;)c(r[i].getAttribute("src"),r[i].width,r[i].height);return s||h()}, g=function(t,o,a){var s=t.getElementsByTagName("footer");if(0<s.length){s=s[0];var e=o.pdf.internal.write,n=o.y;o.pdf.internal.write=function(){}, F(s,o,a);var h=Math.ceil(o.y-n)+5;o.y=n, o.pdf.internal.write=e, o.pdf.margins_doc.bottom+=h;for(var r=function(t){var e=void 0!==t?t.pageNumber:1,n=o.y;o.y=o.pdf.internal.pageSize.getHeight()-o.pdf.margins_doc.bottom, o.pdf.margins_doc.bottom-=h;for(var r=s.getElementsByTagName("span"),i=0;i<r.length;++i)-1<(" "+r[i].className+" ").replace(/[\n\t]/g," ").indexOf(" pageCounter ")&&(r[i].innerHTML=e), -1<(" "+r[i].className+" ").replace(/[\n\t]/g," ").indexOf(" totalPages ")&&(r[i].innerHTML="###jsPDFVarTotalPages###");F(s,o,a), o.pdf.margins_doc.bottom+=h, o.y=n;},i=s.getElementsByTagName("span"),c=0;c<i.length;++c)-1<(" "+i[c].className+" ").replace(/[\n\t]/g," ").indexOf(" totalPages ")&&o.pdf.internal.events.subscribe("htmlRenderingFinished",o.pdf.putTotalPages.bind(o.pdf,"###jsPDFVarTotalPages###"),!0);o.pdf.internal.events.subscribe("addPage",r,!1), r(), B.FOOTER=1;}}, m=function(t,e,n,r,i,o){if(!e)return!1;var a,s,h,c;"string"==typeof e||e.parentNode||(e=""+e.innerHTML), "string"==typeof e&&(a=e.replace(/<\/?script[^>]*?>/gi,""), c="jsPDFhtmlText"+Date.now().toString()+(1e3*Math.random()).toFixed(0), (h=document.createElement("div")).style.cssText="position: absolute !important;clip: rect(1px 1px 1px 1px); /* IE6, IE7 */clip: rect(1px, 1px, 1px, 1px);padding:0 !important;border:0 !important;height: 1px !important;width: 1px !important; top:auto;left:-100px;overflow: hidden;", h.innerHTML='<iframe style="height:1px;width:1px" name="'+c+'" />', document.body.appendChild(h), (s=window.frames[c]).document.open(), s.document.writeln(a), s.document.close(), e=s.document.body);var l,u=new f(t,n,r,i);return p.call(this,e,u,i.elementHandlers,function(t){g(e,u,i.elementHandlers), F(e,u,i.elementHandlers), u.pdf.internal.events.publish("htmlRenderingFinished"), l=u.dispose(), "function"==typeof o?o(l):t&&console.error("jsPDF Warning: rendering issues? provide a callback to fromHTML!");}), l||{x:u.x,y:u.y}}, (f=function(t,e,n,r){return this.pdf=t, this.x=e, this.y=n, this.settings=r, this.watchFunctions=[], this.init(), this}).prototype.init=function(){return this.paragraph={text:[],style:[]}, this.pdf.internal.write("q")}, f.prototype.dispose=function(){return this.pdf.internal.write("Q"), {x:this.x,y:this.y,ready:!0}}, f.prototype.executeWatchFunctions=function(t){var e=!1,n=[];if(0<this.watchFunctions.length){for(var r=0;r<this.watchFunctions.length;++r)!0===this.watchFunctions[r](t)?e=!0:n.push(this.watchFunctions[r]);this.watchFunctions=n;}return e}, f.prototype.splitFragmentsIntoLines=function(t,e){var n,r,i,o,a,s,h,c,l,u,f,d,p,g;for(u=this.pdf.internal.scaleFactor, o={}
29679, s=h=c=g=a=i=l=r=void 0, d=[f=[]], n=0, p=this.settings.width;t.length;)if(a=t.shift(), g=e.shift(), a)if((i=o[(r=g["font-family"])+(l=g["font-style"])])||(i=this.pdf.internal.getFont(r,l).metadata.Unicode, o[r+l]=i), c={widths:i.widths,kerning:i.kerning,fontSize:12*g["font-size"],textIndent:n}, h=this.pdf.getStringUnitWidth(a,c)*c.fontSize/u, "\u2028"==a)f=[], d.push(f);else if(p<n+h){for(s=this.pdf.splitTextToSize(a,p,c), f.push([s.shift(),g]);s.length;)f=[[s.shift(),g]], d.push(f);n=this.pdf.getStringUnitWidth(f[0][0],c)*c.fontSize/u;}else f.push([a,g]), n+=h;if(void 0!==g["text-align"]&&("center"===g["text-align"]||"right"===g["text-align"]||"justify"===g["text-align"]))for(var m=0;m<d.length;++m){var w=this.pdf.getStringUnitWidth(d[m][0][0],c)*c.fontSize/u;0<m&&(d[m][0][1]=T(d[m][0][1]));var y=p-w;if("right"===g["text-align"])d[m][0][1]["margin-left"]=y;else if("center"===g["text-align"])d[m][0][1]["margin-left"]=y/2;else if("justify"===g["text-align"]){var v=d[m][0][0].split(" ").length-1;d[m][0][1]["word-spacing"]=y/v, m===d.length-1&&(d[m][0][1]["word-spacing"]=0);}}return d}, f.prototype.RenderTextFragment=function(t,e){var n,r;r=0, this.pdf.internal.pageSize.getHeight()-this.pdf.margins_doc.bottom<this.y+this.pdf.internal.getFontSize()&&(this.pdf.internal.write("ET","Q"), this.pdf.addPage(), this.y=this.pdf.margins_doc.top, this.pdf.internal.write("q","BT",this.getPdfColor(e.color),this.pdf.internal.getCoordinateString(this.x),this.pdf.internal.getVerticalCoordinateString(this.y),"Td"), r=Math.max(r,e["line-height"],e["font-size"]), this.pdf.internal.write(0,(-12*r).toFixed(2),"Td")), n=this.pdf.internal.getFont(e["font-family"],e["font-style"]);var i=this.getPdfColor(e.color);i!==this.lastTextColor&&(this.pdf.internal.write(i), this.lastTextColor=i), void 0!==e["word-spacing"]&&0<e["word-spacing"]&&this.pdf.internal.write(e["word-spacing"].toFixed(2),"Tw"), this.pdf.internal.write("/"+n.id,(12*e["font-size"]).toFixed(2),"Tf","("+this.pdf.internal.pdfEscape(t)+") Tj"), void 0!==e["word-spacing"]&&this.pdf.internal.write(0,"Tw");}, f.prototype.getPdfColor=function(t){var e,n,r,i=new RGBColor(t),o=/rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+\s*)\)/.exec(t);if(null!=o?(e=parseInt(o[1]), n=parseInt(o[2]), r=parseInt(o[3])):("#"!=t.charAt(0)&&(t=i.ok?i.toHex():"#000000"), e=t.substring(1,3), e=parseInt(e,16), n=t.substring(3,5), n=parseInt(n,16), r=t.substring(5,7), r=parseInt(r,16)), "string"==typeof e&&/^#[0-9A-Fa-f]{6}$/.test(e)){var a=parseInt(e.substr(1),16);e=a>>16&255, n=a>>8&255, r=255&a;}var s=this.f3;return 0===e&&0===n&&0===r||void 0===n?s(e/255)+" g":[s(e/255),s(n/255),s(r/255),"rg"].join(" ")}, f.prototype.f3=function(t){return t.toFixed(3)}, f.prototype.renderParagraph=function(t){var e,n,r,i,o,a,s,h,c,l,u,f,d;if(r=v(this.paragraph.text), f=this.paragraph.style, e=this.paragraph.blockstyle, this.paragraph.priorblockstyle||{}, this.paragraph={text:[],style:[],blockstyle:{},priorblockstyle:e}, r.join("").trim()){s=this.splitFragmentsIntoLines(r,f), h=a=void 0, n=12/this.pdf.internal.scaleFactor, this.priorMarginBottom=this.priorMarginBottom||0, u=(Math.max((e["margin-top"]||0)-this.priorMarginBottom,0)+(e["padding-top"]||0))*n, l=((e["margin-bottom"]||0)+(e["padding-bottom"]||0))*n, this.priorMarginBottom=e["margin-bottom"]||0, "always"===e["page-break-before"]&&(this.pdf.addPage(), this.y=0, u=((e["margin-top"]||0)+(e["padding-top"]||0))*n), c=this.pdf.internal.write, o=i=void 0, this.y+=u, c("q","BT 0 g",this.pdf.internal.getCoordinateString(this.x),this.pdf.internal.getVerticalCoordinateString(this.y),"Td");for(var p=0;s.length;){for(i=h=0, o=(a=s.shift()).length;i!==o;)a[i][0].trim()&&(h=Math.max(h,a[i][1]["line-height"],a[i][1]["font-size"]), d=7*a[i][1]["font-size"]), i++;var g=0,m=0;for(void 0!==a[0][1]["margin-left"]&&0<a[0][1]["margin-left"]&&(g=(m=this.pdf.internal.getCoordinateString(a[0][1]["margin-left"]))-p, p=m), c(g+Math.max(e["margin-left"]||0,0)*n,(-12*h).toFixed(2),"Td"), i=0, o=a.length;i!==o;)a[i][0]&&this.RenderTextFragment(a[i][0],a[i][1]), i++;if(this.y+=h*n, this.executeWatchFunctions(a[0][1])&&0<s.length){var w=[],y=[];
29679s.forEach(function(t){for(var e=0,n=t.length;e!==n;)t[e][0]&&(w.push(t[e][0]+" "), y.push(t[e][1])), ++e;}), s=this.splitFragmentsIntoLines(v(w),y), c("ET","Q"), c("q","BT 0 g",this.pdf.internal.getCoordinateString(this.x),this.pdf.internal.getVerticalCoordinateString(this.y),"Td");}}return t&&"function"==typeof t&&t.call(this,this.x-9,this.y-d/2), c("ET","Q"), this.y+=l}}, f.prototype.setBlockBoundary=function(t){return this.renderParagraph(t)}, f.prototype.setBlockStyle=function(t){return this.paragraph.blockstyle=t}, f.prototype.addText=function(t,e){return this.paragraph.text.push(t), this.paragraph.style.push(e)}, i={helvetica:"helvetica","sans-serif":"helvetica","times new roman":"times",serif:"times",times:"times",monospace:"courier",courier:"courier"}, h={100:"normal",200:"normal",300:"normal",400:"normal",500:"bold",600:"bold",700:"bold",800:"bold",900:"bold",normal:"normal",bold:"bold",bolder:"bold",lighter:"normal"}, a={normal:"normal",italic:"italic",oblique:"italic"}, s={left:"left",right:"right",center:"center",justify:"justify"}, c={none:"none",right:"right",left:"left"}, l={none:"none",both:"both"}, n={normal:1}, t.fromHTML=function(t,e,n,r,i,o){return this.margins_doc=o||{top:0,bottom:0}, r||(r={}), r.elementHandlers||(r.elementHandlers={}), m(this,t,isNaN(e)?4:e,isNaN(n)?4:n,r,i)};}($.API), $.API.addJS=function(t){return s=t, this.internal.events.subscribe("postPutResources",function(t){n=this.internal.newObject(), this.internal.out("<<"), this.internal.out("/Names [(EmbeddedJS) "+(n+1)+" 0 R]"), this.internal.out(">>"), this.internal.out("endobj"), r=this.internal.newObject(), this.internal.out("<<"), this.internal.out("/S /JavaScript"), this.internal.out("/JS ("+s+")"), this.internal.out(">>"), this.internal.out("endobj");}), this.internal.events.subscribe("putCatalog",function(){void 0!==n&&void 0!==r&&this.internal.out("/Names <</JavaScript "+n+" 0 R>>");}), this}, (
29680/**
29681   * jsPDF Outline PlugIn
29682   * Copyright (c) 2014 Steven Spungin (TwelveTone LLC)  [email protected]
29683   *
29684   * Licensed under the MIT License.
29685   * http://opensource.org/licenses/mit-license
29686   */
29687c=$.API).events.push(["postPutResources",function(){var t=this,e=/^(\d+) 0 obj$/;if(0<this.outline.root.children.length)for(var n=t.outline.render().split(/\r\n/),r=0;r<n.length;r++){var i=n[r],o=e.exec(i);if(null!=o){var a=o[1];t.internal.newObjectDeferredBegin(a);}t.internal.write(i);}if(this.outline.createNamedDestinations){var s=this.internal.pages.length,h=[];for(r=0;r<s;r++){var c=t.internal.newObject();h.push(c);var l=t.internal.getPageInfo(r+1);t.internal.write("<< /D["+l.objId+" 0 R /XYZ null null null]>> endobj");}var u=t.internal.newObject();for(t.internal.write("<< /Names [ "), r=0;r<h.length;r++)t.internal.write("(page_"+(r+1)+")"+h[r]+" 0 R");t.internal.write(" ] >>","endobj"), t.internal.newObject(), t.internal.write("<< /Dests "+u+" 0 R"), t.internal.write(">>","endobj");}}]), c.events.push(["putCatalog",function(){0<this.outline.root.children.length&&(this.internal.write("/Outlines",this.outline.makeRef(this.outline.root)), this.outline.createNamedDestinations&&this.internal.write("/Names "+namesOid+" 0 R"));}]), c.events.push(["initialized",function(){var o=this;o.outline={createNamedDestinations:!1,root:{children:[]}}, o.outline.add=function(t,e,n){var r={title:e,options:n,children:[]};return null==t&&(t=this.root), t.children.push(r), r}, o.outline.render=function(){return this.ctx={}, this.ctx.val="", this.ctx.pdf=o, this.genIds_r(this.root), this.renderRoot(this.root), this.renderItems(this.root), this.ctx.val}, o.outline.genIds_r=function(t){t.id=o.internal.newObjectDeferred();for(var e=0;e<t.children.length;e++)this.genIds_r(t.children[e]);}, o.outline.renderRoot=function(t){this.objStart(t), this.line("/Type /Outlines"), 0<t.children.length&&(this.line("/First "+this.makeRef(t.children[0])), this.line("/Last "+this.makeRef(t.children[t.children.length-1]))), this.line("/Count "+this.count_r({count:0},t)), this.objEnd();}, o.outline.renderItems=function(t){for(var e=0;e<t.children.length;e++){var n=t.children[e];this.objStart(n), this.line("/Title "+this.makeString(n.title)), this.line("/Parent "+this.makeRef(t)), 0<e&&this.line("/Prev "+this.makeRef(t.children[e-1])), e<t.children.length-1&&this.line("/Next "+this.makeRef(t.children[e+1])), 0<n.children.length&&(this.line("/First "+this.makeRef(n.children[0])), this.line("/Last "+this.makeRef(n.children[n.children.length-1])));var r=this.count=this.count_r({count:0},n);if(0<r&&this.line("/Count "+r), n.options&&n.options.pageNumber){var i=o.internal.getPageInfo(n.options.pageNumber);this.line("/Dest ["+i.objId+" 0 R /XYZ 0 "+this.ctx.pdf.internal.pageSize.getHeight()*this.ctx.pdf.internal.scaleFactor+" 0]");}this.objEnd();}for(e=0;e<t.children.length;e++)n=t.children[e], this.renderItems(n);}
29687, o.outline.line=function(t){this.ctx.val+=t+"\r\n";}, o.outline.makeRef=function(t){return t.id+" 0 R"}, o.outline.makeString=function(t){return"("+o.internal.pdfEscape(t)+")"}, o.outline.objStart=function(t){this.ctx.val+="\r\n"+t.id+" 0 obj\r\n<<\r\n";}, o.outline.objEnd=function(t){this.ctx.val+=">> \r\nendobj\r\n";}, o.outline.count_r=function(t,e){for(var n=0;n<e.children.length;n++)t.count++, this.count_r(t,e.children[n]);return t.count};}]), P=$.API, E=function(){var t="function"==typeof Deflater;if(!t)throw new Error("requires deflate.js for compression");return t}, q=function(t,e,n,r){var i=5,o=b;switch(r){case P.image_compression.FAST:i=3, o=v;break;case P.image_compression.MEDIUM:i=6, o=x;break;case P.image_compression.SLOW:i=9, o=S;}t=w(t,e,n,o);var a=new Uint8Array(g(i)),s=m(t),h=new Deflater(i),c=h.append(t),l=h.flush(),u=a.length+c.length+l.length,f=new Uint8Array(u+4);return f.set(a), f.set(c,a.length), f.set(l,a.length+c.length), f[u++]=s>>>24&255, f[u++]=s>>>16&255, f[u++]=s>>>8&255, f[u++]=255&s, P.arrayBufferToBinaryString(f)}, g=function(t,e){var n=Math.LOG2E*Math.log(32768)-8<<4|8,r=n<<8;return r|=Math.min(3,(e-1&255)>>1)<<6, r|=0, [n,255&(r+=31-r%31)]}, m=function(t,e){for(var n,r=1,i=0,o=t.length,a=0;0<o;){for(o-=n=e<o?e:o;i+=r+=t[a++], --n;);r%=65521, i%=65521;}return(i<<16|r)>>>0}, w=function(t,e,n,r){for(var i,o,a,s=t.length/e,h=new Uint8Array(t.length+s),c=k(),l=0;l<s;l++){if(a=l*e, i=t.subarray(a,a+e), r)h.set(r(i,n,o),a+l);else{for(var u=0,f=c.length,d=[];u<f;u++)d[u]=c[u](i,n,o);var p=_(d.concat());h.set(d[p],a+l);}o=i;}return h}, l=function(t,e,n){var r=Array.apply([],t);return r.unshift(0), r}, v=function(t,e,n){var r,i=[],o=0,a=t.length;for(i[0]=1;o<a;o++)r=t[o-e]||0, i[o+1]=t[o]-r+256&255;return i}, b=function(t,e,n){var r,i=[],o=0,a=t.length;for(i[0]=2;o<a;o++)r=n&&n[o]||0, i[o+1]=t[o]-r+256&255;return i}, x=function(t,e,n){var r,i,o=[],a=0,s=t.length;for(o[0]=3;a<s;a++)r=t[a-e]||0, i=n&&n[a]||0, o[a+1]=t[a]+256-(r+i>>>1)&255;return o}, S=function(t,e,n){var r,i,o,a,s=[],h=0,c=t.length;for(s[0]=4;h<c;h++)r=t[h-e]||0, i=n&&n[h]||0, o=n&&n[h-e]||0, a=u(r,i,o), s[h+1]=t[h]-a+256&255;return s}, u=function(t,e,n){var r=t+e-n,i=Math.abs(r-t),o=Math.abs(r-e),a=Math.abs(r-n);return i<=o&&i<=a?t:o<=a?e:n}, k=function(){return[l,v,b,x,S]}, _=function(t){for(var e,n,r,i=0,o=t.length;i<o;)((e=f(t[i].slice(1)))<n||!n)&&(n=e, r=i), i++;return r}, f=function(t){for(var e=0,n=t.length,r=0;e<n;)r+=Math.abs(t[e++]);return r}, P.processPNG=function(t,e,n,r,i){var o,a,s,h,c,l,u=this.color_spaces.DEVICE_RGB,f=this.decode.FLATE_DECODE,d=8;if(this.isArrayBuffer(t)&&(t=new Uint8Array(t)), this.isArrayBufferView(t)){if("function"!=typeof PNG||"function"!=typeof kt)throw new Error("PNG support requires png.js and zlib.js");if(t=(o=new PNG(t)).imgData, d=o.bits, u=o.colorSpace, h=o.colors, -1!==[4,6].indexOf(o.colorType)){if(8===o.bits)for(var p,g=(I=32==o.pixelBitlength?new Uint32Array(o.decodePixels().buffer):16==o.pixelBitlength?new Uint16Array(o.decodePixels().buffer):new Uint8Array(o.decodePixels().buffer)).length,m=new Uint8Array(g*o.colors),w=new Uint8Array(g),y=o.pixelBitlength-o.bits,v=0,b=0;v<g;v++){for(x=I[v], p=0;p<y;)m[b++]=x>>>p&255, p+=o.bits;w[v]=x>>>p&255;}if(16===o.bits){g=(I=new Uint32Array(o.decodePixels().buffer)).length, m=new Uint8Array(g*(32/o.pixelBitlength)*o.colors), w=new Uint8Array(g*(32/o.pixelBitlength));for(var x,S=1<o.colors,k=b=v=0;v<g;)x=I[v++], m[b++]=x>>>0&255, S&&(m[b++]=x>>>16&255, x=I[v++], m[b++]=x>>>0&255), w[k++]=x>>>16&255;d=8;}r!==P.image_compression.NONE&&E()?(t=q(m,o.width*o.colors,o.colors,r), l=q(w,o.width,1,r)):(t=m, l=w, f=null);}if(3===o.colorType&&(u=this.color_spaces.INDEXED, c=o.palette, o.transparency.indexed)){var _=o.transparency.indexed,A=0;for(v=0, g=_.length;v<g;++v)A+=_[v];if((A/=255)==g-1&&-1!==_.indexOf(0))s=[_.indexOf(0)];else if(A!==g){var I=o.decodePixels();for(w=new Uint8Array(I.length), v=0, g=I.length;v<g;v++)w[v]=_[I[v]];l=q(w,o.width,1);}}var C=function(t){var e;switch(t){case P.image_compression.FAST:e=11;break;case P.image_compression.MEDIUM:e=13;break;case P.image_compression.SLOW:e=14;break;default:e=12;}return e}(r);return a=f===this.decode.FLATE_DECODE?"/Predictor "+C+" /Colors "+h+" /BitsPerComponent "+d+" /Columns "+o.width:"/Colors "+h+" /BitsPerComponent "+d+" /Columns "+o.width, (this.isArrayBuffer(t)||this.isArrayBufferView(t))&&(t=this.arrayBufferToBinaryString(t)), (l&&this.isArrayBuffer(l)||this.isArrayBufferView(l))&&(l=this.arrayBufferToBinaryString(l)), this.createImageInfo(t,o.width,o.height,u,d,f,e,n,a,s,c,l,C)}throw new Error("Unsupported PNG image data, try using JPEG instead.")}, (
29688/**
29689   * jsPDF gif Support PlugIn
29690   * Copyright (c) 2017 Aras Abbasi 
29691   *
29692   * Licensed under the MIT License.
29693   * http://opensource.org/licenses/mit-license
29694   */
29695A=$.API).processGIF89A=function(t,e,n,r,i){var o=new mt(t),a=o.width,s=o.height,h=[];o.decodeAndBlitFrameRGBA(0,h);var c={data:h,width:a,height:s},l=new yt(100).encode(c,100);return A.processJPEG.call(this,l,e,n,r)}, A.processGIF87A=A.processGIF89A, (
29696/**
29697   * jsPDF bmp Support PlugIn
29698   * Copyright (c) 2018 Aras Abbasi 
29699   *
29700   * Licensed under the MIT License.
29701   * http://opensource.org/licenses/mit-license
29702   */
29703O=$.API).processBMP=function(t,e,n,r,i){var o=new xt(t,!1),a=o.width,s=o.height,h={data:o.getData(),width:a,height:s},c=new yt(100).encode(h,100);return O.processJPEG.call(this,c,e,n,r)}, $.API.setLanguage=function(t){return void 0===this.internal.languageSettings&&(this.internal.languageSettings={}, this.internal.languageSettings.isSubscribed=!1), void 0!=={af:"Afrikaans",sq
29703:"Albanian",ar:"Arabic (Standard)","ar-DZ":"Arabic (Algeria)","ar-BH":"Arabic (Bahrain)","ar-EG":"Arabic (Egypt)","ar-IQ":"Arabic (Iraq)","ar-JO":"Arabic (Jordan)","ar-KW":"Arabic (Kuwait)","ar-LB":"Arabic (Lebanon)","ar-LY":"Arabic (Libya)","ar-MA":"Arabic (Morocco)","ar-OM":"Arabic (Oman)","ar-QA":"Arabic (Qatar)","ar-SA":"Arabic (Saudi Arabia)","ar-SY":"Arabic (Syria)","ar-TN":"Arabic (Tunisia)","ar-AE":"Arabic (U.A.E.)","ar-YE":"Arabic (Yemen)",an:"Aragonese",hy:"Armenian",as:"Assamese",ast:"Asturian",az:"Azerbaijani",eu:"Basque",be:"Belarusian",bn:"Bengali",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",zh:"Chinese","zh-HK":"Chinese (Hong Kong)","zh-CN":"Chinese (PRC)","zh-SG":"Chinese (Singapore)","zh-TW":"Chinese (Taiwan)",cv:"Chuvash",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",nl:"Dutch (Standard)","nl-BE":"Dutch (Belgian)",en:"English","en-AU":"English (Australia)","en-BZ":"English (Belize)","en-CA":"English (Canada)","en-IE":"English (Ireland)","en-JM":"English (Jamaica)","en-NZ":"English (New Zealand)","en-PH":"English (Philippines)","en-ZA":"English (South Africa)","en-TT":"English (Trinidad & Tobago)","en-GB":"English (United Kingdom)","en-US":"English (United States)","en-ZW":"English (Zimbabwe)",eo:"Esperanto",et:"Estonian",fo:"Faeroese",fj:"Fijian",fi:"Finnish",fr:"French (Standard)","fr-BE":"French (Belgium)","fr-CA":"French (Canada)","fr-FR":"French (France)","fr-LU":"French (Luxembourg)","fr-MC":"French (Monaco)","fr-CH":"French (Switzerland)",fy:"Frisian",fur:"Friulian",gd:"Gaelic (Scots)","gd-IE":"Gaelic (Irish)",gl:"Galacian",ka:"Georgian",de:"German (Standard)","de-AT":"German (Austria)","de-DE":"German (Germany)","de-LI":"German (Liechtenstein)","de-LU":"German (Luxembourg)","de-CH":"German (Switzerland)",el:"Greek",gu:"Gujurati",ht:"Haitian",he:"Hebrew",hi:"Hindi",hu:"Hungarian",is:"Icelandic",id:"Indonesian",iu:"Inuktitut",ga:"Irish",it:"Italian (Standard)","it-CH":"Italian (Switzerland)",ja:"Japanese",kn:"Kannada",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ky:"Kirghiz",tlh:"Klingon",ko:"Korean","ko-KP":"Korean (North Korea)","ko-KR":"Korean (South Korea)",la:"Latin",lv:"Latvian",lt:"Lithuanian",lb:"Luxembourgish",mk:"FYRO Macedonian",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mo:"Moldavian",nv:"Navajo",ng:"Ndonga",ne:"Nepali",no:"Norwegian",nb:"Norwegian (Bokmal)",nn:"Norwegian (Nynorsk)",oc:"Occitan",or:"Oriya",om:"Oromo",fa:"Persian","fa-IR":"Persian/Iran",pl:"Polish",pt:"Portuguese","pt-BR":"Portuguese (Brazil)",pa:"Punjabi","pa-IN":"Punjabi (India)","pa-PK":"Punjabi (Pakistan)",qu:"Quechua",rm:"Rhaeto-Romanic",ro:"Romanian","ro-MO":"Romanian (Moldavia)",ru:"Russian","ru-MO":"Russian (Moldavia)",sz:"Sami (Lappish)",sg:"Sango",sa:"Sanskrit",sc:"Sardinian",sd:"Sindhi",si:"Singhalese",sr:"Serbian",sk:"Slovak",sl:"Slovenian",so:"Somani",sb:"Sorbian",es:"Spanish","es-AR":"Spanish (Argentina)","es-BO":"Spanish (Bolivia)","es-CL":"Spanish (Chile)","es-CO":"Spanish (Colombia)","es-CR":"Spanish (Costa Rica)","es-DO":"Spanish (Dominican Republic)","es-EC":"Spanish (Ecuador)","es-SV":"Spanish (El Salvador)","es-GT":"Spanish (Guatemala)","es-HN":"Spanish (Honduras)","es-MX":"Spanish (Mexico)","es-NI":"Spanish (Nicaragua)","es-PA":"Spanish (Panama)","es-PY":"Spanish (Paraguay)","es-PE":"Spanish (Peru)","es-PR":"Spanish (Puerto Rico)","es-ES":"Spanish (Spain)","es-UY":"Spanish (Uruguay)","es-VE":"Spanish (Venezuela)",sx:"Sutu",sw:"Swahili",sv:"Swedish","sv-FI":"Swedish (Finland)","sv-SV":"Swedish (Sweden)",ta:"Tamil",tt:"Tatar",te:"Teluga",th:"Thai",tig:"Tigre",ts:"Tsonga",tn:"Tswana",tr:"Turkish",tk:"Turkmen",uk:"Ukrainian",hsb:"Upper Sorbian",ur:"Urdu",ve:"Venda",vi:"Vietnamese",vo:"Volapuk",wa:"Walloon",cy:"Welsh",xh:"Xhosa",ji:"Yiddish",zu:"Zulu"}[t]&&(this.internal.languageSettings.languageCode=t, !1===this.internal.languageSettings.isSubscribed&&(this.internal.events.subscribe("putCatalog",function(){this.internal.write("/Lang ("+this.internal.languageSettings.languageCode+")");}), this.internal.languageSettings.isSubscribed=!0)), this}, B=$.API, R=B.getCharWidthsArray=function(t,e){var n,r,i,o=(e=e||{}).font||this.internal.getFont(),a=e.fontSize||this.internal.getFontSize(),s=e.charSpace||this.internal.getCharSpace(),h=e.widths?e.widths:o.metadata.Unicode.widths,c=h.fof?h.fof:1,l=e.kerning?e.kerning:o.metadata.Unicode.kerning,u=l.fof?l.fof:1,f=0,d=h[0]||c,p=[];for(n=0, r=t.length;n<r;n++)i=t.charCodeAt(n), "function"==typeof o.metadata.widthOfString?p.push((o.metadata.widthOfGlyph(o.metadata.characterToGlyph(i))+s*(1e3/a)||0)/1e3):p.push((h[i]||d)/c+(l[i]&&l[i][f]||0)/u), f=i;return p}, j=B.getArraySum=function(t){for(var e=t.length,n=0;e;)n+=t[--e];return n}, D=B.getStringUnitWidth=function(t,e){var n=(e=e||{}).fontSize||this.internal.getFontSize(),r=e.font||this.internal.getFont(),i=e.charSpace||this.internal.getCharSpace();return"function"==typeof r.metadata.widthOfString?r.metadata.widthOfString(t,n,i)/n:j(R.apply(this,arguments))}, M=function(t,e,n,r){for(var i=[],o=0,a=t.length,s=0;o!==a&&s+e[o]<n;)s+=e[o], o++;i.push(t.slice(0,o));var h=o;for(s=0;o!==a;)s+e[o]>r&&(i.push(t.slice(h,o)), s=0, h=o), s+=e[o], o++;return h!==o&&i.push(t.slice(h,o)), i}, U=function(t,e,n){n||(n={});var r,i,o,a,s,h,c=[],l=[c],u=n.textIndent||0,f=0,d=0,p=t.split(" "),g=R.apply(this,[" ",n])[0];if(h=-1===n.lineIndent?p[0].length+2:n.lineIndent||0){var m=Array(h).join(" "),w=[];p.map(function(t){1<(t=t.split(/\s*\n/)).length?w=w.concat(t.map(function(t,e){return(e&&t.length?"\n":"")+t})):w.push(t[0]);}), p=w, h=D.apply(this,[m,n]);}for(o=0, a=p.length;o<a;o++){var y=0;if(r=p[o], h&&"\n"==r[0]&&(r=r.substr(1), y=1), i=R.apply(this,[r,n]), e<u+f+(d=j(i))||y){if(e<d){for(s=M.apply(this,[r,i,e-(u+f),e]), c.push(s.shift()), c=[s.pop()];s.length;)l.push([s.shift()]);d=j(i.slice(r.length-(c[0]?c[0].length:0)));}else c=[r];l.push(c), u=d+h, f=g;}else c.push(r), u+=f+d, f=g;}if(h)var v=function(t,e){return(e?m:"")+t.join(" ")};else v=function(t){return t.join(" ")};return l.map(v)}, B.splitTextToSize=function(t,e,n){var r,i=(n=n||{}).fontSize||this.internal.getFontSize(),o=function(t){var e={0:1},n={};if(t.widths&&t.kerning)return{widths:t.widths,kerning:t.kerning};var r=this.internal.getFont(t.fontName,t.fontStyle),i="Unicode";return r.metadata[i]?{widths:r.metadata[i].widths||e,kerning:r.metadata[i].kerning||n}:{font:r.metadata,fontSize:this.internal.getFontSize(),charSpace:this.internal.getCharSpace()}}.call(this,n);r=Array.isArray(t)?t:t.split(/\r?\n/);var a=1*this.internal.scaleFactor*e/i;o.textIndent=n.textIndent?1*n.textIndent*this.internal.scaleFactor/i:0, o.lineIndent=n.lineIndent;var s,h,c=[];for(s=0, h=r.length;s<h;s++)c=c.concat(U.apply(this,[r[s],a,o]));return c}, N=$.API, L={codePages:["WinAnsiEncoding"],WinAnsiEncoding:(z=function(t){for(var e="klmnopqrstuvwxyz",n={},r=0;r<e.length;r++)n[e[r]]="0123456789abcdef"[r];var i,o,a,s,h,c={},l=1,u=c,f=[],d="",p="",g=t.length-1;for(r=1;r!=g;)h=t[r], r+=1, "'"==h?o?(s=o.join(""), o=i):o=[]:o?o.push(h):"{"==h?(f.push([u,s]), u={}, s=i):"}"==h?((a=f.pop())[0][a[1]]=u, s=i, u=a[0]):"-"==h?l=-1:s===i?n.hasOwnProperty(h)?(d+=n[h], s=parseInt(d,16)*l, l=1, d=""):d+=h:n.hasOwnProperty(h)?(p+=n[h], u[s]=parseInt(p,16)*l, l=1, s=i, p=""):p+=h;return c})("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")}, H={Unicode:{Courier:L,"Courier-Bold":L,"Courier-BoldOblique":L,"Courier-Oblique":L,Helvetica:L,"Helvetica-Bold":L,"Helvetica-BoldOblique":L,"Helvetica-Oblique":L,"Times-Roman":L,"Times-Bold":L,"Times-BoldItalic":L,"Times-Italic":L}
29704/** 
29705    Resources:
29706    Font metrics data is reprocessed derivative of contents of
29707    "Font Metrics for PDF Core 14 Fonts" package, which exhibits the following copyright and license:
29708    
29709    Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
29710    
29711    This file and the 14 PostScript(R) AFM files it accompanies may be used,
29712    copied, and distributed for any purpose and without charge, with or without
29713    modification, provided that all copyright notices are retained; that the AFM
29714    files are not distributed without this file; that all modifications to this
29715    file or any of the AFM files are prominently noted in the modified file(s);
29716    and that this paragraph is not modified. Adobe Systems has no responsibility
29717    or obligation to support the use of the AFM files.
29718    
29719    */}, W={Unicode:{"Courier-Oblique":z("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Times-BoldItalic":z("{'widths'{k3o2q4ycx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2r202m2n2n3m2o3m2p5n202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5n4l4m4m4m4n4m4o4s4p4m4q4m4r4s4s4y4t2r4u3m4v4m4w3x4x5t4y4s4z4s5k3x5l4s5m4m5n3r5o3x5p4s5q4m5r5t5s4m5t3x5u3x5v2l5w1w5x2l5y3t5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q2l6r3m6s3r6t1w6u1w6v3m6w1w6x4y6y3r6z3m7k3m7l3m7m2r7n2r7o1w7p3r7q2w7r4m7s3m7t2w7u2r7v2n7w1q7x2n7y3t202l3mcl4mal2ram3man3mao3map3mar3mas2lat4uau1uav3maw3way4uaz2lbk2sbl3t'fof'6obo2lbp3tbq3mbr1tbs2lbu1ybv3mbz3mck4m202k3mcm4mcn4mco4mcp4mcq5ycr4mcs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz2w203k6o212m6o2dw2l2cq2l3t3m3u2l17s3x19m3m}'kerning'{cl{4qu5kt5qt5rs17ss5ts}201s{201ss}201t{cks4lscmscnscoscpscls2wu2yu201ts}201x{2wu2yu}2k{201ts}2w{4qx5kx5ou5qx5rs17su5tu}2x{17su5tu5ou}2y{4qx5kx5ou5qx5rs17ss5ts}'fof'-6ofn{17sw5tw5ou5qw5rs}7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qs}3v{17su5tu5os5qs}7p{17su5tu}ck{4qu5kt5qt5rs17ss5ts}4l{4qu5kt5qt5rs17ss5ts}cm{4qu5kt5qt5rs17ss5ts}cn{4qu5kt5qt5rs17ss5ts}co{4qu5kt5qt5rs17ss5ts}cp{4qu5kt5qt5rs17ss5ts}6l{4qu5ou5qw5rt17su5tu}5q{ckuclucmucnucoucpu4lu}5r{ckuclucmucnucoucpu4lu}7q{cksclscmscnscoscps4ls}6p{4qu5ou5qw5rt17sw5tw}ek{4qu5ou5qw5rt17su5tu}el{4qu5ou5qw5rt17su5tu}em{4qu5ou5qw5rt17su5tu}en{4qu5ou5qw5rt17su5tu}eo{4qu5ou5qw5rt17su5tu}ep{4qu5ou5qw5rt17su5tu}es{17ss5ts5qs4qu}et{4qu5ou5qw5rt17sw5tw}eu{4qu5ou5qw5rt17ss5ts}ev{17ss5ts5qs4qu}6z{17sw5tw5ou5qw5rs}fm{17sw5tw5ou5qw5rs}7n{201ts}fo{17sw5tw5ou5qw5rs}fp{17sw5tw5ou5qw5rs}fq{17sw5tw5ou5qw5rs}7r{cksclscmscnscoscps4ls}fs{17sw5tw5ou5qw5rs}ft{17su5tu}fu{17su5tu}fv{17su5tu}fw{17su5tu}fz{cksclscmscnscoscps4ls}}}"),"Helvetica-Bold":z("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4y
29719dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"),Courier:z("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Courier-BoldOblique":z("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Times-Bold":z("{'widths'{k3q2q5ncx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2l202m2n2n3m2o3m2p6o202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5x4l4s4m4m4n4s4o4s4p4m4q3x4r4y4s4y4t2r4u3m4v4y4w4m4x5y4y4s4z4y5k3x5l4y5m4s5n3r5o4m5p4s5q4s5r6o5s4s5t4s5u4m5v2l5w1w5x2l5y3u5z3m6k2l6l3m6m3r6n2w6o3r6p2w6q2l6r3m6s3r6t1w6u2l6v3r6w1w6x5n6y3r6z3m7k3r7l3r7m2w7n2r7o2l7p3r7q3m7r4s7s3m7t3m7u2w7v2r7w1q7x2r7y3o202l3mcl4sal2lam3man3mao3map3mar3mas2lat4uau1yav3maw3tay4uaz2lbk2sbl3t'fof'6obo2lbp3rbr1tbs2lbu2lbv3mbz3mck4s202k3mcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3rek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3m3u2l17s4s19m3m}'kerning'{cl{4qt5ks5ot5qy5rw17sv5tv}201t{cks4lscmscnscoscpscls4wv}2k{201ts}2w{4qu5ku7mu5os5qx5ru17su5tu}2x{17su5tu5ou5qs}2y{4qv5kv7mu5ot5qz5ru17su5tu}'fof'-6o7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qu}3v{17su5tu5os5qu}fu{17su5tu5ou5qu}7p{17su5tu5ou5qu}ck{4qt5ks5ot5qy5rw17sv5tv}4l{4qt5ks5ot5qy5rw17sv5tv}cm{4qt5ks5ot5qy5rw17sv5tv}cn{4qt5ks5ot5qy5rw17sv5tv}co{4qt5ks5ot5qy5rw17sv5tv}cp{4qt5ks5ot5qy5rw17sv5tv}6l{17st5tt5ou5qu}17s{ckuclucmucnucoucpu4lu4wu}5o{ckuclucmucnucoucpu4lu4wu}5q{ckzclzcmzcnzcozcpz4lz4wu}5r{ckxclxcmxcnxcoxcpx4lx4wu}5t{ckuclucmucnucoucpu4lu4wu}7q{ckuclucmucnucoucpu4lu}6p{17sw5tw5ou5qu}ek{17st5tt5qu}el{17st5tt5ou5qu}em{17st5tt5qu}en{17st5tt5qu}eo{17st5tt5qu}ep{17st5tt5ou5qu}es{17ss5ts5qu}et{17sw5tw5ou5qu}eu{17sw5tw5ou5qu}ev{17ss5ts5qu}6z{17sw5tw5ou5qu5rs}fm{17sw5tw5ou5qu5rs}fn{17sw5tw5ou5qu5rs}fo{17sw5tw5ou5qu5rs}fp{17sw5tw5ou5qu5rs}fq{17sw5tw5ou5qu5rs}7r{cktcltcmtcntcotcpt4lt5os}fs{17sw5tw5ou5qu5rs}ft{17su5tu5ou5qu}7m{5os}fv{17su5tu5ou5qu}fw{17su5tu5ou5qu}fz{cksclscmscnscoscps4ls}}}"),Symbol:z("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}"),Helvetica:z("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4y
29719dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}"),"Helvetica-BoldOblique":z("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4y
29719dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"),ZapfDingbats:z("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}"),"Courier-Bold":z("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Times-Italic":z("{'widths'{k3n2q4ycx2l201n3m201o5t201s2l201t2l201u2l201w3r201x3r201y3r2k1t2l2l202m2n2n3m2o3m2p5n202q5t2r1p2s2l2t2l2u3m2v4n2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w4n3x4n3y4n3z3m4k5w4l3x4m3x4n4m4o4s4p3x4q3x4r4s4s4s4t2l4u2w4v4m4w3r4x5n4y4m4z4s5k3x5l4s5m3x5n3m5o3r5p4s5q3x5r5n5s3x5t3r5u3r5v2r5w1w5x2r5y2u5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q1w6r3m6s3m6t1w6u1w6v2w6w1w6x4s6y3m6z3m7k3m7l3m7m2r7n2r7o1w7p3m7q2w7r4m7s2w7t2w7u2r7v2s7w1v7x2s7y3q202l3mcl3xal2ram3man3mao3map3mar3mas2lat4wau1vav3maw4nay4waz2lbk2sbl4n'fof'6obo2lbp3mbq3obr1tbs2lbu1zbv3mbz3mck3x202k3mcm3xcn3xco3xcp3xcq5tcr4mcs3xct3xcu3xcv3xcw2l2m2ucy2lcz2ldl4mdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr4nfs3mft3mfu3mfv3mfw3mfz2w203k6o212m6m2dw2l2cq2l3t3m3u2l17s3r19m3m}'kerning'{cl{5kt4qw}201s{201sw}201t{201tw2wy2yy6q-t}201x{2wy2yy}2k{201tw}2w{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}2x{17ss5ts5os}2y{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}'fof'-6o6t{17ss5ts5qs}7t{5os}3v{5qs}7p{17su5tu5qs}ck{5kt4qw}4l{5kt4qw}cm{5kt4qw}cn{5kt4qw}co{5kt4qw}cp{5kt4qw}6l{4qs5ks5ou5qw5ru17su5tu}17s{2ks}5q{ckvclvcmvcnvcovcpv4lv}5r{ckuclucmucnucoucpu4lu}5t{2ks}6p{4qs5ks5ou5qw5ru17su5tu}ek{4qs5ks5ou5qw5ru17su5tu}el{4qs5ks5ou5qw5ru17su5tu}em{4qs5ks5ou5qw5ru17su5tu}en{4qs5ks5ou5qw5ru17su5tu}eo{4qs5ks5ou5qw5ru17su5tu}ep{4qs5ks5ou5qw5ru17su5tu}es{5ks5qs4qs}et{4qs5ks5ou5qw5ru17su5tu}eu{4qs5ks5qw5ru17su5tu}ev{5ks5qs4qs}ex{17ss5ts5qs}6z{4qv5ks5ou5qw5ru17su5tu}fm{4qv5ks5ou5qw5ru17su5tu}fn{4qv5ks5ou5qw5ru17su5tu}fo{4qv5ks5ou5qw5ru17su5tu}fp{4qv5ks5ou5qw5ru17su5tu}fq{4qv5ks5ou5qw5ru17su5tu}7r{5os}fs{4qv5ks5ou5qw5ru17su5tu}ft{17su5tu5qs}fu{17su5tu5qs}
29719fv{17su5tu5qs}fw{17su5tu5qs}}}"),"Times-Roman":z("{'widths'{k3n2q4ycx2l201n3m201o6o201s2l201t2l201u2l201w2w201x2w201y2w2k1t2l2l202m2n2n3m2o3m2p5n202q6o2r1m2s2l2t2l2u3m2v3s2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v1w3w3s3x3s3y3s3z2w4k5w4l4s4m4m4n4m4o4s4p3x4q3r4r4s4s4s4t2l4u2r4v4s4w3x4x5t4y4s4z4s5k3r5l4s5m4m5n3r5o3x5p4s5q4s5r5y5s4s5t4s5u3x5v2l5w1w5x2l5y2z5z3m6k2l6l2w6m3m6n2w6o3m6p2w6q2l6r3m6s3m6t1w6u1w6v3m6w1w6x4y6y3m6z3m7k3m7l3m7m2l7n2r7o1w7p3m7q3m7r4s7s3m7t3m7u2w7v3k7w1o7x3k7y3q202l3mcl4sal2lam3man3mao3map3mar3mas2lat4wau1vav3maw3say4waz2lbk2sbl3s'fof'6obo2lbp3mbq2xbr1tbs2lbu1zbv3mbz2wck4s202k3mcm4scn4sco4scp4scq5tcr4mcs3xct3xcu3xcv3xcw2l2m2tcy2lcz2ldl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek2wel2wem2wen2weo2wep2weq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr3sfs3mft3mfu3mfv3mfw3mfz3m203k6o212m6m2dw2l2cq2l3t3m3u1w17s4s19m3m}'kerning'{cl{4qs5ku17sw5ou5qy5rw201ss5tw201ws}201s{201ss}201t{ckw4lwcmwcnwcowcpwclw4wu201ts}2k{201ts}2w{4qs5kw5os5qx5ru17sx5tx}2x{17sw5tw5ou5qu}2y{4qs5kw5os5qx5ru17sx5tx}'fof'-6o7t{ckuclucmucnucoucpu4lu5os5rs}3u{17su5tu5qs}3v{17su5tu5qs}7p{17sw5tw5qs}ck{4qs5ku17sw5ou5qy5rw201ss5tw201ws}4l{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cm{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cn{4qs5ku17sw5ou5qy5rw201ss5tw201ws}co{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cp{4qs5ku17sw5ou5qy5rw201ss5tw201ws}6l{17su5tu5os5qw5rs}17s{2ktclvcmvcnvcovcpv4lv4wuckv}5o{ckwclwcmwcnwcowcpw4lw4wu}5q{ckyclycmycnycoycpy4ly4wu5ms}5r{cktcltcmtcntcotcpt4lt4ws}5t{2ktclvcmvcnvcovcpv4lv4wuckv}7q{cksclscmscnscoscps4ls}6p{17su5tu5qw5rs}ek{5qs5rs}el{17su5tu5os5qw5rs}em{17su5tu5os5qs5rs}en{17su5qs5rs}eo{5qs5rs}ep{17su5tu5os5qw5rs}es{5qs}et{17su5tu5qw5rs}eu{17su5tu5qs5rs}ev{5qs}6z{17sv5tv5os5qx5rs}fm{5os5qt5rs}fn{17sv5tv5os5qx5rs}fo{17sv5tv5os5qx5rs}fp{5os5qt5rs}fq{5os5qt5rs}7r{ckuclucmucnucoucpu4lu5os}fs{17sv5tv5os5qx5rs}ft{17ss5ts5qs}fu{17sw5tw5qs}fv{17sw5tw5qs}fw{17ss5ts5qs}fz{ckuclucmucnucoucpu4lu5os5rs}}}"),"Helvetica-Oblique":z("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4y
29719dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}")}}, N.events.push(["addFont",function(t){var e,n,r,i="Unicode";(e=W[i][t.postScriptName])&&((n=t.metadata[i]?t.metadata[i]:t.metadata[i]={}).widths=e.widths, n.kerning=e.kerning), (r=H[i][t.postScriptName])&&((n=t.metadata[i]?t.metadata[i]:t.metadata[i]={}).encoding=r).codePages&&r.codePages.length&&(t.encoding=r.codePages[0]);}]), G=$, "undefined"!=typeof self&&self||"undefined"!=typeof commonjsGlobal&&commonjsGlobal||"undefined"!=typeof window&&window||Function("return this")(), G.API.events.push(["addFont",function(t){G.API.existsFileInVFS(t.postScriptName)?(t.metadata=G.API.TTFFont.open(t.postScriptName,t.fontName,G.API.getFileFromVFS(t.postScriptName),t.encoding), t.metadata.Unicode=t.metadata.Unicode||{encoding:{},kerning:{},widths:[]}):14<t.id.slice(1)&&console.error("Font does not exist in FileInVFS, import fonts or remove declaration doc.addFont('"+t.postScriptName+"').");}]), (
29720/** @preserve
29721  jsPDF SVG plugin
29722  Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
29723  */
29724V=$.API).addSvg=function(t,e,n,r,i){if(void 0===e||void 0===n)throw new Error("addSVG needs values for 'x' and 'y'");function o(t){for(var e=parseFloat(t[1]),n=parseFloat(t[2]),r=[],i=3,o=t.length;i<o;)"c"===t[i]?(r.push([parseFloat(t[i+1]),parseFloat(t[i+2]),parseFloat(t[i+3]),parseFloat(t[i+4]),parseFloat(t[i+5]),parseFloat(t[i+6])]), i+=7):"l"===t[i]?(r.push([parseFloat(t[i+1]),parseFloat(t[i+2])]), i+=3):i+=1;return[e,n,r]}var a,s,h,c,l,u,f,d,p=(c=document, d=c.createElement("iframe"), l=".jsPDF_sillysvg_iframe {display:none;position:absolute;}", (f=(u=c).createElement("style")).type="text/css", f.styleSheet?f.styleSheet.cssText=l:f.appendChild(u.createTextNode(l)), u.getElementsByTagName("head")[0].appendChild(f), d.name="childframe", d.setAttribute("width",0), d.setAttribute("height",0), d.setAttribute("frameborder","0"), d.setAttribute("scrolling","no"), d.setAttribute("seamless","seamless"), d.setAttribute("class","jsPDF_sillysvg_iframe"), c.body.appendChild(d), d),g=(a=t, (h=((s=p).contentWindow||s.contentDocument).document).write(a), h.close(), h.getElementsByTagName("svg")[0]),m=[1,1],w=parseFloat(g.getAttribute("width")),y=parseFloat(g.getAttribute("height"));w&&y&&(r&&i?m=[r/w,i/y]:r?m=[r/w,r/w]:i&&(m=[i/y,i/y]));var v,b,x,S,k=g.childNodes;for(v=0, b=k.length;v<b;v++)(x=k[v]).tagName&&"PATH"===x.tagName.toUpperCase()&&((S=o(x.getAttribute("d").split(" ")))[0]=S[0]*m[0]+e, S[1]=S[1]*m[1]+n, this.lines.call(this,S[2],S[0],S[1],m));return this}, V.addSVG=V.addSvg, V.addSvgAsImage=function(t,e,n,r,i,o,a,s){if
29724(isNaN(e)||isNaN(n))throw console.error("jsPDF.addSvgAsImage: Invalid coordinates",arguments), new Error("Invalid coordinates passed to jsPDF.addSvgAsImage");if(isNaN(r)||isNaN(i))throw console.error("jsPDF.addSvgAsImage: Invalid measurements",arguments), new Error("Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage");var h=document.createElement("canvas");h.width=r, h.height=i;var c=h.getContext("2d");return c.fillStyle="#fff", c.fillRect(0,0,h.width,h.height), canvg(h,t,{ignoreMouse:!0,ignoreAnimation:!0,ignoreDimensions:!0,ignoreClear:!0}), this.addImage(h.toDataURL("image/jpeg",1),e,n,r,i,a,s), this}, $.API.putTotalPages=function(t){for(var e=new RegExp(t,"g"),n=1;n<=this.internal.getNumberOfPages();n++)for(var r=0;r<this.internal.pages[n].length;r++)this.internal.pages[n][r]=this.internal.pages[n][r].replace(e,this.internal.getNumberOfPages());return this}, $.API.viewerPreferences=function(t,e){var n;t=t||{}, e=e||!1;var r,i,o={HideToolbar:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.3},HideMenubar:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.3},HideWindowUI:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.3},FitWindow:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.3},CenterWindow:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.3},DisplayDocTitle:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.4},NonFullScreenPageMode:{defaultValue:"UseNone",value:"UseNone",type:"name",explicitSet:!1,valueSet:["UseNone","UseOutlines","UseThumbs","UseOC"],pdfVersion:1.3},Direction:{defaultValue:"L2R",value:"L2R",type:"name",explicitSet:!1,valueSet:["L2R","R2L"],pdfVersion:1.3},ViewArea:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:!1,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},ViewClip:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:!1,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},PrintArea:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:!1,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},PrintClip:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:!1,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},PrintScaling:{defaultValue:"AppDefault",value:"AppDefault",type:"name",explicitSet:!1,valueSet:["AppDefault","None"],pdfVersion:1.6},Duplex:{defaultValue:"",value:"none",type:"name",explicitSet:!1,valueSet:["Simplex","DuplexFlipShortEdge","DuplexFlipLongEdge","none"],pdfVersion:1.7},PickTrayByPDFSize:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.7},PrintPageRange:{defaultValue:"",value:"",type:"array",explicitSet:!1,valueSet:null,pdfVersion:1.7},NumCopies:{defaultValue:1,value:1,type:"integer",explicitSet:!1,valueSet:null,pdfVersion:1.7}},a=Object.keys(o),s=[],h=0,c=0,l=0,u=!0;function f(t,e){var n,r=!1;for(n=0;n<t.length;n+=1)t[n]===e&&(r=!0);return r}if(void 0===this.internal.viewerpreferences&&(this.internal.viewerpreferences={}, this.internal.viewerpreferences.configuration=JSON.parse(JSON.stringify(o)), this.internal.viewerpreferences.isSubscribed=!1), n=this.internal.viewerpreferences.configuration, "reset"===t||!0===e){var d=a.length;for(l=0;l<d;l+=1)n[a[l]].value=n[a[l]].defaultValue, n[a[l]].explicitSet=!1;}if("object"===(void 0===t?"undefined":vt(t)))for(r in t)if(i=t[r], f(a,r)&&void 0!==i){if("boolean"===n[r].type&&"boolean"==typeof i)n[r].value=i;else if("name"===n[r].type&&f(n[r].valueSet,i))n[r].value=i;else if("integer"===n[r].type&&Number.isInteger(i))n[r].value=i;else if("array"===n[r].type){for(h=0;h<i.length;h+=1)if(u=!0, 1===i[h].length&&"number"==typeof i[h][0])s.push(String(i[h]));else if(1<i[h].length){for(c=0;c<i[h].length;c+=1)"number"!=typeof i[h][c]&&(u=!1);!0===u&&s.push(String(i[h].join("-")));}n[r].value=String(s);}else n[r].value=n[r].defaultValue;n[r].explicitSet=!0;}return!1===this.internal.viewerpreferences.isSubscribed&&(this.internal.events.subscribe("putCatalog",function(){var t,e=[];for(t in n)!0===n[t].explicitSet&&("name"===n[t].type?e.push("/"+t+" /"+n[t].value):e.push("/"+t+" "+n[t].value));0!==e.length&&this.internal.write("/ViewerPreferences\n<<\n"+e.join("\n")+"\n>>");}), this.internal.viewerpreferences.isSubscribed=!0), this.internal.viewerpreferences.configuration=n, this}, Y=$.API, K=J=X="", Y.addMetadata=function(t,e){return J=e||"http://jspdf.default.namespaceuri/", X=t, this.internal.events.subscribe("postPutResources",function(){if(X){var t='<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:jspdf="'+J+'"><jspdf:metadata>',e=unescape(encodeURIComponent('<x:xmpmeta xmlns:x="adobe:ns:meta/">')),n=unescape(encodeURIComponent(t)),r=unescape(encodeURIComponent(X)),i=unescape(encodeURIComponent("</jspdf:metadata></rdf:Description></rdf:RDF>")),o=unescape(encodeURIComponent("</x:xmpmeta>")),a=n.length+r.length+i.length+e.length+o.length;K=this.internal.newObject(), this.internal.write("<< /Type /Metadata /Subtype /XML /Length "+a+" >>"), this.internal.write("stream"), this.internal.write(e+n+r+i+o), this.internal.write("endstream"), this.internal.write("endobj");}else K="";}), this.internal.events.subscribe("putCatalog",function(){K&&this.internal.write("/Metadata "+K+" 0 R");}), this}, function(l,t){var e=l.API,m=[0];e.events.push(["putFont",function(t){!function(t,e,n){if(t.metadata instanceof l.API.TTFFont&&"Identity-H"===t.encoding){for(var r=t.metadata.Unicode.widths,i=t.metadata.subset.encode(m),o="",a=0;a<i.length;a++)o+=String.fromCharCode(i[a]);var s=n();e("<<"), e("/Length "+o.length), e("/Length1 "+o.length), e(">>"), e("stream"), e(o), e("endstream"), e("endobj");var h=n();e("<<"), e("/Type /FontDescriptor"), e("/FontName /"+t.fontName), e("/FontFile2 "+s+" 0 R"), e("/FontBBox "+l.API.PDFObject.convert(t.metadata.bbox)), e("/Flags "+t.metadata.flags), e("/StemV "+t.metadata.stemV), e("/ItalicAngle "+t.metadata.italicAngle), e("/Asce
29724nt "+t.metadata.ascender), e("/Descent "+t.metadata.decender), e("/CapHeight "+t.metadata.capHeight), e(">>"), e("endobj");var c=n();e("<<"), e("/Type /Font"), e("/BaseFont /"+t.fontName), e("/FontDescriptor "+h+" 0 R"), e("/W "+l.API.PDFObject.convert(r)), e("/CIDToGIDMap /Identity"), e("/DW 1000"), e("/Subtype /CIDFontType2"), e("/CIDSystemInfo"), e("<<"), e("/Supplement 0"), e("/Registry (Adobe)"), e("/Ordering ("+t.encoding+")"), e(">>"), e(">>"), e("endobj"), t.objectNumber=n(), e("<<"), e("/Type /Font"), e("/Subtype /Type0"), e("/BaseFont /"+t.fontName), e("/Encoding /"+t.encoding), e("/DescendantFonts ["+c+" 0 R]"), e(">>"), e("endobj"), t.isAlreadyPutted=!0;}}(t.font,t.out,t.newObject);}]);e.events.push(["putFont",function(t){!function(t,e,n){if(t.metadata instanceof l.API.TTFFont&&"WinAnsiEncoding"===t.encoding){t.metadata.Unicode.widths;for(var r=t.metadata.rawData,i="",o=0;o<r.length;o++)i+=String.fromCharCode(r[o]);var a=n();e("<<"), e("/Length "+i.length), e("/Length1 "+i.length), e(">>"), e("stream"), e(i), e("endstream"), e("endobj");var s=n();for(e("<<"), e("/Descent "+t.metadata.decender), e("/CapHeight "+t.metadata.capHeight), e("/StemV "+t.metadata.stemV), e("/Type /FontDescriptor"), e("/FontFile2 "+a+" 0 R"), e("/Flags 96"), e("/FontBBox "+l.API.PDFObject.convert(t.metadata.bbox)), e("/FontName /"+t.fontName), e("/ItalicAngle "+t.metadata.italicAngle), e("/Ascent "+t.metadata.ascender), e(">>"), e("endobj"), t.objectNumber=n(), o=0;o<t.metadata.hmtx.widths.length;o++)t.metadata.hmtx.widths[o]=parseInt(t.metadata.hmtx.widths[o]*(1e3/t.metadata.head.unitsPerEm));e("<</Subtype/TrueType/Type/Font/BaseFont/"+t.fontName+"/FontDescriptor "+s+" 0 R/Encoding/"+t.encoding+" /FirstChar 29 /LastChar 255 /Widths "+l.API.PDFObject.convert(t.metadata.hmtx.widths)+">>"), e("endobj"), t.isAlreadyPutted=!0;}}(t.font,t.out,t.newObject);}]);var c=function(t){var e,n,r=t.text||"",i=t.x,o=t.y,a=t.options||{},s=t.mutex||{},h=s.pdfEscape,c=s.activeFontKey,l=s.fonts,u=(s.activeFontSize, ""),f=0,d="",p=l[n=c].encoding;if("Identity-H"!==l[n].encoding)return{text:r,x:i,y:o,options:a,mutex:s};for(d=r, n=c, "[object Array]"===Object.prototype.toString.call(r)&&(d=r[0]), f=0;f<d.length;f+=1)l[n].metadata.hasOwnProperty("cmap")&&(e=l[n].metadata.cmap.unicode.codeMap[d[f].charCodeAt(0)]), e?u+=d[f]:d[f].charCodeAt(0)<256&&l[n].metadata.hasOwnProperty("Unicode")?u+=d[f]:u+="";var g="";return parseInt(n.slice(1))<14||"WinAnsiEncoding"===p?g=function(t){for(var e="",n=0;n<t.length;n++)e+=""+t.charCodeAt(n).toString(16);return e}(h(u,n)):"Identity-H"===p&&(g=function(t,e){for(var n,r=e.metadata.Unicode.widths,i=["","0","00","000","0000"],o=[""],a=0,s=t.length;a<s;++a){if(n=e.metadata.characterToGlyph(t.charCodeAt(a)), m.push(n), -1==r.indexOf(n)&&(r.push(n), r.push([parseInt(e.metadata.widthOfGlyph(n),10)])), "0"==n)return o.join("");n=n.toString(16), o.push(i[4-n.length],n);}return o.join("")}(u,l[n])), s.isHex=!0, {text:g,x:i,y:o,options:a,mutex:s}};e.events.push(["postProcessText",function(t){var e=t.text||"",n=t.x,r=t.y,i=t.options,o=t.mutex,a=(i.lang, []),s={text:e,x:n,y:r,options:i,mutex:o};if("[object Array]"===Object.prototype.toString.call(e)){var h=0;for(h=0;h<e.length;h+=1)"[object Array]"===Object.prototype.toString.call(e[h])&&3===e[h].length?a.push([c(Object.assign({},s,{text:e[h][0]})).text,e[h][1],e[h][2]]):a.push(c(Object.assign({},s,{text:e[h]})).text);t.text=a;}else t.text=c(Object.assign({},s,{text:e})).text;}]);}($,"undefined"!=typeof self&&self||"undefined"!=typeof commonjsGlobal&&commonjsGlobal||"undefined"!=typeof window&&window||Function("return this")()), Q=$.API, Z={}, Q.existsFileInVFS=function(t){return Z.hasOwnProperty(t)}, Q.addFileToVFS=function(t,e){return Z[t]=e, this}, Q.getFileFromVFS=function(t){return Z.hasOwnProperty(t)?Z[t]:null}, function(t){if(t.URL=t.URL||t.webkitURL, t.Blob&&t.URL)try{return new Blob}catch(t){}var s=t.BlobBuilder||t.WebKitBlobBuilder||t.MozBlobBuilder||function(t){var s=function(t){return Object.prototype.toString.call(t).match(/^\[object\s(.*)\]$/)[1]},e=function(){this.data=[];},h=function(t,e,n){this.data=t, this.size=t.length, this.type=e, this.encoding=n;},n=e.prototype,r=h.prototype,c=t.FileReaderSync,l=function(t){this.co
29724de=this[this.name=t];},i="NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR".split(" "),o=i.length,a=t.URL||t.webkitURL||t,u=a.createObjectURL,f=a.revokeObjectURL,d=a,p=t.btoa,g=t.atob,m=t.ArrayBuffer,w=t.Uint8Array,y=/^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/;for(h.fake=r.fake=!0;o--;)l.prototype[i[o]]=o+1;return a.createObjectURL||(d=t.URL=function(t){var e,n=document.createElementNS("http://www.w3.org/1999/xhtml","a");return n.href=t, "origin"in n||("data:"===n.protocol.toLowerCase()?n.origin=null:(e=t.match(y), n.origin=e&&e[1])), n}), d.createObjectURL=function(t){var e,n=t.type;return null===n&&(n="application/octet-stream"), t instanceof h?(e="data:"+n, "base64"===t.encoding?e+";base64,"+t.data:"URI"===t.encoding?e+","+decodeURIComponent(t.data):p?e+";base64,"+p(t.data):e+","+encodeURIComponent(t.data)):u?u.call(a,t):void 0}, d.revokeObjectURL=function(t){"data:"!==t.substring(0,5)&&f&&f.call(a,t);}, n.append=function(t){var e=this.data;if(w&&(t instanceof m||t instanceof w)){for(var n="",r=new w(t),i=0,o=r.length;i<o;i++)n+=String.fromCharCode(r[i]);e.push(n);}else if("Blob"===s(t)||"File"===s(t)){if(!c)throw new l("NOT_READABLE_ERR");var a=new c;e.push(a.readAsBinaryString(t));}else t instanceof h?"base64"===t.encoding&&g?e.push(g(t.data)):"URI"===t.encoding?e.push(decodeURIComponent(t.data)):"raw"===t.encoding&&e.push(t.data):("string"!=typeof t&&(t+=""), e.push(unescape(encodeURIComponent(t))));}, n.getBlob=function(t){return arguments.length||(t=null), new h(this.data.join(""),t,"raw")}, n.toString=function(){return"[object BlobBuilder]"}, r.slice=function(t,e,n){var r=arguments.length;return r<3&&(n=null), new h(this.data.slice(t,1<r?e:this.data.length),n,this.encoding)}, r.toString=function(){return"[object Blob]"}, r.close=function(){this.size=0, delete this.data;}, e}(t);t.Blob=function(t,e){var n=e&&e.type||"",r=new s;if(t)for(var i=0,o=t.length;i<o;i++)Uint8Array&&t[i]instanceof Uint8Array?r.append(t[i].buffer):r.append(t[i]);var a=r.getBlob(n);return!a.slice&&a.webkitSlice&&(a.slice=a.webkitSlice), a};var e=Object.getPrototypeOf||function(t){return t.__proto__};t.Blob.prototype=e(new t.Blob);}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||window.content||window);var tt,et,nt,rt,it,ot,at,st,ht,ct,lt,ut,ft,dt,pt,gt,bt=bt||function(s){if(!(void 0===s||"undefined"!=typeof navigator&&/MSIE [1-9]\./.test(navigator.userAgent))){var t=s.document,h=function(){return s.URL||s.webkitURL||s},c=t.createElementNS("http://www.w3.org/1999/xhtml","a"),l="download"in c,u=/constructor/i.test(s.HTMLElement)||s.safari,f=/CriOS\/[\d]+/.test(navigator.userAgent),d=function(t){(s.setImmediate||s.setTimeout)(function(){throw t},0);},p=function(t){setTimeout(function(){"string"==typeof t?h().revokeObjectURL(t):t.remove();},4e4);},g=function(t){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(t.type)?new Blob([String.fromCharCode(65279),t],{type:t.type}):t},r=function(t,n,e){e||(t=g(t));var r,i=this,o="application/octet-stream"===t.type,a=function(){!function(t,e,n){for(var r=(e=[].concat(e)).length;r--;){var i=t["on"+e[r]];if("function"==typeof i)try{i.call(t,n||t);}catch(t){d(t);}}}(i,"writestart progress write writeend".split(" "));};if(i.readyState=i.INIT, l)return r=h().createObjectURL(t), void setTimeout(function(){var t,e;c.href=r, c.download=n, t=c, e=new MouseEvent("click"), t.dispatchEvent(e), a(), p(r), i.readyState=i.DONE;});!function(){if((f||o&&u)&&s.FileReader){var e=new FileReader;return e.onloadend=function(){var t=f?e.result:e.result.replace(/^data:[^;]*;/,"data:attachment/file;");s.open(t,"_blank")||(s.location.href=t), t=void 0, i.readyState=i.DONE, a();}, e.readAsDataURL(t), i.readyState=i.INIT}r||(r=h().createObjectURL(t)), o?s.location.href=r:s.open(r,"_blank")||(s.location.href=r);i.readyState=i.DONE, a(), p(r);}();},e=r.prototype;return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(t,e,n){return e=e||t.name||"download", n||(t=g(t)), navigator.msSaveOrOpenBlob(t,e)}:(e.abort=function(){}, e.readyState=e.INIT=0, e.WRITING=1, e.DONE=2, e.error=e.onwritestart=e.onprogress=e.onwrite=e.onabort=e.onerror=e.onwriteend=null, function(t,e,n){return new r(t,e||t.name||"download",n)})}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||window.content);function mt(x){var t=0;if(71!==x[t++]||73!==x[t++]||70!==x[t++]||56!==x[t++]||56!=(x[t++]+1&253)||97!==x[t++])throw"Invalid GIF 87a/89a header.";var S=x[t++]|x[t++]<<8,e=x[t++]|x[t++]<<8,n=x[t++],r=n>>7,i=1<<(7&n)+1;x[t++];x[t++];var o=null;r&&(o=t, t+=3*i);var a=!0,s=[],h=0,c=null,l=0,u=null;for(this.width=S, this.height=e;a&&t<x.length;)switch(x[t++]){case 33:switch(x[t++]){case 255:if(11!==x[t]||78==x[t+1]&&69==x[t+2]&&84==x[t+3]&&83==x[t+4]&&67==x[t+5]&&65==x[t+6]&&80==x[t+7]&&69==x[t+8]&&50==x[t+9]&&46==x[t+10]&&48==x[t+11]&&3==x[t+12]&&1==x[t+13]&&0==x[t+16]
29724)t+=14, u=x[t++]|x[t++]<<8, t++;else for(t+=12;;){if(0===(_=x[t++]))break;t+=_;}break;case 249:if(4!==x[t++]||0!==x[t+4])throw"Invalid graphics extension block.";var f=x[t++];h=x[t++]|x[t++]<<8, c=x[t++], 0==(1&f)&&(c=null), l=f>>2&7, t++;break;case 254:for(;;){if(0===(_=x[t++]))break;t+=_;}break;default:throw"Unknown graphic control label: 0x"+x[t-1].toString(16)}break;case 44:var d=x[t++]|x[t++]<<8,p=x[t++]|x[t++]<<8,g=x[t++]|x[t++]<<8,m=x[t++]|x[t++]<<8,w=x[t++],y=w>>6&1,v=o,b=!1;if(w>>7){b=!0;v=t, t+=3*(1<<(7&w)+1);}var k=t;for(t++;;){var _;if(0===(_=x[t++]))break;t+=_;}s.push({x:d,y:p,width:g,height:m,has_local_palette:b,palette_offset:v,data_offset:k,data_length:t-k,transparent_index:c,interlaced:!!y,delay:h,disposal:l});break;case 59:a=!1;break;default:throw"Unknown gif block: 0x"+x[t-1].toString(16)}this.numFrames=function(){return s.length}, this.loopCount=function(){return u}, this.frameInfo=function(t){if(t<0||t>=s.length)throw"Frame index out of range.";return s[t]}, this.decodeAndBlitFrameBGRA=function(t,e){var n=this.frameInfo(t),r=n.width*n.height,i=new Uint8Array(r);wt(x,n.data_offset,i,r);var o=n.palette_offset,a=n.transparent_index;null===a&&(a=256);var s=n.width,h=S-s,c=s,l=4*(n.y*S+n.x),u=4*((n.y+n.height)*S+n.x),f=l,d=4*h;!0===n.interlaced&&(d+=4*(s+h)*7);for(var p=8,g=0,m=i.length;g<m;++g){var w=i[g];if(0===c&&(c=s, u<=(f+=d)&&(d=h+4*(s+h)*(p-1), f=l+(s+h)*(p<<1), p>>=1)), w===a)f+=4;else{var y=x[o+3*w],v=x[o+3*w+1],b=x[o+3*w+2];e[f++]=b, e[f++]=v, e[f++]=y, e[f++]=255;}--c;}}, this.decodeAndBlitFrameRGBA=function(t,e){var n=this.frameInfo(t),r=n.width*n.height,i=new Uint8Array(r);wt(x,n.data_offset,i,r);var o=n.palette_offset,a=n.transparent_index;null===a&&(a=256);var s=n.width,h=S-s,c=s,l=4*(n.y*S+n.x),u=4*((n.y+n.height)*S+n.x),f=l,d=4*h;!0===n.interlaced&&(d+=4*(s+h)*7);for(var p=8,g=0,m=i.length;g<m;++g){var w=i[g];if(0===c&&(c=s, u<=(f+=d)&&(d=h+4*(s+h)*(p-1), f=l+(s+h)*(p<<1), p>>=1)), w===a)f+=4;else{var y=x[o+3*w],v=x[o+3*w+1],b=x[o+3*w+2];e[f++]=y, e[f++]=v, e[f++]=b, e[f++]=255;}--c;}};}function wt(t,e,n,r){for(var i=t[e++],o=1<<i,a=o+1,s=a+1,h=i+1,c=(1<<h)-1,l=0,u=0,f=0,d=t[e++],p=new Int32Array(4096),g=null;;){for(;l<16&&0!==d;)u|=t[e++]<<l, l+=8, 1===d?d=t[e++]:--d;if(l<h)break;var m=u&c;if(u>>=h, l-=h, m!==o){if(m===a)break;for(var w=m<s?m:g,y=0,v=w;o<v;)v=p[v]>>8, ++y;var b=v;if(r<f+y+(w!==m?1:0))return void console.log("Warning, gif stream longer than expected.");n[f++]=b;var x=f+=y;for(w!==m&&(n[f++]=b), v=w;y--;)v=p[v], n[--x]=255&v, v>>=8;null!==g&&s<4096&&(p[s++]=g<<8|b, c+1<=s&&h<12&&(++h, c=c<<1|1)), g=m;}else s=a+1, c=(1<<(h=i+1))-1, g=null;}return f!==r&&console.log("Warning, gif stream shorter than expected."), n}"undefined"!='object'&&module.exports?module.exports.saveAs=bt:"undefined"!=typeof undefined&&null!==undefined&&null!==undefined.amd&&undefined("FileSaver.js",function(){return bt}), $.API.adler32cs=(ot="function"==typeof ArrayBuffer&&"function"==typeof Uint8Array, at=null, st=function(){if(!ot)return function(){return!1};try{var t={};"function"==typeof t.Buffer&&(at=t.Buffer);}catch(t){}return function(t){return t instanceof ArrayBuffer||null!==at&&t instanceof at}}(), ht=null!==at?function(t){return new at(t,"utf8").toString("binary")}:function(t){return unescape(encodeURIComponent(t))}, ct=65521, lt=function(t,e){for(var n=65535&t,r=t>>>16,i=0,o=e.length;i<o;i++)n=(n+(255&e.charCodeAt(i)))%ct, r=(r+n)%ct;return(r<<16|n)>>>0}, ut=function(t,e){for(var n=65535&t,r=t>>>16,i=0,o=e.length;i<o;i++)n=(n+e[i])%ct, r=(r+n)%ct;return(r<<16|n)>>>0}, dt=(ft={}).Adler32=(((it=(rt=function(t){if(!(this instanceof rt))throw new TypeError("Constructor cannot called be as a function.");if(!isFinite(t=null==t?1:+t))throw new Error("First arguments needs to be a finite number.");this.checksum=t>>>0;}).prototype={}).constructor=rt).from=((tt=function(t){if(!(this instanceof rt))throw new TypeError("Constructor cannot called be as a function.");if(null==t)throw new Error("First argument needs to be a string.");this.checksum=lt(1,t.toString());}).prototype=it, tt), rt.fromUtf8=((et=function(t){if(!(this instanceof rt))throw new TypeError("Constructor cannot called be as a function.");
29724if(null==t)throw new Error("First argument needs to be a string.");var e=ht(t.toString());this.checksum=lt(1,e);}).prototype=it, et), ot&&(rt.fromBuffer=((nt=function(t){if(!(this instanceof rt))throw new TypeError("Constructor cannot called be as a function.");if(!st(t))throw new Error("First argument needs to be ArrayBuffer.");var e=new Uint8Array(t);return this.checksum=ut(1,e)}).prototype=it, nt)), it.update=function(t){if(null==t)throw new Error("First argument needs to be a string.");return t=t.toString(), this.checksum=lt(this.checksum,t)}, it.updateUtf8=function(t){if(null==t)throw new Error("First argument needs to be a string.");var e=ht(t.toString());return this.checksum=lt(this.checksum,e)}, ot&&(it.updateBuffer=function(t){if(!st(t))throw new Error("First argument needs to be ArrayBuffer.");var e=new Uint8Array(t);return this.checksum=ut(this.checksum,e)}), it.clone=function(){return new dt(this.checksum)}, rt), ft.from=function(t){if(null==t)throw new Error("First argument needs to be a string.");return lt(1,t.toString())}, ft.fromUtf8=function(t){if(null==t)throw new Error("First argument needs to be a string.");var e=ht(t.toString());return lt(1,e)}, ot&&(ft.fromBuffer=function(t){if(!st(t))throw new Error("First argument need to be ArrayBuffer.");var e=new Uint8Array(t);return ut(1,e)}), ft);try{exports.GifWriter=function(w,t,e,n){var y=0,r=void 0===(n=void 0===n?{}:n).loop?null:n.loop,v=void 0===n.palette?null:n.palette;if(t<=0||e<=0||65535<t||65535<e)throw"Width/Height invalid.";function b(t){var e=t.length;if(e<2||256<e||e&e-1)throw"Invalid code/color length, must be power of 2 and 2 .. 256.";return e}w[y++]=71, w[y++]=73, w[y++]=70, w[y++]=56, w[y++]=57, w[y++]=97;var i=0,o=0;if(null!==v){for(var a=b(v);a>>=1;)++i;if(a=1<<i, --i, void 0!==n.background){if(a<=(o=n.background))throw"Background index out of range.";if(0===o)throw"Background index explicitly passed as 0."}}if(w[y++]=255&t, w[y++]=t>>8&255, w[y++]=255&e, w[y++]=e>>8&255, w[y++]=(null!==v?128:0)|i, w[y++]=o, w[y++]=0, null!==v)for(var s=0,h=v.length;s<h;++s){var c=v[s];w[y++]=c>>16&255, w[y++]=c>>8&255, w[y++]=255&c;}if(null!==r){if(r<0||65535<r)throw"Loop count invalid.";w[y++]=33, w[y++]=255, w[y++]=11, w[y++]=78, w[y++]=69, w[y++]=84, w[y++]=83, w[y++]=67, w[y++]=65, w[y++]=80, w[y++]=69, w[y++]=50, w[y++]=46, w[y++]=48, w[y++]=3, w[y++]=1, w[y++]=255&r, w[y++]=r>>8&255, w[y++]=0;}var x=!1;this.addFrame=function(t,e,n,r,i,o){if(!0===x&&(--y, x=!1), o=void 0===o?{}
29724:o, t<0||e<0||65535<t||65535<e)throw"x/y invalid.";if(n<=0||r<=0||65535<n||65535<r)throw"Width/Height invalid.";if(i.length<n*r)throw"Not enough pixels for the frame size.";var a=!0,s=o.palette;if(null==s&&(a=!1, s=v), null==s)throw"Must supply either a local or global palette.";for(var h=b(s),c=0;h>>=1;)++c;h=1<<c;var l=void 0===o.delay?0:o.delay,u=void 0===o.disposal?0:o.disposal;if(u<0||3<u)throw"Disposal out of range.";var f=!1,d=0;if(void 0!==o.transparent&&null!==o.transparent&&(f=!0, (d=o.transparent)<0||h<=d))throw"Transparent color index.";if((0!==u||f||0!==l)&&(w[y++]=33, w[y++]=249, w[y++]=4, w[y++]=u<<2|(!0===f?1:0), w[y++]=255&l, w[y++]=l>>8&255, w[y++]=d, w[y++]=0), w[y++]=44, w[y++]=255&t, w[y++]=t>>8&255, w[y++]=255&e, w[y++]=e>>8&255, w[y++]=255&n, w[y++]=n>>8&255, w[y++]=255&r, w[y++]=r>>8&255, w[y++]=!0===a?128|c-1:0, !0===a)for(var p=0,g=s.length;p<g;++p){var m=s[p];w[y++]=m>>16&255, w[y++]=m>>8&255, w[y++]=255&m;}y=function(e,n,t,r){e[n++]=t;var i=n++,o=1<<t,a=o-1,s=o+1,h=s+1,c=t+1,l=0,u=0;function f(t){for(;t<=l;)e[n++]=255&u, u>>=8, l-=8, n===i+256&&(e[i]=255, i=n++);}function d(t){u|=t<<l, l+=c, f(8);}var p=r[0]&a,g={};d(o);for(var m=1,w=r.length;m<w;++m){var y=r[m]&a,v=p<<8|y,b=g[v];if(void 0===b){for(u|=p<<l, l+=c;8<=l;)e[n++]=255&u, u>>=8, l-=8, n===i+256&&(e[i]=255, i=n++);4096===h?(d(o), h=s+1, c=t+1, g={}):(1<<c<=h&&++c, g[v]=h++), p=y;}else p=b;}return d(p), d(s), f(1), i+1===n?e[i]=0:(e[i]=n-i-1, e[n++]=0), n}(w,y,c<2?2:c,i);}, this.end=function(){return!1===x&&(w[y++]=59, x=!0), y};}, exports.GifReader=mt;}catch(t){}
29725/*
29726    Copyright (c) 2008, Adobe Systems Incorporated
29727    All rights reserved.
29728
29729    Redistribution and use in source and binary forms, with or without 
29730    modification, are permitted provided that the following conditions are
29731    met:
29732
29733    * Redistributions of source code must retain the above copyright notice, 
29734      this list of conditions and the following disclaimer.
29735    
29736    * Redistributions in binary form must reproduce the above copyright
29737      notice, this list of conditions and the following disclaimer in the 
29738      documentation and/or other materials provided with the distribution.
29739    
29740    * Neither the name of Adobe Systems Incorporated nor the names of its 
29741      contributors may be used to endorse or promote products derived from 
29742      this software without specific prior written permission.
29743
29744    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
29745    IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
29746    THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29747    PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
29748    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29749    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
29750    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29751    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29752    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29753    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29754    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29755  */function yt(t){var S,k,_,A,e,u=Math.floor,I=new Array(64),C=new Array(64),T=new Array(64),F=new Array(64),w=new Array(65535),y=new Array(65535),Q=new Array(64),v=new Array(64),P=[],E=0,q=7,O=new Array(64),B=new Array(64),R=new Array(64),n=new Array(256),j=new Array(2048),b=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],D=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],M=[0,1,2,3,4,5,6,7,8,9,10,11],U=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],N=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],z=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],L=[0,1,2,3,4,5,6,7,8,9,10,11],H=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],W=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function r(t,e){for(var n=0,r=0,i=new Array,o=1;o<=16;o++){for(var a=1;a<=t[o];a++)i[e[r]]=[], i[e[r]][0]=n, i[e[r]][1]=o, r++, n++;n*=2;}return i}function G(t){for(var e=t[0],n=t[1]-1;0<=n;)e&1<<n&&(E|=1<<q), n--, --q<0&&(255==E?(V(255), V(0)):V(E), q=7, E=0);}function V(t){P.push(t);}function Y(t){V(t>>8&255), V(255&t);}function X(t,e,n,r,i){for(var o,a=i[0],s=i[240],h=function(t,e){var n,r,i,o,a,s,h,c,l,u,f=0;for(l=0;l<8;++l){n=t[f], r=t[f+1], i=t[f+2], o=t[f+3], a=t[f+4], s=t[f+5], h=t[f+6];var d=n+(c=t[f+7]),p=n-c,g=r+h,m=r-h,w=i+s,y=i-s,v=o+a,b=o-a,x=d+v,S=d-v,k=g+w,_=g-w;t[f]=x+k, t[f+4]=x-k;var A=.707106781*(_+S);t[f+2]=S+A, t[f+6]=S-A;var I=.382683433*((x=b+y)-(_=m+p)),C=.5411961*x+I,T=1.306562965*_+I,F=.707106781*(k=y+m),P=p+F,E=p-F;t[f+5]=E+C, t[f+3]=E-C, t[f+1]=P+T, t[f+7]=P-T, f+=8;}for(l=f=0;l<8;++l){n=t[f], r=t[f+8], i=t[f+16], o=t[f+24], a=t[f+32], s=t[f+40], h=t[f+48];var q=n+(c=t[f+56]),O=n-c,B=r+h,R=r-h,j=i+s,D=i-s,M=o+a,U=o-a,N=q+M,z=q-M,L=B+j,H=B-j;t[f]=N+L, t[f+32]=N-L;var W=.707106781*(H+z);t[f+16]=z+W, t[f+48]=z-W;var G=.382683433*((N=U+D)-(H=R+O)),V=.5411961*N+G,Y=1.306562965*H+G,X=.707106781*(L=D+R),J=O+X,K=O-X;t[f+40]=K+V, t[f+24]=K-V, t[f+8]=J+Y, t[f+56]=J-Y, f++;}for(l=0;l<64;++l)u=t[l]*e[l], Q[l]=0<u?u+.5|0:u-.5|0;return Q}(t,e),c=0;c<64;++c)v[b[c]]=h[c];var l=v[0]-n;n=v[0], 0==l?G(r[0]):(G(r[y[o=32767+l]]), G(w[o]));for(var u=63;0<u&&0==v[u];u--);if(0==u)return G(a), n;for(var f,d=1;d<=u;){for(var p=d;0==v[d]&&d<=u;++d);var g=d-p;if(16<=g){f=g>>4;
29755for(var m=1;m<=f;++m)G(s);g&=15;}o=32767+v[d], G(i[(g<<4)+y[o]]), G(w[o]), d++;}return 63!=u&&G(a), n}function J(t){if(t<=0&&(t=1), 100<t&&(t=100), e!=t){(function(t){for(var e=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],n=0;n<64;n++){var r=u((e[n]*t+50)/100);r<1?r=1:255<r&&(r=255), I[b[n]]=r;}for(var i=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],o=0;o<64;o++){var a=u((i[o]*t+50)/100);a<1?a=1:255<a&&(a=255), C[b[o]]=a;}for(var s=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],h=0,c=0;c<8;c++)for(var l=0;l<8;l++)T[h]=1/(I[b[h]]*s[c]*s[l]*8), F[h]=1/(C[b[h]]*s[c]*s[l]*8), h++;})(t<50?Math.floor(5e3/t):Math.floor(200-2*t)), e=t;}}this.encode=function(t,e){var n,r;(new Date).getTime();e&&J(e), P=new Array, E=0, q=7, Y(65496), Y(65504), Y(16), V(74), V(70), V(73), V(70), V(0), V(1), V(1), V(0), Y(1), Y(1), V(0), V(0), function(){Y(65499), Y(132), V(0);for(var t=0;t<64;t++)V(I[t]);V(1);for(var e=0;e<64;e++)V(C[e]);}(), n=t.width, r=t.height, Y(65472), Y(17), V(8), Y(r), Y(n), V(3), V(1), V(17), V(0), V(2), V(17), V(1), V(3), V(17), V(1), function(){Y(65476), Y(418), V(0);for(var t=0;t<16;t++)V(D[t+1]);for(var e=0;e<=11;e++)V(M[e]);V(16);for(var n=0;n<16;n++)V(U[n+1]);for(var r=0;r<=161;r++)V(N[r]);V(1);for(var i=0;i<16;i++)V(z[i+1]);for(var o=0;o<=11;o++)V(L[o]);V(17);for(var a=0;a<16;a++)V(H[a+1]);for(var s=0;s<=161;s++)V(W[s]);}(), Y(65498), Y(12), V(3), V(1), V(0), V(2), V(17), V(3), V(17), V(0), V(63), V(0);var i=0,o=0,a=0;E=0, q=7, this.encode.displayName="_encode_";for(var s,h,c,l,u,f,d,p,g,m=t.data,w=t.width,y=t.height,v=4*w,b=0;b<y;){for(s=0;s<v;){for(f=u=v*b+s, d=-1, g=p=0;g<64;g++)f=u+(p=g>>3)*v+(d=4*(7&g)), y<=b+p&&(f-=v*(b+1+p-y)), v<=s+d&&(f-=s+d-v+4), h=m[f++], c=m[f++], l=m[f++], O[g]=(j[h]+j[c+256>>0]+j[l+512>>0]>>16)-128, B[g]=(j[h+768>>0]+j[c+1024>>0]+j[l+1280>>0]>>16)-128, R[g]=(j[h+1280>>0]+j[c+1536>>0]+j[l+1792>>0]>>16)-128;i=X(O,T,i,S,_), o=X(B,F,o,k,A), a=X(R,F,a,k,A), s+=32;}b+=8;}if(0<=q){var x=[];x[1]=q+1, x[0]=(1<<q+1)-1, G(x);}return Y(65497), new Uint8Array(P)}, function(){(new Date).getTime();t||(t=50), function(){for(var t=String.fromCharCode,e=0;e<256;e++)n[e]=t(e);}(), S=r(D,M), k=r(z,L), _=r(U,N), A=r(H,W), function(){for(var t=1,e=2,n=1;n<=15;n++){for(var r=t;r<e;r++)y[32767+r]=n, w[32767+r]=[], w[32767+r][1]=n, w[32767+r][0]=r;for(var i=-(e-1);i<=-t;i++)y[32767+i]=n, w[32767+i]=[], w[32767+i][1]=n, w[32767+i][0]=e-1+i;t<<=1, e<<=1;}}(), function(){for(var t=0;t<256;t++)j[t]=19595*t, j[t+256>>0]=38470*t, j[t+512>>0]=7471*t+32768, j[t+768>>0]=-11059*t, j[t+1024>>0]=-21709*t, j[t+1280>>0]=32768*t+8421375, j[t+1536>>0]=-27439*t, j[t+1792>>0]=-5329*t;}(), J(t), (new Date).getTime();}();}try{module.exports=yt;}catch(t){}function xt(t,e){if(this.pos=0, this.buffer=t, this.datav=new DataView(t.buffer), this.is_with_alpha=!!e, this.bottom_up=!0, this.flag=String.fromCharCode(this.buffer[0])+String.fromCharCode(this.buffer[1]), this.pos+=2, -1===["BM","BA","CI","CP","IC","PT"].indexOf(this.flag))throw new Error("Invalid BMP File");this.parseHeader(), this.parseBGR();}xt.prototype.parseHeader=function(){if(this.fileSize=this.datav.getUint32(this.pos,!0), this.pos+=4, this.reserved=this.datav.getUint32(this.pos,!0), this.pos+=4, this.offset=this.datav.getUint32(this.pos,!0), this.pos+=4, this.headerSize=this.datav.getUint32(this.pos,!0), this.pos+=4, this.width=this.datav.getUint32(this.pos,!0), this.pos+=4, this.height=this.datav.getInt32(this.pos,!0), this.pos+=4, this.planes=this.datav.getUint16(this.pos,!0), this.pos+=2, this.bitPP=this.datav.getUint16(this.pos,!0), this.pos+=2, this.compress=this.datav.getUint32(this.pos,!0), this.pos+=4, this.rawSize=this.datav.getUint32(this.pos,!0), this.pos+=4, this.hr=this.datav.getUint32(this.pos,!0), this.pos+=4, this.vr=this.datav.getUint32(this.pos,!0), this.pos+=4, this.colors=this.datav.getUint32(this.pos,!0), this.pos+=4, this.importantColors=this.datav.getUint32(this.pos,!0), this.pos+=4, 16===this.bitPP&&this.is_with_alpha&&(this.bitPP=15), this.bitPP<15){var t=0===this.colors?1<<this.bitPP:this.colors;this.palette=new Array(t);for(var e=0;e<t;e++){var n=this.datav.getUint8(this.pos++,!0),r=this.datav.getUint8(this.pos++,!0),i=this.datav.getUint8(this.pos++,!0),o=this.datav.getUint8(this.pos++,!0);this.palette[e]={red:i,green:r,blue:n,quad:o};}}this.height<0&&(this.height*=-1, this.bottom_up=!1);}, xt.prototype.parseBGR=function(){this.pos=this.offset;try{var t="bit"+this.bitPP,e=this.width*this.height*4;this.data=new Uint8Array(e), this[t]();}catch(t){console.log("bit decode error:"+t);}}, xt.prototype.bit1=function(){var t=Math.ceil(this.width/8),e=t%4,n=0<=this.height?this.height-1:-this.height;for(n=this.height-1;0<=n;
29755n--){for(var r=this.bottom_up?n:this.height-1-n,i=0;i<t;i++)for(var o=this.datav.getUint8(this.pos++,!0),a=r*this.width*4+8*i*4,s=0;s<8&&8*i+s<this.width;s++){var h=this.palette[o>>7-s&1];this.data[a+4*s]=h.blue, this.data[a+4*s+1]=h.green, this.data[a+4*s+2]=h.red, this.data[a+4*s+3]=255;}0!=e&&(this.pos+=4-e);}}, xt.prototype.bit4=function(){for(var t=Math.ceil(this.width/2),e=t%4,n=this.height-1;0<=n;n--){for(var r=this.bottom_up?n:this.height-1-n,i=0;i<t;i++){var o=this.datav.getUint8(this.pos++,!0),a=r*this.width*4+2*i*4,s=o>>4,h=15&o,c=this.palette[s];if(this.data[a]=c.blue, this.data[a+1]=c.green, this.data[a+2]=c.red, this.data[a+3]=255, 2*i+1>=this.width)break;c=this.palette[h], this.data[a+4]=c.blue, this.data[a+4+1]=c.green, this.data[a+4+2]=c.red, this.data[a+4+3]=255;}0!=e&&(this.pos+=4-e);}}, xt.prototype.bit8=function(){for(var t=this.width%4,e=this.height-1;0<=e;e--){for(var n=this.bottom_up?e:this.height-1-e,r=0;r<this.width;r++){var i=this.datav.getUint8(this.pos++,!0),o=n*this.width*4+4*r;if(i<this.palette.length){var a=this.palette[i];this.data[o]=a.red, this.data[o+1]=a.green, this.data[o+2]=a.blue, this.data[o+3]=255;}else this.data[o]=255, this.data[o+1]=255, this.data[o+2]=255, this.data[o+3]=255;}0!=t&&(this.pos+=4-t);}}, xt.prototype.bit15=function(){for(var t=this.width%3,e=parseInt("11111",2),n=this.height-1;0<=n;n--){for(var r=this.bottom_up?n:this.height-1-n,i=0;i<this.width;i++){var o=this.datav.getUint16(this.pos,!0);this.pos+=2;var a=(o&e)/e*255|0,s=(o>>5&e)/e*255|0,h=(o>>10&e)/e*255|0,c=o>>15?255:0,l=r*this.width*4+4*i;this.data[l]=h, this.data[l+1]=s, this.data[l+2]=a, this.data[l+3]=c;}this.pos+=t;}}, xt.prototype.bit16=function(){for(var t=this.width%3,e=parseInt("11111",2),n=parseInt("111111",2),r=this.height-1;0<=r;r--){for(var i=this.bottom_up?r:this.height-1-r,o=0;o<this.width;o++){var a=this.datav.getUint16(this.pos,!0);this.pos+=2;var s=(a&e)/e*255|0,h=(a>>5&n)/n*255|0,c=(a>>11)/e*255|0,l=i*this.width*4+4*o;this.data[l]=c, this.data[l+1]=h, this.data[l+2]=s, this.data[l+3]=255;}this.pos+=t;}}, xt.prototype.bit24=function(){for(var t=this.height-1;0<=t;t--){for(var e=this.bottom_up?t:this.height-1-t,n=0;n<this.width;n++){var r=this.datav.getUint8(this.pos++,!0),i=this.datav.getUint8(this.pos++,!0),o=this.datav.getUint8(this.pos++,!0),a=e*this.width*4+4*n;this.data[a]=o, this.data[a+1]=i, this.data[a+2]=r, this.data[a+3]=255;}this.pos+=this.width%4;}}, xt.prototype.bit32=function(){for(var t=this.height-1;0<=t;t--)for(var e=this.bottom_up?t:this.height-1-t,n=0;n<this.width;n++){var r=this.datav.getUint8(this.pos++,!0),i=this.datav.getUint8(this.pos++,!0),o=this.datav.getUint8(this.pos++,!0),a=this.datav.getUint8(this.pos++,!0),s=e*this.width*4+4*n;this.data[s]=o, this.data[s+1]=i, this.data[s+2]=r, this.data[s+3]=a;}}, xt.prototype.getData=function(){return this.data};try{module.exports=function(t){var e=new xt(t);return{data:e.getData(),width:e.width,height:e.height}};}catch(t){}
29756/*
29757   Copyright (c) 2013 Gildas Lormeau. All rights reserved.
29758
29759   Redistribution and use in source and binary forms, with or without
29760   modification, are permitted provided that the following conditions are met:
29761
29762   1. Redistributions of source code must retain the above copyright notice,
29763   this list of conditions and the following disclaimer.
29764
29765   2. Redistributions in binary form must reproduce the above copyright 
29766   notice, this list of conditions and the following disclaimer in 
29767   the documentation and/or other materials provided with the distribution.
29768
29769   3. The names of the authors may not be used to endorse or promote products
29770   derived from this software without specific prior written permission.
29771
29772   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
29773   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
29774   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
29775   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
29776   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29777   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
29778   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29779   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29780   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
29781   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29782   */
29783/*
29784   Copyright (c) 2013 Gildas Lormeau. All rights reserved.
29785
29786   Redistribution and use in source and binary forms, with or without
29787   modification, are permitted provided that the following conditions are met:
29788
29789   1. Redistributions of source code must retain the above copyright notice,
29790   this list of conditions and the following disclaimer.
29791
29792   2. Redistributions in binary form must reproduce the above copyright 
29793   notice, this list of conditions and the following disclaimer in 
29794   the documentation and/or other materials provided with the distribution.
29795
29796   3. The names of the authors may not be used to endorse or promote products
29797   derived from this software without specific prior written permission.
29798
29799   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
29800   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
29801   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
29802   INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
29803   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29804   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
29805   OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29806   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29807   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
29808   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29809   */
29810!function(t){var p=15,g=573,e=[0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,0,0,16,17,18,18,19,19,20,20,20,20,21,21,21,21,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29];function ut(){var d=this;function h(t,e){for(var n=0;n|=1&t, t>>>=1, n<<=1, 0<--e;);return n>>>1}d.build_tree=function(t){var e,n,r,i=d.dyn_tree,o=d.stat_desc.static_tree,a=d.stat_desc.elems,s=-1;for(t.heap_len=0, t.heap_max=g, e=0;e<a;e++)0!==i[2*e]?(t.heap[++t.heap_len]=s=e, t.depth[e]=0):i[2*e+1]=0;for(;t.heap_len<2;)i[2*(r=t.heap[++t.heap_len]=s<2?++s:0)]=1, t.depth[r]=0, t.opt_len--, o&&(t.static_len-=o[2*r+1]);for(d.max_code=s, e=Math.floor(t.heap_len/2);1<=e;e--)t.pqdownheap(i,e);for(r=a;e=t.heap[1], t.heap[1]=t.heap[t.heap_len--], t.pqdownheap(i,1), n=t.heap[1], t.heap[--t.heap_max]=e, t.heap[--t.heap_max]=n, i[2*r]=i[2*e]+i[2*n], t.depth[r]=Math.max(t.depth[e],t.depth[n])+1, i[2*e+1]=i[2*n+1]=r, t.heap[1]=r++, t.pqdownheap(i,1), 2<=t.heap_len;);t.heap[--t.heap_max]=t.heap[1], function(t){var e,n,r,i,o,a,s=d.dyn_tree,h=d.stat_desc.static_tree,c=d.stat_desc.extra_bits,l=d.stat_desc.extra_base,u=d.stat_desc.max_length,f=0;for(i=0;i<=p;i++)t.bl_count[i]=0;for(s[2*t.heap[t.heap_max]+1]=0, e=t.heap_max+1;e<g;e++)u<(i=s[2*s[2*(n=t.heap[e])+1]+1]+1)&&(i=u, f++), s[2*n+1]=i, n>d.max_code||(t.bl_count[i]++, o=0, l<=n&&(o=c[n-l]), a=s[2*n], t.opt_len+=a*(i+o), h&&(t.static_len+=a*(h[2*n+1]+o)));if(0!==f){do{for(i=u-1;0===t.bl_count[i];)i--;t.bl_count[i]--, t.bl_count[i+1]+=2, t.bl_count[u]--, f-=2;}while(0<f);for(i=u;0!==i;i--)for(n=t.bl_count[i];0!==n;)(r=t.heap[--e])>d.max_code||(s[2*r+1]!=i&&(t.opt_len+=(i-s[2*r+1])*s[2*r], s[2*r+1]=i), n--);}}(t), function(t,e,n){var r,i,o,a=[],s=0;for(r=1;r<=p;r++)a[r]=s=s+n[r-1]<<1;for(i=0;i<=e;i++)0!==(o=t[2*i+1])&&(t[2*i]=h(a[o]++,o));}(i,d.max_code,t.bl_count);};}function ft(t,e,n,r,i){var o=this;o.static_tree=t, o.extra_bits=e, o.extra_base=n, o.elems=r, o.max_length=i;}ut._length_code=[0,1,2,3,4,5,6,7,8,8,9,9,10,10,11,11,12,12,12,12,13,13,13,13,14,14,14,14,15,15,15,15,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28], ut.base_length=[0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224,0], ut.base_dist=[0,1,2,3,4,6,8,12,16,24,32,48,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096,6144,8192,12288,16384,24576], ut.d_code=function(t){return t<256?e[t]:e[256+(t>>
29810>7)]}, ut.extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0], ut.extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13], ut.extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7], ut.bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15], ft.static_ltree=[12,8,140,8,76,8,204,8,44,8,172,8,108,8,236,8,28,8,156,8,92,8,220,8,60,8,188,8,124,8,252,8,2,8,130,8,66,8,194,8,34,8,162,8,98,8,226,8,18,8,146,8,82,8,210,8,50,8,178,8,114,8,242,8,10,8,138,8,74,8,202,8,42,8,170,8,106,8,234,8,26,8,154,8,90,8,218,8,58,8,186,8,122,8,250,8,6,8,134,8,70,8,198,8,38,8,166,8,102,8,230,8,22,8,150,8,86,8,214,8,54,8,182,8,118,8,246,8,14,8,142,8,78,8,206,8,46,8,174,8,110,8,238,8,30,8,158,8,94,8,222,8,62,8,190,8,126,8,254,8,1,8,129,8,65,8,193,8,33,8,161,8,97,8,225,8,17,8,145,8,81,8,209,8,49,8,177,8,113,8,241,8,9,8,137,8,73,8,201,8,41,8,169,8,105,8,233,8,25,8,153,8,89,8,217,8,57,8,185,8,121,8,249,8,5,8,133,8,69,8,197,8,37,8,165,8,101,8,229,8,21,8,149,8,85,8,213,8,53,8,181,8,117,8,245,8,13,8,141,8,77,8,205,8,45,8,173,8,109,8,237,8,29,8,157,8,93,8,221,8,61,8,189,8,125,8,253,8,19,9,275,9,147,9,403,9,83,9,339,9,211,9,467,9,51,9,307,9,179,9,435,9,115,9,371,9,243,9,499,9,11,9,267,9,139,9,395,9,75,9,331,9,203,9,459,9,43,9,299,9,171,9,427,9,107,9,363,9,235,9,491,9,27,9,283,9,155,9,411,9,91,9,347,9,219,9,475,9,59,9,315,9,187,9,443,9,123,9,379,9,251,9,507,9,7,9,263,9,135,9,391,9,71,9,327,9,199,9,455,9,39,9,295,9,167,9,423,9,103,9,359,9,231,9,487,9,23,9,279,9,151,9,407,9,87,9,343,9,215,9,471,9,55,9,311,9,183,9,439,9,119,9,375,9,247,9,503,9,15,9,271,9,143,9,399,9,79,9,335,9,207,9,463,9,47,9,303,9,175,9,431,9,111,9,367,9,239,9,495,9,31,9,287,9,159,9,415,9,95,9,351,9,223,9,479,9,63,9,319,9,191,9,447,9,127,9,383,9,255,9,511,9,0,7,64,7,32,7,96,7,16,7,80,7,48,7,112,7,8,7,72,7,40,7,104,7,24,7,88,7,56,7,120,7,4,7,68,7,36,7,100,7,20,7,84,7,52,7,116,7,3,8,131,8,67,8,195,8,35,8,163,8,99,8,227,8], ft.static_dtree=[0,5,16,5,8,5,24,5,4,5,20,5,12,5,28,5,2,5,18,5,10,5,26,5,6,5,22,5,14,5,30,5,1,5,17,5,9,5,25,5,5,5,21,5,13,5,29,5,3,5,19,5,11,5,27,5,7,5,23,5], ft.static_l_desc=new ft(ft.static_ltree,ut.extra_lbits,257,286,p), ft.static_d_desc=new ft(ft.static_dtree,ut.extra_dbits,0,30,p), ft.static_bl_desc=new ft(null,ut.extra_blbits,0,19,7);function n(t,e,n,r,i){var o=this;o.good_length=t, o.max_lazy=e, o.nice_length=n, o.max_chain=r, o.func=i;}var dt=[new n(0,0,0,0,0),new n(4,4,8,4,1),new n(4,5,16,8,1),new n(4,6,32,32,1),new n(4,4,16,16,2),new n(8,16,32,32,2),new n(8,16,128,128,2),new n(8,32,128,256,2),new n(32,128,258,1024,2),new n(32,258,258,4096,2)],pt=["need dictionary","stream end","","","stream error","data error","","buffer error","",""],gt=262;function mt(t,e,n,r){var i=t[2*e],o=t[2*n];return i<o||i==o&&r[e]<=r[n]}function r(){var h,c,l,u,f,d,p,g,i,m,w,y,v,a,b,x,S,k,_,A,I,C,T,F,P,E,q,O,B,R,s,j,D,M,U,N,z,o,L,H,W,G=this,V=new ut,Y=new ut,X=new ut;function J(){var t;for(t=0;t<286;t++)s[2*t]=0;for(t=0;t<30;t++)j[2*t]=0;for(t=0;t<19;t++)D[2*t]=0;s[512]=1, G.opt_len=G.static_len=0, N=o=0;}function K(t,e){var n,r,i=-1,o=t[1],a=0,s=7,h=4;for(0===o&&(s=138, h=3), t[2*(e+1)+1]=65535, n=0;n<=e;n++)r=o, o=t[2*(n+1)+1], ++a<s&&r==o||(a<h?D[2*r]+=a:0!==r?(r!=i&&D[2*r]++, D[32]++):a<=10?D[34]++:D[36]++, i=r, (a=0)===o?(s=138, h=3):r==o?(s=6, h=3):(s=7, h=4));}function Q(t){G.pending_buf[G.pending++]=t;}function Z(t){Q(255&t), Q(t>>>8&255);}function $(t,e){var n,r=e;16-r<W?(Z(H|=(n=t)<<W&65535), H=n>>>16-W, W+=r-16):(H|=t<<W&65535, W+=r);}function tt(t,e){var n=2*t;$(65535&e[n],65535&e[n+1]);}function et(t,e){var n,r,i=-1,o=t[1],a=0,s=7,h=4;for(0===o&&(s=138, h=3), n=0;n<=e;n++)if(r=o, o=t[2*(n+1)+1], !(++a<s&&r==o)){if(a<h)for(;tt(r,D), 0!=--a;);else 0!==r?(r!=i&&(tt(r,D), a--), tt(16,D), $(a-3,2)):a<=10?(tt(17,D), $(a-3,3)):(tt(18,D), $(a-11,7));i=r, (a=0)===o?(s=138, h=3):r==o?(s=6, h=3):(s=7, h=4);}}function nt(){16==W?(Z(H), W=H=0):8<=W&&(Q(255&H), H>>>=8, W-=8);}function rt(t,e){var n,r,i;if(G.pending_buf[z+2*N]=t>>>8&255, G.pending_buf[z+2*N+1]=255&t, G.pending_buf[M+N]=255&e, N++, 0===t?s[2*e]++:(o++, t--, s[2*(ut._length_code[e]+256+1)]++, j[2*ut.d_code(t)]++), 0==(8191&N)&&2<q){for(n=8*N, r
29810=I-S, i=0;i<30;i++)n+=j[2*i]*(5+ut.extra_dbits[i]);if(n>>>=3, o<Math.floor(N/2)&&n<Math.floor(r/2))return!0}return N==U-1}function it(t,e){var n,r,i,o,a=0;if(0!==N)for(;n=G.pending_buf[z+2*a]<<8&65280|255&G.pending_buf[z+2*a+1], r=255&G.pending_buf[M+a], a++, 0===n?tt(r,t):(tt((i=ut._length_code[r])+256+1,t), 0!==(o=ut.extra_lbits[i])&&$(r-=ut.base_length[i],o), tt(i=ut.d_code(--n),e), 0!==(o=ut.extra_dbits[i])&&$(n-=ut.base_dist[i],o)), a<N;);tt(256,t), L=t[513];}function ot(){8<W?Z(H):0<W&&Q(255&H), W=H=0;}function at(t,e,n){var r,i,o;$(0+(n?1:0),3), r=t, i=e, o=!0, ot(), L=8, o&&(Z(i), Z(~i)), G.pending_buf.set(g.subarray(r,r+i),G.pending), G.pending+=i;}function e(t,e,n){var r,i,o=0;0<q?(V.build_tree(G), Y.build_tree(G), o=function(){var t;for(K(s,V.max_code), K(j,Y.max_code), X.build_tree(G), t=18;3<=t&&0===D[2*ut.bl_order[t]+1];t--);return G.opt_len+=3*(t+1)+5+5+4, t}(), r=G.opt_len+3+7>>>3, (i=G.static_len+3+7>>>3)<=r&&(r=i)):r=i=e+5, e+4<=r&&-1!=t?at(t,e,n):i==r?($(2+(n?1:0),3), it(ft.static_ltree,ft.static_dtree)):($(4+(n?1:0),3), function(t,e,n){var r;for($(t-257,5), $(e-1,5), $(n-4,4), r=0;r<n;r++)$(D[2*ut.bl_order[r]+1],3);et(s,t-1), et(j,e-1);}(V.max_code+1,Y.max_code+1,o+1), it(s,j)), J(), n&&ot();}function st(t){e(0<=S?S:-1,I-S,t), S=I, h.flush_pending();}function ht(){var t,e,n,r;do{if(0===(r=i-T-I)&&0===I&&0===T)r=f;else if(-1==r)r--;else if(f+f-gt<=I){for(g.set(g.subarray(f,f+f),0), C-=f, I-=f, S-=f, n=t=v;e=65535&w[--n], w[n]=f<=e?e-f:0, 0!=--t;);for(n=t=f;e=65535&m[--n], m[n]=f<=e?e-f:0, 0!=--t;);r+=f;}if(0===h.avail_in)return;t=h.read_buf(g,I+T,r), 3<=(T+=t)&&(y=((y=255&g[I])<<x^255&g[I+1])&b);}while(T<gt&&0!==h.avail_in)}function ct(t){var e,n,r=P,i=I,o=F,a=f-gt<I?I-(f-gt):0,s=R,h=p,c=I+258,l=g[i+o-1],u=g[i+o];B<=F&&(r>>=2), T<s&&(s=T);do{if(g[(e=t)+o]==u&&g[e+o-1]==l&&g[e]==g[i]&&g[++e]==g[i+1]){i+=2, e++;do{}while(g[++i]==g[++e]&&g[++i]==g[++e]&&g[++i]==g[++e]&&g[++i]==g[++e]&&g[++i]==g[++e]&&g[++i]==g[++e]&&g[++i]==g[++e]&&g[++i]==g[++e]&&i<c);if(n=258-(c-i), i=c-258, o<n){if(C=t, s<=(o=n))break;l=g[i+o-1], u=g[i+o];}}}while((t=65535&m[t&h])>a&&0!=--r);return o<=T?o:T}function lt(t){return t.total_in=t.total_out=0, t.msg=null, G.pending=0, G.pending_out=0, c=113, u=0, V.dyn_tree=s, V.stat_desc=ft.static_l_desc, Y.dyn_tree=j, Y.stat_desc=ft.static_d_desc, X.dyn_tree=D, X.stat_desc=ft.static_bl_desc, W=H=0, L=8, J(), function(){var t;for(i=2*f, t=w[v-1]=0;t<v-1;t++)w[t]=0;E=dt[q].max_lazy, B=dt[q].good_length, R=dt[q].nice_length, P=dt[q].max_chain, k=F=2, y=A=T=S=I=0;}(), 0}G.depth=[], G.bl_count=[], G.heap=[], s=[], j=[], D=[], G.pqdownheap=function(t,e){for(var n=G.heap,r=n[e],i=e<<1;i<=G.heap_len&&(i<G.heap_len&&mt(t,n[i+1],n[i],G.depth)&&i++, !mt(t,r,n[i],G.depth));)n[e]=n[i], e=i, i<<=1;n[e]=r;}, G.deflateInit=function(t,e,n,r,i,o){return r||(r=8), i||(i=8), o||(o=0), t.msg=null, -1==e&&(e=6), i<1||9<i||8!=r||n<9||15<n||e<0||9<e||o<0||2<o?-2:(t.dstate=G, p=(f=1<<(d=n))-1, b=(v=1<<(a=i+7))-1, x=Math.floor((a+3-1)/3), g=new Uint8Array(2*f), m=[], w=[], U=1<<i+6, G.pending_buf=new Uint8Array(4*U), l=4*U, z=Math.floor(U/2), M=3*U, q=e, O=o, lt(t))}, G.deflateEnd=function(){return 42!=c&&113!=c&&666!=c?-2:(G.pending_buf=null, g=m=w=null, G.dstate=null, 113==c?-3:0)}, G.deflateParams=function(t,e,n){var r=0;return-1==e&&(e=6), e<0||9<e||n<0||2<n?-2:(dt[q].func!=dt[e].func&&0!==t.total_in&&(r=t.deflate(1)), q!=e&&(E=dt[q=e].max_lazy, B=dt[q].good_length, R=dt[q].nice_length, P=dt[q].max_chain), O=n, r)}, G.deflateSetDictionary=function(t,e,n){var r,i=n,o=0;if(!e||42!=c)return-2;if(i<3)return 0;for(f-gt<i&&(o=n-(i=f-gt)), g.set(e.subarray(o,o+i),0), S=I=i, y=((y=255&g[0])<<x^255&g[1])&b, r=0;r<=i-3;r++)y=(y<<x^255&g[r+2])&b, m[r&p]=w[y], w[y]=r;return 0}, G.deflate=function(t,e){var n,r,i,o,a,s;if(4<e||e<0)return-2;if(!t.next_out||!t.next_in&&0!==t.avail_in||666==c&&4!=e)return t.msg=pt[4], -2;if(0===t.avail_out)return t.msg=pt[7], -5;if(h=t, o=u, u=e, 42==c&&(r=8+(d-8<<4)<<8, 3<(i=(q-1&255)>>1)&&(i=3), r|=i<<6, 0!==I&&(r|=32), c=113, Q((s=r+=31-r%31)>>8&255), Q(255&s)), 0!==G.pending){if(h.flush_pending(), 0===h.avail_out)return u=-1, 0}else if(0===h.avail_in&&e<=o&&4!=e)return h.msg=pt[7], -5;if(666==c&&0!==h.avail_in)return t.msg=pt[7], -5;if(0!==h.avail_in||0!==T||0!=e&&666!=c){switch(a=-1, dt[q].func){case 0:a=function(t){var e,n=65535;for(l-5<n&&(n=l-5);;){if(T<=1){if(ht(), 0===T&&0==t)return 0;if(0===T)break}if(I+=T, e=S+n, ((T=0)===I||e<=I)&&(T=I-e, I=e, st(!1), 0===h.avail_out))return 0;if(f-gt<=I-S&&(st(!1), 0===h.avail_out))return 0}return st(4==t), 0===h.avail_out?4==t?2:0:4==t?3:1}(e);break;case 1:a=function(t){for(var e,n=0;;){if(T<gt){if(ht(), T<gt&&0==t)return 0;if(0===T)break}if(3<=T&&(y=(y<<x^255&g[I+2])&b, n=65535&w[y], m[I&p]=w[y], w[y]=I), 0!==n&&(I-n&65535)<=f-gt&&2!=O&&(k=ct(n)), 3<=k)if(e=rt(I-C,k-3), T-=k, k<=E&&3<=T){for(k--;y=(y<<x^255&g[++I+2])&b, n=65535&w[y], m[I&p]=w[y], w[y]=I, 0!=--k;);I++;}else I+=k, k=0, y=((y=255&g[I])<<x^255&g[I+1])&b;else e=rt(0,255&g[I]), T--, I++;if(e&&(st(!1), 0===h.avail_out))return 0}return st(4==t), 0===h.avail_out?4==t?2:0:4==t?3:1}(e);break;case 2:a=function(t){for(var e,n,r=0;;){if(T<gt){if(ht(), T<gt&&0==t)return 0;if(0===T)break}if(3<=T&&(y=(y<<x^255&g[I+2])&b, r=65535&w[y], m[I&p]=w[y], w[y]=I), F=k, _=C, k=2, 0!==r&&F<E&&(I-r&65535)<=f-gt&&(2!=O&&(k=ct(r)), k<=5&&(1==O||3==k&&4096<I-C)&&(k=2)), 3<=F&&k<=F){for(n=I+T-3, e=rt(I-1-_,F-3), T-=F-1, F-=2;++I<=n&&(y=(y<<x^255&g[I+2])&b, r=65535&w[y], m[I&p]=w[y], w[y]=I), 0!=--F;);if(A=0, k=2, I++, e&&(st(!1), 0===h.avail_out))return 0}else if(0!==A){if((e=rt(0,255&g[I-1]))&&st(!1), I++, T--, 0===h.avail_out)return 0}else A=1, I++, T--;}return 0!==A&&(e=rt(0,255&g[I-1]), A=0), st(4==t), 0===h.avail_out?4==t?2:0:4==t?3:1}(e);}if(2!=a&&3!=a||(c=666), 0==a||2==a)return 0===h.avail_out&&(u=-1), 0;if(1==a){if(1==e)$(2,3), tt(256,ft.static_ltree), nt(), 1+L+10-W<9&&($(2,3), tt(256,ft.static_ltree), nt()), L=7;else if(at(0,0,!1), 3==e)for(n=0;n<v;n++)w[n]=0;if(h.flush_pending(), 0===h.avail_out)return u=-1, 0}}return 4!=e?0:1};}function i(){var t=this;t.next_in_index=0, t.next_out_index=0, t.avail_in=0, t.total_in=0, t.avail_out=0, t.total_out=0;}i.prototype={deflateInit:function(t,e){return this.dstate=new r, e||(e=p), this.dstate.deflateInit(this,t,e)},deflate:function(t){return this.dstate?this.dstate.deflate(this,t):-2},deflateEnd:function(){if(!this.dstate)return-2;var t=this.dstate.deflateEnd();return this.dstate=null, t},deflateParams:function(t,e){return this.dstate?this.dstate.deflateParams(this,t,e):-2},deflateSetDictionary:function(t,e){return this.dstate?this.dstate.deflateSetDictionary(this,t,e):-2},read_buf:function(t,e,n){var r=this,i=r.avail_in;return n<i&&(i=n), 0===i?0:(r.avail_in-=i, t.set(r.next_in.subarray(r.next_in_index,r.next_in_index+i),e), r.next_in_index+=i, r.total_in+=i, i)},flush_pending:function(){var t=this,e=t.dstate.pending;e>t.avail_out&&(e=t.avail_out), 0!==e&&(t.next_out.set(t.dstate.pending_buf.subarray(t.dstate.pending_out,t.dstate.pending_out+e),t.next_out_index), t.next_out_index+=e, t.dstate.pending_out+=e, t.total_out+=e, t.avail_out-=e, t.dstate.pending-=e, 0===t.dstate.pending&&(t.dstate.pending_out=0));}};var o=t.zip||t;o.Deflater=o._jzlib_Deflater=function(t){var s=new i,h=new Uint8Array(512),e=t?t.level:-1;void 0===e&&(e=-1), s.deflateInit(e), s.next_out=h, this.append=function(t,e){var n,r=[],i=0,o=0,a=0;if(t.length){s.next_in_index=0, s.next_in=t, s.avail_in=t.length;do{if(s.next_out_index=0, s.avail_out=512, 0!=s.deflate(0))throw new Error("deflating: "+s.msg);s.next_out_index&&(512==s.next_out_index?r.push(new Uint8Array(h)):r.push(new Uint8Array(h.subarray(0,s.next_out_index)))), a+=s.next_out_index, e&&0<s.next_in_index&&s.next_in_index!=i&&(e(s.next_in_index), i=s.next_in_index);}while(0<s.avail_in||0===s.avail_out);return n=new Uint8Array(a), r.forEach(function(t){n.set(t,o), o+=t.length;}), n}}, this.flush=function(){var t,e,n=[],r=0,i=0;do{if(s.next_out_index=0, s.avail_out=512, 1!=(t=s.deflate(4))&&0!=t)throw new Error("deflating: "+s.msg);0<512-s.avail_out&&n.push(new Uint8Array(h.subarray(0,s.next_out_index))), i+=s.next_out_index;}while(0<s.avail_in||0===s.avail_out);
29810return s.deflateEnd(), e=new Uint8Array(i), n.forEach(function(t){e.set(t,r), r+=t.length;}), e};};}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||"undefined"!=typeof commonjsGlobal&&commonjsGlobal||Function('return typeof this === "object" && this.content')()||Function("return this")()), function(t){function f(t){var e;this.ok=!1, "#"==t.charAt(0)&&(t=t.substr(1,6)), t=(t=t.replace(/ /g,"")).toLowerCase();var l={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",feldspar:"d19275",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee9
298100",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslateblue:"8470ff",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",violetred:"d02090",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"};for(var n in l)t==n&&(t=l[n]);for(var u=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],process:function(t){return[parseInt(t[1]),parseInt(t[2]),parseInt(t[3])]}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:["#00ff00","336699"],process:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:["#fb0","f0f"],process:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}}],r=0;r<u.length;r++){var i=u[r].re,o=u[r].process,a=i.exec(t);a&&(e=o(a), this.r=e[0], this.g=e[1], this.b=e[2], this.ok=!0);}this.r=this.r<0||isNaN(this.r)?0:255<this.r?255:this.r, this.g=this.g<0||isNaN(this.g)?0:255<this.g?255:this.g, this.b=this.b<0||isNaN(this.b)?0:255<this.b?255:this.b, this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")"}, this.toHex=function(){var t=this.r.toString(16),e=this.g.toString(16),n=this.b.toString(16);return 1==t.length&&(t="0"+t), 1==e.length&&(e="0"+e), 1==n.length&&(n="0"+n), "#"+t+e+n}, this.getHelpXML=function(){for(var t=new Array,e=0;e<u.length;e++)for(var n=u[e].example,r=0;r<n.length;r++)t[t.length]=n[r];for(var i in l)t[t.length]=i;var o=document.createElement("ul");o.setAttribute("id","rgbcolor-examples");for(e=0;e<t.length;e++)try{var a=document.createElement("li"),s=new f(t[e]),h=document.createElement("div");h.style.cssText="margin: 3px; border: 1px solid black; background:"+s.toHex()+"; color:"+s.toHex(), h.appendChild(document.createTextNode("test"));var c=document.createTextNode(" "+t[e]+" -> "+s.toRGB()+" -> "+s.toHex());a.appendChild(h), a.appendChild(c), o.appendChild(a);}catch(t){}return o};}"undefined"!=typeof undefined&&undefined.amd?undefined("RGBColor",function(){return f}):"undefined"!='object'&&module.exports&&(module.exports=f), t.RGBColor=f;}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||"undefined"!=typeof commonjsGlobal&&commonjsGlobal||Function('return typeof this === "object" && this.content')()||Function("return this")()), function(t){module.exports=t();}(function(){return function o(a,s,h){function c(n,t){if(!s[n]){if(!a[n]){var e="function"==typeof commonjsRequire&&commonjsRequire;if(!t&&e)return e(n,!0);if(l)return l(n,!0);var r=new Error("Cannot find module '"+n+"'");throw r.code="MODULE_NOT_FOUND", r}var i=s[n]={exports:{}};a[n][0].call(i.exports,function(t){var e=a[n][1][t];return c(e||t)},i,i.exports,o,a,s,h);}return s[n].exports}for(var l="function"==typeof commonjsRequire&&commonjsRequire,t=0;t<h.length;t++)c(h[t]);return c}({1:[function(t,q,O){(function(E){!function(t){var e="object"==typeof O&&O,n="object"==typeof q&&q&&q.exports==e&&q,r="object"==typeof E&&E;r.global!==r&&r.window!==r||(t=r);var i,o,w=2147483647,y=36,v=1,b=26,a=38,s=700,x=72,S=128,k="-",h=/^xn--/,c=/[^ -~]/,l=/\x2E|\u3002|\uFF0E|\uFF61/g,u={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >
29810= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=y-v,_=Math.floor,A=String.fromCharCode;function I(t){throw RangeError(u[t])}function d(t,e){for(var n=t.length;n--;)t[n]=e(t[n]);return t}function p(t,e){return d(t.split(l),e).join(".")}function C(t){for(var e,n,r=[],i=0,o=t.length;i<o;)55296<=(e=t.charCodeAt(i++))&&e<=56319&&i<o?56320==(64512&(n=t.charCodeAt(i++)))?r.push(((1023&e)<<10)+(1023&n)+65536):(r.push(e), i--):r.push(e);return r}function T(t){return d(t,function(t){var e="";return 65535<t&&(e+=A((t-=65536)>>>10&1023|55296), t=56320|1023&t), e+=A(t)}).join("")}function F(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function P(t,e,n){var r=0;for(t=n?_(t/s):t>>1, t+=_(t/e);f*b>>1<t;r+=y)t=_(t/f);return _(r+(f+1)*t/(t+a))}function g(t){var e,n,r,i,o,a,s,h,c,l,u,f=[],d=t.length,p=0,g=S,m=x;for((n=t.lastIndexOf(k))<0&&(n=0), r=0;r<n;++r)128<=t.charCodeAt(r)&&I("not-basic"), f.push(t.charCodeAt(r));for(i=0<n?n+1:0;i<d;){for(o=p, a=1, s=y;d<=i&&I("invalid-input"), u=t.charCodeAt(i++), (y<=(h=u-48<10?u-22:u-65<26?u-65:u-97<26?u-97:y)||h>_((w-p)/a))&&I("overflow"), p+=h*a, !(h<(c=s<=m?v:m+b<=s?b:s-m));s+=y)a>_(w/(l=y-c))&&I("overflow"), a*=l;m=P(p-o,e=f.length+1,0==o), _(p/e)>w-g&&I("overflow"), g+=_(p/e), p%=e, f.splice(p++,0,g);}return T(f)}function m(t){var e,n,r,i,o,a,s,h,c,l,u,f,d,p,g,m=[];for(f=(t=C(t)).length, e=S, o=x, a=n=0;a<f;++a)(u=t[a])<128&&m.push(A(u));for(r=i=m.length, i&&m.push(k);r<f;){for(s=w, a=0;a<f;++a)e<=(u=t[a])&&u<s&&(s=u);for(s-e>_((w-n)/(d=r+1))&&I("overflow"), n+=(s-e)*d, e=s, a=0;a<f;++a)if((u=t[a])<e&&++n>w&&I("overflow"), u==e){for(h=n, c=y;!(h<(l=c<=o?v:o+b<=c?b:c-o));c+=y)g=h-l, p=y-l, m.push(A(F(l+g%p,0))), h=_(g/p);m.push(A(F(h,0))), o=P(n,d,r==i), n=0, ++r;}++n, ++e;}return m.join("")}if(i={version:"1.2.4",ucs2:{decode:C,encode:T},decode:g,encode:m,toASCII:function(t){return p(t,function(t){return c.test(t)?"xn--"+m(t):t})},toUnicode:function(t){return p(t,function(t){return h.test(t)?g(t.slice(4).toLowerCase()):t})}}, e&&!e.nodeType)if(n)n.exports=i;else for(o in i)i.hasOwnProperty(o)&&(e[o]=i[o]);else t.punycode=i;}(this);}).call(this,"undefined"!=typeof commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});},{}],2:[function(t,e,n){var i=t("./log");function u(t,e){for(var n=3===t.nodeType?document.createTextNode(t.nodeValue):t.cloneNode(!1),r=t.firstChild;r;)!0!==e&&1===r.nodeType&&"SCRIPT"===r.nodeName||n.appendChild(u(r,e)), r=r.nextSibling;return 1===t.nodeType&&(n._scrollTop=t.scrollTop, n._scrollLeft=t.scrollLeft, "CANVAS"===t.nodeName?function(e,t){try{t&&(t.width=e.width, t.height=e.height, t.getContext("2d").putImageData(e.getContext("2d").getImageData(0,0,e.width,e.height),0,0));}catch(t){i("Unable to copy canvas content from",e,t);}}(t,n):"TEXTAREA"!==t.nodeName&&"SELECT"!==t.nodeName||(n.value=t.value)), n}e.exports=function(o,t,e,n,a,s,h){var c=u(o.documentElement,a.javascriptEnabled),l=t.createElement("iframe");return l.className="html2canvas-container", l.style.visibility="hidden", l.style.position="fixed", l.style.left="-10000px", l.style.top="0px", l.style.border="0", l.width=e, l.height=n, l.scrolling="no", t.body.appendChild(l), new Promise(function(e){var t,n,r,i=l.contentWindow.document;l.contentWindow.onload=l.onload=function(){var t=setInterval(function(){0<i.body.childNodes.length&&(!function t(e){if(1===e.nodeType){e.scrollTop=e._scrollTop, e.scrollLeft=e._scrollLeft;for(var n=e.firstChild;n;)t(n), n=n.nextSibling;}}(i.documentElement), clearInterval(t), "view"===a.type&&(l.contentWindow.scrollTo(s,h), !/(iPad|iPhone|iPod)/g.test(navigator.userAgent)||l.contentWindow.scrollY===h&&l.contentWindow.scrollX===s||(i.documentElement.style.top=-h+"px", i.documentElement.style.left=-s+"px", i.documentElement.style.position="absolute")), e(l));},50);}, i.open(), i.write("<!DOCTYPE html><html></html>"), n=s, r=h, !(t=o).defaultView||n===t.defaultView.pageXOffset&&r===t.defaultView.pageYOffset||t.defaultView.scrollTo(n,r), i.replaceChild(i.adoptNode(c),i.documentElement), i.close();})};},{"./log":13}],3:[function(t,e,n){function r(t){this.r=0, this.g=0, this.b=0, this.a=null;this.fromArray(t)||this.namedColor(t)||this.rgb(t)||this.rgba(t)||this.hex6(t)||this.hex3(t);}r.prototype.darken=function(t){var e=1-t;return new r([Math.round(this.r*e),Math.round(this.g*e),Math.round(this.b*e),this.a])}, r.prototype.isTransparent=function(){return 0===this.a}, r.prototype.isBlack=function(){return 0===this.r&&0===this.g&&0===this.b}, r.prototype.fromArray=function(t){return Array.isArray(t)&&(this.r=Math.min(t[0],255), this.g=Math.min(t[1],255), this.b=Math.min(t[2],255), 3<t.length&&(this.a=t[3])), Array.isArray(t)};var i=/^#([a-f0-9]{3})$/i;r.prototype.hex3=function(t){var e;return null!==(e=t.match(i))&&(this.r=parseInt(e[1][0]+e[1][0],16), this.g=parseInt(e[1][1]+e[1][1],16), this.b=parseInt(e[1][2]+e[1][2],16)), null!==e};var o=/^#([a-f0-9]{6})$/i;r.prototype.hex6=function(t){var e=null;
29810return null!==(e=t.match(o))&&(this.r=parseInt(e[1].substring(0,2),16), this.g=parseInt(e[1].substring(2,4),16), this.b=parseInt(e[1].substring(4,6),16)), null!==e};var a=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;r.prototype.rgb=function(t){var e;return null!==(e=t.match(a))&&(this.r=Number(e[1]), this.g=Number(e[2]), this.b=Number(e[3])), null!==e};var s=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;r.prototype.rgba=function(t){var e;return null!==(e=t.match(s))&&(this.r=Number(e[1]), this.g=Number(e[2]), this.b=Number(e[3]), this.a=Number(e[4])), null!==e}, r.prototype.toString=function(){return null!==this.a&&1!==this.a?"rgba("+[this.r,this.g,this.b,this.a].join(",")+")":"rgb("+[this.r,this.g,this.b].join(",")+")"}, r.prototype.namedColor=function(t){t=t.toLowerCase();var e=h[t];if(e)this.r=e[0], this.g=e[1], this.b=e[2];else if("transparent"===t)return this.r=this.g=this.b=this.a=0, !0;return!!e}, r.prototype.isColor=!0;var h={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};e.exports=r;},{}],4:[function(t,e,n){var p=t("./support"),d=t("./renderers/canvas"),g=t("./imageloader"),m=t("./nodeparser"),r=t("./nodecontainer"),w=t("./log"),i=t("./utils"),y=t("./clone"),v=t("./proxy").loadUrlDocument,b=i.getBounds,x="data-html2canvas-node",S=0;function o(t,e){var n,r,i=S++;if((e=e||{}).logging&&(w.options.logging=!0, w.options.start=Date.now()), e.async=void 0===e.async||e.async, e.allowTaint=void 0!==e.allowTaint&&e.allowTaint, e.removeContainer=void 0===e.removeContainer||e.removeContainer, e.javascriptEnabled=void 0!==e.javascriptEnabled&&e.javascriptEnabled, e.imageTimeout=void 0===e.imageTimeout?1e4:e.imageTimeout, e.renderer="function"==typeof e.renderer?e.renderer:d, e.strict=!!e.strict, "string"==typeof t){if("string"!=typeof e.proxy)return Promise.reject("Proxy must be used when rendering url");var o=null!=e.width?e.width:window.innerWidth,a=null!=e.height?e.height:window.innerHeight;return v((n=t, r=document.createElement("a"), r.href=n, r.href=r.href, r),e.proxy,document,o,a,e).then(function(t){return k(t.contentWindow.document.documentElement,t,e,o,a)})}var s,h,c,l,u,f=(void 0===t?[document.documentElement]:t.length?t:[t])[0];return f.setAttribute(x+i,i), (s=f.ownerDocument, h=e, c=f.ownerDocument.defaultView.innerWidth, l=f.ownerDocument.defaultView.innerHeight, u=i, y(s,s,c,l,h,s.defaultView.pageXOffset,s.defaultView.pageYOffset).then(function(t){w("Document cloned");var e=x+u,n="["+e+"='"+u+"']";s.querySelector(n).removeAttribute(e);var r=t.contentWindow,i=r.document.querySelector(n),o="function"==typeof h.onclone?Promise.resolve(h.onclone(r.document)):Promise.resolve(!0);return o.then(function(){return k(i,t,h,c,l)})})).then(function(t){return"function"==typeof e.onrendered&&(w("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas"), e.onrendered(t)), t})}o.CanvasRenderer=d, o.NodeContainer=r, o.log=w, o.utils=i;var a="undefined"==typeof document||"function"!=typeof Object.create||"function"!=typeof document.createElement("canvas").getContext?function(){return Promise.reject("No canvas support")}:o;function k(n,r,i,t,e){var o,a,s=r.contentWindow,h=new p(s.document),c=new g(i,h),l=b(n),u="view"===i.type?t:(o=s.document, Math.max(Math.max(o.body.scrollWidth,o.documentElement.scrollWidth),Math.max(o.body.offsetWidth,o.documentElement.offsetWidth),Math.max(o.body.clientWidth,o.documentElement.clientWidth))),f="view"===i.type?e:(a=s.document, Math.max(Math.max(a.body.scrollHeight,a.documentElement.scrollHeight),Math.max(a.body.offsetHeight,a.documentElement.offsetHeight),Math.max(a.body.clientHeight,a.documentElement.clientHeight))),d=new i.renderer(u,f,c,i,document);return new m(n,d,h,c,i).ready.then(function(){var t,e;return w("Finished rendering"), t="view"===i.type?_(d.canvas,{width:d.canvas.width,height:d.canvas.height,top:0,left:0,x:0,y:0}):n===s.document.body||n===s.document.documentElement||null!=i.canvas?d.canvas:_(d.canvas,{width:null!=i.width?i.width:l.width,height:null!=i.height?i.height:l.height,top:l.top,left
29810:l.left,x:0,y:0}), e=r, i.removeContainer&&(e.parentNode.removeChild(e), w("Cleaned up container")), t})}function _(t,e){var n=document.createElement("canvas"),r=Math.min(t.width-1,Math.max(0,e.left)),i=Math.min(t.width,Math.max(1,e.left+e.width)),o=Math.min(t.height-1,Math.max(0,e.top)),a=Math.min(t.height,Math.max(1,e.top+e.height));n.width=e.width, n.height=e.height;var s=i-r,h=a-o;return w("Cropping canvas at:","left:",e.left,"top:",e.top,"width:",s,"height:",h), w("Resulting crop with width",e.width,"and height",e.height,"with x",r,"and y",o), n.getContext("2d").drawImage(t,r,o,s,h,e.x,e.y,s,h), n}e.exports=a;},{"./clone":2,"./imageloader":11,"./log":13,"./nodecontainer":14,"./nodeparser":15,"./proxy":16,"./renderers/canvas":20,"./support":22,"./utils":26}],5:[function(t,e,n){var r=t("./log"),i=t("./utils").smallImage;e.exports=function t(e){if(this.src=e, r("DummyImageContainer for",e), !this.promise||!this.image){r("Initiating DummyImageContainer"), t.prototype.image=new Image;var n=this.image;t.prototype.promise=new Promise(function(t,e){n.onload=t, n.onerror=e, n.src=i(), !0===n.complete&&t(n);});}};},{"./log":13,"./utils":26}],6:[function(t,e,n){var h=t("./utils").smallImage;e.exports=function(t,e){var n,r,i=document.createElement("div"),o=document.createElement("img"),a=document.createElement("span"),s="Hidden Text";i.style.visibility="hidden", i.style.fontFamily=t, i.style.fontSize=e, i.style.margin=0, i.style.padding=0, document.body.appendChild(i), o.src=h(), o.width=1, o.height=1, o.style.margin=0, o.style.padding=0, o.style.verticalAlign="baseline", a.style.fontFamily=t, a.style.fontSize=e, a.style.margin=0, a.style.padding=0, a.appendChild(document.createTextNode(s)), i.appendChild(a), i.appendChild(o), n=o.offsetTop-a.offsetTop+1, i.removeChild(a), i.appendChild(document.createTextNode(s)), i.style.lineHeight="normal", o.style.verticalAlign="super", r=o.offsetTop-i.offsetTop+1, document.body.removeChild(i), this.baseline=n, this.lineWidth=1, this.middle=r;};},{"./utils":26}],7:[function(t,e,n){var r=t("./font");function i(){this.data={};}i.prototype.getMetrics=function(t,e){return void 0===this.data[t+"-"+e]&&(this.data[t+"-"+e]=new r(t,e)), this.data[t+"-"+e]}, e.exports=i;},{"./font":6}],8:[function(o,t,e){var a=o("./utils").getBounds,i=o("./proxy").loadUrlDocument;function n(e,t,n){this.image=null, this.src=e;var r=this,i=a(e);this.promise=(t?new Promise(function(t){"about:blank"===e.contentWindow.document.URL||null==e.contentWindow.document.documentElement?e.contentWindow.onload=e.onload=function(){t(e);}:t(e);}):this.proxyLoad(n.proxy,i,n)).then(function(t){return o("./core")(t.contentWindow.document.documentElement,{type:"view",width:t.width,height:t.height,proxy:n.proxy,javascriptEnabled:n.javascriptEnabled,removeContainer:n.removeContainer,allowTaint:n.allowTaint,imageTimeout:n.imageTimeout/2})}).then(function(t){return r.image=t});}n.prototype.proxyLoad=function(t,e,n){var r=this.src;return i(r.src,t,r.ownerDocument,e.width,e.height,n)}, t.exports=n;},{"./core":4,"./proxy":16,"./utils":26}],9:[function(t,e,n){function r(t){this.src=t.value, this.colorStops=[], this.type=null, this.x0=.5, this.y0=.5, this.x1=.5, this.y1=.5, this.promise=Promise.resolve(!0);}r.TYPES={LINEAR:1,RADIAL:2}, r.REGEXP_COLORSTOP=/^\s*(rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*[0-9\.]+)?\s*\)|[a-z]{3,20}|#[a-f0-9]{3,6})(?:\s+(\d{1,3}(?:\.\d+)?)(%|px)?)?(?:\s|$)/i, e.exports=r;},{}],10:[function(t,e,n){e.exports=function(n,r){this.src=n, this.image=new Image;var i=this;this.tainted=null, this.promise=new Promise(function(t,e){i.image.onload=t, i.image.onerror=e, r&&(i.image.crossOrigin="anonymous"), i.image.src=n, !0===i.image.complete&&t(i.image);});};},{}],11:[function(t,e,n){var o=t("./log"),r=t("./imagecontainer"),i=t("./dummyimagecontainer"),a=t("./proxyimagecontainer"),s=t("./framecontainer"),h=t("./svgcontainer"),c=t("./svgnodecontainer"),l=t("./lineargradientcontainer"),u=t("./webkitgradientcontainer"),f=t("./utils").bind;function d(t,e){this.link=null, this.options=t, this.support=e, this.origin=this.getOrigin(window.location.href);}d.prototype.findImages=function(t){var e=[];return t.reduce(function(t,e){switch(e.node.nodeName){case"IMG":return t.concat([{args:[e.node.src],method:"url"}]);case"svg":case"IFRAME":return t.concat([{args:[e.node],method:e.node.nodeName}])}return t}
29810,[]).forEach(this.addImage(e,this.loadImage),this), e}, d.prototype.findBackgroundImage=function(t,e){return e.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(t,this.loadImage),this), t}, d.prototype.addImage=function(n,r){return function(e){e.args.forEach(function(t){this.imageExists(n,t)||(n.splice(0,0,r.call(this,e)), o("Added image #"+n.length,"string"==typeof t?t.substring(0,100):t));},this);}}, d.prototype.hasImageBackground=function(t){return"none"!==t.method}, d.prototype.loadImage=function(t){if("url"===t.method){var e=t.args[0];return!this.isSVG(e)||this.support.svg||this.options.allowTaint?e.match(/data:image\/.*;base64,/i)?new r(e.replace(/url\(['"]{0,}|['"]{0,}\)$/gi,""),!1):this.isSameOrigin(e)||!0===this.options.allowTaint||this.isSVG(e)?new r(e,!1):this.support.cors&&!this.options.allowTaint&&this.options.useCORS?new r(e,!0):this.options.proxy?new a(e,this.options.proxy):new i(e):new h(e)}return"linear-gradient"===t.method?new l(t):"gradient"===t.method?new u(t):"svg"===t.method?new c(t.args[0],this.support.svg):"IFRAME"===t.method?new s(t.args[0],this.isSameOrigin(t.args[0].src),this.options):new i(t)}, d.prototype.isSVG=function(t){return"svg"===t.substring(t.length-3).toLowerCase()||h.prototype.isInline(t)}, d.prototype.imageExists=function(t,e){return t.some(function(t){return t.src===e})}, d.prototype.isSameOrigin=function(t){return this.getOrigin(t)===this.origin}, d.prototype.getOrigin=function(t){var e=this.link||(this.link=document.createElement("a"));return e.href=t, e.href=e.href, e.protocol+e.hostname+e.port}, d.prototype.getPromise=function(e){return this.timeout(e,this.options.imageTimeout).catch(function(){return new i(e.src).promise.then(function(t){e.image=t;})})}, d.prototype.get=function(e){var n=null;return this.images.some(function(t){return(n=t).src===e})?n:null}, d.prototype.fetch=function(t){return this.images=t.reduce(f(this.findBackgroundImage,this),this.findImages(t)), this.images.forEach(function(e,n){e.promise.then(function(){o("Succesfully loaded image #"+(n+1),e);},function(t){o("Failed loading image #"+(n+1),e,t);});}), this.ready=Promise.all(this.images.map(this.getPromise,this)), o("Finished searching images"), this}, d.prototype.timeout=function(n,r){var i,t=Promise.race([n.promise,new Promise(function(t,e){i=setTimeout(function(){o("Timed out loading image",n), e(n);},r);})]).then(function(t){return clearTimeout(i), t});return t.catch(function(){clearTimeout(i);}), t}, e.exports=d;},{"./dummyimagecontainer":5,"./framecontainer":8,"./imagecontainer":10,"./lineargradientcontainer":12,"./log":13,"./proxyimagecontainer":17,"./svgcontainer":23,"./svgnodecontainer":24,"./utils":26,"./webkitgradientcontainer":27}],12:[function(t,e,n){var i=t("./gradientcontainer"),o=t("./color");function r(t){i.apply(this,arguments), this.type=i.TYPES.LINEAR;var e=r.REGEXP_DIRECTION.test(t.args[0])||!i.REGEXP_COLORSTOP.test(t.args[0]);e?t.args[0].split(/\s+/).reverse().forEach(function(t,e){switch(t){case"left":this.x0=0, this.x1=1;break;case"top":this.y0=0, this.y1=1;break;case"right":this.x0=1, this.x1=0;break;case"bottom":this.y0=1, this.y1=0;break;case"to":var n=this.y0,r=this.x0;this.y0=this.y1, this.x0=this.x1, this.x1=r, this.y1=n;break;case"center":break;default:var i=.01*parseFloat(t,10);if(isNaN(i))break;0===e?(this.y0=i, this.y1=1-this.y0):(this.x0=i, this.x1=1-this.x0);}},this):(this.y0=0, this.y1=1), this.colorStops=t.args.slice(e?1:0).map(function(t){var e=t.match(i.REGEXP_COLORSTOP),n=+e[2],r=0===n?"%":e[3];return{color:new o(e[1]),stop:"%"===r?n/100:null}}), null===this.colorStops[0].stop&&(this.colorStops[0].stop=0), null===this.colorStops[this.colorStops.length-1].stop&&(this.colorStops[this.colorStops.length-1].stop=1), this.colorStops.forEach(function(n,r){null===n.stop&&this.colorStops.slice(r).some(function(t,e){return null!==t.stop&&(n.stop=(t.stop-this.colorStops[r-1].stop)/(e+1)+this.colorStops[r-1].stop, !0)},this);},this);}r.prototype=Object.create(i.prototype), r.REGEXP_DIRECTION=/^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i, e.exports=r;},{"./color":3,"./gradientcontainer":9}],13:[function(t,e,n){var r=function(){r.options.logging&&window.console&&window.console.log&&Function.prototype.bind.call(window.console.log,window.console).apply(window.console,[Date.now()-r.options.start+"ms","html2canvas:"].concat([].slice.call(arguments,0)));};r.options={logging:!1}, e.exports=r;},{}],14:[function(t,e,n){var o=t("./color"),r=t("./utils"),i=r.getBounds,a=r.parseBackgroun
29810ds,s=r.offsetBounds;function h(t,e){this.node=t, this.parent=e, this.stack=null, this.bounds=null, this.borders=null, this.clip=[], this.backgroundClip=[], this.offsetBounds=null, this.visible=null, this.computedStyles=null, this.colors={}, this.styles={}, this.backgroundImages=null, this.transformData=null, this.transformMatrix=null, this.isPseudoElement=!1, this.opacity=null;}function c(t){return-1!==t.toString().indexOf("%")}function l(t){return t.replace("px","")}function u(t){return parseFloat(t)}h.prototype.cloneTo=function(t){t.visible=this.visible, t.borders=this.borders, t.bounds=this.bounds, t.clip=this.clip, t.backgroundClip=this.backgroundClip, t.computedStyles=this.computedStyles, t.styles=this.styles, t.backgroundImages=this.backgroundImages, t.opacity=this.opacity;}, h.prototype.getOpacity=function(){return null===this.opacity?this.opacity=this.cssFloat("opacity"):this.opacity}, h.prototype.assignStack=function(t){(this.stack=t).children.push(this);}, h.prototype.isElementVisible=function(){return this.node.nodeType===Node.TEXT_NODE?this.parent.visible:"none"!==this.css("display")&&"hidden"!==this.css("visibility")&&!this.node.hasAttribute("data-html2canvas-ignore")&&("INPUT"!==this.node.nodeName||"hidden"!==this.node.getAttribute("type"))}, h.prototype.css=function(t){return this.computedStyles||(this.computedStyles=this.isPseudoElement?this.parent.computedStyle(this.before?":before":":after"):this.computedStyle(null)), this.styles[t]||(this.styles[t]=this.computedStyles[t])}, h.prototype.prefixedCss=function(e){var n=this.css(e);return void 0===n&&["webkit","moz","ms","o"].some(function(t){return void 0!==(n=this.css(t+e.substr(0,1).toUpperCase()+e.substr(1)))},this), void 0===n?null:n}, h.prototype.computedStyle=function(t){return this.node.ownerDocument.defaultView.getComputedStyle(this.node,t)}, h.prototype.cssInt=function(t){var e=parseInt(this.css(t),10);return isNaN(e)?0:e}, h.prototype.color=function(t){return this.colors[t]||(this.colors[t]=new o(this.css(t)))}, h.prototype.cssFloat=function(t){var e=parseFloat(this.css(t));return isNaN(e)?0:e}, h.prototype.fontWeight=function(){var t=this.css("fontWeight");switch(parseInt(t,10)){case 401:t="bold";break;case 400:t="normal";}return t}, h.prototype.parseClip=function(){var t=this.css("clip").match(this.CLIP);return t?{top:parseInt(t[1],10),right:parseInt(t[2],10),bottom:parseInt(t[3],10),left:parseInt(t[4],10)}:null}, h.prototype.parseBackgroundImages=function(){return this.backgroundImages||(this.backgroundImages=a(this.css("backgroundImage")))}, h.prototype.cssList=function(t,e){var n=(this.css(t)||"").split(",");return 1===(n=(n=n[e||0]||n[0]||"auto").trim().split(" ")).length&&(n=[n[0],c(n[0])?"auto":n[0]]), n}, h.prototype.parseBackgroundSize=function(t,e,n){var r,i,o=this.cssList("backgroundSize",n);if(c(o[0]))r=t.width*parseFloat(o[0])/100;else{if(/contain|cover/.test(o[0])){var a=t.width/t.height,s=e.width/e.height;return a<s^"contain"===o[0]?{width:t.height*s,height:t.height}:{width:t.width,height:t.width/s}}r=parseInt(o[0],10);}return i="auto"===o[0]&&"auto"===o[1]?e.height:"auto"===o[1]?r/e.width*e.height:c(o[1])?t.height*parseFloat(o[1])/100:parseInt(o[1],10), "auto"===o[0]&&(r=i/e.height*e.width), {width:r,height:i}}, h.prototype.parseBackgroundPosition=function(t,e,n,r){var i,o,a=this.cssList("backgroundPosition",n);return i=c(a[0])?(t.width-(r||e).width)*(parseFloat(a[0])/100):parseInt(a[0],10), o="auto"===a[1]?i/e.width*e.height:c(a[1])?(t.height-(r||e).height)*parseFloat(a[1])/100:parseInt(a[1],10), "auto"===a[0]&&(i=o/e.height*e.width), {left:i,top:o}}, h.prototype.parseBackgroundRepeat=function(t){return this.cssList("backgroundRepeat",t)[0]}, h.prototype.parseTextShadows=function(){var t=this.css("textShadow"),e=[];if(t&&"none"!==t)for(var n=t.match(this.TEXT_SHADOW_PROPERTY),r=0;n&&r<n.length;r++){var i=n[r].match(this.TEXT_SHADOW_VALUES);e.push({color:new o(i[0]),offsetX:i[1]?parseFloat(i[1].replace("px","")):0,offsetY:i[2]?parseFloat(i[2].replace("px","")):0,blur:i[3]?i[3].replace("px",""):0});}return e}, h.prototype.parseTransform=function(){if(!this.transformData)if(this.hasTransform()){var t=this.parseBounds(),e=this.prefixedCss("transformOrigin").split(" ").map(l).map(u);e[0]+=t.left, e[1]+=t.top, this.transformData={origin:e,matrix:this.parseTransformMatrix()};}else this.transformData={origin:[0,0],matrix:[1,0,0,1,0,0]};return this.transformData}, h.prototype.parseTransformMatrix=function(){if(!this.transformMatrix){var t=this.prefixedCss("transform"),e=t?function(t){{if(t&&"matrix"===t[1])return t[2].split(",").map(function(t){return parseFloat(t.trim())});if(t&&"matrix3d"===t[1]){var e=t[2].split(",").map(function(t){return parseFloat(t.trim())});return[e[0],e[1],e[4],e[5],e[12],e[13]]}}}(t.match(this.MATRIX_PROPERTY)):null;this.transformMatrix=e||[1,0,0,1,0,0];}return this.transformMatrix}, h.prototype.parseBounds=function(){return this.bounds||(this.bounds=this.hasTransform()?s(this.node):i(this.node))}, h.prototype.hasTransform=function(){return"1,0,0,1,0,0"!==this.parseTransformMatrix().join(",")||this.parent&&this.parent.hasTransform()}, h.prototype.getValue=function(){var t,e,n=this.node.value||"";return"SELECT"===this.node.tagName?(t=this.node, n=(e=t.options[t.selectedIndex||0])&&e.text||""):"password"===this.node.type&&(n=Array(n.length+1).join("•")), 0===n.length?this.node.placeholder||"":n}, h.prototype.MATRIX_PROPERTY=/(matrix|matrix3d)\((.+)\)/, h.prototype.TEXT_SHADOW_PROPERTY=/((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g, h.prototype.TEXT_SHADOW_VALUES=/(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g, h.prototype.CLIP=/^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/, e.exports=h;},{"./color":3,"./utils":26}],15:[function(t,e,n){var s=t("./log"),h=t("punycode"),c=t("./nodecontainer"),f=t("./textcontainer"),d=t("./pseudoelementcontainer"),l=t("./fontmetrics"),u=t("./color"),p=t("./stackingcontext"),r=t("./utils"),g=r.bind,a=r.getBounds,m=r.parseBackgroun
29810ds,w=r.offsetBounds;function i(t,e,n,r,i){s("Starting NodeParser"), this.renderer=e, this.options=i, this.range=null, this.support=n, this.renderQueue=[], this.stack=new p(!0,1,t.ownerDocument,null);var o=new c(t,null);if(i.background&&e.rectangle(0,0,e.width,e.height,new u(i.background)), t===t.ownerDocument.documentElement){var a=new c(o.color("backgroundColor").isTransparent()?t.ownerDocument.body:t.ownerDocument.documentElement,null);e.rectangle(0,0,e.width,e.height,a.color("backgroundColor"));}o.visibile=o.isElementVisible(), this.createPseudoHideStyles(t.ownerDocument), this.disableAnimations(t.ownerDocument), this.nodes=L([o].concat(this.getChildren(o)).filter(function(t){return t.visible=t.isElementVisible()}).map(this.getPseudoElements,this)), this.fontMetrics=new l, s("Fetched nodes, total:",this.nodes.length), s("Calculate overflow clips"), this.calculateOverflowClips(), s("Start fetching images"), this.images=r.fetch(this.nodes.filter(j)), this.ready=this.images.ready.then(g(function(){return s("Images loaded, starting parsing"), s("Creating stacking contexts"), this.createStackingContexts(), s("Sorting stacking contexts"), this.sortStackingContexts(this.stack), this.parse(this.stack), s("Render queue created with "+this.renderQueue.length+" items"), new Promise(g(function(t){i.async?"function"==typeof i.async?i.async.call(this,this.renderQueue,t):0<this.renderQueue.length?(this.renderIndex=0, this.asyncRenderer(this.renderQueue,t)):t():(this.renderQueue.forEach(this.paint,this), t());},this))},this));}function o(t){return t.parent&&t.parent.clip.length}function y(){}i.prototype.calculateOverflowClips=function(){this.nodes.forEach(function(t){if(j(t)){D(t)&&t.appendToDOM(), t.borders=this.parseBorders(t);var e="hidden"===t.css("overflow")?[t.borders.clip]:[],n=t.parseClip();n&&-1!==["absolute","fixed"].indexOf(t.css("position"))&&e.push([["rect",t.bounds.left+n.left,t.bounds.top+n.top,n.right-n.left,n.bottom-n.top]]), t.clip=o(t)?t.parent.clip.concat(e):e, t.backgroundClip="hidden"!==t.css("overflow")?t.clip.concat([t.borders.clip]):t.clip, D(t)&&t.cleanDOM();}else M(t)&&(t.clip=o(t)?t.parent.clip:[]);D(t)||(t.bounds=null);},this);}, i.prototype.asyncRenderer=function(t,e,n){n=n||Date.now(), this.paint(t[this.renderIndex++]), t.length===this.renderIndex?e():n+20>Date.now()?this.asyncRenderer(t,e,n):setTimeout(g(function(){this.asyncRenderer(t,e);},this),0);}, i.prototype.createPseudoHideStyles=function(t){this.createStyles(t,"."+d.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE+':before { content: "" !important; display: none !important; }.'+d.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER+':after { content: "" !important; display: none !important; }');}, i.prototype.disableAnimations=function(t){this.createStyles(t,"* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; -webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}");}, i.prototype.createStyles=function(t,e){var n=t.createElement("style");n.innerHTML=e, t.body.appendChild(n);}, i.prototype.getPseudoElements=function(t){var e=[[t]];if(t.node.nodeType===Node.ELEMENT_NODE){var n=this.getPseudoElement(t,":before"),r=this.getPseudoElement(t,":after");n&&e.push(n), r&&e.push(r);}return L(e)}, i.prototype.getPseudoElement=function(t,e){var n=t.computedStyle(e);if(!n||!n.content||"none"===n.content||"-moz-alt-content"===n.content||"none"===n.display)return null;for(var r,i,o=(r=n.content, (i=r.substr(0,1))===r.substr(r.length-1)&&i.match(/'|"/)?r.substr(1,r.length-2):r),a="url"===o.substr(0,3),s=document.createElement(a?"img":"html2canvaspseudoelement"),h=new d(s,t,e),c=n.length-1;0<=c;c--){var l=n.item(c).replace(/(\-[a-z])/g,function(t){return t.toUpperCase().replace("-","")});s.style[l]=n[l];}if(s.className=d.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE+" "+d.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER, a)return s.src=m(o)[0].args[0], [h];var u=document.createTextNode(o);return s.appendChild(u), [h,new f(u,h)]}, i.prototype.getChildren=function(n){return L([].filter.call(n.node.childNodes,q).map(function(t){var e=[t.nodeType===Node.TEXT_NODE?new f(t,n):new c(t,n)].filter(z);return t.nodeType===Node.ELEMENT_NODE&&e.length&&"TEXTAREA"!==t.tagName?e[0].isElementVisible()?e.concat(this.getChildren(e[0])):[]:e},this))}, i.prototype.newStackingContext=function(t,e){var n=new p(e,t.getOpacity(),t.node,t.parent);t.cloneTo(n), (e?n.getParentStack(this):n.parent.stack).contexts.push(n), t.stack=n;}, i.prototype.createStackingContexts=function(){this.nodes.forEac
29810h(function(t){var e,n;j(t)&&(this.isRootElement(t)||t.getOpacity()<1||(n=(e=t).css("position"), "auto"!==(-1!==["absolute","relative","fixed"].indexOf(n)?e.css("zIndex"):"auto"))||this.isBodyWithTransparentRoot(t)||t.hasTransform())?this.newStackingContext(t,!0):j(t)&&(O(t)&&T(t)||-1!==["inline-block","inline-table"].indexOf(t.css("display"))||B(t))?this.newStackingContext(t,!1):t.assignStack(t.parent.stack);},this);}, i.prototype.isBodyWithTransparentRoot=function(t){return"BODY"===t.node.nodeName&&t.parent.color("backgroundColor").isTransparent()}, i.prototype.isRootElement=function(t){return null===t.parent}, i.prototype.sortStackingContexts=function(t){var n;t.contexts.sort((n=t.contexts.slice(0), function(t,e){return t.cssInt("zIndex")+n.indexOf(t)/n.length-(e.cssInt("zIndex")+n.indexOf(e)/n.length)})), t.contexts.forEach(this.sortStackingContexts,this);}, i.prototype.parseTextBounds=function(a){return function(t,e,n){if("none"!==a.parent.css("textDecoration").substr(0,4)||0!==t.trim().length){if(this.support.rangeBounds&&!a.parent.hasTransform()){var r=n.slice(0,e).join("").length;return this.getRangeBounds(a.node,r,t.length)}if(a.node&&"string"==typeof a.node.data){var i=a.node.splitText(t.length),o=this.getWrapperBounds(a.node,a.parent.hasTransform());return a.node=i, o}}else this.support.rangeBounds&&!a.parent.hasTransform()||(a.node=a.node.splitText(t.length));return{}}}, i.prototype.getWrapperBounds=function(t,e){var n=t.ownerDocument.createElement("html2canvaswrapper"),r=t.parentNode,i=t.cloneNode(!0);n.appendChild(t.cloneNode(!0)), r.replaceChild(n,t);var o=e?w(n):a(n);return r.replaceChild(i,n), o}, i.prototype.getRangeBounds=function(t,e,n){var r=this.range||(this.range=t.ownerDocument.createRange());return r.setStart(t,e), r.setEnd(t,e+n), r.getBoundingClientRect()}, i.prototype.parse=function(t){var e=t.contexts.filter(I),n=t.children.filter(j),r=n.filter(R(B)),i=r.filter(R(O)).filter(R(F)),o=n.filter(R(O)).filter(B),a=r.filter(R(O)).filter(F),s=t.contexts.concat(r.filter(O)).filter(T),h=t.children.filter(M).filter(E),c=t.contexts.filter(C);e.concat(i).concat(o).concat(a).concat(s).concat(h).concat(c).forEach(function(t){this.renderQueue.push(t), P(t)&&(this.parse(t), this.renderQueue.push(new y));},this);}, i.prototype.paint=function(t){try{t instanceof y?this.renderer.ctx.restore():M(t)?(D(t.parent)&&t.parent.appendToDOM(), this.paintText(t), D(t.parent)&&t.parent.cleanDOM()):this.paintNode(t);}catch(t){if(s(t), this.options.strict)throw t}}, i.prototype.paintNode=function(t){P(t)&&(this.renderer.setOpacity(t.opacity), this.renderer.ctx.save(), t.hasTransform()&&this.renderer.setTransform(t.parseTransform())), "INPUT"===t.node.nodeName&&"checkbox"===t.node.type?this.paintCheckbox(t):"INPUT"===t.node.nodeName&&"radio"===t.node.type?this.paintRadio(t):this.paintElement(t);}, i.prototype.paintElement=function(n){var r=n.parseBounds();this.renderer.clip(n.backgroundClip,function(){this.renderer.renderBackground(n,r,n.borders.borders.map(N));},this), this.renderer.clip(n.clip,function(){this.renderer.renderBorders(n.borders.borders);},this), this.renderer.clip(n.backgroundClip,function(){switch(n.node.nodeName){case"svg":case"IFRAME":var t=this.images.get(n.node);t?this.renderer.renderImage(n,r,n.borders,t):s("Error loading <"+n.node.nodeName+">",n.node);break;case"IMG":var e=this.images.get(n.node.src);e?this.renderer.renderImage(n,r,n.borders,e):s("Error loading <img>",n.node.src);break;case"CANVAS":this.renderer.renderImage(n,r,n.borders,{image:n.node});break;case"SELECT":case"INPUT":case"TEXTAREA":this.paintFormValue(n);}},this);}, i.prototype.paintCheckbox=function(t){var e=t.parseBounds(),n=Math.min(e.width,e.height),r={width:n-1,height:n-1,top:e.top,left:e.left},i=[3,3],o=[i,i,i,i],a=[1,1,1,1].map(function(t){return{color:new u("#A5A5A5"),width:t}}),s=S(r,o,a);this.renderer.clip(t.backgroundClip,function(){this.renderer.rectangle(r.left+1,r.top+1,r.width-2,r.height-2,new u("#DEDEDE")), this.renderer.renderBorders(b(a,r,s,o)), t.node.checked&&(this.renderer.font(new u("#424242"),"normal","normal","bold",n-3+"px","arial"), this.renderer.text("✔",r.left+n/6,r.top+n-1));},this);}, i.prototype.paintRadio=function(t){var e=t.parseBounds(),n=Math.min(e.width,e.height)-2;this.renderer.clip(t.backgroundClip,function(){this.renderer.circleStroke(e.left+1,e.top+1,n,new u("#DEDEDE"),1,new u("#A5A5A5")), t.node.checked&&this.renderer.circle(Math.ceil(e.left+n/4)+1,Math.ceil(e.top+n/4)+1,Math.floor(n/2),new u("#424242"));},this);}, i.prototype.paintFormValue=function(e){var t=e.getValue();if(0<t.length){var n=e.node.ownerDocument,r=n.createElement("html2canvaswrapper");["lineHeight","textAlign","fontFamily","fontWeight","fontSize","color","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","borderLeftStyle","borderTopStyle","borderLeftWidth","borderTopWidth","boxSizing","whiteSpace","wordWrap"].forEach(function(t){try{r.style[t]=e.css(t);}catch(t){s("html2canvas: Parse: Exception caught in renderFormValue: "+t.message);}});var i=e.parseBounds();r.style.position="fixed", r.style.left=i.left+"px", r.style.top=i.top+"px", r.textContent=t, n.body.appendChild(r), this.paintText(new f(r.firstChild,e)), n.body.removeChild(r);}}, i.prototype.paintText=function(n){n.applyTextTransform();var t,e=h.ucs2.decode(n.node.data),r=this.options.letterRendering&&!/^(normal|none|0px)$/.test(n.parent.css("letterSpacing"))||(t=n.node.data, /[^\u0000-\u00ff]/.test(t))?e.map(function(t){return h.ucs2.encode([t])}):function(t){var e,n=[],r=0,i=!1;for(;t.length;)o=t[r], -1!==[32,13,10,9,45].indexOf(o)===i?((e=t.splice(0,r)).length&&n.push(h.ucs2.encode(e)), i=!i, r=0):r++, r>=t.length&&(e=t.splice(0,r)).length&&n.push(h.ucs2.encode(e));var o;return n}(e),i=n.parent.fontWeight(),o=n.parent.css("fontSize"),a=n.parent.css("fontFamily"),s=n.parent.parseTextShadows();this.renderer.font(n.parent.color("color"),n.parent.css("fontStyle"),n.parent.css("fontVariant"),i,o,a), s.length?this.renderer.fontShadow(s[0].color,s[0].offsetX,s[0].offsetY,s[0].blur):this.renderer.clearShadow(), this.renderer.clip(n.parent.clip,function(){r.map(this.parseTextBounds(n),this).forEac
vendor: 5,354 bytes, line 29810
29810h(function(t,e){t&&!1===/^\s*$/.test(r[e])&&(this.renderer.text(r[e],t.left,t.bottom), this.renderTextDecoration(n.parent,t,this.fontMetrics.getMetrics(a,o)));},this);},this);}, i.prototype.renderTextDecoration=function(t,e,n){switch(t.css("textDecoration").split(" ")[0]){case"underline":this.renderer.rectangle(e.left,Math.round(e.top+n.baseline+n.lineWidth),e.width,1,t.color("color"));break;case"overline":this.renderer.rectangle(e.left,Math.round(e.top),e.width,1,t.color("color"));break;case"line-through":this.renderer.rectangle(e.left,Math.ceil(e.top+n.middle+n.lineWidth),e.width,1,t.color("color"));}};var v={inset:[["darken",.6],["darken",.1],["darken",.1],["darken",.6]]};function b(a,s,h,c){return a.map(function(t,e){if(0<t.width){var n=s.left,r=s.top,i=s.width,o=s.height-a[2].width;switch(e){case 0:o=a[0].width, t.args=_({c1:[n,r],c2:[n+i,r],c3:[n+i-a[1].width,r+o],c4:[n+a[3].width,r+o]},c[0],c[1],h.topLeftOuter,h.topLeftInner,h.topRightOuter,h.topRightInner);break;case 1:n=s.left+s.width-a[1].width, i=a[1].width, t.args=_({c1:[n+i,r],c2:[n+i,r+o+a[2].width],c3:[n,r+o],c4:[n,r+a[0].width]},c[1],c[2],h.topRightOuter,h.topRightInner,h.bottomRightOuter,h.bottomRightInner);break;case 2:r=r+s.height-a[2].width, o=a[2].width, t.args=_({c1:[n+i,r+o],c2:[n,r+o],c3:[n+a[3].width,r],c4:[n+i-a[3].width,r]},c[2],c[3],h.bottomRightOuter,h.bottomRightInner,h.bottomLeftOuter,h.bottomLeftInner);break;case 3:i=a[3].width, t.args=_({c1:[n,r+o+a[2].width],c2:[n,r],c3:[n+i,r+a[0].width],c4:[n+i,r+o]},c[3],c[0],h.bottomLeftOuter,h.bottomLeftInner,h.topLeftOuter,h.topLeftInner);}}return t})}function x(t,e,n,r){var i=(Math.sqrt(2)-1)/3*4,o=n*i,a=r*i,s=t+n,h=e+r;return{topLeft:k({x:t,y:h},{x:t,y:h-a},{x:s-o,y:e},{x:s,y:e}),topRight:k({x:t,y:e},{x:t+o,y:e},{x:s,y:h-a},{x:s,y:h}),bottomRight:k({x:s,y:e},{x:s,y:e+a},{x:t+o,y:h},{x:t,y:h}),bottomLeft:k({x:s,y:h},{x:s-o,y:h},{x:t,y:e+a},{x:t,y:e})}}function S(t,e,n){var r=t.left,i=t.top,o=t.width,a=t.height,s=e[0][0]<o/2?e[0][0]:o/2,h=e[0][1]<a/2?e[0][1]:a/2,c=e[1][0]<o/2?e[1][0]:o/2,l=e[1][1]<a/2?e[1][1]:a/2,u=e[2][0]<o/2?e[2][0]:o/2,f=e[2][1]<a/2?e[2][1]:a/2,d=e[3][0]<o/2?e[3][0]:o/2,p=e[3][1]<a/2?e[3][1]:a/2,g=o-c,m=a-f,w=o-u,y=a-p;return{topLeftOuter:x(r,i,s,h).topLeft.subdivide(.5),topLeftInner:x(r+n[3].width,i+n[0].width,Math.max(0,s-n[3].width),Math.max(0,h-n[0].width)).topLeft.subdivide(.5),topRightOuter:x(r+g,i,c,l).topRight.subdivide(.5),topRightInner:x(r+Math.min(g,o+n[3].width),i+n[0].width,g>o+n[3].width?0:c-n[3].width,l-n[0].width).topRight.subdivide(.5),bottomRightOuter:x(r+w,i+m,u,f).bottomRight.subdivide(.5),bottomRightInner:x(r+Math.min(w,o-n[3].width),i+Math.min(m,a+n[0].width),Math.max(0,u-n[1].width),f-n[2].width).bottomRight.subdivide(.5),bottomLeftOuter:x(r,i+y,d,p).bottomLeft.subdivide(.5),bottomLeftInner:x(r+n[3].width,i+y,Math.max(0,d-n[3].width),p-n[2].width).bottomLeft.subdivide(.5)}}function k(s,h,c,l){var u=function(t,e,n){return{x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}};return{start:s,startControl:h,endControl:c,end:l,subdivide:function(t){var e=u(s,h,t),n=u(h,c,t),r=u(c,l,t),i=u(e,n,t),o=u(n,r,t),a=u(i,o,t);return[k(s,e,i,a),k(a,o,r,l)]},curveTo:function(t){t.push(["bezierCurve",h.x,h.y,c.x,c.y,l.x,l.y]);},curveToReversed:function(t){t.push(["bezierCurve",c.x,c.y,h.x,h.y,s.x,s.y]);}}}function _(t,e,n,r,i,o,a){var s=[];return 0<e[0]||0<e[1]?(s.push(["line",r[1].start.x,r[1].start.y]), r[1].curveTo(s)):s.push(["line",t.c1[0],t.c1[1]]), 0<n[0]||0<n[1]?(s.push(["line",o[0].start.x,o[0].start.y]), o[0].curveTo(s), s.push(["line",a[0].end.x,a[0].end.y]), a[0].curveToReversed(s)):(s.push(["line",t.c2[0],t.c2[1]]), s.push(["line",t.c3[0],t.c3[1]])), 0<e[0]||0<e[1]?(s.push(["line",i[1].end.x,i[1].end.y]), i[1].curveToReversed(s)):s.push(["line",t.c4[0],t.c4[1]]), s}function A(t,e,n,r,i,o,a){0<e[0]||0<e[1]?(t.push(["line",r[0].start.x,r[0].start.y]), r[0].curveTo(t), r[1].curveTo(t)):t.push(["line",o,a]), (0<n[0]||0<n[1])&&t.push(["line",i[0].start.x,i[0].start.y]);}function I(t){return t.cssInt("zIndex")<0}function C(t){return 0<t.cssInt("zIndex")}function T(t){return 0===t.cssInt("zIndex")}function F(t){return-1!==["inline","inline-block","inline-table"].indexOf(t.css("display"))}function P(t){return t instanceof p}function E(t){return 0<t.node.data.trim().length}function q(t){return t.nodeType===Node.TEXT_NODE||t.nodeType===Node.ELEMENT_NODE}function O(t){return"static"!==t.css("position")}function B(t){return"none"!==t.css("float")}function R(t){var e=this;return function(){return!t.apply(e,arguments)}}function j(t){return t.node.nodeType===Node.ELEMENT_NODE}function D(t){return!0===t.isPseudoElement}function M(t){return t.node.nodeType===Node.TEXT_NODE}function U(t){return parseInt(t,10)}function N(t){return t.width}function z(t){return t.node.nodeType!==Node.ELEMENT_NODE||-1===["SCRIPT","HEAD","TITLE","OBJECT","BR","OPTION"].indexOf(t.node.nodeName)}function L(t){return[].concat.apply([],t)}i.prototype.parseBorders=function(o){var r,t=o.parseBounds(),e=(r=o, ["TopLeft","TopRight","BottomRight","BottomLeft"].map(function(t){var e=r.css("border"+t+"Radius"),n=e.split(" ");return n.length<=1&&(n[1]=n[0]), n.map(U)})),n=["Top","Right","Bottom","Left"].map(function(t,e){var n=o.css("border"+t+"Style"),r=o.color("border"+t+"Color");"inset"===n&&r.isBlack()&&(r=new u([255,255,255,r.a]));var i=v[n]?v[n][e]:null;
29810return{width:o.cssInt("border"+t+"Width"),color:i?r[i[0]](i[1]):r,args:null}}),i=S(t,e,n);return{clip:this.parseBackgroundClip(o,i,n,e,t),borders:b(n,t,i,e)}}, i.prototype.parseBackgroundClip=function(t,e,n,r,i){var o=[];switch(t.css("backgroundClip")){case"content-box":case"padding-box":A(o,r[0],r[1],e.topLeftInner,e.topRightInner,i.left+n[3].width,i.top+n[0].width), A(o,r[1],r[2],e.topRightInner,e.bottomRightInner,i.left+i.width-n[1].width,i.top+n[0].width), A(o,r[2],r[3],e.bottomRightInner,e.bottomLeftInner,i.left+i.width-n[1].width,i.top+i.height-n[2].width), A(o,r[3],r[0],e.bottomLeftInner,e.topLeftInner,i.left+n[3].width,i.top+i.height-n[2].width);break;default:A(o,r[0],r[1],e.topLeftOuter,e.topRightOuter,i.left,i.top), A(o,r[1],r[2],e.topRightOuter,e.bottomRightOuter,i.left+i.width,i.top), A(o,r[2],r[3],e.bottomRightOuter,e.bottomLeftOuter,i.left+i.width,i.top+i.height), A(o,r[3],r[0],e.bottomLeftOuter,e.topLeftOuter,i.left,i.top+i.height);}return o}, e.exports=i;},{"./color":3,"./fontmetrics":7,"./log":13,"./nodecontainer":14,"./pseudoelementcontainer":18,"./stackingcontext":21,"./textcontainer":25,"./utils":26,punycode:1}],16:[function(t,e,n){var a=t("./xhr"),r=t("./utils"),s=t("./log"),h=t("./clone"),c=r.decode64;function l(t,e,n){var r="withCredentials"in new XMLHttpRequest;if(!e)return Promise.reject("No proxy configured");var i=f(r),o=d(e,t,i);return r?a(o):u(n,o,i).then(function(t){return c(t.content)})}var i=0;function u(i,o,a){return new Promise(function(e,n){var t=i.createElement("script"),r=function(){delete window.html2canvas.proxy[a], i.body.removeChild(t);};window.html2canvas.proxy[a]=function(t){r(), e(t);}, t.src=o, t.onerror=function(t){r(), n(t);}, i.body.appendChild(t);})}function f(t){return t?"":"html2canvas_"+Date.now()+"_"+ ++i+"_"+Math.round(1e5*Math.random())}function d(t,e,n){return t+"?url="+encodeURIComponent(e)+(n.length?"&callback=html2canvas.proxy."+n:"")}n.Proxy=l, n.ProxyURL=function(t,e,n){var r="crossOrigin"in new Image,i=f(r),o=d(e,t,i);return r?Promise.resolve(o):u(n,o,i).then(function(t){return"data:"+t.type+";base64,"+t.content})}, n.loadUrlDocument=function(t,e,n,r,i,o){return new l(t,e,window.document).then((a=t, function(e){var n,t=new DOMParser;try{n=t.parseFromString(e,"text/html");}catch(t){s("DOMParser not supported, falling back to createHTMLDocument"), n=document.implementation.createHTMLDocument("");try{n.open(), n.write(e), n.close();}catch(t){s("createHTMLDocument write not supported, falling back to document.body.innerHTML"), n.body.innerHTML=e;}}var r=n.querySelector("base");if(!r||!r.href.host){var i=n.createElement("base");i.href=a, n.head.insertBefore(i,n.head.firstChild);}return n})).then(function(t){return h(t,n,r,i,o,0,0)});var a;};},{"./clone":2,"./log":13,"./utils":26,"./xhr":28}],17:[function(t,e,n){var o=t("./proxy").ProxyURL;e.exports=function(n,r){var t=document.createElement("a");t.href=n, n=t.href, this.src=n, this.image=new Image;var i=this;this.promise=new Promise(function(t,e){i.image.crossOrigin="Anonymous", i.image.onload=t, i.image.onerror=e, new o(n,r,document).then(function(t){i.image.src=t;}).catch(e);});};},{"./proxy":16}],18:[function(t,e,n){var r=t("./nodecontainer");function i(t,e,n){r.call(this,t,e), this.isPseudoElement=!0, this.before=":before"===n;}i.prototype.cloneTo=function(t){i.prototype.cloneTo.call(this,t), t.isPseudoElement=!0, t.before=this.before;}, (i.prototype=Object.create(r.prototype)).appendToDOM=function(){this.before?this.parent.node.insertBefore(this.node,this.parent.node.firstChild):this.parent.node.appendChild(this.node), this.parent.node.className+=" "+this.getHideClass();}, i.prototype.cleanDOM=function(){this.node.parentNode.removeChild(this.node), this.parent.node.className=this.parent.node.className.replace(this.getHideClass(),"");}, i.prototype.getHideClass=function(){return this["PSEUDO_HIDE_ELEMENT_CLASS_"+(this.before?"BEFORE":"AFTER")]}, i.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE="___html2canvas___pseudoelement_before", i.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER="___html2canvas___pseudoelement_after", e.exports=i;},{"./nodecontainer":14}],19:[function(t,e,n){var h=t("./log");function r(t,e,n,r,i){this.width=t, this.height=e, this.images=n, this.options=r, this.document=i;}r.prototype.renderImage=function(t,e,n,r){var i=t.cssInt("paddingLeft"),o=t.cssInt("paddingTop"),a=t.cssInt("paddingRight"),s=t.cssInt("paddingBottom"),h=n.borders,c=e.width-(h[1].width+h[3].width+i+a),l=e.height-(h[0].width+h[2].width+o+s);this.drawImage(r,0,0,r.image.width||c,r.image.height||l,e.left+i+h[3].width,e.top+o+h[0].width,c,l);}
29810, r.prototype.renderBackground=function(t,e,n){0<e.height&&0<e.width&&(this.renderBackgroundColor(t,e), this.renderBackgroundImage(t,e,n));}, r.prototype.renderBackgroundColor=function(t,e){var n=t.color("backgroundColor");n.isTransparent()||this.rectangle(e.left,e.top,e.width,e.height,n);}, r.prototype.renderBorders=function(t){t.forEach(this.renderBorder,this);}, r.prototype.renderBorder=function(t){t.color.isTransparent()||null===t.args||this.drawShape(t.args,t.color);}, r.prototype.renderBackgroundImage=function(o,a,s){o.parseBackgroundImages().reverse().forEach(function(t,e,n){switch(t.method){case"url":var r=this.images.get(t.args[0]);r?this.renderBackgroundRepeating(o,a,r,n.length-(e+1),s):h("Error loading background-image",t.args[0]);break;case"linear-gradient":case"gradient":var i=this.images.get(t.value);i?this.renderBackgroundGradient(i,a,s):h("Error loading background-image",t.args[0]);break;case"none":break;default:h("Unknown background-image type",t.args[0]);}},this);}, r.prototype.renderBackgroundRepeating=function(t,e,n,r,i){var o=t.parseBackgroundSize(e,n.image,r),a=t.parseBackgroundPosition(e,n.image,r,o);switch(t.parseBackgroundRepeat(r)){case"repeat-x":case"repeat no-repeat":this.backgroundRepeatShape(n,a,o,e,e.left+i[3],e.top+a.top+i[0],99999,o.height,i);break;case"repeat-y":case"no-repeat repeat":this.backgroundRepeatShape(n,a,o,e,e.left+a.left+i[3],e.top+i[0],o.width,99999,i);break;case"no-repeat":this.backgroundRepeatShape(n,a,o,e,e.left+a.left+i[3],e.top+a.top+i[0],o.width,o.height,i);break;default:this.renderBackgroundRepeat(n,a,o,{top:e.top,left:e.left},i[3],i[0]);}}, e.exports=r;},{"./log":13}],20:[function(t,e,n){var r=t("../renderer"),i=t("../lineargradientcontainer"),o=t("../log");function a(t,e){r.apply(this,arguments), this.canvas=this.options.canvas||this.document.createElement("canvas"), this.options.canvas||(this.canvas.width=t, this.canvas.height=e), this.ctx=this.canvas.getContext("2d"), this.taintCtx=this.document.createElement("canvas").getContext("2d"), this.ctx.textBaseline="bottom", this.variables={}, o("Initialized CanvasRenderer with size",t,"x",e);}function s(t){return 0<t.length}(a.prototype=Object.create(r.prototype)).setFillStyle=function(t){return this.ctx.fillStyle="object"==typeof t&&t.isColor?t.toString():t, this.ctx}, a.prototype.rectangle=function(t,e,n,r,i){this.setFillStyle(i).fillRect(t,e,n,r);}, a.prototype.circle=function(t,e,n,r){this.setFillStyle(r), this.ctx.beginPath(), this.ctx.arc(t+n/2,e+n/2,n/2,0,2*Math.PI,!0), this.ctx.closePath(), this.ctx.fill();}, a.prototype.circleStroke=function(t,e,n,r,i,o){this.circle(t,e,n,r), this.ctx.strokeStyle=o.toString(), this.ctx.stroke();}, a.prototype.drawShape=function(t,e){this.shape(t), this.setFillStyle(e).fill();}, a.prototype.taints=function(e){if(null===e.tainted){this.taintCtx.drawImage(e.image,0,0);try{this.taintCtx.getImageData(0,0,1,1), e.tainted=!1;}catch(t){this.taintCtx=document.createElement("canvas").getContext("2d"), e.tainted=!0;}}return e.tainted}, a.prototype.drawImage=function(t,e,n,r,i,o,a,s,h){this.taints(t)&&!this.options.allowTaint||this.ctx.drawImage(t.image,e,n,r,i,o,a,s,h);}, a.prototype.clip=function(t,e,n){this.ctx.save(), t.filter(s).forEach(function(t){this.shape(t).clip();},this), e.call(n), this.ctx.restore();}, a.prototype.shape=function(t){return this.ctx.beginPath(), t.forEach(function(t,e){"rect"===t[0]?this.ctx.rect.apply(this.ctx,t.slice(1)):this.ctx[0===e?"moveTo":t[0]+"To"].apply(this.ctx,t.slice(1));},this), this.ctx.closePath(), this.ctx}, a.prototype.font=function(t,e,n,r,i,o){this.setFillStyle(t).font=[e,n,r,i,o].join(" ").split(",")[0];}, a.prototype.fontShadow=function(t,e,n,r){this.setVariable("shadowColor",t.toString()).setVariable("shadowOffsetY",e).setVariable("shadowOffsetX",n).setVariable("shadowBlur",r);}, a.prototype.clearShadow=function(){this.setVariable("shadowColor","rgba(0,0,0,0)");}, a.prototype.setOpacity=function(t){this.ctx.globalAlpha=t;}, a.prototype.setTransform=function(t){this.ctx.translate(t.origin[0],t.origin[1]), this.ctx.transform.apply(this.ctx,t.matrix), this.ctx.translate(-t.origin[0],-t.origin[1]);}, a.prototype.setVariable=function(t,e){return this.variables[t]!==e&&(this.variables[t]=this.ctx[t]=e), this}, a.prototype.text=function(t,e,n){this.ctx.fillText(t,e,n);}, a.prototype.backgroundRepeatShape=function(t,e,n,r,i,o,a,s,h){var c=[["line",Math.round(i),Math.round(o)],["line",Math.round(i+a),Math.round(o)],["line",Math.round(i+a),Math.round(s+o)],["line",Math.round(i),Math.round(s+o)]];
29810this.clip([c],function(){this.renderBackgroundRepeat(t,e,n,r,h[3],h[0]);},this);}, a.prototype.renderBackgroundRepeat=function(t,e,n,r,i,o){var a=Math.round(r.left+e.left+i),s=Math.round(r.top+e.top+o);this.setFillStyle(this.ctx.createPattern(this.resizeImage(t,n),"repeat")), this.ctx.translate(a,s), this.ctx.fill(), this.ctx.translate(-a,-s);}, a.prototype.renderBackgroundGradient=function(t,e){if(t instanceof i){var n=this.ctx.createLinearGradient(e.left+e.width*t.x0,e.top+e.height*t.y0,e.left+e.width*t.x1,e.top+e.height*t.y1);t.colorStops.forEach(function(t){n.addColorStop(t.stop,t.color.toString());}), this.rectangle(e.left,e.top,e.width,e.height,n);}}, a.prototype.resizeImage=function(t,e){var n=t.image;if(n.width===e.width&&n.height===e.height)return n;var r=document.createElement("canvas");return r.width=e.width, r.height=e.height, r.getContext("2d").drawImage(n,0,0,n.width,n.height,0,0,e.width,e.height), r}, e.exports=a;},{"../lineargradientcontainer":12,"../log":13,"../renderer":19}],21:[function(t,e,n){var i=t("./nodecontainer");function r(t,e,n,r){i.call(this,n,r), this.ownStacking=t, this.contexts=[], this.children=[], this.opacity=(this.parent?this.parent.stack.opacity:1)*e;}(r.prototype=Object.create(i.prototype)).getParentStack=function(t){var e=this.parent?this.parent.stack:null;return e?e.ownStacking?e:e.getParentStack(t):t.stack}, e.exports=r;},{"./nodecontainer":14}],22:[function(t,e,n){function r(t){this.rangeBounds=this.testRangeBounds(t), this.cors=this.testCORS(), this.svg=this.testSVG();}r.prototype.testRangeBounds=function(t){var e,n,r=!1;return t.createRange&&(e=t.createRange()).getBoundingClientRect&&((n=t.createElement("boundtest")).style.height="123px", n.style.display="block", t.body.appendChild(n), e.selectNode(n), 123===e.getBoundingClientRect().height&&(r=!0), t.body.removeChild(n)), r}, r.prototype.testCORS=function(){return void 0!==(new Image).crossOrigin}, r.prototype.testSVG=function(){var t=new Image,e=document.createElement("canvas"),n=e.getContext("2d");t.src="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";try{n.drawImage(t,0,0), e.toDataURL();}catch(t){return!1}return!0}, e.exports=r;},{}],23:[function(t,e,n){var r=t("./xhr"),i=t("./utils").decode64;function o(t){this.src=t, this.image=null;var n=this;this.promise=this.hasFabric().then(function(){return n.isInline(t)?Promise.resolve(n.inlineFormatting(t)):r(t)}).then(function(e){return new Promise(function(t){window.html2canvas.svg.fabric.loadSVGFromString(e,n.createCanvas.call(n,t));})});}o.prototype.hasFabric=function(){return window.html2canvas.svg&&window.html2canvas.svg.fabric?Promise.resolve():Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg"))}, o.prototype.inlineFormatting=function(t){return/^data:image\/svg\+xml;base64,/.test(t)?this.decode64(this.removeContentType(t)):this.removeContentType(t)}, o.prototype.removeContentType=function(t){return t.replace(/^data:image\/svg\+xml(;base64)?,/,"")}, o.prototype.isInline=function(t){return/^data:image\/svg\+xml/i.test(t)}, o.prototype.createCanvas=function(r){var i=this;return function(t,e){var n=new window.html2canvas.svg.fabric.StaticCanvas("c");i.image=n.lowerCanvasEl, n.setWidth(e.width).setHeight(e.height).add(window.html2canvas.svg.fabric.util.groupSVGElements(t,e)).renderAll(), r(n.lowerCanvasEl);}}, o.prototype.decode64=function(t){return"function"==typeof window.atob?window.atob(t):i(t)}, e.exports=o;},{"./utils":26,"./xhr":28}],24:[function(t,e,n){var r=t("./svgcontainer");function i(n,t){this.src=n, this.image=null;var r=this;this.promise=t?new Promise(function(t,e){r.image=new Image, r.image.onload=t, r.image.onerror=e, r.image.src="data:image/svg+xml,"+(new XMLSerializer).serializeToString(n), !0===r.image.complete&&t(r.image);}):this.hasFabric().then(function(){return new Promise(function(t){window.html2canvas.svg.fabric.parseSVGDocument(n,r.createCanvas.call(r,t));})});}i.prototype=Object.create(r.prototype), e.exports=i;},{"./svgcontainer":23}],25:[function(t,e,n){var r=t("./nodecontainer");function i(t,e){r.call(this,t,e);}function o(t,e,n){if(0<t.length)return e+n.toUpperCase()}(i.prototype=Object.create(r.prototype)).applyTextTransform=function(){this.node.data=this.transform(this.parent.css("textTransform"));}, i.prototype.transform=function(t){var e=this.node.data;switch(t){case"lowercase":return e.toLowerCase();case"capitalize":return e.replace(/(^|\s|:|-|\(|\))([a-z])/g,o);case"uppercase":return e.toUpperCase();default:return e}}, e.exports=i;},{"./nodecontainer":14}],26:[function(t,e,n){n.smallImage=function(){return"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"}, n.bind=function(t,e){return function(){return t.apply(e,arguments)}}, n.decode64=function(t){var e,n,r,i,o,a,s,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
29810+/",c=t.length,l="";for(e=0;e<c;e+=4)o=h.indexOf(t[e])<<2|(n=h.indexOf(t[e+1]))>>4, a=(15&n)<<4|(r=h.indexOf(t[e+2]))>>2, s=(3&r)<<6|(i=h.indexOf(t[e+3])), l+=64===r?String.fromCharCode(o):64===i||-1===i?String.fromCharCode(o,a):String.fromCharCode(o,a,s);return l}, n.getBounds=function(t){if(t.getBoundingClientRect){var e=t.getBoundingClientRect(),n=null==t.offsetWidth?e.width:t.offsetWidth;return{top:e.top,bottom:e.bottom||e.top+e.height,right:e.left+n,left:e.left,width:n,height:null==t.offsetHeight?e.height:t.offsetHeight}}return{}}, n.offsetBounds=function(t){var e=t.offsetParent?n.offsetBounds(t.offsetParent):{top:0,left:0};return{top:t.offsetTop+e.top,bottom:t.offsetTop+t.offsetHeight+e.top,right:t.offsetLeft+e.left+t.offsetWidth,left:t.offsetLeft+e.left,width:t.offsetWidth,height:t.offsetHeight}}, n.parseBackgrounds=function(t){var e,n,r,i,o,a,s,h=[],c=0,l=0,u=function(){e&&('"'===n.substr(0,1)&&(n=n.substr(1,n.length-2)), n&&s.push(n), "-"===e.substr(0,1)&&0<(i=e.indexOf("-",1)+1)&&(r=e.substr(0,i), e=e.substr(i)), h.push({prefix:r,method:e.toLowerCase(),value:o,args:s,image:null})), s=[], e=r=n=o="";};return s=[], e=r=n=o="", t.split("").forEach(function(t){if(!(0===c&&-1<" \r\n\t".indexOf(t))){switch(t){case'"':a?a===t&&(a=null):a=t;break;case"(":if(a)break;if(0===c)return c=1, void(o+=t);l++;break;case")":if(a)break;if(1===c){if(0===l)return c=0, o+=t, void u();l--;}break;case",":if(a)break;if(0===c)return void u();if(1===c&&0===l&&!e.match(/^url$/i))return s.push(n), n="", void(o+=t)}o+=t, 0===c?e+=t:n+=t;}}), u(), h};},{}],27:[function(t,e,n){var r=t("./gradientcontainer");function i(t){r.apply(this,arguments), this.type="linear"===t.args[0]?r.TYPES.LINEAR:r.TYPES.RADIAL;}i.prototype=Object.create(r.prototype), e.exports=i;},{"./gradientcontainer":9}],28:[function(t,e,n){e.exports=function(r){return new Promise(function(t,e){var n=new XMLHttpRequest;n.open("GET",r), n.onload=function(){200===n.status?t(n.responseText):e(new Error(n.statusText));}, n.onerror=function(){e(new Error("Network Error"));}, n.send();})};},{}]},{},[4])(4)}), function(t){var n="+".charCodeAt(0),r="/".charCodeAt(0),i="0".charCodeAt(0),o="a".charCodeAt(0),a="A".charCodeAt(0),s="-".charCodeAt(0),h="_".charCodeAt(0),l=function(t){var e=t.charCodeAt(0);return e===n||e===s?62:e===r||e===h?63:e<i?-1:e<i+10?e-i+26+26:e<a+26?e-a:e<o+26?e-o+26:void 0};t.API.TTFFont=function(){function i(t,e,n){var r;if(this.rawData=t, r=this.contents=new X(t), this.contents.pos=4, "ttcf"===r.readString(4)){if(!e)throw new Error("Mu
29810st specify a font name for TTC files.");throw new Error("Font "+e+" not found in TTC file.")}r.pos=0, this.parse(), this.subset=new T(this), this.registerTTF();}return i.open=function(t,e,n,r){return new i(function(t){var e,n,r,i,o,a;if(0<t.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var s=t.length;o="="===t.charAt(s-2)?2:"="===t.charAt(s-1)?1:0, a=new Uint8Array(3*t.length/4-o), r=0<o?t.length-4:t.length;var h=0;function c(t){a[h++]=t;}for(n=e=0;e<r;e+=4, n+=3)c((16711680&(i=l(t.charAt(e))<<18|l(t.charAt(e+1))<<12|l(t.charAt(e+2))<<6|l(t.charAt(e+3))))>>16), c((65280&i)>>8), c(255&i);return 2===o?c(255&(i=l(t.charAt(e))<<2|l(t.charAt(e+1))>>4)):1===o&&(c((i=l(t.charAt(e))<<10|l(t.charAt(e+1))<<4|l(t.charAt(e+2))>>2)>>8&255), c(255&i)), a}(n),e,r)}, i.prototype.parse=function(){return this.directory=new e(this.contents), this.head=new d(this), this.name=new b(this), this.cmap=new m(this), this.hhea=new g(this), this.maxp=new x(this), this.hmtx=new S(this), this.post=new y(this), this.os2=new w(this), this.loca=new C(this), this.glyf=new _(this), this.ascender=this.os2.exists&&this.os2.ascender||this.hhea.ascender, this.decender=this.os2.exists&&this.os2.decender||this.hhea.decender, this.lineGap=this.os2.exists&&this.os2.lineGap||this.hhea.lineGap, this.bbox=[this.head.xMin,this.head.yMin,this.head.xMax,this.head.yMax]}, i.prototype.registerTTF=function(){var i,t,e,n,r;if(this.scaleFactor=1e3/this.head.unitsPerEm, this.bbox=function(){var t,e,n,r;for(r=[], t=0, e=(n=this.bbox).length;t<e;t++)i=n[t], r.push(Math.round(i*this.scaleFactor));return r}.call(this), this.stemV=0, this.post.exists?(e=255&(n=this.post.italic_angle), !0&(t=n>>16)&&(t=-(1+(65535^t))), this.italicAngle=+(t+"."+e)):this.italicAngle=0, this.ascender=Math.round(this.ascender*this.scaleFactor), this.decender=Math.round(this.decender*this.scaleFactor), this.lineGap=Math.round(this.lineGap*this.scaleFactor), this.capHeight=this.os2.exists&&this.os2.capHeight||this.ascender, this.xHeight=this.os2.exists&&this.os2.xHeight||0, this.familyClass=(this.os2.exists&&this.os2.familyClass||0)>>8, this.isSerif=1===(r=this.familyClass)||2===r||3===r||4===r||5===r||7===r, this.isScript=10===this.familyClass, this.flags=0, this.post.isFixedPitch&&(this.flags|=1), this.isSerif&&(this.flags|=2), this.isScript&&(this.flags|=8), 0!==this.italicAngle&&(this.flags|=64), this.flags|=32, !this.cmap.unicode)throw new Error("No unicode cmap for font")}, i.prototype.characterToGlyph=function(t){var e;return(null!=(e=this.cmap.unicode)?e.codeMap[t]:void 0)||0}, i.prototype.widthOfGlyph=function(t){var e;return e=1e3/this.head.unitsPerEm, this.hmtx.forGlyph(t).advance*e}, i.prototype.widthOfString=function(t,e,n){var r,i,o,a,s;for(i=a=o=0, s=(t=""+t).length;0<=s?a<s:s<a;i=0<=s?++a:--a)r=t.charCodeAt(i), o+=this.widthOfGlyph(this.characterToGlyph(r))+n*(1e3/e)||0;return o*(e/1e3)}, i.prototype.lineHeight=function(t,e){var n;return null==e&&(e=!1), n=e?this.lineGap:0, (this.ascender+n-this.decender)/1e3*t}, i}();var c,X=function(){function t(t){this.data=null!=t?t:[], this.pos=0, this.length=this.data.length;}return t.prototype.readByte=function(){return this.data[this.pos++]}, t.prototype.writeByte=function(t){return this.data[this.pos++]=t}, t.prototype.readUInt32=function(){return 16777216*this.readByte()+(this.readByte()<<16)+(this.readByte()<<8)+this.readByte()}, t.prototype.writeUInt32=function(t){return this.writeByte(t>>>24&255), this.writeByte(t>>16&255), this.writeByte(t>>8&255), this.writeByte(255&t)}, t.prototype.readInt32=function(){var t;return 2147483648<=(t=this.readUInt32())?t-4294967296:t}, t.prototype.writeInt32=function(t){return t<0&&(t+=4294967296), this.writeUInt32(t)}, t.prototype.readUInt16=function(){return this.readByte()<<8|this.readByte()}, t.prototype.writeUInt16=function(t){return this.writeByte(t>>8&255), this.writeByte(255&t)}, t.prototype.readInt16=function(){var t;return 32768<=(t=this.readUInt16())?t-65536:t}, t.prototype.writeInt16=function(t){return t<0&&(t+=65536), this.writeUInt16(t)}, t.prototype.readString=function(t){var e,n,r;for(n=[], e=r=0;0<=t?r<t:t<r;e=0<=t?++r:--r)n[e]=String.fromCharCode(this.readByte());return n.join("")}, t.prototype.writeString=function(t){var e,n,r,i;for(i=[], e=n=0, r=t.length;0<=r?n<r:r<n;e=0<=r?++n:--n)i.push(this.writeByte(t.charCodeAt(e)));return i}, t.prototype.readShort=function(){return this.readInt16()}, t.prototype.writeShort=function(t){return this.writeInt16(t)}, t.prototype.readLongLong=function(){var t,e,n,r,i,o,a,s;return t=this.readByte(), e=this.readByte(), n=this.readByte(), r=this.readByte(), i=this.readByte(), o=this.readByte(), a=this.readByte(), s=this.readByte(), 128&t?-1*(72057594037927940*(255^t)+281474976710656*(255^e)+1099511627776*(255^n)+4294967296*(255^r)+16777216*(255^i)+65536*(255^o)+256*(255^a)+(255^s)+1):72057594037927940*t+281474976710656*e+1099511627776*n+4294967296*r+16777216*i+65536*o+256*a+s}, t.prototype.readInt=function(){return this.readInt32()}, t.prototype.writeInt=function(t){return this.writeInt32(t)}, t.prototype.read=function(t){var e,n;for(e=[], n=0;0<=t?n<t:t<n;0<=t?++n:--n)e.push(this.readByte());return e}, t.prototype.write=function(t){var e,n,r,i;for(i=[], n=0, r=t.length;n<r;n++)e=t[n], i.push(this.writeByte(e));return i}, t}(),e=function(){var p;function t(t){var e,n,r;for(this.scalarType=t.readInt(), this.tableCount=t.readShort(), this.searchRange=t.readShort(), this.entrySelector=t.readShort(), this.rangeShift=t.readShort(), this.tables={}, n=0, r=this.tableCount;0<=r?n<r:r<n;0<=r?++n:--n)e={tag:t.readString(4),checksum:t.readInt(),offset:t.readInt(),length:t.readInt()}, this.tables[e.tag]=e;}return t.prototype.encode=function(t){var e,n,r,i,o,a,s,h,c,l,u,f,d;for(d in u=Object.keys(t).length, a=Math.log(2), c=16*Math.floor(Math.log(u)/a), i=Math.floor(c/a), h=16*u-c, (n=new X).writeInt(this.scalarType), n.writeShort(u), n.writeShort(c), n.writeShort(i), n.writeShort(h), r=16*u, s=n.pos+r, o=null, f=[], t)for(l=t[d], n.writeString(d), n.writeInt(p(l)), n.writeInt(s), n.writeInt(l.length), f=f.concat(l), "head"===d&&(o=s), s+=l.length;s%4;)f.push(0), s++;return n.write(f), e=2981146554-p(n.data), n.pos=o+8, n.writeUInt32(e), n.data}, p=function(t){var e,n,r,i;for(t=k.call(t);t.length%4;)t.push(0);for(n=new X(t), r=e=0, i=t.length;r<i;r+=4)e+=n.readUInt32();return 4294967295&e}, t}(),u={}.hasOwnProperty,f=function(t,e){for(var n in e)u.call(e,n)&&(t[n]=e[n]);function r(){this.constructor=t;}return r.prototype=e.prototype, t.prototype=new r, t.__super__=e.prototype, t};c=function(){function t(t){var e;this.file=t, e=this.file.directory.tables[this.tag], this.exists=!!e, e&&(this.offset=e.offset, this.length=e.length, this.parse(this.file.contents));}return t.prototype.parse=function(){}, t.prototype.encode=function(){}, t.prototype.raw=function(){return this.exists?(this.file.contents.pos=this.offset, this.file.contents.read(this.length)):null}, t}();var d=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return f(e,c), e.prototype.tag="head", e.prototype.parse=function(t){return t.pos=this.offset, this.version=t.readInt(), this.revision=t.readInt(), this.checkSumAdjustment=t.readInt(), this.magicNumber=t.readInt(), this.flags=t.readShort(), this.unitsPerEm=t.readShort(), this.created=t.readLongLong(), this.modified=t.readLongLong(), this.xMin=t.readShort(), this.yMin=t.readShort(), this.xMax=t.readShort(), this.yMax=t.readShort(), this.macStyle=t.readShort(), this.lowestRecPPEM=t.readShort(), this.fontDirectionHint=t.readShort(), this.indexToLocFormat=t.readShort(), this.glyphDataFormat=t.readShort()}, e}(),p=function(){function t(n,t){var e,r,i,o,a,s,h,c,l,u,f,d,p,g,m,w,y,v;switch(this.platformID=n.readUInt16(), this.encodingID=n.readShort(), this.offset=t+n.readInt(), l=n.pos, n.pos=this.offset, this.format=n.readUInt16(), this.length=n.readUInt16(), this.language=n.readUInt16(), this.isUnicode=3===this.platformID&&1===this.encodingID&&4===this.format||0===this.platformID&&4===this.format, this.codeMap={}, this.format){case 0:for(s=m=0;m<256;s=++m)this.codeMap[s]=n.readByte();break;case 4:for(f=n.readUInt16(), u=f/2, n.pos+=6, i=function(){var t,e;for(e=[], s=t=0;0<=u?t<u:u<t;s=0<=u?++t:--t)e.push(n.readUInt16());return e}(), n.pos+=2, p=function(){var t,e;for(e=[], s=t=0;0<=u?t<u:u<t;s=0<=u?++t:--t)e.push(n.readUInt16());return e}(), h=function(){var t,e;for(e=[], s=t=0;0<=u?t<u:u<t;s=0<=u?++t:--t)e.push(n.readUInt16());return e}(), c=function(){var t,e;for(e=[], s=t=0;0<=u?t<u:u<t;s=0<=u?++t:--t)e.push(n.readUInt16());return e}(), r=(this.length-n.pos+this.offset)/2, a=function(){var t,e;for(e=[], s=t=0;0<=r?t<r:r<t;s=0<=r?++t:--t)e.push(n.readUInt16());return e}(), s=w=0, v=i.length;w<v;s=++w)for(g=i[s], e=y=d=p[s];d<=g?y<=g:g<=y;e=d<=g?++y:--y)0===c[s]?o=e+h[s]:0!==(o=a[c[s]/2+(e-d)-(u-s)]||0)&&(o+=h[s]), this.codeMap[e]=65535&o;}n.pos=l;}return t.encode=function(t,e){var n,r,i,o,a,s,h,c,l,u,f,d,p,g,m,w,y,v,b,x,S,k,_,A,I,C,T,F,P,E,q,O,B,R,j,D,M,U,N,z,L,H,W,G,V,Y;switch(F=new X, o=Object.keys(t).sort(function(t,e){return t-e}), e){case"macroman":for(p=0, g=function(){var t,e;for(e=[], d=t=0;t<256;d=++t)e.push(0);return e}(), w={0:0}, i={}, P=0, B=o.length;P<B;P++)null==w[W=t[r=o[P]]]&&(w[W]=++p), i[r]={old:t[r],new:w[t[r]]}, g[r]=w[t[r]];return F.writeUInt16(1), F.writeUInt16(0), F.writeUInt32(12), F.writeUInt16(0), F.writeUInt16(262), F.writeUInt16(0), F.write(g), {charMap:i,subtable:F.data,maxGlyphID:p+1};case"unicode":for(C=[], l=[], w={}, n={}, m=h=null, E=y=0, R=o.length;E<R;E++)null==w[b=t[r=o[E]]]&&(w[b]=++y), n[r]={old:b,new:w[b]}, a=w[b]-r, null!=m&&a===h||(m&&l.push(m), C.push(r), h=a), m=r;
29810for(m&&l.push(m), l.push(65535), C.push(65535), A=2*(_=C.length), k=2*Math.pow(Math.log(_)/Math.LN2,2), u=Math.log(k/2)/Math.LN2, S=2*_-k, s=[], x=[], f=[], d=q=0, j=C.length;q<j;d=++q){if(I=C[d], c=l[d], 65535===I){s.push(0), x.push(0);break}if(32768<=I-(T=n[I].new))for(s.push(0), x.push(2*(f.length+_-d)), r=O=I;I<=c?O<=c:c<=O;r=I<=c?++O:--O)f.push(n[r].new);else s.push(T-I), x.push(0);}for(F.writeUInt16(3), F.writeUInt16(1), F.writeUInt32(12), F.writeUInt16(4), F.writeUInt16(16+8*_+2*f.length), F.writeUInt16(0), F.writeUInt16(A), F.writeUInt16(k), F.writeUInt16(u), F.writeUInt16(S), L=0, D=l.length;L<D;L++)r=l[L], F.writeUInt16(r);for(F.writeUInt16(0), H=0, M=C.length;H<M;H++)r=C[H], F.writeUInt16(r);for(G=0, U=s.length;G<U;G++)a=s[G], F.writeUInt16(a);for(V=0, N=x.length;V<N;V++)v=x[V], F.writeUInt16(v);for(Y=0, z=f.length;Y<z;Y++)p=f[Y], F.writeUInt16(p);return{charMap:n,subtable:F.data,maxGlyphID:y+1}}}, t}(),m=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return f(e,c), e.prototype.tag="cmap", e.prototype.parse=function(t){var e,n,r;for(t.pos=this.offset, this.version=t.readUInt16(), n=t.readUInt16(), this.tables=[], this.unicode=null, r=0;0<=n?r<n:n<r;0<=n?++r:--r)e=new p(t,this.offset), this.tables.push(e), e.isUnicode&&null==this.unicode&&(this.unicode=e);return!0}, e.encode=function(t,e){var n,r;return null==e&&(e="macroman"), n=p.encode(t,e), (r=new X).writeUInt16(0), r.writeUInt16(1), n.table=r.data.concat(n.subtable), n}, e}(),g=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return f(e,c), e.prototype.tag="hhea", e.prototype.parse=function(t){return t.pos=this.offset, this.version=t.readInt(), this.ascender=t.readShort(), this.decender=t.readShort(), this.lineGap=t.readShort(), this.advanceWidthMax=t.readShort(), this.minLeftSideBearing=t.readShort(), this.minRightSideBearing=t.readShort(), this.xMaxExtent=t.readShort(), this.caretSlopeRise=t.readShort(), this.caretSlopeRun=t.readShort(), this.caretOffset=t.readShort(), t.pos+=8, this.metricDataFormat=t.readShort(), this.numberOfMetrics=t.readUInt16()}, e}(),w=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return f(e,c), e.prototype.tag="OS/2", e.prototype.parse=function(n){if(n.pos=this.offset, this.version=n.readUInt16(), this.averageCharWidth=n.readShort(), this.weightClass=n.readUInt16(), this.widthClass=n.readUInt16(), this.type=n.readShort(), this.ySubscriptXSize=n.readShort(), this.ySubscriptYSize=n.readShort(), this.ySubscriptXOffset=n.readShort(), this.ySubscriptYOffset=n.readShort(), this.ySuperscriptXSize=n.readShort(), this.ySuperscriptYSize=n.readShort(), this.ySuperscriptXOffset=n.readShort(), this.ySuperscriptYOffset=n.readShort(), this.yStrikeoutSize=n.readShort(), this.yStrikeoutPosition=n.readShort(), this.familyClass=n.readShort(), this.panose=function(){var t,e;for(e=[], t=0;t<10;++t)e.push(n.readByte());return e}(), this.charRange=function(){var t,e;for(e=[], t=0;t<4;++t)e.push(n.readInt());return e}(), this.vendorID=n.readString(4), this.selection=n.readShort(), this.firstCharIndex=n.readShort(), this.lastCharIndex=n.readShort(), 0<this.version&&(this.ascent=n.readShort(), this.descent=n.readShort(), this.lineGap=n.readShort(), this.winAscent=n.readShort(), this.winDescent=n.readShort(), this.codePageRange=function(){var t,e;for(e=[], t=0;t<2;++t)e.push(n.readInt());return e}(), 1<this.version))return this.xHeight=n.readShort(), this.capHeight=n.readShort(), this.defaultChar=n.readShort(), this.breakChar=n.readShort(), this.maxContext=n.readShort()}, e}(),y=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return f(e,c), e.prototype.tag="post", e.prototype.parse=function(r){var t,e,n,i;switch(r.pos=this.offset, this.format=r.readInt(), this.italicAngle=r.readInt(), this.underlinePosition=r.readShort(), this.underlineThickness=r.readShort(), this.isFixedPitch=r.readInt(), this.minMemType42=r.readInt(), this.maxMemType42=r.readInt(), this.minMemType1=r.readInt(), this.maxMemType1=r.readInt(), this.format){case 65536:break;case 131072:for(e=r.readUInt16(), this.glyphNameIndex=[], n=0;0<=e?n<e:e<n;0<=e?++n:--n)this.glyphNameIndex.push(r.readUInt16());for(this.names=[], i=[];r.pos<this.offset+this.length;)t=r.readByte(), i.push(this.names.push(r.readString(t)));return i;case 151552:return e=r.readUInt16(), this.offsets=r.read(e);case 196608:break;case 262144:return this.map=function(){var t,e,n;for(n=[], t=0, e=this.file.maxp.numGlyphs;0<=e?t<e:e<t;0<=e?++t:--t)n.push(r.readUInt32());return n}.call(this)}}, e}(),v=function(t,e){this.raw=t, this.length=t.length, this.platformID=e.platformID, this.encodingID=e.encodingID, this.languageID=e.languageID;},b=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return f(e,c), e.prototype.tag="name", e.prototype.parse=function(t){var e,n,r,i,o,a,s,h,c,l,u,f;for(t.pos=this.offset, t.readShort(), e=t.readShort(), a=t.readShort(), n=[], i=c=0;0<=e?c<e:e<c;i=0<=e?++c:--c)n.push({platformID:t.readShort(),encodingID:t.readShort(),languageID:t.readShort(),nameID:t.readShort(),length:t.readShort(),offset:this.offset+a+t.readShort()});for(s={}, i=l=0, u=n.length;l<u;i=++l)r=n[i], t.pos=r.offset, h=t.readString(r.length), o=new v(h,r), null==s[f=r.nameID]&&(s[f]=[]), s[r.nameID].push(o);return this.strings=s, this.copyright=s[0], this.fontFamily=s[1], this.fontSubfam
29810ily=s[2], this.uniqueSubfamily=s[3], this.fontName=s[4], this.version=s[5], this.postscriptName=s[6][0].raw.replace(/[\x00-\x19\x80-\xff]/g,""), this.trademark=s[7], this.manufacturer=s[8], this.designer=s[9], this.description=s[10], this.vendorUrl=s[11], this.designerUrl=s[12], this.license=s[13], this.licenseUrl=s[14], this.preferredFamily=s[15], this.preferredSubfamily=s[17], this.compatibleFull=s[18], this.sampleText=s[19]}, e}(),x=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return f(e,c), e.prototype.tag="maxp", e.prototype.parse=function(t){return t.pos=this.offset, this.version=t.readInt(), this.numGlyphs=t.readUInt16(), this.maxPoints=t.readUInt16(), this.maxContours=t.readUInt16(), this.maxCompositePoints=t.readUInt16(), this.maxComponentContours=t.readUInt16(), this.maxZones=t.readUInt16(), this.maxTwilightPoints=t.readUInt16(), this.maxStorage=t.readUInt16(), this.maxFunctionDefs=t.readUInt16(), this.maxInstructionDefs=t.readUInt16(), this.maxStackElements=t.readUInt16(), this.maxSizeOfInstructions=t.readUInt16(), this.maxComponentElements=t.readUInt16(), this.maxComponentDepth=t.readUInt16()}, e}(),S=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return f(e,c), e.prototype.tag="hmtx", e.prototype.parse=function(n){var t,r,i,e,o,a,s;for(n.pos=this.offset, this.metrics=[], e=0, a=this.file.hhea.numberOfMetrics;0<=a?e<a:a<e;0<=a?++e:--e)this.metrics.push({advance:n.readUInt16(),lsb:n.readInt16()});for(r=this.file.maxp.numGlyphs-this.file.hhea.numberOfMetrics, this.leftSideBearings=function(){var t,e;for(e=[], t=0;0<=r?t<r:r<t;0<=r?++t:--t)e.push(n.readInt16());return e}(), this.widths=function(){var t,e,n,r;for(r=[], t=0, e=(n=this.metrics).length;t<e;t++)i=n[t], r.push(i.advance);return r}.call(this), t=this.widths[this.widths.length-1], s=[], o=0;0<=r?o<r:r<o;0<=r?++o:--o)s.push(this.widths.push(t));return s}, e.prototype.forGlyph=function(t){return t in this.metrics?this.metrics[t]:{advance:this.metrics[this.metrics.length-1].advance,lsb:this.leftSideBearings[t-this.metrics.length]}}, e}(),k=[].slice,_=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return f(e,c), e.prototype.tag="glyf", e.prototype.parse=function(t){return this.cache={}}, e.prototype.glyphFor=function(t){var e,n,r,i,o,a,s,h,c,l;return(t=t)in this.cache?this.cache[t]:(i=this.file.loca, e=this.file.contents, n=i.indexOf(t), 0===(r=i.lengthOf(t))?this.cache[t]=null:(e.pos=this.offset+n, o=(a=new X(e.read(r))).readShort(), h=a.readShort(), l=a.readShort(), s=a.readShort(), c=a.readShort(), this.cache[t]=-1===o?new I(a,h,l,s,c):new A(a,o,h,l,s,c), this.cache[t]))}, e.prototype.encode=function(t,e,n){var r,i,o,a,s;for(o=[], i=[], a=0, s=e.length;a<s;a++)r=t[e[a]], i.push(o.length), r&&(o=o.concat(r.encode(n)));return i.push(o.length), {table:o,offsets:i}}, e}(),A=function(){function t(t,e,n,r,i,o){this.raw=t, this.numberOfContours=e, this.xMin=n, this.yMin=r, this.xMax=i, this.yMax=o, this.compound=!1;}return t.prototype.encode=function(){return this.raw.data}, t}(),I=function(){function t(t,e,n,r,i){var o,a;for(this.raw=t, this.xMin=e, this.yMin=n, this.xMax=r, this.yMax=i, this.compound=!0, this.glyphIDs=[], this.glyphOffsets=[], o=this.raw;a=o.readShort(), this.glyphOffsets.push(o.pos), this.glyphIDs.push(o.readShort()), 32&a;)o.pos+=1&a?4:2, 128&a?o.pos+=8:64&a?o.pos+=4:8&a&&(o.pos+=2);}return t.prototype.encode=function(t){var e,n,r,i,o;for(n=new X(k.call(this.raw.data)), e=r=0, i=(o=this.glyphIDs).length;r<i;e=++r)o[e], n.pos=this.glyphOffsets[e];return n.data}, t}(),C=function(t){function e(){return e.__super__.constructor.apply(this,arguments)}return f(e,c), e.prototype.tag="loca", e.prototype.parse=function(r){var t;return r.pos=this.offset, t=this.file.head.indexToLocFormat, this.offsets=0===t?function(){var t,e,n;for(n=[], t=0, e=this.length;t<e;t+=2)n.push(2*r.readUInt16());return n}.call(this):function(){var t,e,n;for(n=[], t=0, e=this.length;t<e;t+=4)n.push(r.readUInt32());return n}.call(this)}, e.prototype.indexOf=function(t){return this.offsets[t]}, e.prototype.lengthOf=function(t){return this.offsets[t+1]-this.offsets[t]}, e.prototype.encode=function(t,e){for(var n=new Uint32Array(this.offsets.length),r=0,i=0,o=0;o<n.length;++o)if(n[o]=r, i<e.length&&e[i]==o){++i, n[o]=r;var a=this.offsets[o],s=this.offsets[o+1]-a;0<s&&(r+=s);}for(var h=new Array(4*n.length),c=0;c<n.length;
vendor: 4,528 bytes, line 29810
29810++c)h[4*c+3]=255&n[c], h[4*c+2]=(65280&n[c])>>8, h[4*c+1]=(16711680&n[c])>>16, h[4*c]=(4278190080&n[c])>>24;return h}, e}(),T=function(){function t(t){this.font=t, this.subset={}, this.unicodes={}, this.next=33;}return t.prototype.generateCmap=function(){var t,e,n,r,i;for(e in r=this.font.cmap.tables[0].codeMap, t={}, i=this.subset)n=i[e], t[e]=r[n];return t}, t.prototype.glyphsFor=function(t){var e,n,r,i,o,a,s;for(r={}, o=0, a=t.length;o<a;o++)r[i=t[o]]=this.font.glyf.glyphFor(i);for(i in e=[], r)(null!=(n=r[i])?n.compound:void 0)&&e.push.apply(e,n.glyphIDs);if(0<e.length)for(i in s=this.glyphsFor(e))n=s[i], r[i]=n;return r}, t.prototype.encode=function(t){var e,n,r,i,o,a,s,h,c,l,u,f,d,p,g;for(n in e=m.encode(this.generateCmap(),"unicode"), i=this.glyphsFor(t), u={0:0}, g=e.charMap)u[(a=g[n]).old]=a.new;for(f in l=e.maxGlyphID, i)f in u||(u[f]=l++);return h=function(t){var e,n;for(e in n={}, t)n[t[e]]=e;return n}(u), c=Object.keys(h).sort(function(t,e){return t-e}), d=function(){var t,e,n;for(n=[], t=0, e=c.length;t<e;t++)o=c[t], n.push(h[o]);return n}(), r=this.font.glyf.encode(i,d,u), s=this.font.loca.encode(r.offsets,d), p={cmap:this.font.cmap.raw(),glyf:r.table,loca:s,hmtx:this.font.hmtx.raw(),hhea:this.font.hhea.raw(),maxp:this.font.maxp.raw(),post:this.font.post.raw(),name:this.font.name.raw(),head:this.font.head.raw()}, this.font.os2.exists&&(p["OS/2"]=this.font.os2.raw()), this.font.directory.encode(p)}, t}();t.API.PDFObject=function(){var o;function a(){}return o=function(t,e){return(Array(e+1).join("0")+t).slice(-e)}, a.convert=function(r){var i,t,e,n;if(Array.isArray(r))return"["+function(){var t,e,n;for(n=[], t=0, e=r.length;t<e;t++)i=r[t], n.push(a.convert(i));return n}().join(" ")+"]";if("string"==typeof r)return"/"+r;if(null!=r?r.isString:void 0)return"("+r+")";if(r instanceof Date)return"(D:"+o(r.getUTCFullYear(),4)+o(r.getUTCMonth(),2)+o(r.getUTCDate(),2)+o(r.getUTCHours(),2)+o(r.getUTCMinutes(),2)+o(r.getUTCSeconds(),2)+"Z)";if("[object Object]"==={}.toString.call(r)){for(t in e=["<<"], r)n=r[t], e.push("/"+t+" "+a.convert(n));return e.push(">>"), e.join("\n")}return""+r}, a}();}($), pt="undefined"!=typeof self&&self||"undefined"!=typeof window&&window||"undefined"!=typeof commonjsGlobal&&commonjsGlobal||Function('return typeof this === "object" && this.content')()||Function("return this")(), gt=function(){var c,n,r;function i(t){var e,n,r,i,o,a,s,h,c,l,u,f,d,p;for(this.data=t, this.pos=8, this.palette=[], this.imgData=[], this.transparency={}, this.animation=null, this.text={}, a=null;;){switch(e=this.readUInt32(), c=function(){var t,e;for(e=[], t=0;t<4;++t)e.push(String.fromCharCode(this.data[this.pos++]));return e}.call(this).join("")){case"IHDR":this.width=this.readUInt32(), this.height=this.readUInt32(), this.bits=this.data[this.pos++], this.colorType=this.data[this.pos++], this.compressionMethod=this.data[this.pos++], this.filterMethod=this.data[this.pos++], this.interlaceMethod=this.data[this.pos++];break;case"acTL":this.animation={numFrames:this.readUInt32(),numPlays:this.readUInt32()||1/0,frames:[]};break;case"PLTE":this.palette=this.read(e);break;case"fcTL":a&&this.animation.frames.push(a), this.pos+=4, a={width:this.readUInt32(),height:this.readUInt32(),xOffset:this.readUInt32(),yOffset:this.readUInt32()}, o=this.readUInt16(), i=this.readUInt16()||100, a.delay=1e3*o/i, a.disposeOp=this.data[this.pos++], a.blendOp=this.data[this.pos++], a.data=[];break;case"IDAT":case"fdAT":for("fdAT"===c&&(this.pos+=4, e-=4), t=(null!=a?a.data:void 0)||this.imgData, f=0;0<=e?f<e:e<f;0<=e?++f:--f)t.push(this.data[this.pos++]);break;case"tRNS":switch(this.transparency={}, this.colorType){case 3:if(r=this.palette.length/3, this.transparency.indexed=this.read(e), this.transparency.indexed.length>r)throw new Error("More transparent colors than palette size");if(0<(l=r-this.transparency.indexed.length))for(d=0;0<=l?d<l:l<d;0<=l?++d:--d)this.transparency.indexed.push(255);break;case 0:this.transparency.grayscale=this.read(e)[0];break;case 2:this.transparency.rgb=this.read(e);}break;case"tEXt":s=(u=this.read(e)).indexOf(0), h=String.fromCharCode.apply(String,u.slice(0,s)), this.text[h]=String.fromCharCode.apply(String,u.slice(s+1));break;case"IEND":return a&&this.animation.frames.push(a), this.colors=function(){switch(this.colorType){case 0:case 3:case 4:return 1;case 2:case 6:return 3}}.call(this), this.hasAlphaChannel=4===(p=this.colorType)||6===p, n=this.colors+(this.hasAlphaChannel?1:0), this.pixelBitlength=this.bits*n, this.colorSpace
29810=function(){switch(this.colors){case 1:return"DeviceGray";case 3:return"DeviceRGB"}}.call(this), void(this.imgData=new Uint8Array(this.imgData));default:this.pos+=e;}if(this.pos+=4, this.pos>this.data.length)throw new Error("Incomplete or corrupt PNG file")}}i.load=function(t,e,n){var r;return"function"==typeof e&&(n=e), (r=new XMLHttpRequest).open("GET",t,!0), r.responseType="arraybuffer", r.onload=function(){var t;return t=new i(new Uint8Array(r.response||r.mozResponseArrayBuffer)), "function"==typeof(null!=e?e.getContext:void 0)&&t.render(e), "function"==typeof n?n(t):void 0}, r.send(null)}, i.prototype.read=function(t){var e,n;for(n=[], e=0;0<=t?e<t:t<e;0<=t?++e:--e)n.push(this.data[this.pos++]);return n}, i.prototype.readUInt32=function(){return this.data[this.pos++]<<24|this.data[this.pos++]<<16|this.data[this.pos++]<<8|this.data[this.pos++]}, i.prototype.readUInt16=function(){return this.data[this.pos++]<<8|this.data[this.pos++]}, i.prototype.decodePixels=function(E){var q=this.pixelBitlength/8,O=new Uint8Array(this.width*this.height*q),B=0,R=this;if(null==E&&(E=this.imgData), 0===E.length)return new Uint8Array(0);function t(t,e,n,r){var i,o,a,s,h,c,l,u,f,d,p,g,m,w,y,v,b,x,S,k,_,A=Math.ceil((R.width-t)/n),I=Math.ceil((R.height-e)/r),C=R.width==A&&R.height==I;for(w=q*A, g=C?O:new Uint8Array(w*I), c=E.length, o=m=0;m<I&&B<c;){switch(E[B++]){case 0:for(s=b=0;b<w;s=b+=1)g[o++]=E[B++];break;case 1:for(s=x=0;x<w;s=x+=1)i=E[B++], h=s<q?0:g[o-q], g[o++]=(i+h)%256;break;case 2:for(s=S=0;S<w;s=S+=1)i=E[B++], a=(s-s%q)/q, y=m&&g[(m-1)*w+a*q+s%q], g[o++]=(y+i)%256;break;case 3:for(s=k=0;k<w;s=k+=1)i=E[B++], a=(s-s%q)/q, h=s<q?0:g[o-q], y=m&&g[(m-1)*w+a*q+s%q], g[o++]=(i+Math.floor((h+y)/2))%256;break;case 4:for(s=_=0;_<w;s=_+=1)i=E[B++], a=(s-s%q)/q, h=s<q?0:g[o-q], 0===m?y=v=0:(y=g[(m-1)*w+a*q+s%q], v=a&&g[(m-1)*w+(a-1)*q+s%q]), l=h+y-v, u=Math.abs(l-h), d=Math.abs(l-y), p=Math.abs(l-v), f=u<=d&&u<=p?h:d<=p?y:v, g[o++]=(i+f)%256;break;default:throw new Error("Invalid filter algorithm: "+E[B-1])}if(!C){var T=((e+m*r)*R.width+t)*q,F=m*w;for(s=0;s<A;s+=1){for(var P=0;P<q;P+=1)O[T++]=g[F++];T+=(n-1)*q;}}m++;}}return E=(E=new kt(E)).getBytes(), 1==R.interlaceMethod?(t(0,0,8,8), t(4,0,8,8), t(0,4,4,8), t(2,0,4,4), t(0,2,2,4), t(1,0,2,2), t(0,1,1,2)):t(0,0,1,1), O}, i.prototype.decodePalette=function(){var t,e,n,r,i,o,a,s,h;for(n=this.palette, o=this.transparency.indexed||[], i=new Uint8Array((o.length||0)+n.length), r=0, n.length, e=a=t=0, s=n.length;a<s;e=a+=3)i[r++]=n[e], i[r++]=n[e+1], i[r++]=n[e+2], i[r++]=null!=(h=o[t++])?h:255;return i}, i.prototype.copyToImageData=function(t,e){var n,r,i,o,a,s,h,c,l,u,f;if(r=this.colors, l=null, n=this.hasAlphaChannel, this.palette.length&&(l=null!=(f=this._decodedPalette)?f:this._decodedPalette=this.decodePalette(), r=4, n=!0), c=(i=t.data||t).length, a=l||e, o=s=0, 1===r)for(;o<c;)h=l?4*e[o/4]:s, u=a[h++], i[o++]=u, i[o++]=u, i[o++]=u, i[o++]=n?a[h++]:255, s=h;else for(;o<c;)h=l?4*e[o/4]:s, i[o++]=a[h++], i[o++]=a[h++], i[o++]=a[h++], i[o++]=n?a[h++]:255, s=h;}, i.prototype.decode=function(){var t;return t=new Uint8Array(this.width*this.height*4), this.copyToImageData(t,this.decodePixels()), t};try{n=pt.document.createElement("canvas"), r=n.getContext("2d");}catch(t){return-1}return c=function(t){var e;return r.width=t.width, r.height=t.height, r.clearRect(0,0,t.width,t.height), r.putImageData(t,0,0), (e=new Image).src=n.toDataURL(), e}, i.prototype.decodeFrames=function(t){var e,n,r,i,o,a,s,h;if(this.animation){for(h=[], n=o=0, a=(s=this.animation.frames).length;o<a;n=++o)e=s[n], r=t.createImageData(e.width,e.height), i=this.decodePixels(new Uint8Array(e.data)), this.copyToImageData(r,i), e.imageData=r, h.push(e.image=c(r));return h}}, i.prototype.renderFrame=function(t,e){var n,r,i;return n=(r=this.animation.frames)[e], i=r[e-1], 0===e&&t.clearRect(0,0,this.width,this.height), 1===(null!=i?i.disposeOp:void 0)?t.clearRect(i.xOffset,i.yOffset,i.width,i.height):2===(null!=i?i.disposeOp:void 0)&&t.putImageData(i.imageData,i.xOffset,i.yOffset), 0===n.blendOp&&t.clearRect(n.xOffset,n.yOffset,n.width,n.height), t.drawImage(n.image,n.xOffset,n.yOffset)}, i.prototype.animate=function(n){var r,i,o,a,s,t,h=this;return i=0, t=this.animation, a=t.numFrames, o=t.frames, s=t.numPlays, (r=function(){var t,e;if(t=i++%a, e=o[t], h.renderFrame(n,t), 1<a&&i/a<s)return h.animation._timeout=setTimeout(r,e.delay)})()}, i.prototype.stopAnimation=function(){var t;return clearTimeout(null!=(t=this.animation)?t._timeout:void 0)}, i.prototype.render=function(t){var e,n;return t._png&&t._png.stopAnimation(), t._png=this, t.width=this.width, t.height=this.height, e=t.getContext("2d"), this.animation?(this.decodeFrames(e), this.animate(e)):(n=e.createImageData(this.width,this.height), this.copyToImageData(n,this.decodePixels()), e.putImageData(n,0,0))}, i}(), pt.PNG=gt;
29811/*
29812   * Extracted from pdf.js
29813   * https://github.com/andreasgal/pdf.js
29814   *
29815   * Copyright (c) 2011 Mozilla Foundation
29816   *
29817   * Contributors: Andreas Gal <[email protected]>
29818   *               Chris G Jones <[email protected]>
29819   *               Shaon Barman <[email protected]>
29820   *               Vivien Nicolas <[email protected]>
29821   *               Justin D'Arcangelo <[email protected]>
29822   *               Yury Delendik
29823   *
29824   * 
29825   */
29826var St=function(){function t(){this.pos=0, this.bufferLength=0, this.eof=!1, this.buffer=null;}return t.prototype={ensureBuffer:function(t){var e=this.buffer,n=e?e.byteLength:0;if(t<n)return e;for(var r=512;r<t;)r<<=1;for(var i=new Uint8Array(r),o=0;o<n;++o)i[o]=e[o];return this.buffer=i},getByte:function(){for(var t=this.pos;this.bufferLength<=t;){if(this.eof)return null;this.readBlock();}return this.buffer[this.pos++]},getBytes:function(t){var e=this.pos;if(t){this.ensureBuffer(e+t);for(var n=e+t;!this.eof&&this.bufferLength<n;)this.readBlock();var r=this.bufferLength;r<n&&(n=r);}else{for(;!this.eof;)this.readBlock();n=this.bufferLength;}return this.pos=n, this.buffer.subarray(e,n)},lookChar:function(){for(var t=this.pos;this.bufferLength<=t;){if(this.eof)return null;this.readBlock();}return String.fromCharCode(this.buffer[this.pos])},getChar:function(){for(var t=this.pos;this.bufferLength<=t;){if(this.eof)return null;this.readBlock();}return String.fromCharCode(this.buffer[this.pos++])},makeSubStream:function(t,e,n){for(var r=t+e;this.bufferLength<=r&&!this.eof;)this.readBlock();return new Stream(this.buffer,t,e,n)},skip:function(t){t||(t=1), this.pos+=t;},reset:function(){this.pos=0;}}, t}(),kt=function(){if("undefined"!=typeof Uint32Array){var F=new Uint32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),P=new Uint32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),E=new Uint32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),q=[new Uint32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,5243
2982669,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],O=[new Uint32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];return(t.prototype=Object.create(St.prototype)).getBits=function(t){for(var e,n=this.codeSize,r=this.codeBuf,i=this.bytes,o=this.bytesPos;n<t;)void 0===(e=i[o++])&&B("Bad encoding in flate stream"), r|=e<<n, n+=8;return e=r&(1<<t)-1, this.codeBuf=r>>t, this.codeSize=n-=t, this.bytesPos=o, e}, t.prototype.getCode=function(t){for(var e=t[0],n=t[1],r=this.codeSize,i=this.codeBuf,o=this.bytes,a=this.bytesPos;r<n;){var s;void 0===(s=o[a++])&&B("Bad encoding in flate stream"), i|=s<<r, r+=8;}var h=e[i&(1<<n)-1],c=h>>16,l=65535&h;return(0==r||r<c||0==c)&&B("Bad encoding in flate stream"), this.codeBuf=i>>c, this.codeSize=r-c, this.bytesPos=a, l}, t.prototype.generateHuffmanTable=function(t){for(var e=t.length,n=0,r=0;r<e;++r)t[r]>n&&(n=t[r]);for(var i=1<<n,o=new Uint32Array(i),a=1,s=0,h=2;a<=n;++a, s<<=1, h<<=1)for(var c=0;c<e;++c)if(t[c]==a){var l=0,u=s;for(r=0;r<a;++r)l=l<<1|1&u, u>>=1;for(r=l;r<i;r+=h)o[r]=a<<16|c;++s;}return[o,n]}, t.prototype.readBlock=function(){function t(t,e,n,r,i){for(var o=t.getBits(n)+r;0<o--;)e[h++]=i;}var e=this.getBits(3);if(1&e&&(this.eof=!0), 0!=(e>>=1)){var n,r;if(1==e)n=q, r=O;else if(2==e){for(var i=this.getBits(5)+257,o=this.getBits(5)+1,a=this.getBits(4)+4,s=Array(F.length),h=0;h<a;)s[F[h++]]=this.getBits(3);for(var c=this.generateHuffmanTable(s),l=0,u=(h=0, i+o),f=new Array(u);h<u;){var d=this.getCode(c);16==d?t(this,f,2,3,l):17==d?t(this,f,3,3,l=0):18==d?t(this,f,7,11,l=0):f[h++]=l=d;}n=this.generateHuffmanTable(f.slice(0,i)), r=this.generateHuffmanTable(f.slice(i,u));}else B("Unknown block type in flate stream");for(var p=(I=this.buffer)?I.length:0,g=this.bufferLength;;){var m=this.getCode(n);if(m<256)p<=g+1&&(p=(I=this.ensureBuffer(g+1)).length), I[g++]=m;else{if(256==m)return void(this.bufferLength=g);var w=(m=P[m-=257])>>16;0<w&&(w=this.getBits(w));l=(65535&m)+w;m=this.getCode(r), 0<(w=(m=E[m])>>16)&&(w=this.getBits(w));var y=(65535&m)+w;p<=g+l&&(p=(I=this.ensureBuffer(g+l)).length);for(var v=0;v<l;++v, ++g)I[g]=I[g-y];}}}else{var b,x=this.bytes,S=this.bytesPos;void 0===(b=x[S++])&&B("Bad block header in flate stream");var k=b;void 0===(b=x[S++])&&B("Bad block header in flate stream"), k|=b<<8, void 0===(b=x[S++])&&B("Bad block header in flate stream");var _=b;void 0===(b=x[S++])&&B("Bad block header in flate stream"), (_|=b<<8)!=(65535&~k)&&B("Bad uncompressed block length in flate stream"), this.codeBuf=0, this.codeSize=0;var A=this.bufferLength,I=this.ensureBuffer(A+k),C=A+k;this.bufferLength=C;for(var T=A;T<C;++T){if(void 0===(b=x[S++])){this.eof=!0;break}I[T]=b;}this.bytesPos=S;}}, t}function B(t){throw new Error(t)}function t(t){var e=0,n=t[e++],r=t[e++];-1!=n&&-1!=r||B("Invalid header in flate stream"), 8!=(15&n)&&B("Unknown compression method in flate stream"), ((n<<8)+r)%31!=0&&B("Bad FCHECK in flate stream"), 32&r&&B("FDICT bit set in flate stream"), this.bytes=t, this.bytesPos=2, this.codeSize=0, this.codeBuf=0, St.call(this);}}();return function(t){if("object"!=typeof t.console){t.console={};for(var e,n,r=t.console,i=function(){},o=["memory"],a="assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn".split(",");e=o.pop();)r[e]||(r[e]={});for(;n=a.pop();)r[n]||(r[n]=i);}var s,h,c,l,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
29826+/=";void 0===t.btoa&&(t.btoa=function(t){var e,n,r,i,o,a=0,s=0,h="",c=[];if(!t)return t;for(;e=(o=t.charCodeAt(a++)<<16|t.charCodeAt(a++)<<8|t.charCodeAt(a++))>>18&63, n=o>>12&63, r=o>>6&63, i=63&o, c[s++]=u.charAt(e)+u.charAt(n)+u.charAt(r)+u.charAt(i), a<t.length;);h=c.join("");var l=t.length%3;return(l?h.slice(0,l-3):h)+"===".slice(l||3)}), void 0===t.atob&&(t.atob=function(t){var e,n,r,i,o,a,s=0,h=0,c=[];if(!t)return t;for(t+="";e=(a=u.indexOf(t.charAt(s++))<<18|u.indexOf(t.charAt(s++))<<12|(i=u.indexOf(t.charAt(s++)))<<6|(o=u.indexOf(t.charAt(s++))))>>16&255, n=a>>8&255, r=255&a, c[h++]=64==i?String.fromCharCode(e):64==o?String.fromCharCode(e,n):String.fromCharCode(e,n,r), s<t.length;);return c.join("")}), Array.prototype.map||(Array.prototype.map=function(t){if(null==this||"function"!=typeof t)throw new TypeError;for(var e=Object(this),n=e.length>>>0,r=new Array(n),i=1<arguments.length?arguments[1]:void 0,o=0;o<n;o++)o in e&&(r[o]=t.call(i,e[o],o,e));return r}), Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}), Array.prototype.forEach||(Array.prototype.forEach=function(t,e){if(null==this||"function"!=typeof t)throw new TypeError;for(var n=Object(this),r=n.length>>>0,i=0;i<r;i++)i in n&&t.call(e,n[i],i,n);}), Object.keys||(Object.keys=(s=Object.prototype.hasOwnProperty, h=!{toString:null}.propertyIsEnumerable("toString"), l=(c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length, function(t){if("object"!=typeof t&&("function"!=typeof t||null===t))throw new TypeError;var e,n,r=[];for(e in t)s.call(t,e)&&r.push(e);if(h)for(n=0;n<l;n++)s.call(t,c[n])&&r.push(c[n]);return r})), "function"!=typeof Object.assign&&(Object.assign=function(t){if(null==t)throw new TypeError("Cannot convert undefined or null to object");t=Object(t);for(var e=1;e<arguments.length;e++){var n=arguments[e];if(null!=n)for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r]);}return t}), String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}), String.prototype.trimLeft||(String.prototype.trimLeft=function(){return this.replace(/^\s+/g,"")}), String.prototype.trimRight||(String.prototype.trimRight=function(){return this.replace(/\s+$/g,"")});}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||"undefined"!=typeof commonjsGlobal&&commonjsGlobal||Function('return typeof this === "object" && this.content')()||Function("return this")()), $});
29827});
29828
29829var jspdf_min_1 = jspdf_min.jsPDF;
29830var jspdf_min_2 = jspdf_min.saveAs;
29831var jspdf_min_3 = jspdf_min.GifWriter;
29832var jspdf_min_4 = jspdf_min.GifReader;
29833
29834var Path = createCommonjsModule(function (module, exports) {
29835Object.defineProperty(exports, "__esModule", {
29836    value: true
29837});
29838var PATH = exports.PATH = {
29839    VECTOR: 0,
29840    BEZIER_CURVE: 1,
29841    CIRCLE: 2
29842};
29843});
29844
29845unwrapExports(Path);
29846var Path_1 = Path.PATH;
29847
29848var Color_1 = createCommonjsModule(function (module, exports) {
29849Object.defineProperty(exports, "__esModule", {
29850    value: true
29851});
29852
29853var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
29854
29855var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
29856
29857function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
29858
29859var HEX3 = /^#([a-f0-9]{3})$/i;
29860var hex3 = function hex3(value) {
29861    var match = value.match(HEX3);
29862    if (match) {
29863        return [parseInt(match[1][0] + match[1][0], 16), parseInt(match[1][1] + match[1][1], 16), parseInt(match[1][2] + match[1][2], 16), null];
29864    }
29865    return false;
29866};
29867
29868var HEX6 = /^#([a-f0-9]{6})$/i;
29869var hex6 = function hex6(value) {
29870    var match = value.match(HEX6);
29871    if (match) {
29872        return [parseInt(match[1].substring(0, 2), 16), parseInt(match[1].substring(2, 4), 16), parseInt(match[1].substring(4, 6), 16), null];
29873    }
29874    return false;
29875};
29876
29877var RGB = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
29878var rgb = function rgb(value) {
29879    var match = value.match(RGB);
29880    if (match) {
29881        return [Number(match[1]), Number(match[2]), Number(match[3]), null];
29882    }
29883    return false;
29884};
29885
29886var RGBA = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
29887var rgba = function rgba(value) {
29888    var match = value.match(RGBA);
29889    if (match && match.length > 4) {
29890        return [Number(match[1]), Number(match[2]), Number(match[3]), Number(match[4])];
29891    }
29892    return false;
29893};
29894
29895var fromArray = function fromArray(array) {
29896    return [Math.min(array[0], 255), Math.min(array[1], 255), Math.min(array[2], 255), array.length > 3 ? array[3] : null];
29897};
29898
29899var namedColor = function namedColor(name) {
29900    var color = NAMED_COLORS[name.toLowerCase()];
29901    return color ? color : false;
29902};
29903
29904var Color = function () {
29905    function Color(value) {
29906        _classCallCheck(this, Color);
29907
29908        var _ref = Array.isArray(value) ? fromArray(value) : hex3(value) || rgb(value) || rgba(value) || namedColor(value) || hex6(value) || [0, 0, 0, null],
29909            _ref2 = _slicedToArray(_ref, 4),
29910            r = _ref2[0],
29911            g = _ref2[1],
29912            b = _ref2[2],
29913            a = _ref2[3];
29914
29915        this.r = r;
29916        this.g = g;
29917        this.b = b;
29918        this.a = a;
29919    }
29920
29921    _createClass(Color, [{
29922        key: 'isTransparent',
29923        value: function isTransparent() {
29924            return this.a === 0;
29925        }
29926    }, {
29927        key: 'toString',
29928        value: function toString() {
29929            return this.a !== null && this.a !== 1 ? 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + this.a + ')' : 'rgb(' + this.r + ',' + this.g + ',' + this.b + ')';
29930        }
29931    }]);
29932
29933    return Color;
29934}();
29935
29936exports.default = Color;
29937
29938
29939var NAMED_COLORS = {
29940    transparent: [0, 0, 0, 0],
29941    aliceblue: [240, 248, 255, null],
29942    antiquewhite: [250, 235, 215, null],
29943    aqua: [0, 255, 255, null],
29944    aquamarine: [127, 255, 212, null],
29945    azure: [240, 255, 255, null],
29946    beige: [245, 245, 220, null],
29947    bisque: [255, 228, 196, null],
29948    black: [0, 0, 0, null],
29949    blanchedalmond: [255, 235, 205, null],
29950    blue: [0, 0, 255, null],
29951    blueviolet: [138, 43, 226, null],
29952    brown: [165, 42, 42, null],
29953    burlywood: [222, 184, 135, null],
29954    cadetblue: [95, 158, 160, null],
29955    chartreuse: [127, 255, 0, null],
29956    chocolate: [210, 105, 30, null],
29957    coral: [255, 127, 80, null],
29958    cornflowerblue: [100, 149, 237, null],
29959    cornsilk: [255, 248, 220, null],
29960    crimson: [220, 20, 60, null],
29961    cyan: [0, 255, 255, null],
29962    darkblue: [0, 0, 139, null],
29963    darkcyan: [0, 139, 139, null],
29964    darkgoldenrod: [184, 134, 11, null],
29965    darkgray: [169, 169, 169, null],
29966    darkgreen: [0, 100, 0, null],
29967    darkgrey: [169, 169, 169, null],
29968    darkkhaki: [189, 183, 107, null],
29969    darkmagenta: [139, 0, 139, null],
29970    darkolivegreen: [85, 107, 47, null],
29971    darkorange: [255, 140, 0, null],
29972    darkorchid: [153, 50, 204, null],
29973    darkred: [139, 0, 0, null],
29974    darksalmon: [233, 150, 122, null],
29975    darkseagreen: [143, 188, 143, null],
29976    darkslateblue: [72, 61, 139, null],
29977    darkslategray: [47, 79, 79, null],
29978    darkslategrey: [47, 79, 79, null],
29979    darkturquoise: [0, 206, 209, null],
29980    darkviolet: [148, 0, 211, null],
29981    deeppink: [255, 20, 147, null],
29982    deepskyblue: [0, 191, 255, null],
29983    dimgray: [105, 105, 105, null],
29984    dimgrey: [105, 105, 105, null],
29985    dodgerblue: [30, 144, 255, null],
29986    firebrick: [178, 34, 34, null],
29987    floralwhite: [255, 250, 240, null],
29988    forestgreen: [34, 139, 34, null],
29989    fuchsia: [255, 0, 255, null],
29990    gainsboro: [220, 220, 220, null],
29991    ghostwhite: [248, 248, 255, null],
29992    gold: [255, 215, 0, null],
29993    goldenrod: [218, 165, 32, null],
29994    gray: [128, 128, 128, null],
29995    green: [0, 128, 0, null],
29996    greenyellow: [173, 255, 47, null],
29997    grey: [128, 128, 128, null],
29998    honeydew: [240, 255, 240, null],
29999    hotpink: [255, 105, 180, null],
30000    indianred: [205, 92, 92, null],
30001    indigo: [75, 0, 130, null],
30002    ivory: [255, 255, 240, null],
30003    khaki: [240, 230, 140, null],
30004    lavender: [230, 230, 250, null],
30005    lavenderblush: [255, 240, 245, null],
30006    lawngreen: [124, 252, 0, null],
30007    lemonchiffon: [255, 250, 205, null],
30008    lightblue: [173, 216, 230, null],
30009    lightcoral: [240, 128, 128, null],
30010    lightcyan: [224, 255, 255, null],
30011    lightgoldenrodyellow: [250, 250, 210, null],
30012    lightgray: [211, 211, 211, null],
30013    lightgreen: [144, 238, 144, null],
30014    lightgrey: [211, 211, 211, null],
30015    lightpink: [255, 182, 193, null],
30016    lightsalmon: [255, 160, 122, null],
30017    lightseagreen: [32, 178, 170, null],
30018    lightskyblue: [135, 206, 250, null],
30019    lightslategray: [119, 136, 153, null],
30020    lightslategrey: [119, 136, 153, null],
30021    lightsteelblue: [176, 196, 222, null],
30022    lightyellow: [255, 255, 224, null],
30023    lime: [0, 255, 0, null],
30024    limegreen: [50, 205, 50, null],
30025    linen: [250, 240, 230, null],
30026    magenta: [255, 0, 255, null],
30027    maroon: [128, 0, 0, null],
30028    mediumaquamarine: [102, 205, 170, null],
30029    mediumblue: [0, 0, 205, null],
30030    mediumorchid: [186, 85, 211, null],
30031    mediumpurple: [147, 112, 219, null],
30032    mediumseagreen: [60, 179, 113, null],
30033    mediumslateblue: [123, 104, 238, null],
30034    mediumspringgreen: [0, 250, 154, null],
30035    mediumturquoise: [72, 209, 204, null],
30036    mediumvioletred: [199, 21, 133, null],
30037    midnightblue: [25, 25, 112, null],
30038    mintcream: [245, 255, 250, null],
30039    mistyrose: [255, 228, 225, null],
30040    moccasin: [255, 228, 181, null],
30041    navajowhite: [255, 222, 173, null],
30042    navy: [0, 0, 128, null],
30043    oldlace: [253, 245, 230, null],
30044    olive: [128, 128, 0, null],
30045    olivedrab: [107, 142, 35, null],
30046    orange: [255, 165, 0, null],
30047    orangered: [255, 69, 0, null],
30048    orchid: [218, 112, 214, null],
30049    palegoldenrod: [238, 232, 170, null],
30050    palegreen: [152, 251, 152, null],
30051    paleturquoise: [175, 238, 238, null],
30052    palevioletred: [219, 112, 147, null],
30053    papayawhip: [255, 239, 213, null],
30054    peachpuff: [255, 218, 185, null],
30055    peru: [205, 133, 63, null],
30056    pink: [255, 192, 203, null],
30057    plum: [221, 160, 221, null],
30058    powderblue: [176, 224, 230, null],
30059    purple: [128, 0, 128, null],
30060    rebeccapurple: [102, 51, 153, null],
30061    red: [255, 0, 0, null],
30062    rosybrown: [188, 143, 143, null],
30063    royalblue: [65, 105, 225, null],
30064    saddlebrown: [139, 69, 19, null],
30065    salmon: [250, 128, 114, null],
30066    sandybrown: [244, 164, 96, null],
30067    seagreen: [46, 139, 87, null],
30068    seashell: [255, 245, 238, null],
30069    sienna: [160, 82, 45, null],
30070    silver: [192, 192, 192, null],
30071    skyblue: [135, 206, 235, null],
30072    slateblue: [106, 90, 205, null],
30073    slategray: [112, 128, 144, null],
30074    slategrey: [112, 128, 144, null],
30075    snow: [255, 250, 250, null],
30076    springgreen: [0, 255, 127, null],
30077    steelblue: [70, 130, 180, null],
30078    tan: [210, 180, 140, null],
30079    teal: [0, 128, 128, null],
30080    thistle: [216, 191, 216, null],
30081    tomato: [255, 99, 71, null],
30082    turquoise: [64, 224, 208, null],
30083    violet: [238, 130, 238, null],
30084    wheat: [245, 222, 179, null],
30085    white: [255, 255, 255, null],
30086    whitesmoke: [245, 245, 245, null],
30087    yellow: [255, 255, 0, null],
30088    yellowgreen: [154, 205, 50, null]
30089};
30090
30091var TRANSPARENT = exports.TRANSPARENT = new Color([0, 0, 0, 0]);
30092});
30093
30094unwrapExports(Color_1);
30095var Color_2 = Color_1.TRANSPARENT;
30096
30097var textDecoration = createCommonjsModule(function (module, exports
30097) {
30098Object.defineProperty(exports, "__esModule", {
30099    value: true
30100});
30101exports.parseTextDecoration = exports.TEXT_DECORATION_LINE = exports.TEXT_DECORATION = exports.TEXT_DECORATION_STYLE = undefined;
30102
30103
30104
30105var _Color2 = _interopRequireDefault(Color_1);
30106
30107function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30108
30109var TEXT_DECORATION_STYLE = exports.TEXT_DECORATION_STYLE = {
30110    SOLID: 0,
30111    DOUBLE: 1,
30112    DOTTED: 2,
30113    DASHED: 3,
30114    WAVY: 4
30115};
30116
30117var TEXT_DECORATION = exports.TEXT_DECORATION = {
30118    NONE: null
30119};
30120
30121var TEXT_DECORATION_LINE = exports.TEXT_DECORATION_LINE = {
30122    UNDERLINE: 1,
30123    OVERLINE: 2,
30124    LINE_THROUGH: 3,
30125    BLINK: 4
30126};
30127
30128var parseLine = function parseLine(line) {
30129    switch (line) {
30130        case 'underline':
30131            return TEXT_DECORATION_LINE.UNDERLINE;
30132        case 'overline':
30133            return TEXT_DECORATION_LINE.OVERLINE;
30134        case 'line-through':
30135            return TEXT_DECORATION_LINE.LINE_THROUGH;
30136    }
30137    return TEXT_DECORATION_LINE.BLINK;
30138};
30139
30140var parseTextDecorationLine = function parseTextDecorationLine(line) {
30141    if (line === 'none') {
30142        return null;
30143    }
30144
30145    return line.split(' ').map(parseLine);
30146};
30147
30148var parseTextDecorationStyle = function parseTextDecorationStyle(style) {
30149    switch (style) {
30150        case 'double':
30151            return TEXT_DECORATION_STYLE.DOUBLE;
30152        case 'dotted':
30153            return TEXT_DECORATION_STYLE.DOTTED;
30154        case 'dashed':
30155            return TEXT_DECORATION_STYLE.DASHED;
30156        case 'wavy':
30157            return TEXT_DECORATION_STYLE.WAVY;
30158    }
30159    return TEXT_DECORATION_STYLE.SOLID;
30160};
30161
30162var parseTextDecoration = exports.parseTextDecoration = function parseTextDecoration(style) {
30163    var textDecorationLine = parseTextDecorationLine(style.textDecorationLine ? style.textDecorationLine : style.textDecoration);
30164    if (textDecorationLine === null) {
30165        return TEXT_DECORATION.NONE;
30166    }
30167
30168    var textDecorationColor = style.textDecorationColor ? new _Color2.default(style.textDecorationColor) : null;
30169    var textDecorationStyle = parseTextDecorationStyle(style.textDecorationStyle);
30170
30171    return {
30172        textDecorationLine: textDecorationLine,
30173        textDecorationColor: textDecorationColor,
30174        textDecorationStyle: textDecorationStyle
30175    };
30176};
30177});
30178
30179unwrapExports(textDecoration);
30180var textDecoration_1 = textDecoration.parseTextDecoration;
30181var textDecoration_2 = textDecoration.TEXT_DECORATION_LINE;
30182var textDecoration_3 = textDecoration.TEXT_DECORATION;
30183var textDecoration_4 = textDecoration.TEXT_DECORATION_STYLE;
30184
30185var CanvasRenderer_1 = createCommonjsModule(function (module, exports) {
30186Object.defineProperty(exports, "__esModule", {
30187    value: true
30188});
30189
30190var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
30191
30192
30193
30194
30195
30196function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30197
30198var addColorStops = function addColorStops(gradient, canvasGradient) {
30199    var maxStop = Math.max.apply(null, gradient.colorStops.map(function (colorStop) {
30200        return colorStop.stop;
30201    }));
30202    var f = 1 / Math.max(1, maxStop);
30203    gradient.colorStops.forEach(function (colorStop) {
30204        canvasGradient.addColorStop(f * colorStop.stop, colorStop.color.toString());
30205    });
30206};
30207
30208var CanvasRenderer = function () {
30209    function CanvasRenderer(canvas) {
30210        _classCallCheck(this, CanvasRenderer);
30211
30212        this.canvas = canvas ? canvas : document.createElement('canvas');
30213    }
30214
30215    _createClass(CanvasRenderer, [{
30216        key: 'render',
30217        value: function render(options) {
30218            this.ctx = this.canvas.getContext('2d');
30219            this.options = options;
30220            this.canvas.width = Math.floor(options.width * options.scale);
30221            this.canvas.height = Math.floor(options.height * options.scale);
30222            this.canvas.style.width = options.width + 'px';
30223            this.canvas.style.height = options.height + 'px';
30224
30225            this.ctx.scale(this.options.scale, this.options.scale);
30226            this.ctx.translate(-options.x, -options.y);
30227            this.ctx.textBaseline = 'bottom';
30228            options.logger.log('Canvas renderer initialized (' + options.width + 'x' + options.height + ' at ' + options.x + ',' + options.y + ') with scale ' + this.options.scale);
30229        }
30230    }, {
30231        key: 'clip',
30232        value: function clip(clipPaths, callback) {
30233            var _this = this;
30234
30235            if (clipPaths.length) {
30236                this.ctx.save();
30237                clipPaths.forEach(function (path) {
30238                    _this.path(path);
30239                    _this.ctx.clip();
30240                });
30241            }
30242
30243            callback();
30244
30245            if (clipPaths.length) {
30246                this.ctx.restore();
30247            }
30248        }
30249    }, {
30250        key: 'drawImage',
30251        value: function drawImage(image, source, destination) {
30252            this.ctx.drawImage(image, source.left, source.top, source.width, source.height, destination.left, destination.top, destination.width, destination.height);
30253        }
30254    }, {
30255        key: 'drawShape',
30256        value: function drawShape(path, color) {
30257            this.path(path);
30258            this.ctx.fillStyle = color.toString();
30259            this.ctx.fill();
30260        }
30261    }, {
30262        key: 'fill',
30263        value: function fill(color) {
30264            this.ctx.fillStyle = color.toString();
30265            this.ctx.fill();
30266        }
30267    }, {
30268        key: 'getTarget',
30269        value: function getTarget() {
30270            this.canvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0);
30271            return Promise.resolve(this.canvas);
30272        }
30273    }, {
30274        key: 'path',
30275        value: function path(_path) {
30276            var _this2 = this;
30277
30278            this.ctx.beginPath();
30279            if (Array.isArray(_path)) {
30280                _path.forEach(function (point, index) {
30281                    var start = point.type === Path.PATH.VECTOR ? point : point.start;
30282                    if (index === 0) {
30283                        _this2.ctx.moveTo(start.x, start.y);
30284                    } else {
30285                        _this2.ctx.lineTo(start.x, start.y);
30286                    }
30287
30288                    if (point.type === Path.PATH.BEZIER_CURVE) {
30289                        _this2.ctx.bezierCurveTo(point.startControl.x, point.startControl.y, point.endControl.x, point.endControl.y, point.end.x, point.end.y);
30290                    }
30291                });
30292            } else {
30293                this.ctx.arc(_path.x + _path.radius, _path.y + _path.radius, _path.radius, 0, Math.PI * 2, true);
30294            }
30295
30296            this.ctx.closePath();
30297        }
30298    }, {
30299        key: 'rectangle',
30300        value: function rectangle(x, y, width, height, color) {
30301            this.ctx.fillStyle = color.toString();
30302            this.ctx.fillRect(x, y, width, height);
30303        }
30304    }, {
30305        key: 'renderLinearGradient',
30306        value: function renderLinearGradient(bounds, gradient) {
30307            var linearGradient = this.ctx.createLinearGradient(bounds.left + gradient.direction.x1, bounds.top + gradient.direction.y1, bounds.left + gradient.direction.x0, bounds.top + gradient.direction.y0);
30308
30309            addColorStops(gradient, linearGradient);
30310            this.ctx.fillStyle = linearGradient;
30311            this.ctx.fillRect(bounds.left, bounds.top, bounds.width, bounds.height);
30312        }
30313    }, {
30314        key: 'renderRadialGradient',
30315        value: function renderRadialGradient(bounds, gradient) {
30316            var _this3 = this;
30317
30318            var x = bounds.left + gradient.center.x;
30319            var y = bounds.top + gradient.center.y;
30320
30321            var radialGradient = this.ctx.createRadialGradient(x, y, 0, x, y, gradient.radius.x);
30322            if (!radialGradient) {
30323                return;
30324            }
30325
30326            addColorStops(gradient, radialGradient);
30327            this.ctx.fillStyle = radialGradient;
30328
30329            if (gradient.radius.x !== gradient.radius.y) {
30330                // transforms for elliptical radial gradient
30331                var midX = bounds.left + 0.5 * bounds.width;
30332                var midY = bounds.top + 0.5 * bounds.height;
30333                var f = gradient.radius.y / gradient.radius.x;
30334                var invF = 1 / f;
30335
30336                this.transform(midX, midY, [1, 0, 0, f, 0, 0], function () {
30337                    return _this3.ctx.fillRect(bounds.left, invF * (bounds.top - midY) + midY, bounds.width, bounds.height * invF);
30338                });
30339            } else {
30340                this.ctx.fillRect(bounds.left, bounds.top, bounds.width, bounds.height);
30341            }
30342        }
30343    }, {
30344        key: 'renderRepeat',
30345        value: function renderRepeat(path, image, imageSize, offsetX, offsetY) {
30346            this.path(path);
30347            this.ctx.fillStyle = this.ctx.createPattern(this.resizeImage(image, imageSize), 'repeat');
30348            this.ctx.translate(offsetX, offsetY);
30349            this.ctx.fill();
30350            this.ctx.translate(-offsetX, -offsetY);
30351        }
30352    }, {
30353        key: 'renderTextNode',
30354        value: function renderTextNode(textBounds, color, font, textDecoration$$1, textShadows) {
30355            var _this4 = this;
30356
30357            this.ctx.font = [font.fontStyle, font.fontVariant, font.fontWeight, font.fontSize, font.fontFamily].join(' ');
30358
30359            textBounds.forEach(function (text) {
30360                _this4.ctx.fillStyle = color.toString();
30361                if (textShadows && text.text.trim().length) {
30362                    textShadows.slice(0).reverse().forEach(function (textShadow) {
30363                        _this4.ctx.shadowColor = textShadow.color.toString();
30364                        _this4.ctx.shadowOffsetX = textShadow.offsetX * _this4.options.scale;
30365                        _this4.ctx.shadowOffsetY = textShadow.offsetY * _this4.options.scale;
30366                        _this4.ctx.shadowBlur = textShadow.blur;
30367
30368                        _this4.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
30369                    });
30370                } else {
30371                    _this4.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
30372                }
30373
30374                if (textDecoration$$1 !== null) {
30375                    var textDecorationColor = textDecoration$$1.textDecorationColor || color;
30376                    textDecoration$$1.textDecorationLine.forEach(function (textDecorationLine) {
30377                        switch (textDecorationLine) {
30378                            case textDecoration.TEXT_DECORATION_LINE.UNDERLINE:
30379                                // Draws a line at the baseline of the font
30380                                // TODO As some browsers display the line as more than 1px if the font-size is big,
30381                                // need to take that into account both in position and size
30382                                var _options$fontMetrics$ = _this4.options.fontMetrics.getMetrics(font),
30383                                    baseline = _options$fontMetrics$.baseline;
30384
30385                                _this4.rectangle(text.bounds.left, Math.round(text.bounds.top + baseline), text.bounds.width, 1, textDecorationColor);
30386                                break;
30387                            case textDecoration.TEXT_DECORATION_LINE.OVERLINE:
30388                                _this4.rectangle(text.bounds.left, Math.round(text.bounds.top), text.bounds.width, 1, textDecorationColor);
30389                                break;
30390                            case textDecoration.TEXT_DECORATION_LINE.LINE_THROUGH:
30391                                // TODO try and find exact position for line-through
30392                                var _options$fontMetrics$2 = _this4.options.fontMetrics.getMetrics(font),
30393                                    middle = _options$fontMetrics$2.middle;
30394
30395                                _this4.rectangle(text.bounds.left, Math.ceil(text.bounds.top + middle), text.bounds.width, 1, textDecorationColor);
30396                                break;
30397                        }
30398                    });
30399                }
30400            });
30401        }
30402    }, {
30403        key: 'resizeImage',
30404        value: function resizeImage(image, size) {
30405            if (image.width === size.width && image.height === size.height) {
30406                return image;
30407            }
30408
30409            var canvas = this.canvas.ownerDocument.createElement('canvas');
30410            canvas.width = size.width;
30411            canvas.height = size.height;
30412            var ctx = canvas.getContext('2d');
30413            ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height);
30414            return canvas;
30415        }
30416    }, {
30417        key: 'setOpacity',
30418        value: function setOpacity(opacity) {
30419            this.ctx.globalAlpha = opacity;
30420        }
30421    }, {
30422        key: 'transform',
30423        value: function transform(offsetX, offsetY, matrix, callback) {
30424            this.ctx.save();
30425            this.ctx.translate(offsetX, offsetY);
30426            this.ctx.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
30427            this.ctx.translate(-offsetX, -offsetY);
30428
30429            callback();
30430
30431            this.ctx.restore();
30432        }
30433    }]);
30434
30435    return CanvasRenderer;
30436}();
30437
30438exports.default = CanvasRenderer;
30439});
30440
30441unwrapExports(CanvasRenderer_1);
30442
30443var Logger_1 = createCommonjsModule(function (module, exports) {
30444Object.defineProperty(exports, "__esModule", {
30445    value: true
30446});
30447
30448var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
30449
30450function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30451
30452var Logger = function () {
30453    function Logger(enabled, id, start) {
30454        _classCallCheck(this, Logger);
30455
30456        this.enabled = typeof window !== 'undefined' && enabled;
30457        this.start = start ? start : Date.now();
30458        this.id = id;
30459    }
30460
30461    _createClass(Logger, [{
30462        key: 'child',
30463        value: function child(id) {
30464            return new Logger(this.enabled, id, this.start);
30465        }
30466
30467        // eslint-disable-next-line flowtype/no-weak-types
30468
30469    }, {
30470        key: 'log',
30471        value: function log() {
30472            if (this.enabled && window.console && window.console.log) {
30473                for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
30474                    args[_key] = arguments[_key];
30475                }
30476
30477                Function.prototype.bind.call(window.console.log, window.console).apply(window.console, [Date.now() - this.start + 'ms', this.id ? 'html2canvas (' + this.id + '):' : 'html2canvas:'].concat([].slice.call(args, 0)));
30478            }
30479        }
30480
30481        // eslint-disable-next-line flowtype/no-weak-types
30482
30483    }, {
30484        key: 'error',
30485        value: function error() {
30486            if (this.enabled && window.console && window.console.error) {
30487                for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
30488                    args[_key2] = arguments[_key2];
30489                }
30490
30491                Function.prototype.bind.call(window.console.error, window.console).apply(window.console, [Date.now() - this.start + 'ms', this.id ? 'html2canvas (' + this.id + '):' : 'html2canvas:'].concat([].slice.call(args, 0)));
30492            }
30493        }
30494    }]);
30495
30496    return Logger;
30497}();
30498
30499exports.default = Logger;
30500});
30501
30502unwrapExports(Logger_1);
30503
30504var Util = createCommonjsModule(function (module, exports) {
30505Object.defineProperty(exports, "__esModule", {
30506    value: true
30507});
30508var contains = exports.contains = function contains(bit, value) {
30509    return (bit & value) !== 0;
30510};
30511
30512var distance = exports.distance = function distance(a, b) {
30513    return Math.sqrt(a * a + b * b);
30514};
30515
30516var copyCSSStyles = exports.copyCSSStyles = function copyCSSStyles(style, target) {
30517    // Edge does not provide value for cssText
30518    for (var i = style.length - 1; i >= 0; i--) {
30519        var property = style.item(i);
30520        // Safari shows pseudoelements if content is set
30521        if (property !== 'content') {
30522            target.style.setProperty(property, style.getPropertyValue(property));
30523        }
30524    }
30525    return target;
30526};
30527
30528var SMALL_IMAGE = exports.SMALL_IMAGE = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
30529});
30530
30531unwrapExports(Util);
30532var Util_1 = Util.contains;
30533var Util_2 = Util.distance;
30534var Util_3 = Util.copyCSSStyles;
30535var Util_4 = Util.SMALL_IMAGE;
30536
30537var Length_1 = createCommonjsModule(function (module, exports) {
30538Object.defineProperty(exports, "__esModule", {
30539    value: true
30540});
30541exports.calculateLengthFromValueWithUnit = exports.LENGTH_TYPE = undefined;
30542
30543var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
30544
30545
30546
30547var _NodeContainer2 = _interopRequireDefault(NodeContainer_1);
30548
30549function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30550
30551function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30552
30553var LENGTH_TYPE = exports.LENGTH_TYPE = {
30554    PX: 0,
30555    PERCENTAGE: 1
30556};
30557
30558var Length = function () {
30559    function Length(value) {
30560        _classCallCheck(this, Length);
30561
30562        this.type = value.substr(value.length - 1) === '%' ? LENGTH_TYPE.PERCENTAGE : LENGTH_TYPE.PX;
30563        var parsedValue = parseFloat(value);
30564        this.value = isNaN(parsedValue) ? 0 : parsedValue;
30565    }
30566
30567    _createClass(Length, [{
30568        key: 'isPercentage',
30569        value: function isPercentage() {
30570            return this.type === LENGTH_TYPE.PERCENTAGE;
30571        }
30572    }, {
30573        key: 'getAbsoluteValue',
30574        value: function getAbsoluteValue(parentLength) {
30575            return this.isPercentage() ? parentLength * (this.value / 100) : this.value;
30576        }
30577    }], [{
30578        key: 'create',
30579        value: function create(v) {
30580            return new Length(v);
30581        }
30582    }]);
30583
30584    return Length;
30585}();
30586
30587exports.default = Length;
30588
30589
30590var getRootFontSize = function getRootFontSize(container) {
30591    var parent = container.parent;
30592    return parent ? getRootFontSize(parent) : parseFloat(container.style.font.fontSize);
30593};
30594
30595var calculateLengthFromValueWithUnit = exports.calculateLengthFromValueWithUnit = function calculateLengthFromValueWithUnit(container, value, unit) {
30596    switch (unit) {
30597        case 'px':
30598        case '%':
30599            return new Length(value + unit);
30600        case 'em':
30601        case 'rem':
30602            var length = new Length(value);
30603            length.value *= unit === 'em' ? parseFloat(container.style.font.fontSize) : getRootFontSize(container);
30604            return length;
30605        default:
30606            // TODO: handle correctly if unknown unit is used
30607            return new Length('0');
30608    }
30609};
30610});
30611
30612unwrapExports(Length_1);
30613var Length_2 = Length_1.calculateLengthFromValueWithUnit;
30614var Length_3 = Length_1.LENGTH_TYPE;
30615
30616var Size_1 = createCommonjsModule(function (module, exports) {
30617Object.defineProperty(exports, "__esModule", {
30618    value: true
30619});
30620
30621function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30622
30623var Size = function Size(width, height) {
30624    _classCallCheck(this, Size);
30625
30626    this.width = width;
30627    this.height = height;
30628};
30629
30630exports.default = Size;
30631});
30632
30633unwrapExports(Size_1);
30634
30635var Vector_1 = createCommonjsModule(function (module, exports) {
30636Object.defineProperty(exports, "__esModule", {
30637    value: true
30638});
30639
30640
30641
30642function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30643
30644var Vector = function Vector(x, y) {
30645    _classCallCheck(this, Vector);
30646
30647    this.type = Path.PATH.VECTOR;
30648    this.x = x;
30649    this.y = y;
30650    
30651};
30652
30653exports.default = Vector;
30654});
30655
30656unwrapExports(Vector_1);
30657
30658var BezierCurve_1 = createCommonjsModule(function (module, exports) {
30659Object.defineProperty(exports, "__esModule", {
30660    value: true
30661});
30662
30663var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
30664
30665
30666
30667
30668
30669var _Vector2 = _interopRequireDefault(Vector_1);
30670
30671function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30672
30673function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30674
30675var lerp = function lerp(a, b, t) {
30676    return new _Vector2.default(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
30677};
30678
30679var BezierCurve = function () {
30680    function BezierCurve(start, startControl, endControl, end) {
30681        _classCallCheck(this, BezierCurve);
30682
30683        this.type = Path.PATH.BEZIER_CURVE;
30684        this.start = start;
30685        this.startControl = startControl;
30686        this.endControl = endControl;
30687        this.end = end;
30688    }
30689
30690    _createClass(BezierCurve, [{
30691        key: 'subdivide',
30692        value: function subdivide(t, firstHalf) {
30693            var ab = lerp(this.start, this.startControl, t);
30694            var bc = lerp(this.startControl, this.endControl, t);
30695            var cd = lerp(this.endControl, this.end, t);
30696            var abbc = lerp(ab, bc, t);
30697            var bccd = lerp(bc, cd, t);
30698            var dest = lerp(abbc, bccd, t);
30699            return firstHalf ? new BezierCurve(this.start, ab, abbc, dest) : new BezierCurve(dest, bccd, cd, this.end);
30700        }
30701    }, {
30702        key: 'reverse',
30703        value: function reverse() {
30704            return new BezierCurve(this.end, this.endControl, this.startControl, this.start);
30705        }
30706    }]);
30707
30708    return BezierCurve;
30709}();
30710
30711exports.default = BezierCurve;
30712});
30713
30714unwrapExports(BezierCurve_1);
30715
30716var Bounds_1 = createCommonjsModule(function (module, exports) {
30717Object.defineProperty(exports, "__esModule", {
30718    value: true
30719});
30720exports.parseBoundCurves = exports.calculatePaddingBoxPath = exports.calculateBorderBoxPath = exports.parsePathForBorder = exports.parseDocumentSize = exports.calculateContentBox = exports.calculatePaddingBox = exports.parseBounds = exports.Bounds = undefined;
30721
30722var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
30723
30724
30725
30726var _Vector2 = _interopRequireDefault(Vector_1);
30727
30728
30729
30730var _BezierCurve2 = _interopRequireDefault(BezierCurve_1);
30731
30732function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30733
30734function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30735
30736var TOP = 0;
30737var RIGHT = 1;
30738var BOTTOM = 2;
30739var LEFT = 3;
30740
30741var H = 0;
30742var V = 1;
30743
30744var Bounds = exports.Bounds = function () {
30745    function Bounds(x, y, w, h) {
30746        _classCallCheck(this, Bounds);
30747
30748        this.left = x;
30749        this.top = y;
30750        this.width = w;
30751        this.height = h;
30752    }
30753
30754    _createClass(Bounds, null, [{
30755        key: 'fromClientRect',
30756        value: function fromClientRect(clientRect, scrollX, scrollY) {
30757            return new Bounds(clientRect.left + scrollX, clientRect.top + scrollY, clientRect.width, clientRect.height);
30758        }
30759    }]);
30760
30761    return Bounds;
30762}();
30763
30764var parseBounds = exports.parseBounds = function parseBounds(node, scrollX, scrollY) {
30765    return Bounds.fromClientRect(node.getBoundingClientRect(), scrollX, scrollY);
30766};
30767
30768var calculatePaddingBox = exports.calculatePaddingBox = function calculatePaddingBox(bounds, borders) {
30769    return new Bounds(bounds.left + borders[LEFT].borderWidth, bounds.top + borders[TOP].borderWidth, bounds.width - (borders[RIGHT].borderWidth + borders[LEFT].borderWidth), bounds.height - (borders[TOP].borderWidth + borders[BOTTOM].borderWidth));
30770};
30771
30772var calculateContentBox = exports.calculateContentBox = function calculateContentBox(bounds, padding, borders) {
30773    // TODO support percentage paddings
30774    var paddingTop = padding[TOP].value;
30775    var paddingRight = padding[RIGHT].value;
30776    var paddingBottom = padding[BOTTOM].value;
30777    var paddingLeft = padding[LEFT].value;
30778
30779    return new Bounds(bounds.left + paddingLeft + borders[LEFT].borderWidth, bounds.top + paddingTop + borders[TOP].borderWidth, bounds.width - (borders[RIGHT].borderWidth + borders[LEFT].borderWidth + paddingLeft + paddingRight), bounds.height - (borders[TOP].borderWidth + borders[BOTTOM].borderWidth + paddingTop + paddingBottom));
30780};
30781
30782var parseDocumentSize = exports.parseDocumentSize = function parseDocumentSize(document) {
30783    var body = document.body;
30784    var documentElement = document.documentElement;
30785
30786    if (!body || !documentElement) {
30787        throw new Error('');
30788    }
30789    var width = Math.max(Math.max(body.scrollWidth, documentElement.scrollWidth), Math.max(body.offsetWidth, documentElement.offsetWidth), Math.max(body.clientWidth, documentElement.clientWidth));
30790
30791    var height = Math.max(Math.max(body.scrollHeight, documentElement.scrollHeight), Math.max(body.offsetHeight, documentElement.offsetHeight), Math.max(body.clientHeight, documentElement.clientHeight));
30792
30793    return new Bounds(0, 0, width, height);
30794};
30795
30796var parsePathForBorder = exports.parsePathForBorder = function parsePathForBorder(curves, borderSide) {
30797    switch (borderSide) {
30798        case TOP:
30799            return createPathFromCurves(curves.topLeftOuter, curves.topLeftInner, curves.topRightOuter, curves.topRightInner);
30800        case RIGHT:
30801            return createPathFromCurves(curves.topRightOuter, curves.topRightInner, curves.bottomRightOuter, curves.bottomRightInner);
30802        case BOTTOM:
30803            return createPathFromCurves(curves.bottomRightOuter, curves.bottomRightInner, curves.bottomLeftOuter, curves.bottomLeftInner);
30804        case LEFT:
30805        default:
30806            return createPathFromCurves(curves.bottomLeftOuter, curves.bottomLeftInner, curves.topLeftOuter, curves.topLeftInner);
30807    }
30808};
30809
30810var createPathFromCurves = function createPathFromCurves(outer1, inner1, outer2, inner2) {
30811    var path = [];
30812    if (outer1 instanceof _BezierCurve2.default) {
30813        path.push(outer1.subdivide(0.5, false));
30814    } else {
30815        path.push(outer1);
30816    }
30817
30818    if (outer2 instanceof _BezierCurve2.default) {
30819        path.push(outer2.subdivide(0.5, true));
30820    } else {
30821        path.push(outer2);
30822    }
30823
30824    if (inner2 instanceof _BezierCurve2.default) {
30825        path.push(inner2.subdivide(0.5, true).reverse());
30826    } else {
30827        path.push(inner2);
30828    }
30829
30830    if (inner1 instanceof _BezierCurve2.default) {
30831        path.push(inner1.subdivide(0.5, false).reverse());
30832    } else {
30833        path.push(inner1);
30834    }
30835
30836    return path;
30837};
30838
30839var calculateBorderBoxPath = exports.calculateBorderBoxPath = function calculateBorderBoxPath(curves) {
30840    return [curves.topLeftOuter, curves.topRightOuter, curves.bottomRightOuter, curves.bottomLeftOuter];
30841};
30842
30843var calculatePaddingBoxPath = exports.calculatePaddingBoxPath = function calculatePaddingBoxPath(curves) {
30844    return [curves.topLeftInner, curves.topRightInner, curves.bottomRightInner, curves.bottomLeftInner];
30845};
30846
30847var parseBoundCurves = exports.parseBoundCurves = function parseBoundCurves(bounds, borders, borderRadius) {
30848    var tlh = borderRadius[CORNER.TOP_LEFT][H].getAbsoluteValue(bounds.width);
30849    var tlv = borderRadius[CORNER.TOP_LEFT][V].getAbsoluteValue(bounds.height);
30850    var trh = borderRadius[CORNER.TOP_RIGHT][H].getAbsoluteValue(bounds.width);
30851    var trv = borderRadius[CORNER.TOP_RIGHT][V].getAbsoluteValue(bounds.height);
30852    var brh = borderRadius[CORNER.BOTTOM_RIGHT][H].getAbsoluteValue(bounds.width);
30853    var brv = borderRadius[CORNER.BOTTOM_RIGHT][V].getAbsoluteValue(bounds.height);
30854    var blh = borderRadius[CORNER.BOTTOM_LEFT][H].getAbsoluteValue(bounds.width);
30855    var blv = borderRadius[CORNER.BOTTOM_LEFT][V].getAbsoluteValue(bounds.height);
30856
30857    var factors = [];
30858    factors.push((tlh + trh) / bounds.width);
30859    factors.push((blh + brh) / bounds.width);
30860    factors.push((tlv + blv) / bounds.height);
30861    factors.push((trv + brv) / bounds.height);
30862    var maxFactor = Math.max.apply(Math, factors);
30863
30864    if (maxFactor > 1) {
30865        tlh /= maxFactor;
30866        tlv /= maxFactor;
30867        trh /= maxFactor;
30868        trv /= maxFactor;
30869        brh /= maxFactor;
30870        brv /= maxFactor;
30871        blh /= maxFactor;
30872        blv /= maxFactor;
30873    }
30874
30875    var topWidth = bounds.width - trh;
30876    var rightHeight = bounds.height - brv;
30877    var bottomWidth = bounds.width - brh;
30878    var leftHeight = bounds.height - blv;
30879
30880    return {
30881        topLeftOuter: tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left, bounds.top, tlh, tlv, CORNER.TOP_LEFT) : new _Vector2.default(bounds.left, bounds.top),
30882        topLeftInner: tlh > 0 || tlv > 0 ? getCurvePoints(bounds.left + borders[LEFT].borderWidth, bounds.top + borders[TOP].borderWidth, Math.max(0, tlh - borders[LEFT].borderWidth), Math.max(0, tlv - borders[TOP].borderWidth), CORNER.TOP_LEFT) : new _Vector2.default(bounds.left + borders[LEFT].borderWidth, bounds.top + borders[TOP].borderWidth),
30883        topRightOuter: trh > 0 || trv > 0 ? getCurvePoints(bounds.left + topWidth, bounds.top, trh, trv, CORNER.TOP_RIGHT) : new _Vector2.default(bounds.left + bounds.width, bounds.top),
30884        topRightInner: trh > 0 || trv > 0 ? getCurvePoints(bounds.left + Math.min(topWidth, bounds.width + borders[LEFT].borderWidth), bounds.top + borders[TOP].borderWidth, topWidth > bounds.width + borders[LEFT].borderWidth ? 0 : trh - borders[LEFT].borderWidth, trv - borders[TOP].borderWidth, CORNER.TOP_RIGHT) : new _Vector2.default(bounds.left + bounds.width - borders[RIGHT].borderWidth, bounds.top + borders[TOP].borderWidth),
30885        bottomRightOuter: brh > 0 || brv > 0 ? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh, brv, CORNER.BOTTOM_RIGHT) : new _Vector2.default(bounds.left + bounds.width, bounds.top + bounds.height),
30886        bottomRightInner: brh > 0 || brv > 0 ? getCurvePoints(bounds.left + Math.min(bottomWidth, bounds.width - borders[LEFT].borderWidth), bounds.top + Math.min(rightHeight, bounds.height + borders[TOP].borderWidth), Math.max(0, brh - borders[RIGHT].borderWidth), brv - borders[BOTTOM].borderWidth, CORNER.BOTTOM_RIGHT) : new _Vector2.default(bounds.left + bounds.width - borders[RIGHT].borderWidth, bounds.top + bounds.height - borders[BOTTOM].borderWidth),
30887        bottomLeftOuter: blh > 0 || blv > 0 ? getCurvePoints(bounds.left, bounds.top + leftHeight, blh, blv, CORNER.BOTTOM_LEFT) : new _Vector2.default(bounds.left, bounds.top + bounds.height),
30888        bottomLeftInner: blh > 0 || blv > 0 ? getCurvePoints(bounds.left + borders[LEFT].borderWidth, bounds.top + leftHeight, Math.max(0, blh - borders[LEFT].borderWidth), blv - borders[BOTTOM].borderWidth, CORNER.BOTTOM_LEFT) : new _Vector2.default(bounds.left + borders[LEFT].borderWidth, bounds.top + bounds.height - borders[BOTTOM].borderWidth)
30889    };
30890};
30891
30892var CORNER = {
30893    TOP_LEFT: 0,
30894    TOP_RIGHT: 1,
30895    BOTTOM_RIGHT: 2,
30896    BOTTOM_LEFT: 3
30897};
30898
30899var getCurvePoints = function getCurvePoints(x, y, r1, r2, position) {
30900    var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
30901    var ox = r1 * kappa; // control point offset horizontal
30902    var oy = r2 * kappa; // control point offset vertical
30903    var xm = x + r1; // x-middle
30904    var ym = y + r2; // y-middle
30905
30906    switch (position) {
30907        case CORNER.TOP_LEFT:
30908            return new _BezierCurve2.default(new _Vector2.default(x, ym), new _Vector2.default(x, ym - oy), new _Vector2.default(xm - ox, y), new _Vector2.default(xm, y));
30909        case CORNER.TOP_RIGHT:
30910            return new _BezierCurve2.default(new _Vector2.default(x, y), new _Vector2.default(x + ox, y), new _Vector2.default(xm, ym - oy), new _Vector2.default(xm, ym));
30911        case CORNER.BOTTOM_RIGHT:
30912            return new _BezierCurve2.default(new _Vector2.default(xm, y), new _Vector2.default(xm, y + oy), new _Vector2.default(x + ox, ym), new _Vector2.default(x, ym));
30913        case CORNER.BOTTOM_LEFT:
30914        default:
30915            return new _BezierCurve2.default(new _Vector2.default(xm, ym), new _Vector2.default(xm - ox, ym), new _Vector2.default(x, y + oy), new _Vector2.default(x, y));
30916    }
30917};
30918});
30919
30920unwrapExports(Bounds_1);
30921var Bounds_2 = Bounds_1.parseBoundCurves;
30922var Bounds_3 = Bounds_1.calculatePaddingBoxPath;
30923var Bounds_4 = Bounds_1.calculateBorderBoxPath;
30924var Bounds_5 = Bounds_1.parsePathForBorder;
30925var Bounds_6 = Bounds_1.parseDocumentSize;
30926var Bounds_7 = Bounds_1.calculateContentBox;
30927var Bounds_8 = Bounds_1.calculatePaddingBox;
30928var Bounds_9 = Bounds_1.parseBounds;
30929var Bounds_10 = Bounds_1.Bounds;
30930
30931var padding = createCommonjsModule(function (module, exports) {
30932Object.defineProperty(exports, "__esModule", {
30933    value: true
30934});
30935exports.parsePadding = exports.PADDING_SIDES = undefined;
30936
30937
30938
30939var _Length2 = _interopRequireDefault(Length_1);
30940
30941function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30942
30943var PADDING_SIDES = exports.PADDING_SIDES = {
30944    TOP: 0,
30945    RIGHT: 1,
30946    BOTTOM: 2,
30947    LEFT: 3
30948};
30949
30950var SIDES = ['top', 'right', 'bottom', 'left'];
30951
30952var parsePadding = exports.parsePadding = function parsePadding(style) {
30953    return SIDES.map(function (side) {
30954        return new _Length2.default(style.getPropertyValue('padding-' + side));
30955    });
30956};
30957});
30958
30959unwrapExports(padding);
30960var padding_1 = padding.parsePadding;
30961var padding_2 = padding.PADDING_SIDES;
30962
30963var background = createCommonjsModule(function (module, exports) {
30964Object.defineProperty(exports, "__esModule", {
30965    value: true
30966});
30967exports.parseBackgroundImage = exports.parseBackground = exports.calculateBackgroundRepeatPath = exports.calculateBackgroundPosition = exports.calculateBackgroungPositioningArea = exports.calculateBackgroungPaintingArea = exports.calculateGradientBackgroundSize = exports.calculateBackgroundSize = exports.BACKGROUND_ORIGIN = exports.BACKGROUND_CLIP = exports.BACKGROUND_SIZE = exports.BACKGROUND_REPEAT = undefined;
30968
30969
30970
30971var _Color2 = _interopRequireDefault(Color_1);
30972
30973
30974
30975var _Length2 = _interopRequireDefault(Length_1);
30976
30977
30978
30979var _Size2 = _interopRequireDefault(Size_1);
30980
30981
30982
30983var _Vector2 = _interopRequireDefault(Vector_1);
30984
30985
30986
30987
30988
30989function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30990
30991function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30992
30993var BACKGROUND_REPEAT = exports.BACKGROUND_REPEAT = {
30994    REPEAT: 0,
30995    NO_REPEAT: 1,
30996    REPEAT_X: 2,
30997    REPEAT_Y: 3
30998};
30999
31000var BACKGROUND_SIZE = exports.BACKGROUND_SIZE = {
31001    AUTO: 0,
31002    CONTAIN: 1,
31003    COVER: 2,
31004    LENGTH: 3
31005};
31006
31007var BACKGROUND_CLIP = exports.BACKGROUND_CLIP = {
31008    BORDER_BOX: 0,
31009    PADDING_BOX: 1,
31010    CONTENT_BOX: 2
31011};
31012
31013var BACKGROUND_ORIGIN = exports.BACKGROUND_ORIGIN = BACKGROUND_CLIP;
31014
31015var AUTO = 'auto';
31016
31017var BackgroundSize = function BackgroundSize(size) {
31018    _classCallCheck(this, BackgroundSize);
31019
31020    switch (size) {
31021        case 'contain':
31022            this.size = BACKGROUND_SIZE.CONTAIN;
31023            break;
31024        case 'cover':
31025            this.size = BACKGROUND_SIZE.COVER;
31026            break;
31027        case 'auto':
31028            this.size = BACKGROUND_SIZE.AUTO;
31029            break;
31030        default:
31031            this.value = new _Length2.default(size);
31032    }
31033};
31034
31035var calculateBackgroundSize = exports.calculateBackgroundSize = function calculateBackgroundSize(backgroundImage, image, bounds) {
31036    var width = 0;
31037    var height = 0;
31038    var size = backgroundImage.size;
31039    if (size[0].size === BACKGROUND_SIZE.CONTAIN || size[0].size === BACKGROUND_SIZE.COVER) {
31040        var targetRatio = bounds.width / bounds.height;
31041        var currentRatio = image.width / image.height;
31042        return targetRatio < currentRatio !== (size[0].size === BACKGROUND_SIZE.COVER) ? new _Size2.default(bounds.width, bounds.width / currentRatio) : new _Size2.default(bounds.height * currentRatio, bounds.height);
31043    }
31044
31045    if (size[0].value) {
31046        width = size[0].value.getAbsoluteValue(bounds.width);
31047    }
31048
31049    if (size[0].size === BACKGROUND_SIZE.AUTO && size[1].size === BACKGROUND_SIZE.AUTO) {
31050        height = image.height;
31051    } else if (size[1].size === BACKGROUND_SIZE.AUTO) {
31052        height = width / image.width * image.height;
31053    } else if (size[1].value) {
31054        height = size[1].value.getAbsoluteValue(bounds.height);
31055    }
31056
31057    if (size[0].size === BACKGROUND_SIZE.AUTO) {
31058        width = height / image.height * image.width;
31059    }
31060
31061    return new _Size2.default(width, height);
31062};
31063
31064var calculateGradientBackgroundSize = exports.calculateGradientBackgroundSize = function calculateGradientBackgroundSize(backgroundImage, bounds) {
31065    var size = backgroundImage.size;
31066    var width = size[0].value ? size[0].value.getAbsoluteValue(bounds.width) : bounds.width;
31067    var height = size[1].value ? size[1].value.getAbsoluteValue(bounds.height) : size[0].value ? width : bounds.height;
31068
31069    return new _Size2.default(width, height);
31070};
31071
31072var AUTO_SIZE = new BackgroundSize(AUTO);
31073
31074var calculateBackgroungPaintingArea = exports.calculateBackgroungPaintingArea = function calculateBackgroungPaintingArea(curves, clip) {
31075    switch (clip) {
31076        case BACKGROUND_CLIP.BORDER_BOX:
31077            return (0, Bounds_1.calculateBorderBoxPath)(curves);
31078        case BACKGROUND_CLIP.PADDING_BOX:
31079        default:
31080            return (0, Bounds_1.calculatePaddingBoxPath)(curves);
31081    }
31082};
31083
31084var calculateBackgroungPositioningArea = exports.calculateBackgroungPositioningArea = function calculateBackgroungPositioningArea(backgroundOrigin, bounds, padding$$1, border) {
31085    var paddingBox = (0, Bounds_1.calculatePaddingBox)(bounds, border);
31086
31087    switch (backgroundOrigin) {
31088        case BACKGROUND_ORIGIN.BORDER_BOX:
31089            return bounds;
31090        case BACKGROUND_ORIGIN.CONTENT_BOX:
31091            var paddingLeft = padding$$1[padding.PADDING_SIDES.LEFT].getAbsoluteValue(bounds.width);
31092            var paddingRight = padding$$1[padding.PADDING_SIDES.RIGHT].getAbsoluteValue(bounds.width);
31093            var paddingTop = padding$$1[padding.PADDING_SIDES.TOP].getAbsoluteValue(bounds.width);
31094            var paddingBottom = padding$$1[padding.PADDING_SIDES.BOTTOM].getAbsoluteValue(bounds.width);
31095            return new Bounds_1.Bounds(paddingBox.left + paddingLeft, paddingBox.top + paddingTop, paddingBox.width - paddingLeft - paddingRight, paddingBox.height - paddingTop - paddingBottom);
31096        case BACKGROUND_ORIGIN.PADDING_BOX:
31097        default:
31098            return paddingBox;
31099    }
31100};
31101
31102var calculateBackgroundPosition = exports.calculateBackgroundPosition = function calculateBackgroundPosition(position, size, bounds) {
31103    return new _Vector2.default(position[0].getAbsoluteValue(bounds.width - size.width), position[1].getAbsoluteValue(bounds.height - size.height));
31104};
31105
31106var calculateBackgroundRepeatPath = exports.calculateBackgroundRepeatPath = function calculateBackgroundRepeatPath(background, position, size, backgroundPositioningArea, bounds) {
31107    var repeat = background.repeat;
31108    switch (repeat) {
31109        case BACKGROUND_REPEAT.REPEAT_X:
31110            return [new _Vector2.default(Math.round(bounds.left), Math.round(backgroundPositioningArea.top + position.y)), new _Vector2.default(Math.round(bounds.left + bounds.width), Math.round(backgroundPositioningArea.top + position.y)), new _Vector2.default(Math.round(bounds.left + bounds.width), Math.round(size.height + backgroundPositioningArea.top + position.y)), new _Vector2.default(Math.round(bounds.left), Math.round(size.height + backgroundPositioningArea.top + position.y))];
31111        case BACKGROUND_REPEAT.REPEAT_Y:
31112            return [new _Vector2.default(Math.round(backgroundPositioningArea.left + position.x), Math.round(bounds.top)), new _Vector2.default(Math.round(backgroundPositioningArea.left + position.x + size.width), Math.round(bounds.top)), new _Vector2.default(Math.round(backgroundPositioningArea.left + position.x + size.width), Math.round(bounds.height + bounds.top)), new _Vector2.default(Math.round(backgroundPositioningArea.left + position.x), Math.round(bounds.height + bounds.top))];
31113        case BACKGROUND_REPEAT.NO_REPEAT:
31114            return [new _Vector2.default(Math.round(backgroundPositioningArea.left + position.x), Math.round(backgroundPositioningArea.top + position.y)), new _Vector2.default(Math.round(backgroundPositioningArea.left + position.x + size.width), Math.round(backgroundPositioningArea.top + position.y)), new _Vector2.default(Math.round(backgroundPositioningArea.left + position.x + size.width), Math.round(backgroundPositioningArea.top + position.y + size.height)), new _Vector2.default(Math.round(backgroundPositioningArea.left + position.x), Math.round(backgroundPositioningArea.top + position.y + size.height))];
31115        default:
31116            return [new _Vector2.default(Math.round(bounds.left), Math.round(bounds.top)), new _Vector2.default(Math.round(bounds.left + bounds.width), Math.round(bounds.top)), new _Vector2.default(Math.round(bounds.left + bounds.width), Math.round(bounds.height + bounds.top)), new _Vector2.default(Math.round(bounds.left), Math.round(bounds.height + bounds.top))];
31117    }
31118};
31119
31120var parseBackground = exports.parseBackground = function parseBackground(style, resourceLoader) {
31121    return {
31122        backgroundColor: new _Color2.default(style.backgroundColor),
31123        backgroundImage: parseBackgroundImages(style, resourceLoader),
31124        backgroundClip: parseBackgroundClip(style.backgroundClip),
31125        backgroundOrigin: parseBackgroundOrigin(style.backgroundOrigin)
31126    };
31127};
31128
31129var parseBackgroundClip = function parseBackgroundClip(backgroundClip) {
31130    switch (backgroundClip) {
31131        case 'padding-box':
31132            return BACKGROUND_CLIP.PADDING_BOX;
31133        case 'content-box':
31134            return BACKGROUND_CLIP.CONTENT_BOX;
31135    }
31136    return BACKGROUND_CLIP.BORDER_BOX;
31137};
31138
31139var parseBackgroundOrigin = function parseBackgroundOrigin(backgroundOrigin) {
31140    switch (backgroundOrigin) {
31141        case 'padding-box':
31142            return BACKGROUND_ORIGIN.PADDING_BOX;
31143        case 'content-box':
31144            return BACKGROUND_ORIGIN.CONTENT_BOX;
31145    }
31146    return BACKGROUND_ORIGIN.BORDER_BOX;
31147};
31148
31149var parseBackgroundRepeat = function parseBackgroundRepeat(backgroundRepeat) {
31150    switch (backgroundRepeat.trim()) {
31151        case 'no-repeat':
31152            return BACKGROUND_REPEAT.NO_REPEAT;
31153        case 'repeat-x':
31154        case 'repeat no-repeat':
31155            return BACKGROUND_REPEAT.REPEAT_X;
31156        case 'repeat-y':
31157        case 'no-repeat repeat':
31158            return BACKGROUND_REPEAT.REPEAT_Y;
31159        case 'repeat':
31160            return BACKGROUND_REPEAT.REPEAT;
31161    }
31162
31163    return BACKGROUND_REPEAT.REPEAT;
31164};
31165
31166var parseBackgroundImages = function parseBackgroundImages(style, resourceLoader) {
31167    var sources = parseBackgroundImage(style.backgroundImage).map(function (backgroundImage) {
31168        if (backgroundImage.method === 'url') {
31169            var key = resourceLoader.loadImage(backgroundImage.args[0]);
31170            backgroundImage.args = key ? [key] : [];
31171        }
31172        return backgroundImage;
31173    });
31174    var positions = style.backgroundPosition.split(',');
31175    var repeats = style.backgroundRepeat.split(',');
31176    var sizes = style.backgroundSize.split(',');
31177
31178    return sources.map(function (source, index) {
31179        var size = (sizes[index] || AUTO).trim().split(' ').map(parseBackgroundSize);
31180        var position = (positions[index] || AUTO).trim().split(' ').map(parseBackgoundPosition);
31181
31182        return {
31183            source: source,
31184            repeat: parseBackgroundRepeat(typeof repeats[index] === 'string' ? repeats[index] : repeats[0]),
31185            size: size.length < 2 ? [size[0], AUTO_SIZE] : [size[0], size[1]],
31186            position: position.length < 2 ? [position[0], position[0]] : [position[0], position[1]]
31187        };
31188    });
31189};
31190
31191var parseBackgroundSize = function parseBackgroundSize(size) {
31192    return size === 'auto' ? AUTO_SIZE : new BackgroundSize(size);
31193};
31194
31195var parseBackgoundPosition = function parseBackgoundPosition(position) {
31196    switch (position) {
31197        case 'bottom':
31198        case 'right':
31199            return new _Length2.default('100%');
31200        case 'left':
31201        case 'top':
31202            return new _Length2.default('0%');
31203        case 'auto':
31204            return new _Length2.default('0');
31205    }
31206    return new _Length2.default(position);
31207};
31208
31209var parseBackgroundImage = exports.parseBackgroundImage = function parseBackgroundImage(image) {
31210    var whitespace = /^\s$/;
31211    var results = [];
31212
31213    var args = [];
31214    var method = '';
31215    var quote = null;
31216    var definition = '';
31217    var mode = 0;
31218    var numParen = 0;
31219
31220    var appendResult = function appendResult() {
31221        var prefix = '';
31222        if (method) {
31223            if (definition.substr(0, 1) === '"') {
31224                definition = definition.substr(1, definition.length - 2);
31225            }
31226
31227            if (definition) {
31228                args.push(definition.trim());
31229            }
31230
31231            var prefix_i = method.indexOf('-', 1) + 1;
31232            if (method.substr(0, 1) === '-' && prefix_i > 0) {
31233                prefix = method.substr(0, prefix_i).toLowerCase();
31234                method = method.substr(prefix_i);
31235            }
31236            method = method.toLowerCase();
31237            if (method !== 'none') {
31238                results.push({
31239                    prefix: prefix,
31240                    method: method,
31241                    args: args
31242                });
31243            }
31244        }
31245        args = [];
31246        method = definition = '';
31247    };
31248
31249    image.split('').forEach(function (c) {
31250        if (mode === 0 && whitespace.test(c)) {
31251            return;
31252        }
31253        switch (c) {
31254            case '"':
31255                if (!quote) {
31256                    quote = c;
31257                } else if (quote === c) {
31258                    quote = null;
31259                }
31260                break;
31261            case '(':
31262                if (quote) {
31263                    break;
31264                } else if (mode === 0) {
31265                    mode = 1;
31266                    return;
31267                } else {
31268                    numParen++;
31269                }
31270                break;
31271            case ')':
31272                if (quote) {
31273                    break;
31274                } else if (mode === 1) {
31275                    if (numParen === 0) {
31276                        mode = 0;
31277                        appendResult();
31278                        return;
31279                    } else {
31280                        numParen--;
31281                    }
31282                }
31283                break;
31284
31285            case ',':
31286                if (quote) {
31287                    break;
31288                } else if (mode === 0) {
31289                    appendResult();
31290                    return;
31291                } else if (mode === 1) {
31292                    if (numParen === 0 && !method.match(/^url$/i)) {
31293                        args.push(definition.trim());
31294                        definition = '';
31295                        return;
31296                    }
31297                }
31298                break;
31299        }
31300
31301        if (mode === 0) {
31302            method += c;
31303        } else {
31304            definition += c;
31305        }
31306    });
31307
31308    appendResult();
31309    return results;
31310};
31311});
31312
31313unwrapExports(background);
31314var background_1 = background.parseBackgroundImage;
31315var background_2 = background.parseBackground;
31316var background_3 = background.calculateBackgroundRepeatPath;
31317var background_4 = background.calculateBackgroundPosition;
31318var background_5 = background.calculateBackgroungPositioningArea;
31319var background_6 = background.calculateBackgroungPaintingArea;
31320var background_7 = background.calculateGradientBackgroundSize;
31321var background_8 = background.calculateBackgroundSize;
31322var background_9 = background.BACKGROUND_ORIGIN;
31323var background_10 = background.BACKGROUND_CLIP;
31324var background_11 = background.BACKGROUND_SIZE;
31325var background_12 = background.BACKGROUND_REPEAT;
31326
31327var border = createCommonjsModule(function (module, exports) {
31328Object.defineProperty(exports, "__esModule", {
31329    value: true
31330});
31331exports.parseBorder = exports.BORDER_SIDES = exports.BORDER_STYLE = undefined;
31332
31333
31334
31335var _Color2 = _interopRequireDefault(Color_1);
31336
31337function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
31338
31339var BORDER_STYLE = exports.BORDER_STYLE = {
31340    NONE: 0,
31341    SOLID: 1
31342};
31343
31344var BORDER_SIDES = exports.BORDER_SIDES = {
31345    TOP: 0,
31346    RIGHT: 1,
31347    BOTTOM: 2,
31348    LEFT: 3
31349};
31350
31351var SIDES = Object.keys(BORDER_SIDES).map(function (s) {
31352    return s.toLowerCase();
31353});
31354
31355var parseBorderStyle = function parseBorderStyle(style) {
31356    switch (style) {
31357        case 'none':
31358            return BORDER_STYLE.NONE;
31359    }
31360    return BORDER_STYLE.SOLID;
31361};
31362
31363var parseBorder = exports.parseBorder = function parseBorder(style) {
31364    return SIDES.map(function (side) {
31365        var borderColor = new _Color2.default(style.getPropertyValue('border-' + side + '-color'));
31366        var borderStyle = parseBorderStyle(style.getPropertyValue('border-' + side + '-style'));
31367        var borderWidth = parseFloat(style.getPropertyValue('border-' + side + '-width'));
31368        return {
31369            borderColor: borderColor,
31370            borderStyle: borderStyle,
31371            borderWidth: isNaN(borderWidth) ? 0 : borderWidth
31372        };
31373    });
31374};
31375});
31376
31377unwrapExports(border);
31378var border_1 = border.parseBorder;
31379var border_2 = border.BORDER_SIDES;
31380var border_3 = border.BORDER_STYLE;
31381
31382var borderRadius = createCommonjsModule(function (module, exports
31382) {
31383Object.defineProperty(exports, "__esModule", {
31384    value: true
31385});
31386exports.parseBorderRadius = undefined;
31387
31388var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
31389
31390
31391
31392var _Length2 = _interopRequireDefault(Length_1);
31393
31394function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
31395
31396var SIDES = ['top-left', 'top-right', 'bottom-right', 'bottom-left'];
31397
31398var parseBorderRadius = exports.parseBorderRadius = function parseBorderRadius(style) {
31399    return SIDES.map(function (side) {
31400        var value = style.getPropertyValue('border-' + side + '-radius');
31401
31402        var _value$split$map = value.split(' ').map(_Length2.default.create),
31403            _value$split$map2 = _slicedToArray(_value$split$map, 2),
31404            horizontal = _value$split$map2[0],
31405            vertical = _value$split$map2[1];
31406
31407        return typeof vertical === 'undefined' ? [horizontal, horizontal] : [horizontal, vertical];
31408    });
31409};
31410});
31411
31412unwrapExports(borderRadius);
31413var borderRadius_1 = borderRadius.parseBorderRadius;
31414
31415var display = createCommonjsModule(function (module, exports) {
31416Object.defineProperty(exports, "__esModule", {
31417    value: true
31418});
31419var DISPLAY = exports.DISPLAY = {
31420    NONE: 1 << 0,
31421    BLOCK: 1 << 1,
31422    INLINE: 1 << 2,
31423    RUN_IN: 1 << 3,
31424    FLOW: 1 << 4,
31425    FLOW_ROOT: 1 << 5,
31426    TABLE: 1 << 6,
31427    FLEX: 1 << 7,
31428    GRID: 1 << 8,
31429    RUBY: 1 << 9,
31430    SUBGRID: 1 << 10,
31431    LIST_ITEM: 1 << 11,
31432    TABLE_ROW_GROUP: 1 << 12,
31433    TABLE_HEADER_GROUP: 1 << 13,
31434    TABLE_FOOTER_GROUP: 1 << 14,
31435    TABLE_ROW: 1 << 15,
31436    TABLE_CELL: 1 << 16,
31437    TABLE_COLUMN_GROUP: 1 << 17,
31438    TABLE_COLUMN: 1 << 18,
31439    TABLE_CAPTION: 1 << 19,
31440    RUBY_BASE: 1 << 20,
31441    RUBY_TEXT: 1 << 21,
31442    RUBY_BASE_CONTAINER: 1 << 22,
31443    RUBY_TEXT_CONTAINER: 1 << 23,
31444    CONTENTS: 1 << 24,
31445    INLINE_BLOCK: 1 << 25,
31446    INLINE_LIST_ITEM: 1 << 26,
31447    INLINE_TABLE: 1 << 27,
31448    INLINE_FLEX: 1 << 28,
31449    INLINE_GRID: 1 << 29
31450};
31451
31452var parseDisplayValue = function parseDisplayValue(display) {
31453    switch (display) {
31454        case 'block':
31455            return DISPLAY.BLOCK;
31456        case 'inline':
31457            return DISPLAY.INLINE;
31458        case 'run-in':
31459            return DISPLAY.RUN_IN;
31460        case 'flow':
31461            return DISPLAY.FLOW;
31462        case 'flow-root':
31463            return DISPLAY.FLOW_ROOT;
31464        case 'table':
31465            return DISPLAY.TABLE;
31466        case 'flex':
31467            return DISPLAY.FLEX;
31468        case 'grid':
31469            return DISPLAY.GRID;
31470        case 'ruby':
31471            return DISPLAY.RUBY;
31472        case 'subgrid':
31473            return DISPLAY.SUBGRID;
31474        case 'list-item':
31475            return DISPLAY.LIST_ITEM;
31476        case 'table-row-group':
31477            return DISPLAY.TABLE_ROW_GROUP;
31478        case 'table-header-group':
31479            return DISPLAY.TABLE_HEADER_GROUP;
31480        case 'table-footer-group':
31481            return DISPLAY.TABLE_FOOTER_GROUP;
31482        case 'table-row':
31483            return DISPLAY.TABLE_ROW;
31484        case 'table-cell':
31485            return DISPLAY.TABLE_CELL;
31486        case 'table-column-group':
31487            return DISPLAY.TABLE_COLUMN_GROUP;
31488        case 'table-column':
31489            return DISPLAY.TABLE_COLUMN;
31490        case 'table-caption':
31491            return DISPLAY.TABLE_CAPTION;
31492        case 'ruby-base':
31493            return DISPLAY.RUBY_BASE;
31494        case 'ruby-text':
31495            return DISPLAY.RUBY_TEXT;
31496        case 'ruby-base-container':
31497            return DISPLAY.RUBY_BASE_CONTAINER;
31498        case 'ruby-text-container':
31499            return DISPLAY.RUBY_TEXT_CONTAINER;
31500        case 'contents':
31501            return DISPLAY.CONTENTS;
31502        case 'inline-block':
31503            return DISPLAY.INLINE_BLOCK;
31504        case 'inline-list-item':
31505            return DISPLAY.INLINE_LIST_ITEM;
31506        case 'inline-table':
31507            return DISPLAY.INLINE_TABLE;
31508        case 'inline-flex':
31509            return DISPLAY.INLINE_FLEX;
31510        case 'inline-grid':
31511            return DISPLAY.INLINE_GRID;
31512    }
31513
31514    return DISPLAY.NONE;
31515};
31516
31517var setDisplayBit = function setDisplayBit(bit, display) {
31518    return bit | parseDisplayValue(display);
31519};
31520
31521var parseDisplay = exports.parseDisplay = function parseDisplay(display) {
31522    return display.split(' ').reduce(setDisplayBit, 0);
31523};
31524});
31525
31526unwrapExports(display);
31527var display_1 = display.DISPLAY;
31528var display_2 = display.parseDisplay;
31529
31530var float_1 = createCommonjsModule(function (module, exports) {
31531Object.defineProperty(exports, "__esModule", {
31532    value: true
31533});
31534var FLOAT = exports.FLOAT = {
31535    NONE: 0,
31536    LEFT: 1,
31537    RIGHT: 2,
31538    INLINE_START: 3,
31539    INLINE_END: 4
31540};
31541
31542var parseCSSFloat = exports.parseCSSFloat = function parseCSSFloat(float) {
31543    switch (float) {
31544        case 'left':
31545            return FLOAT.LEFT;
31546        case 'right':
31547            return FLOAT.RIGHT;
31548        case 'inline-start':
31549            return FLOAT.INLINE_START;
31550        case 'inline-end':
31551            return FLOAT.INLINE_END;
31552    }
31553    return FLOAT.NONE;
31554};
31555});
31556
31557unwrapExports(float_1);
31558var float_2 = float_1.FLOAT;
31559var float_3 = float_1.parseCSSFloat;
31560
31561var font = createCommonjsModule(function (module, exports) {
31562Object.defineProperty(exports, "__esModule", {
31563    value: true
31564});
31565
31566
31567var parseFontWeight = function parseFontWeight(weight) {
31568    switch (weight) {
31569        case 'normal':
31570            return 400;
31571        case 'bold':
31572            return 700;
31573    }
31574
31575    var value = parseInt(weight, 10);
31576    return isNaN(value) ? 400 : value;
31577};
31578
31579var parseFont = exports.parseFont = function parseFont(style) {
31580    var fontFamily = style.fontFamily;
31581    var fontSize = style.fontSize;
31582    var fontStyle = style.fontStyle;
31583    var fontVariant = style.fontVariant;
31584    var fontWeight = parseFontWeight(style.fontWeight);
31585
31586    return {
31587        fontFamily: fontFamily,
31588        fontSize: fontSize,
31589        fontStyle: fontStyle,
31590        fontVariant: fontVariant,
31591        fontWeight: fontWeight
31592    };
31593};
31594});
31595
31596unwrapExports(font);
31597var font_1 = font.parseFont;
31598
31599var letterSpacing = createCommonjsModule(function (module, exports) {
31600Object.defineProperty(exports, "__esModule", {
31601    value: true
31602});
31603var parseLetterSpacing = exports.parseLetterSpacing = function parseLetterSpacing(letterSpacing) {
31604    if (letterSpacing === 'normal') {
31605        return 0;
31606    }
31607    var value = parseFloat(letterSpacing);
31608    return isNaN(value) ? 0 : value;
31609};
31610});
31611
31612unwrapExports(letterSpacing);
31613var letterSpacing_1 = letterSpacing.parseLetterSpacing;
31614
31615var lineBreak = createCommonjsModule(function (module, exports) {
31616Object.defineProperty(exports, "__esModule", {
31617    value: true
31618});
31619var LINE_BREAK = exports.LINE_BREAK = {
31620    NORMAL: 'normal',
31621    STRICT: 'strict'
31622};
31623
31624var parseLineBreak = exports.parseLineBreak = function parseLineBreak(wordBreak) {
31625    switch (wordBreak) {
31626        case 'strict':
31627            return LINE_BREAK.STRICT;
31628        case 'normal':
31629        default:
31630            return LINE_BREAK.NORMAL;
31631    }
31632};
31633});
31634
31635unwrapExports(lineBreak);
31636var lineBreak_1 = lineBreak.LINE_BREAK;
31637var lineBreak_2 = lineBreak.parseLineBreak;
31638
31639var listStyle = createCommonjsModule(function (module, exports) {
31640Object.defineProperty(exports, "__esModule", {
31641    value: true
31642});
31643exports.parseListStyle = exports.parseListStyleType = exports.LIST_STYLE_TYPE = exports.LIST_STYLE_POSITION = undefined;
31644
31645
31646
31647var LIST_STYLE_POSITION = exports.LIST_STYLE_POSITION = {
31648    INSIDE: 0,
31649    OUTSIDE: 1
31650};
31651
31652var LIST_STYLE_TYPE = exports.LIST_STYLE_TYPE = {
31653    NONE: -1,
31654    DISC: 0,
31655    CIRCLE: 1,
31656    SQUARE: 2,
31657    DECIMAL: 3,
31658    CJK_DECIMAL: 4,
31659    DECIMAL_LEADING_ZERO: 5,
31660    LOWER_ROMAN: 6,
31661    UPPER_ROMAN: 7,
31662    LOWER_GREEK: 8,
31663    LOWER_ALPHA: 9,
31664    UPPER_ALPHA: 10,
31665    ARABIC_INDIC: 11,
31666    ARMENIAN: 12,
31667    BENGALI: 13,
31668    CAMBODIAN: 14,
31669    CJK_EARTHLY_BRANCH: 15,
31670    CJK_HEAVENLY_STEM: 16,
31671    CJK_IDEOGRAPHIC: 17,
31672    DEVANAGARI: 18,
31673    ETHIOPIC_NUMERIC: 19,
31674    GEORGIAN: 20,
31675    GUJARATI: 21,
31676    GURMUKHI: 22,
31677    HEBREW: 22,
31678    HIRAGANA: 23,
31679    HIRAGANA_IROHA: 24,
31680    JAPANESE_FORMAL: 25,
31681    JAPANESE_INFORMAL: 26,
31682    KANNADA: 27,
31683    KATAKANA: 28,
31684    KATAKANA_IROHA: 29,
31685    KHMER: 30,
31686    KOREAN_HANGUL_FORMAL: 31,
31687    KOREAN_HANJA_FORMAL: 32,
31688    KOREAN_HANJA_INFORMAL: 33,
31689    LAO: 34,
31690    LOWER_ARMENIAN: 35,
31691    MALAYALAM: 36,
31692    MONGOLIAN: 37,
31693    MYANMAR: 38,
31694    ORIYA: 39,
31695    PERSIAN: 40,
31696    SIMP_CHINESE_FORMAL: 41,
31697    SIMP_CHINESE_INFORMAL: 42,
31698    TAMIL: 43,
31699    TELUGU: 44,
31700    THAI: 45,
31701    TIBETAN: 46,
31702    TRAD_CHINESE_FORMAL: 47,
31703    TRAD_CHINESE_INFORMAL: 48,
31704    UPPER_ARMENIAN: 49,
31705    DISCLOSURE_OPEN: 50,
31706    DISCLOSURE_CLOSED: 51
31707};
31708
31709var parseListStyleType = exports.parseListStyleType = function parseListStyleType(type) {
31710    switch (type) {
31711        case 'disc':
31712            return LIST_STYLE_TYPE.DISC;
31713        case 'circle':
31714            return LIST_STYLE_TYPE.CIRCLE;
31715        case 'square':
31716            return LIST_STYLE_TYPE.SQUARE;
31717        case 'decimal':
31718            return LIST_STYLE_TYPE.DECIMAL;
31719        case 'cjk-decimal':
31720            return LIST_STYLE_TYPE.CJK_DECIMAL;
31721        case 'decimal-leading-zero':
31722            return LIST_STYLE_TYPE.DECIMAL_LEADING_ZERO;
31723        case 'lower-roman':
31724            return LIST_STYLE_TYPE.LOWER_ROMAN;
31725        case 'upper-roman':
31726            return LIST_STYLE_TYPE.UPPER_ROMAN;
31727        case 'lower-greek':
31728            return LIST_STYLE_TYPE.LOWER_GREEK;
31729        case 'lower-alpha':
31730            return LIST_STYLE_TYPE.LOWER_ALPHA;
31731        case 'upper-alpha':
31732            return LIST_STYLE_TYPE.UPPER_ALPHA;
31733        case 'arabic-indic':
31734            return LIST_STYLE_TYPE.ARABIC_INDIC;
31735        case 'armenian':
31736            return LIST_STYLE_TYPE.ARMENIAN;
31737        case 'bengali':
31738            return LIST_STYLE_TYPE.BENGALI;
31739        case 'cambodian':
31740            return LIST_STYLE_TYPE.CAMBODIAN;
31741        case 'cjk-earthly-branch':
31742            return LIST_STYLE_TYPE.CJK_EARTHLY_BRANCH;
31743        case 'cjk-heavenly-stem':
31744            return LIST_STYLE_TYPE.CJK_HEAVENLY_STEM;
31745        case 'cjk-ideographic':
31746            return LIST_STYLE_TYPE.CJK_IDEOGRAPHIC;
31747        case 'devanagari':
31748            return LIST_STYLE_TYPE.DEVANAGARI;
31749        case 'ethiopic-numeric':
31750            return LIST_STYLE_TYPE.ETHIOPIC_NUMERIC;
31751        case 'georgian':
31752            return LIST_STYLE_TYPE.GEORGIAN;
31753        case 'gujarati':
31754            return LIST_STYLE_TYPE.GUJARATI;
31755        case 'gurmukhi':
31756            return LIST_STYLE_TYPE.GURMUKHI;
31757        case 'hebrew':
31758            return LIST_STYLE_TYPE.HEBREW;
31759        case 'hiragana':
31760            return LIST_STYLE_TYPE.HIRAGANA;
31761        case 'hiragana-iroha':
31762            return LIST_STYLE_TYPE.HIRAGANA_IROHA;
31763        case 'japanese-formal':
31764            return LIST_STYLE_TYPE.JAPANESE_FORMAL;
31765        case 'japanese-informal':
31766            return LIST_STYLE_TYPE.JAPANESE_INFORMAL;
31767        case 'kannada':
31768            return LIST_STYLE_TYPE.KANNADA;
31769        case 'katakana':
31770            return LIST_STYLE_TYPE.KATAKANA;
31771        case 'katakana-iroha':
31772            return LIST_STYLE_TYPE.KATAKANA_IROHA;
31773        case 'khmer':
31774            return LIST_STYLE_TYPE.KHMER;
31775        case 'korean-hangul-formal':
31776            return LIST_STYLE_TYPE.KOREAN_HANGUL_FORMAL;
31777        case 'korean-hanja-formal':
31778            return LIST_STYLE_TYPE.KOREAN_HANJA_FORMAL;
31779        case 'korean-hanja-informal':
31780            return LIST_STYLE_TYPE.KOREAN_HANJA_INFORMAL;
31781        case 'lao':
31782            return LIST_STYLE_TYPE.LAO;
31783        case 'lower-armenian':
31784            return LIST_STYLE_TYPE.LOWER_ARMENIAN;
31785        case 'malayalam':
31786            return LIST_STYLE_TYPE.MALAYALAM;
31787        case 'mongolian':
31788            return LIST_STYLE_TYPE.MONGOLIAN;
31789        case 'myanmar':
31790            return LIST_STYLE_TYPE.MYANMAR;
31791        case 'oriya':
31792            return LIST_STYLE_TYPE.ORIYA;
31793        case 'persian':
31794            return LIST_STYLE_TYPE.PERSIAN;
31795        case 'simp-chinese-formal':
31796            return LIST_STYLE_TYPE.SIMP_CHINESE_FORMAL;
31797        case 'simp-chinese-informal':
31798            return LIST_STYLE_TYPE.SIMP_CHINESE_INFORMAL;
31799        case 'tamil':
31800            return LIST_STYLE_TYPE.TAMIL;
31801        case 'telugu':
31802            return LIST_STYLE_TYPE.TELUGU;
31803        case 'thai':
31804            return LIST_STYLE_TYPE.THAI;
31805        case 'tibetan':
31806            return LIST_STYLE_TYPE.TIBETAN;
31807        case 'trad-chinese-formal':
31808            return LIST_STYLE_TYPE.TRAD_CHINESE_FORMAL;
31809        case 'trad-chinese-informal':
31810            return LIST_STYLE_TYPE.TRAD_CHINESE_INFORMAL;
31811        case 'upper-armenian':
31812            return LIST_STYLE_TYPE.UPPER_ARMENIAN;
31813        case 'disclosure-open':
31814            return LIST_STYLE_TYPE.DISCLOSURE_OPEN;
31815        case 'disclosure-closed':
31816            return LIST_STYLE_TYPE.DISCLOSURE_CLOSED;
31817        case 'none':
31818        default:
31819            return LIST_STYLE_TYPE.NONE;
31820    }
31821};
31822
31823var parseListStyle = exports.parseListStyle = function parseListStyle(style) {
31824    var listStyleImage = (0, background.parseBackgroundImage)(style.getPropertyValue('list-style-image'));
31825    return {
31826        listStyleType: parseListStyleType(style.getPropertyValue('list-style-type')),
31827        listStyleImage: listStyleImage.length ? listStyleImage[0] : null,
31828        listStylePosition: parseListStylePosition(style.getPropertyValue('list-style-position'))
31829    };
31830};
31831
31832var parseListStylePosition = function parseListStylePosition(position) {
31833    switch (position) {
31834        case 'inside':
31835            return LIST_STYLE_POSITION.INSIDE;
31836        case 'outside':
31837        default:
31838            return LIST_STYLE_POSITION.OUTSIDE;
31839    }
31840};
31841});
31842
31843unwrapExports(listStyle);
31844var listStyle_1 = listStyle.parseListStyle;
31845var listStyle_2 = listStyle.parseListStyleType;
31846var listStyle_3 = listStyle.LIST_STYLE_TYPE;
31847var listStyle_4 = listStyle.LIST_STYLE_POSITION;
31848
31849var margin = createCommonjsModule(function (module, exports) {
31850Object.defineProperty(exports, "__esModule", {
31851    value: true
31852});
31853exports.parseMargin = undefined;
31854
31855
31856
31857var _Length2 = _interopRequireDefault(Length_1);
31858
31859function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
31860
31861var SIDES = ['top', 'right', 'bottom', 'left'];
31862
31863var parseMargin = exports.parseMargin = function parseMargin(style) {
31864    return SIDES.map(function (side) {
31865        return new _Length2.default(style.getPropertyValue('margin-' + side));
31866    });
31867};
31868});
31869
31870unwrapExports(margin);
31871var margin_1 = margin.parseMargin;
31872
31873var overflow = createCommonjsModule(function (module, exports) {
31874Object.defineProperty(exports, "__esModule", {
31875    value: true
31876});
31877var OVERFLOW = exports.OVERFLOW = {
31878    VISIBLE: 0,
31879    HIDDEN: 1,
31880    SCROLL: 2,
31881    AUTO: 3
31882};
31883
31884var parseOverflow = exports.parseOverflow = function parseOverflow(overflow) {
31885    switch (overflow) {
31886        case 'hidden':
31887            return OVERFLOW.HIDDEN;
31888        case 'scroll':
31889            return OVERFLOW.SCROLL;
31890        case 'auto':
31891            return OVERFLOW.AUTO;
31892        case 'visible':
31893        default:
31894            return OVERFLOW.VISIBLE;
31895    }
31896};
31897});
31898
31899unwrapExports(overflow);
31900var overflow_1 = overflow.OVERFLOW;
31901var overflow_2 = overflow.parseOverflow;
31902
31903var overflowWrap = createCommonjsModule(function (module, exports) {
31904Object.defineProperty(exports, "__esModule", {
31905    value: true
31906});
31907var OVERFLOW_WRAP = exports.OVERFLOW_WRAP = {
31908    NORMAL: 0,
31909    BREAK_WORD: 1
31910};
31911
31912var parseOverflowWrap = exports.parseOverflowWrap = function parseOverflowWrap(overflow) {
31913    switch (overflow) {
31914        case 'break-word':
31915            return OVERFLOW_WRAP.BREAK_WORD;
31916        case 'normal':
31917        default:
31918            return OVERFLOW_WRAP.NORMAL;
31919    }
31920};
31921});
31922
31923unwrapExports(overflowWrap);
31924var overflowWrap_1 = overflowWrap.OVERFLOW_WRAP;
31925var overflowWrap_2 = overflowWrap.parseOverflowWrap;
31926
31927var position = createCommonjsModule(function (module, exports) {
31928Object.defineProperty(exports, "__esModule", {
31929    value: true
31930});
31931var POSITION = exports.POSITION = {
31932    STATIC: 0,
31933    RELATIVE: 1,
31934    ABSOLUTE: 2,
31935    FIXED: 3,
31936    STICKY: 4
31937};
31938
31939var parsePosition = exports.parsePosition = function parsePosition(position) {
31940    switch (position) {
31941        case 'relative':
31942            return POSITION.RELATIVE;
31943        case 'absolute':
31944            return POSITION.ABSOLUTE;
31945        case 'fixed':
31946            return POSITION.FIXED;
31947        case 'sticky':
31948            return POSITION.STICKY;
31949    }
31950
31951    return POSITION.STATIC;
31952};
31953});
31954
31955unwrapExports(position);
31956var position_1 = position.POSITION;
31957var position_2 = position.parsePosition;
31958
31959var textShadow = createCommonjsModule(function (module, exports) {
31960Object.defineProperty(exports, "__esModule", {
31961    value: true
31962});
31963exports.parseTextShadow = undefined;
31964
31965
31966
31967var _Color2 = _interopRequireDefault(Color_1);
31968
31969function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
31970
31971var NUMBER = /^([+-]|\d|\.)$/i;
31972
31973var parseTextShadow = exports.parseTextShadow = function parseTextShadow(textShadow) {
31974    if (textShadow === 'none' || typeof textShadow !== 'string') {
31975        return null;
31976    }
31977
31978    var currentValue = '';
31979    var isLength = false;
31980    var values = [];
31981    var shadows = [];
31982    var numParens = 0;
31983    var color = null;
31984
31985    var appendValue = function appendValue() {
31986        if (currentValue.length) {
31987            if (isLength) {
31988                values.push(parseFloat(currentValue));
31989            } else {
31990                color = new _Color2.default(currentValue);
31991            }
31992        }
31993        isLength = false;
31994        currentValue = '';
31995    };
31996
31997    var appendShadow = function appendShadow() {
31998        if (values.length && color !== null) {
31999            shadows.push({
32000                color: color,
32001                offsetX: values[0] || 0,
32002                offsetY: values[1] || 0,
32003                blur: values[2] || 0
32004            });
32005        }
32006        values.splice(0, values.length);
32007        color = null;
32008    };
32009
32010    for (var i = 0; i < textShadow.length; i++) {
32011        var c = textShadow[i];
32012        switch (c) {
32013            case '(':
32014                currentValue += c;
32015                numParens++;
32016                break;
32017            case ')':
32018                currentValue += c;
32019                numParens--;
32020                break;
32021            case ',':
32022                if (numParens === 0) {
32023                    appendValue();
32024                    appendShadow();
32025                } else {
32026                    currentValue += c;
32027                }
32028                break;
32029            case ' ':
32030                if (numParens === 0) {
32031                    appendValue();
32032                } else {
32033                    currentValue += c;
32034                }
32035                break;
32036            default:
32037                if (currentValue.length === 0 && NUMBER.test(c)) {
32038                    isLength = true;
32039                }
32040                currentValue += c;
32041        }
32042    }
32043
32044    appendValue();
32045    appendShadow();
32046
32047    if (shadows.length === 0) {
32048        return null;
32049    }
32050
32051    return shadows;
32052};
32053});
32054
32055unwrapExports(textShadow);
32056var textShadow_1 = textShadow.parseTextShadow;
32057
32058var textTransform = createCommonjsModule(function (module, exports
32058) {
32059Object.defineProperty(exports, "__esModule", {
32060    value: true
32061});
32062var TEXT_TRANSFORM = exports.TEXT_TRANSFORM = {
32063    NONE: 0,
32064    LOWERCASE: 1,
32065    UPPERCASE: 2,
32066    CAPITALIZE: 3
32067};
32068
32069var parseTextTransform = exports.parseTextTransform = function parseTextTransform(textTransform) {
32070    switch (textTransform) {
32071        case 'uppercase':
32072            return TEXT_TRANSFORM.UPPERCASE;
32073        case 'lowercase':
32074            return TEXT_TRANSFORM.LOWERCASE;
32075        case 'capitalize':
32076            return TEXT_TRANSFORM.CAPITALIZE;
32077    }
32078
32079    return TEXT_TRANSFORM.NONE;
32080};
32081});
32082
32083unwrapExports(textTransform);
32084var textTransform_1 = textTransform.TEXT_TRANSFORM;
32085var textTransform_2 = textTransform.parseTextTransform;
32086
32087var transform = createCommonjsModule(function (module, exports) {
32088Object.defineProperty(exports, "__esModule", {
32089    value: true
32090});
32091exports.parseTransform = undefined;
32092
32093
32094
32095var _Length2 = _interopRequireDefault(Length_1);
32096
32097function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
32098
32099var toFloat = function toFloat(s) {
32100    return parseFloat(s.trim());
32101};
32102
32103var MATRIX = /(matrix|matrix3d)\((.+)\)/;
32104
32105var parseTransform = exports.parseTransform = function parseTransform(style) {
32106    var transform = parseTransformMatrix(style.transform || style.webkitTransform || style.mozTransform ||
32107    // $FlowFixMe
32108    style.msTransform ||
32109    // $FlowFixMe
32110    style.oTransform);
32111    if (transform === null) {
32112        return null;
32113    }
32114
32115    return {
32116        transform: transform,
32117        transformOrigin: parseTransformOrigin(style.transformOrigin || style.webkitTransformOrigin || style.mozTransformOrigin ||
32118        // $FlowFixMe
32119        style.msTransformOrigin ||
32120        // $FlowFixMe
32121        style.oTransformOrigin)
32122    };
32123};
32124
32125// $FlowFixMe
32126var parseTransformOrigin = function parseTransformOrigin(origin) {
32127    if (typeof origin !== 'string') {
32128        var v = new _Length2.default('0');
32129        return [v, v];
32130    }
32131    var values = origin.split(' ').map(_Length2.default.create);
32132    return [values[0], values[1]];
32133};
32134
32135// $FlowFixMe
32136var parseTransformMatrix = function parseTransformMatrix(transform) {
32137    if (transform === 'none' || typeof transform !== 'string') {
32138        return null;
32139    }
32140
32141    var match = transform.match(MATRIX);
32142    if (match) {
32143        if (match[1] === 'matrix') {
32144            var matrix = match[2].split(',').map(toFloat);
32145            return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]];
32146        } else {
32147            var matrix3d = match[2].split(',').map(toFloat);
32148            return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
32149        }
32150    }
32151    return null;
32152};
32153});
32154
32155unwrapExports(transform);
32156var transform_1 = transform.parseTransform;
32157
32158var visibility = createCommonjsModule(function (module, exports) {
32159Object.defineProperty(exports, "__esModule", {
32160    value: true
32161});
32162var VISIBILITY = exports.VISIBILITY = {
32163    VISIBLE: 0,
32164    HIDDEN: 1,
32165    COLLAPSE: 2
32166};
32167
32168var parseVisibility = exports.parseVisibility = function parseVisibility(visibility) {
32169    switch (visibility) {
32170        case 'hidden':
32171            return VISIBILITY.HIDDEN;
32172        case 'collapse':
32173            return VISIBILITY.COLLAPSE;
32174        case 'visible':
32175        default:
32176            return VISIBILITY.VISIBLE;
32177    }
32178};
32179});
32180
32181unwrapExports(visibility);
32182var visibility_1 = visibility.VISIBILITY;
32183var visibility_2 = visibility.parseVisibility;
32184
32185var wordBreak = createCommonjsModule(function (module, exports) {
32186Object.defineProperty(exports, "__esModule", {
32187    value: true
32188});
32189var WORD_BREAK = exports.WORD_BREAK = {
32190    NORMAL: 'normal',
32191    BREAK_ALL: 'break-all',
32192    KEEP_ALL: 'keep-all'
32193};
32194
32195var parseWordBreak = exports.parseWordBreak = function parseWordBreak(wordBreak) {
32196    switch (wordBreak) {
32197        case 'break-all':
32198            return WORD_BREAK.BREAK_ALL;
32199        case 'keep-all':
32200            return WORD_BREAK.KEEP_ALL;
32201        case 'normal':
32202        default:
32203            return WORD_BREAK.NORMAL;
32204    }
32205};
32206});
32207
32208unwrapExports(wordBreak);
32209var wordBreak_1 = wordBreak.WORD_BREAK;
32210var wordBreak_2 = wordBreak.parseWordBreak;
32211
32212var zIndex = createCommonjsModule(function (module, exports) {
32213Object.defineProperty(exports, "__esModule", {
32214    value: true
32215});
32216var parseZIndex = exports.parseZIndex = function parseZIndex(zIndex) {
32217    var auto = zIndex === 'auto';
32218    return {
32219        auto: auto,
32220        order: auto ? 0 : parseInt(zIndex, 10)
32221    };
32222};
32223});
32224
32225unwrapExports(zIndex);
32226var zIndex_1 = zIndex.parseZIndex;
32227
32228var ForeignObjectRenderer_1 = createCommonjsModule(function (module, exports) {
32229Object.defineProperty(exports, "__esModule", {
32230    value: true
32231});
32232
32233var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
32234
32235function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
32236
32237var ForeignObjectRenderer = function () {
32238    function ForeignObjectRenderer(element) {
32239        _classCallCheck(this, ForeignObjectRenderer);
32240
32241        this.element = element;
32242    }
32243
32244    _createClass(ForeignObjectRenderer, [{
32245        key: 'render',
32246        value: function render(options) {
32247            var _this = this;
32248
32249            this.options = options;
32250            this.canvas = document.createElement('canvas');
32251            this.ctx = this.canvas.getContext('2d');
32252            this.canvas.width = Math.floor(options.width) * options.scale;
32253            this.canvas.height = Math.floor(options.height) * options.scale;
32254            this.canvas.style.width = options.width + 'px';
32255            this.canvas.style.height = options.height + 'px';
32256
32257            options.logger.log('ForeignObject renderer initialized (' + options.width + 'x' + options.height + ' at ' + options.x + ',' + options.y + ') with scale ' + options.scale);
32258            var svg = createForeignObjectSVG(Math.max(options.windowWidth, options.width) * options.scale, Math.max(options.windowHeight, options.height) * options.scale, options.scrollX * options.scale, options.scrollY * options.scale, this.element);
32259
32260            return loadSerializedSVG(svg).then(function (img) {
32261                if (options.backgroundColor) {
32262                    _this.ctx.fillStyle = options.backgroundColor.toString();
32263                    _this.ctx.fillRect(0, 0, options.width * options.scale, options.height * options.scale);
32264                }
32265
32266                _this.ctx.drawImage(img, -options.x * options.scale, -options.y * options.scale);
32267                return _this.canvas;
32268            });
32269        }
32270    }]);
32271
32272    return ForeignObjectRenderer;
32273}();
32274
32275exports.default = ForeignObjectRenderer;
32276var createForeignObjectSVG = exports.createForeignObjectSVG = function createForeignObjectSVG(width, height, x, y, node) {
32277    var xmlns = 'http://www.w3.org/2000/svg';
32278    var svg = document.createElementNS(xmlns, 'svg');
32279    var foreignObject = document.createElementNS(xmlns, 'foreignObject');
32280    svg.setAttributeNS(null, 'width', width);
32281    svg.setAttributeNS(null, 'height', height);
32282
32283    foreignObject.setAttributeNS(null, 'width', '100%');
32284    foreignObject.setAttributeNS(null, 'height', '100%');
32285    foreignObject.setAttributeNS(null, 'x', x);
32286    foreignObject.setAttributeNS(null, 'y', y);
32287    foreignObject.setAttributeNS(null, 'externalResourcesRequired', 'true');
32288    svg.appendChild(foreignObject);
32289
32290    foreignObject.appendChild(node);
32291
32292    return svg;
32293};
32294
32295var loadSerializedSVG = exports.loadSerializedSVG = function loadSerializedSVG(svg) {
32296    return new Promise(function (resolve, reject) {
32297        var img = new Image();
32298        img.onload = function () {
32299            return resolve(img);
32300        };
32301        img.onerror = reject;
32302
32303        img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(new XMLSerializer().serializeToString(svg));
32304    });
32305};
32306});
32307
32308unwrapExports(ForeignObjectRenderer_1);
32309var ForeignObjectRenderer_2 = ForeignObjectRenderer_1.createForeignObjectSVG;
32310var ForeignObjectRenderer_3 = ForeignObjectRenderer_1.loadSerializedSVG;
32311
32312var Feature = createCommonjsModule(function (module, exports) {
32313Object.defineProperty(exports, "__esModule", {
32314    value: true
32315});
32316
32317
32318
32319var testRangeBounds = function testRangeBounds(document) {
32320    var TEST_HEIGHT = 123;
32321
32322    if (document.createRange) {
32323        var range = document.createRange();
32324        if (range.getBoundingClientRect) {
32325            var testElement = document.createElement('boundtest');
32326            testElement.style.height = TEST_HEIGHT + 'px';
32327            testElement.style.display = 'block';
32328            document.body.appendChild(testElement);
32329
32330            range.selectNode(testElement);
32331            var rangeBounds = range.getBoundingClientRect();
32332            var rangeHeight = Math.round(rangeBounds.height);
32333            document.body.removeChild(testElement);
32334            if (rangeHeight === TEST_HEIGHT) {
32335                return true;
32336            }
32337        }
32338    }
32339
32340    return false;
32341};
32342
32343// iOS 10.3 taints canvas with base64 images unless crossOrigin = 'anonymous'
32344var testBase64 = function testBase64(document, src) {
32345    var img = new Image();
32346    var canvas = document.createElement('canvas');
32347    var ctx = canvas.getContext('2d');
32348
32349    return new Promise(function (resolve) {
32350        // Single pixel base64 image renders fine on iOS 10.3???
32351        img.src = src;
32352
32353        var onload = function onload() {
32354            try {
32355                ctx.drawImage(img, 0, 0);
32356                canvas.toDataURL();
32357            } catch (e) {
32358                return resolve(false);
32359            }
32360
32361            return resolve(true);
32362        };
32363
32364        img.onload = onload;
32365        img.onerror = function () {
32366            return resolve(false);
32367        };
32368
32369        if (img.complete === true) {
32370            setTimeout(function () {
32371                onload();
32372            }, 500);
32373        }
32374    });
32375};
32376
32377var testCORS = function testCORS() {
32378    return typeof new Image().crossOrigin !== 'undefined';
32379};
32380
32381var testResponseType = function testResponseType() {
32382    return typeof new XMLHttpRequest().responseType === 'string';
32383};
32384
32385var testSVG = function testSVG(document) {
32386    var img = new Image();
32387    var canvas = document.createElement('canvas');
32388    var ctx = canvas.getContext('2d');
32389    img.src = 'data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\'></svg>';
32390
32391    try {
32392        ctx.drawImage(img, 0, 0);
32393        canvas.toDataURL();
32394    } catch (e) {
32395        return false;
32396    }
32397    return true;
32398};
32399
32400var isGreenPixel = function isGreenPixel(data) {
32401    return data[0] === 0 && data[1] === 255 && data[2] === 0 && data[3] === 255;
32402};
32403
32404var testForeignObject = function testForeignObject(document) {
32405    var canvas = document.createElement('canvas');
32406    var size = 100;
32407    canvas.width = size;
32408    canvas.height = size;
32409    var ctx = canvas.getContext('2d');
32410    ctx.fillStyle = 'rgb(0, 255, 0)';
32411    ctx.fillRect(0, 0, size, size);
32412
32413    var img = new Image();
32414    var greenImageSrc = canvas.toDataURL();
32415    img.src = greenImageSrc;
32416    var svg = (0, ForeignObjectRenderer_1.createForeignObjectSVG)(size, size, 0, 0, img);
32417    ctx.fillStyle = 'red';
32418    ctx.fillRect(0, 0, size, size);
32419
32420    return (0, ForeignObjectRenderer_1.loadSerializedSVG)(svg).then(function (img) {
32421        ctx.drawImage(img, 0, 0);
32422        var data = ctx.getImageData(0, 0, size, size).data;
32423        ctx.fillStyle = 'red';
32424        ctx.fillRect(0, 0, size, size);
32425
32426        var node = document.createElement('div');
32427        node.style.backgroundImage = 'url(' + greenImageSrc + ')';
32428        node.style.height = size + 'px';
32429        // Firefox 55 does not render inline <img /> tags
32430        return isGreenPixel(data) ? (0, ForeignObjectRenderer_1.loadSerializedSVG)((0, ForeignObjectRenderer_1.createForeignObjectSVG)(size, size, 0, 0, node)) : Promise.reject(false);
32431    }).then(function (img) {
32432        ctx.drawImage(img, 0, 0);
32433        // Edge does not render background-images
32434        return isGreenPixel(ctx.getImageData(0, 0, size, size).data);
32435    }).catch(function (e) {
32436        return false;
32437    });
32438};
32439
32440var FEATURES = {
32441    // $FlowFixMe - get/set properties not yet supported
32442    get SUPPORT_RANGE_BOUNDS() {
32443        var value = testRangeBounds(document);
32444        Object.defineProperty(FEATURES, 'SUPPORT_RANGE_BOUNDS', { value: value });
32445        return value;
32446    },
32447    // $FlowFixMe - get/set properties not yet supported
32448    get SUPPORT_SVG_DRAWING() {
32449        var value = testSVG(document);
32450        Object.defineProperty(FEATURES, 'SUPPORT_SVG_DRAWING', { value: value });
32451        return value;
32452    },
32453    // $FlowFixMe - get/set properties not yet supported
32454    get SUPPORT_BASE64_DRAWING() {
32455        return function (src) {
32456            var _value = testBase64(document, src);
32457            Object.defineProperty(FEATURES, 'SUPPORT_BASE64_DRAWING', { value: function value() {
32458                    return _value;
32459                } });
32460            return _value;
32461        };
32462    },
32463    // $FlowFixMe - get/set properties not yet supported
32464    get SUPPORT_FOREIGNOBJECT_DRAWING() {
32465        var value = typeof Array.from === 'function' && typeof window.fetch === 'function' ? testForeignObject(document) : Promise.resolve(false);
32466        Object.defineProperty(FEATURES, 'SUPPORT_FOREIGNOBJECT_DRAWING', { value: value });
32467        return value;
32468    },
32469    // $FlowFixMe - get/set properties not yet supported
32470    get SUPPORT_CORS_IMAGES() {
32471        var value = testCORS();
32472        Object.defineProperty(FEATURES, 'SUPPORT_CORS_IMAGES', { value: value });
32473        return value;
32474    },
32475    // $FlowFixMe - get/set properties not yet supported
32476    get SUPPORT_RESPONSE_TYPE() {
32477        var value = testResponseType();
32478        Object.defineProperty(FEATURES, 'SUPPORT_RESPONSE_TYPE', { value: value });
32479        return value;
32480    },
32481    // $FlowFixMe - get/set properties not yet supported
32482    get SUPPORT_CORS_XHR() {
32483        var value = 'withCredentials' in new XMLHttpRequest();
32484        Object.defineProperty(FEATURES, 'SUPPORT_CORS_XHR', { value: value });
32485        return value;
32486    }
32487};
32488
32489exports.default = FEATURES;
32490});
32491
32492unwrapExports(Feature);
32493
32494var Util$2 = createCommonjsModule(function (module, exports) {
32495Object.defineProperty(exports, "__esModule", {
32496    value: true
32497});
32498var toCodePoints = exports.toCodePoints = function toCodePoints(str) {
32499    var codePoints = [];
32500    var i = 0;
32501    var length = str.length;
32502    while (i < length) {
32503        var value = str.charCodeAt(i++);
32504        if (value >= 0xd800 && value <= 0xdbff && i < length) {
32505            var extra = str.charCodeAt(i++);
32506            if ((extra & 0xfc00) === 0xdc00) {
32507                codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
32508            } else {
32509                codePoints.push(value);
32510                i--;
32511            }
32512        } else {
32513            codePoints.push(value);
32514        }
32515    }
32516    return codePoints;
32517};
32518
32519var fromCodePoint = exports.fromCodePoint = function fromCodePoint() {
32520    if (String.fromCodePoint) {
32521        return String.fromCodePoint.apply(String, arguments);
32522    }
32523
32524    var length = arguments.length;
32525    if (!length) {
32526        return '';
32527    }
32528
32529    var codeUnits = [];
32530
32531    var index = -1;
32532    var result = '';
32533    while (++index < length) {
32534        var codePoint = arguments.length <= index ? undefined : arguments[index];
32535        if (codePoint <= 0xffff) {
32536            codeUnits.push(codePoint);
32537        } else {
32538            codePoint -= 0x10000;
32539            codeUnits.push((codePoint >> 10) + 0xd800, codePoint % 0x400 + 0xdc00);
32540        }
32541        if (index + 1 === length || codeUnits.length > 0x4000) {
32542            result += String.fromCharCode.apply(String, codeUnits);
32543            codeUnits.length = 0;
32544        }
32545    }
32546    return result;
32547};
32548
32549var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
32550
32551// Use a lookup table to find the index.
32552var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
32553for (var i = 0; i < chars.length; i++) {
32554    lookup[chars.charCodeAt(i)] = i;
32555}
32556
32557var decode = exports.decode = function decode(base64) {
32558    var bufferLength = base64.length * 0.75,
32559        len = base64.length,
32560        i = void 0,
32561        p = 0,
32562        encoded1 = void 0,
32563        encoded2 = void 0,
32564        encoded3 = void 0,
32565        encoded4 = void 0;
32566
32567    if (base64[base64.length - 1] === '=') {
32568        bufferLength--;
32569        if (base64[base64.length - 2] === '=') {
32570            bufferLength--;
32571        }
32572    }
32573
32574    var buffer = typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint8Array.prototype.slice !== 'undefined' ? new ArrayBuffer(bufferLength) : new Array(bufferLength);
32575    var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer);
32576
32577    for (i = 0; i < len; i += 4) {
32578        encoded1 = lookup[base64.charCodeAt(i)];
32579        encoded2 = lookup[base64.charCodeAt(i + 1)];
32580        encoded3 = lookup[base64.charCodeAt(i + 2)];
32581        encoded4 = lookup[base64.charCodeAt(i + 3)];
32582
32583        bytes[p++] = encoded1 << 2 | encoded2 >> 4;
32584        bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
32585        bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
32586    }
32587
32588    return buffer;
32589};
32590
32591var polyUint16Array = exports.polyUint16Array = function polyUint16Array(buffer) {
32592    var length = buffer.length;
32593    var bytes = [];
32594    for (var _i = 0; _i < length; _i += 2) {
32595        bytes.push(buffer[_i + 1] << 8 | buffer[_i]);
32596    }
32597    return bytes;
32598};
32599
32600var polyUint32Array = exports.polyUint32Array = function polyUint32Array(buffer) {
32601    var length = buffer.length;
32602    var bytes = [];
32603    for (var _i2 = 0; _i2 < length; _i2 += 4) {
32604        bytes.push(buffer[_i2 + 3] << 24 | buffer[_i2 + 2] << 16 | buffer[_i2 + 1] << 8 | buffer[_i2]);
32605    }
32606    return bytes;
32607};
32608});
32609
32610unwrapExports(Util$2);
32611var Util_1$1 = Util$2.toCodePoints;
32612var Util_2$1 = Util$2.fromCodePoint;
32613var Util_3$1 = Util$2.decode;
32614var Util_4$1 = Util$2.polyUint16Array;
32615var Util_5 = Util$2.polyUint32Array;
32616
32617var Trie_1 = createCommonjsModule(function (module, exports) {
32618Object.defineProperty(exports, "__esModule", {
32619    value: true
32620});
32621exports.Trie = exports.createTrieFromBase64 = exports.UTRIE2_INDEX_2_MASK = exports.UTRIE2_INDEX_2_BLOCK_LENGTH = exports.UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = exports.UTRIE2_INDEX_1_OFFSET = exports.UTRIE2_UTF8_2B_INDEX_2_LENGTH = exports.UTRIE2_UTF8_2B_INDEX_2_OFFSET = exports.UTRIE2_INDEX_2_BMP_LENGTH = exports.UTRIE2_LSCP_INDEX_2_LENGTH = exports.UTRIE2_DATA_MASK = exports.UTRIE2_DATA_BLOCK_LENGTH = exports.UTRIE2_LSCP_INDEX_2_OFFSET = exports.UTRIE2_SHIFT_1_2 = exports.UTRIE2_INDEX_SHIFT = exports.UTRIE2_SHIFT_1 = exports.UTRIE2_SHIFT_2 = undefined;
32622
32623var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
32624
32625
32626
32627function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
32628
32629/** Shift size for getting the index-2 table offset. */
32630var UTRIE2_SHIFT_2 = exports.UTRIE2_SHIFT_2 = 5;
32631
32632/** Shift size for getting the index-1 table offset. */
32633var UTRIE2_SHIFT_1 = exports.UTRIE2_SHIFT_1 = 6 + 5;
32634
32635/**
32636 * Shift size for shifting left the index array values.
32637 * Increases possible data size with 16-bit index values at the cost
32638 * of compactability.
32639 * This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY.
32640 */
32641var UTRIE2_INDEX_SHIFT = exports.UTRIE2_INDEX_SHIFT = 2;
32642
32643/**
32644 * Difference between the two shift sizes,
32645 * for getting an index-1 offset from an index-2 offset. 6=11-5
32646 */
32647var UTRIE2_SHIFT_1_2 = exports.UTRIE2_SHIFT_1_2 = UTRIE2_SHIFT_1 - UTRIE2_SHIFT_2;
32648
32649/**
32650 * The part of the index-2 table for U+D800..U+DBFF stores values for
32651 * lead surrogate code _units_ not code _points_.
32652 * Values for lead surrogate code _points_ are indexed with this portion of the table.
32653 * Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.)
32654 */
32655var UTRIE2_LSCP_INDEX_2_OFFSET = exports.UTRIE2_LSCP_INDEX_2_OFFSET = 0x10000 >> UTRIE2_SHIFT_2;
32656
32657/** Number of entries in a data block. 32=0x20 */
32658var UTRIE2_DATA_BLOCK_LENGTH = exports.UTRIE2_DATA_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_2;
32659/** Mask for getting the lower bits for the in-data-block offset. */
32660var UTRIE2_DATA_MASK = exports.UTRIE2_DATA_MASK = UTRIE2_DATA_BLOCK_LENGTH - 1;
32661
32662var UTRIE2_LSCP_INDEX_2_LENGTH = exports.UTRIE2_LSCP_INDEX_2_LENGTH = 0x400 >> UTRIE2_SHIFT_2;
32663/** Count the lengths of both BMP pieces. 2080=0x820 */
32664var UTRIE2_INDEX_2_BMP_LENGTH = exports.UTRIE2_INDEX_2_BMP_LENGTH = UTRIE2_LSCP_INDEX_2_OFFSET + UTRIE2_LSCP_INDEX_2_LENGTH;
32665/**
32666 * The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820.
32667 * Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2.
32668 */
32669var UTRIE2_UTF8_2B_INDEX_2_OFFSET = exports.UTRIE2_UTF8_2B_INDEX_2_OFFSET = UTRIE2_INDEX_2_BMP_LENGTH;
32670var UTRIE2_UTF8_2B_INDEX_2_LENGTH = exports.UTRIE2_UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */
32671/**
32672 * The index-1 table, only used for supplementary code points, at offset 2112=0x840.
32673 * Variable length, for code points up to highStart, where the last single-value range starts.
32674 * Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1.
32675 * (For 0x100000 supplementary code points U+10000..U+10ffff.)
32676 *
32677 * The part of the index-2 table for supplementary code points starts
32678 * after this index-1 table.
32679 *
32680 * Both the index-1 table and the following part of the index-2 table
32681 * are omitted completely if there is only BMP data.
32682 */
32683var UTRIE2_INDEX_1_OFFSET = exports.UTRIE2_INDEX_1_OFFSET = UTRIE2_UTF8_2B_INDEX_2_OFFSET + UTRIE2_UTF8_2B_INDEX_2_LENGTH;
32684
32685/**
32686 * Number of index-1 entries for the BMP. 32=0x20
32687 * This part of the index-1 table is omitted from the serialized form.
32688 */
32689var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = exports.UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> UTRIE2_SHIFT_1;
32690
32691/** Number of entries in an index-2 block. 64=0x40 */
32692var UTRIE2_INDEX_2_BLOCK_LENGTH = exports.UTRIE2_INDEX_2_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_1_2;
32693/** Mask for getting the lower bits for the in-index-2-block offset. */
32694var UTRIE2_INDEX_2_MASK = exports.UTRIE2_INDEX_2_MASK = UTRIE2_INDEX_2_BLOCK_LENGTH - 1;
32695
32696var createTrieFromBase64 = exports.createTrieFromBase64 = function createTrieFromBase64(base64) {
32697    var buffer = (0, Util$2.decode)(base64);
32698    var view32 = Array.isArray(buffer) ? (0, Util$2.polyUint32Array)(buffer) : new Uint32Array(buffer);
32699    var view16 = Array.isArray(buffer) ? (0, Util$2.polyUint16Array)(buffer) : new Uint16Array(buffer);
32700    var headerLength = 24;
32701
32702    var index = view16.slice(headerLength / 2, view32[4] / 2);
32703    var data = view32[5] === 2 ? view16.slice((headerLength + view32[4]) / 2) : view32.slice(Math.ceil((headerLength + view32[4]) / 4));
32704
32705    return new Trie(view32[0], view32[1], view32[2], view32[3], index, data);
32706};
32707
32708var Trie = exports.Trie = function () {
32709    function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) {
32710        _classCallCheck(this, Trie);
32711
32712        this.initialValue = initialValue;
32713        this.errorValue = errorValue;
32714        this.highStart = highStart;
32715        this.highValueIndex = highValueIndex;
32716        this.index = index;
32717        this.data = data;
32718    }
32719
32720    /**
32721     * Get the value for a code point as stored in the Trie.
32722     *
32723     * @param codePoint the code point
32724     * @return the value
32725     */
32726
32727
32728    _createClass(Trie, [{
32729        key: 'get',
32730        value: function get(codePoint) {
32731            var ix = void 0;
32732            if (codePoint >= 0) {
32733                if (codePoint < 0x0d800 || codePoint > 0x0dbff && codePoint <= 0x0ffff) {
32734                    // Ordinary BMP code point, excluding leading surrogates.
32735                    // BMP uses a single level lookup.  BMP index starts at offset 0 in the Trie2 index.
32736                    // 16 bit data is stored in the index array itself.
32737                    ix = this.index[codePoint >> UTRIE2_SHIFT_2];
32738                    ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
32739                    return this.data[ix];
32740                }
32741
32742                if (codePoint <= 0xffff) {
32743                    // Lead Surrogate Code Point.  A Separate index section is stored for
32744                    // lead surrogate code units and code points.
32745                    //   The main index has the code unit data.
32746                    //   For this function, we need the code point data.
32747                    // Note: this expression could be refactored for slightly improved efficie
32747ncy, but
32748                    //       surrogate code points will be so rare in practice that it's not worth it.
32749                    ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET + (codePoint - 0xd800 >> UTRIE2_SHIFT_2)];
32750                    ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
32751                    return this.data[ix];
32752                }
32753
32754                if (codePoint < this.highStart) {
32755                    // Supplemental code point, use two-level lookup.
32756                    ix = UTRIE2_INDEX_1_OFFSET - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH + (codePoint >> UTRIE2_SHIFT_1);
32757                    ix = this.index[ix];
32758                    ix += codePoint >> UTRIE2_SHIFT_2 & UTRIE2_INDEX_2_MASK;
32759                    ix = this.index[ix];
32760                    ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
32761                    return this.data[ix];
32762                }
32763                if (codePoint <= 0x10ffff) {
32764                    return this.data[this.highValueIndex];
32765                }
32766            }
32767
32768            // Fall through.  The code point is outside of the legal range of 0..0x10ffff.
32769            return this.errorValue;
32770        }
32771    }]);
32772
32773    return Trie;
32774}();
32775});
32776
32777unwrapExports(Trie_1);
32778var Trie_2 = Trie_1.Trie;
32779var Trie_3 = Trie_1.createTrieFromBase64;
32780var Trie_4 = Trie_1.UTRIE2_INDEX_2_MASK;
32781var Trie_5 = Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH;
32782var Trie_6 = Trie_1.UTRIE2_OMITTED_BMP_INDEX_1_LENGTH;
32783var Trie_7 = Trie_1.UTRIE2_INDEX_1_OFFSET;
32784var Trie_8 = Trie_1.UTRIE2_UTF8_2B_INDEX_2_LENGTH;
32785var Trie_9 = Trie_1.UTRIE2_UTF8_2B_INDEX_2_OFFSET;
32786var Trie_10 = Trie_1.UTRIE2_INDEX_2_BMP_LENGTH;
32787var Trie_11 = Trie_1.UTRIE2_LSCP_INDEX_2_LENGTH;
32788var Trie_12 = Trie_1.UTRIE2_DATA_MASK;
32789var Trie_13 = Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
32790var Trie_14 = Trie_1.UTRIE2_LSCP_INDEX_2_OFFSET;
32791var Trie_15 = Trie_1.UTRIE2_SHIFT_1_2;
32792var Trie_16 = Trie_1.UTRIE2_INDEX_SHIFT;
32793var Trie_17 = Trie_1.UTRIE2_SHIFT_1;
32794var Trie_18 = Trie_1.UTRIE2_SHIFT_2;
32795
32796var linebreakTrie = 'KwAAAAAAAAAACA4AIDoAAPAfAAACAAAAAAAIABAAGABAAEgAUABYAF4AZgBeAGYAYABoAHAAeABeAGYAfACEAIAAiACQAJgAoACoAK0AtQC9AMUAXgBmAF4AZgBeAGYAzQDVAF4AZgDRANkA3gDmAOwA9AD8AAQBDAEUARoBIgGAAIgAJwEvATcBPwFFAU0BTAFUAVwBZAFsAXMBewGDATAAiwGTAZsBogGkAawBtAG8AcIBygHSAdoB4AHoAfAB+AH+AQYCDgIWAv4BHgImAi4CNgI+AkUCTQJTAlsCYwJrAnECeQKBAk0CiQKRApkCoQKoArACuALAAsQCzAIwANQC3ALkAjAA7AL0AvwCAQMJAxADGAMwACADJgMuAzYDPgOAAEYDSgNSA1IDUgNaA1oDYANiA2IDgACAAGoDgAByA3YDfgOAAIQDgACKA5IDmgOAAIAAogOqA4AAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAK8DtwOAAIAAvwPHA88D1wPfAyAD5wPsA/QD/AOAAIAABAQMBBIEgAAWBB4EJgQuBDMEIAM7BEEEXgBJBCADUQRZBGEEaQQwADAAcQQ+AXkEgQSJBJEEgACYBIAAoASoBK8EtwQwAL8ExQSAAIAAgACAAIAAgACgAM0EXgBeAF4AXgBeAF4AXgBeANUEXgDZBOEEXgDpBPEE+QQBBQkFEQUZBSEFKQUxBTUFPQVFBUwFVAVcBV4AYwVeAGsFcwV7BYMFiwWSBV4AmgWgBacFXgBeAF4AXgBeAKsFXgCyBbEFugW7BcIFwgXIBcIFwgXQBdQF3AXkBesF8wX7BQMGCwYTBhsGIwYrBjMGOwZeAD8GRwZNBl4AVAZbBl4AXgBeAF4AXgBeAF4AXgBeAF4AXgBeAGMGXgBqBnEGXgBeAF4AXgBeAF4AXgBeAF4AXgB5BoAG4wSGBo4GkwaAAIADHgR5AF4AXgBeAJsGgABGA4AAowarBrMGswagALsGwwbLBjAA0wbaBtoG3QbaBtoG2gbaBtoG2gblBusG8wb7BgMHCwcTBxsHCwcjBysHMAc1BzUHOgdCB9oGSgdSB1oHYAfaBloHaAfaBlIH2gbaBtoG2gbaBtoG2gbaBjUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHbQdeAF4ANQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQd1B30HNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B4MH2gaKB68EgACAAIAAgACAAIAAgACAAI8HlwdeAJ8HpweAAIAArwe3B14AXgC/B8UHygcwANAH2AfgB4AA6AfwBz4B+AcACFwBCAgPCBcIogEYAR8IJwiAAC8INwg/CCADRwhPCFcIXwhnCEoDGgSAAIAAgABvCHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIhAiLCI4IMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlggwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAANQc1BzUHNQc1BzUHNQc1BzUHNQc1B54INQc1B6II2gaqCLIIugiAAIAAvgjGCIAAgACAAIAAgACAAIAAgACAAIAAywiHAYAA0wiAANkI3QjlCO0I9Aj8CIAAgACAAAIJCgkSCRoJIgknCTYHLwk3CZYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiAAIAAAAFAA
32796XgBeAGAAcABeAHwAQACQAKAArQC9AJ4AXgBeAE0A3gBRAN4A7AD8AMwBGgEAAKcBNwEFAUwBXAF4QkhCmEKnArcCgAHHAsABz4LAAcABwAHAAd+C6ABoAG+C/4LAAcABwAHAAc+DF4MAAcAB54M3gweDV4Nng3eDaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAEeDqABVg6WDqABoQ6gAaABoAHXDvcONw/3DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DncPAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcAB7cPPwlGCU4JMACAAIAAgABWCV4JYQmAAGkJcAl4CXwJgAkwADAAMAAwAIgJgACLCZMJgACZCZ8JowmrCYAAswkwAF4AXgB8AIAAuwkABMMJyQmAAM4JgADVCTAAMAAwADAAgACAAIAAgACAAIAAgACAAIAAqwYWBNkIMAAwADAAMADdCeAJ6AnuCR4E9gkwAP4JBQoNCjAAMACAABUK0wiAAB0KJAosCjQKgAAwADwKQwqAAEsKvQmdCVMKWwowADAAgACAALcEMACAAGMKgABrCjAAMAAwADAAMAAwADAAMAAwADAAMAAeBDAAMAAwADAAMAAwADAAMAAwADAAMAAwAIkEPQFzCnoKiQSCCooKkAqJBJgKoAqkCokEGAGsCrQKvArBCjAAMADJCtEKFQHZCuEK/gHpCvEKMAAwADAAMACAAIwE+QowAIAAPwEBCzAAMAAwADAAMACAAAkLEQswAIAAPwEZCyELgAAOCCkLMAAxCzkLMAAwADAAMAAwADAAXgBeAEELMAAwADAAMAAwADAAMAAwAEkLTQtVC4AAXAtkC4AAiQkwADAAMAAwADAAMAAwADAAbAtxC3kLgAuFC4sLMAAwAJMLlwufCzAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAApwswADAAMACAAIAAgACvC4AAgACAAIAAgACAALcLMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAvwuAAMcLgACAAIAAgACAAIAAyguAAIAAgACAAIAA0QswADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAANkLgACAAIAA4AswADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACJCR4E6AswADAAhwHwC4AA+AsADAgMEAwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMACAAIAAGAwdDCUMMAAwAC0MNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQw1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHPQwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADUHNQc1BzUHNQc1BzUHNQc2BzAAMAA5DDUHNQc1BzUHNQc1BzUHNQc1BzUHNQdFDDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAgACAAIAATQxSDFoMMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAF4AXgBeAF4AXgBeAF4AYgxeAGoMXgBxDHkMfwxeAIUMXgBeAI0MMAAwADAAMAAwAF4AXgCVDJ0MMAAwADAAMABeAF4ApQxeAKsMswy7DF4Awgy9DMoMXgBeAF4AXgBeAF4AXgBeAF4AXgDRDNkMeQBqCeAM3Ax8AOYM7Az0DPgMXgBeAF4AXgBeAF4AXgBeAF4AXgBeAF4AXgBeAF4AXgCgAAANoAAHDQ4NFg0wADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAeDSYNMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIAAgACAAIAAgACAAC4NMABeAF4ANg0wADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAD4NRg1ODVYNXg1mDTAAbQ0wADAAMAAwADAAMAAwADAA2gbaBtoG2gbaBtoG2gbaBnUNeg3CBYANwgWFDdoGjA3aBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gaUDZwNpA2oDdoG2gawDbcNvw3HDdoG2gbPDdYN3A3fDeYN2gbsDfMN2gbaBvoN/g3aBgYODg7aBl4AXgBeABYOXgBeACUG2gYeDl4AJA5eACwO2w3aBtoGMQ45DtoG2gbaBtoGQQ7aBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gZJDjUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B1EO2gY1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQdZDjUHNQc1BzUHNQc1B2EONQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHaA41BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B3AO2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gY1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B2EO2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gZJDtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBkkOeA6gAKAAoAAwADAAMAAwA
32796KAAoACgAKAAoACgAKAAgA4wADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAD//wQABAAEAAQABAAEAAQABAAEAA0AAwABAAEAAgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAKABMAFwAeABsAGgAeABcAFgASAB4AGwAYAA8AGAAcAEsASwBLAEsASwBLAEsASwBLAEsAGAAYAB4AHgAeABMAHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAFgAbABIAHgAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYADQARAB4ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAUABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkAFgAaABsAGwAbAB4AHQAdAB4ATwAXAB4ADQAeAB4AGgAbAE8ATwAOAFAAHQAdAB0ATwBPABcATwBPAE8AFgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAFAATwBAAE8ATwBPAEAATwBQAFAATwBQAB4AHgAeAB4AHgAeAB0AHQAdAB0AHgAdAB4ADgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgBQAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkACQAJAAkACQAJAAkABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAFAAHgAeAB4AKwArAFAAUABQAFAAGABQACsAKwArACsAHgAeAFAAHgBQAFAAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUAAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAYAA0AKwArAB4AHgAbACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAB4ABAAEAB4ABAAEABMABAArACsAKwArACsAKwArACsAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAKwArACsAKwArAFYAVgBWAB4AHgArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AGgAaABoAGAAYAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQAEwAEACsAEwATAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABLAEsASwBLAEsASwBLAEsASwBLABoAGQAZAB4AUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABMAUAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABABQAFAABAAEAB4ABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUAAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAFAABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQAUABQAB4AHgAYABMAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAFAABAAEAAQABAAEAFAABAAEAAQAUAAEAAQABAAEAAQAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArACsAHgArAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAAQABAANAA0ASwBLAEsASwBLAEsASwBLAEsASwAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAKwArACsAUABQAFAAUAArACsABABQAAQABAAEAAQABAAEAAQAKwArAAQABAArACsABAAEAAQAUAArACsAKwArACsAKwArACsABAArACsAKwArAFAAUAArAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAGgAaAFAAUABQAFAAUABMAB4AGwBQAB4AKwArACsABAAEAAQAKwBQAFAAUABQAFAAUAArACsAKwArAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUAArAFAAUAArACsABAArAAQABAAEAAQABAArACsAKwArAAQABAArACsABAAEAAQAKwArACsABAArACsAKwArACsAKwArAFAAUABQAFAAKwBQACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwAEAAQAUABQAFAABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUABQAFAAUAArACsABABQAAQABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQAKwArAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwAeABsAKwArACsAKwArACsAKwBQAAQABAAEAAQABAAEACsABAAEAAQAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwArAAQABAArACsABAAEAAQAKwArACsAKwArACsAKwArAAQABAArACsAKwArAFAAUAArAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwAeAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwAEAFAAKwBQAFAAUABQAFAAUAArACsAKwBQAFAAUAArAFAAUABQAFAAKwArACsAUABQACsAUAArAFAAUAArACsAKwBQAFAAKwArACsAUABQAFAAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAAQABAAEAAQAKwArACsABAAEAAQAKwAEAAQABAAEACsAKwBQACsAKwArACsAKwArAAQAKwArACsAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAB4AHgAeAB4AHgAeABsAHgArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABAArACsAKwArACsAKwArAAQABAArAFAAUABQACsAKwArACsAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAB4AUAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABAArACsAKwArACsAKwArAAQABAArACsAKwArACsAKwArAFAAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABABQAB4AKwArACsAKwBQAFAAUAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQABoAUABQAFAAUABQAFAAKwArAAQABAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQACsAUAArACsAUABQAFAAUABQAFAAUAArACsAKwAEACsAKwArACsABAAEAAQABAAEAAQAKwAEACsABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgAqACsAKwArACsAGwBcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAeAEsASwBLAEsASwBLAEsASwBLAEsADQANACsAKwArACsAKwBcAFwAKwBcACsAKwBcAFwAKwBcACsAKwBcACsAKwArACsAKwArAFwAXABcAFwAKwBcAFwAXABcAFwAXABcACsAXABcAFwAKwBcACsAXAArACsAXABcACsAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgArACoAKgBcACsAKwBcAFwAXABcAFwAKwBcACsAKgAqACoAKgAqACoAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAFwAXABcAFwAUAAOAA4ADgAOAB4ADgAOAAkADgAOAA0ACQATABMAEwATABMACQAeABMAHgAeAB4ABAAEAB4AHgAeAB4AHgAeAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUAANAAQAHgAEAB4ABAAWABEAFgARAAQABABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAAQABAAEAAQABAANAAQABABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsADQANAB4AHgAeAB4AHgAeAAQAHgAeAB4AHgAeAB4AKwAeAB4ADgAOAA0ADgAeAB4AHgAeAB4ACQAJACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqAFwASwBLAEsASwBLAEsASwBLAEsASwANAA0AHgAeAB4AHgBcAFwAXABcAFwAXAAqACoAKgAqAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAKgAqACoAKgAqACoAKgBcAFwAXAAqACoAKgAqAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAXAAqAEsASwBLAEsASwBLAEsASwBLAEsAKgAqACoAKgAqACoAUABQAFAAUABQAFAAKwBQACsAKwArACsAKwBQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQACsAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwAEAAQABAAeAA0AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYAEQArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAADQANAA0AUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAA0ADQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsABAAEACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoADQANABUAXAANAB4ADQAbAFwAKgArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAB4AHgATABMADQANAA4AHgATABMAHgAEAAQABAAJACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAUABQAFAAUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwAeACsAKwArABMAEwBLAEsASwBLAEsASwBLAEsASwBLAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwBcAFwAXABcAFwAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBcACsAKwArACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEACsAKwAeAB4AXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgArACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgArACsABABLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKgAqACoAKgAqACoAKgBcACoAKgAqACoAKgAqACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAUABQAFAAUABQAFAAUAArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsADQANAB4ADQANAA0ADQAeAB4AHgAeAB4AHgAeAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAHgAeAB4AHgBQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwANAA0ADQANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwBQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAA0AUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsABAAEAAQAHgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAUABQAFAABABQAFAAUABQAAQABAAEAFAAUAAEAAQABAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAKwBQACsAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAHgAeAB4AHgAeAB4AHgAeAFAAHgAeAB4AUABQAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAKwArAB4AHgAeAB4AHgAeACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAUABQAFAAKwAeAB4AHgAeAB4AHgAeAA4AHgArAA0ADQANAA0ADQANAA0ACQANAA0ADQAIAAQACwAEAAQADQAJAA0ADQAMAB0AHQAeABcAFwAWABcAFwAXABYAFwAdAB0AHgAeABQAFAAUAA0AAQABAAQABAAEAAQABAAJABoAGgAaABoAGgAaABoAGgAeABcAFwAdABUAFQAeAB4AHgAeAB4AHgAYABYAEQAVABUAFQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgANAB4ADQANAA0ADQAeAA0ADQANAAcAHgAeAB4AHgArAAQABAAEAAQABAAEAAQABAAEAAQAUABQACsAKwBPAFAAUABQAFAAUAAeAB4AHgAWABEATwBQAE8ATwBPAE8AUABQAFAAUABQAB4AHgAeABYAEQArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAGwAbABsAGwAbABsAGwAaABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAaABsAGwAbABsAGgAbABsAGgAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgBQABoAHgAdAB4AUAAeABoAHgAeAB4AHgAeAB4AHgAeAB4ATwAeAFAAGwAeAB4AUABQAFAAUABQAB4AHgAeAB0AH
32796QAeAFAAHgBQAB4AUAAeAFAATwBQAFAAHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AUABQAFAAUABPAE8AUABQAFAAUABQAE8AUABQAE8AUABPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBQAFAAUABQAE8ATwBPAE8ATwBPAE8ATwBPAE8AUABQAFAAUABQAFAAUABQAFAAHgAeAFAAUABQAFAATwAeAB4AKwArACsAKwAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB0AHQAeAB4AHgAdAB0AHgAeAB0AHgAeAB4AHQAeAB0AGwAbAB4AHQAeAB4AHgAeAB0AHgAeAB0AHQAdAB0AHgAeAB0AHgAdAB4AHQAdAB0AHQAdAB0AHgAdAB4AHgAeAB4AHgAdAB0AHQAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAdAB4AHgAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHgAdAB0AHQAdAB4AHgAdAB0AHgAeAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHQAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABQAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAlACUAHgAeAB4AHgAeAB4AHgAeAB4AFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQBPAE8ATw
32796BPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBQAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeAB4AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAdAB0AHQAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAeAB4AHgAeAB0AHQAeAB4AHgAeAB0AHQAdAB4AHgAdAB4AHgAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB0AHQAeAB4AHQAeAB4AHgAeAB0AHQAeAB4AHgAeACUAJQAdAB0AJQAeACUAJQAlACAAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAHgAeAB4AHgAdAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHQAdAB0AHgAdACUAHQAdAB4AHQAdAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAHQAdAB0AHQAlAB4AJQAlACUAHQAlACUAHQAdAB0AJQAlAB0AHQAlAB0AHQAlACUAJQAeAB0AHgAeAB4AHgAdAB0AJQAdAB0AHQAdAB0AHQAlACUAJQAlACUAHQAlACUAIAAlAB0AHQAlACUAJQAlACUAJQAlACUAHgAeAB4AJQAlACAAIAAgACAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeABcAFwAXABcAFwAXAB4AEwATACUAHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAWABEAFgARAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAeAB4AKwArACsAKwArABMADQANAA0AUAATAA0AUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUAANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAA0ADQANAA0ADQANAA0ADQAeAA0AFgANAB4AHgAXABcAHgAeABcAFwAWABEAFgARABYAEQAWABEADQANAA0ADQATAFAADQANAB4ADQANAB4AHgAeAB4AHgAMAAwADQANAA0AHgANAA0AFgANAA0ADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArAA0AEQARACUAJQBHAFcAVwAWABEAFgARABYAEQAWABEAFgARACUAJQAWABEAFgARABYAEQAWABEAFQAWABEAEQAlAFcAVwBXAFcAVwBXAFcAVwBXAAQABAAEAAQABAAEACUAVwBXAFcAVwA2ACUAJQBXAFcAVwBHAEcAJQAlACUAKwBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBRAFcAUQBXAFEAVwBXAFcAVwBXAFcAUQBXAFcAVwBXAFcAVwBRAFEAKwArAAQABAAVABUARwBHAFcAFQBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBRAFcAVwBXAFcAVwBXAFEAUQBXAFcAVwBXABUAUQBHAEcAVwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwArACUAJQBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAKwArACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAE8ATw
32796BPAE8ATwBPAE8ATwAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADQATAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQAHgBQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAeAA0ADQANAA0ADQArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAAQAUABQAFAABABQAFAAUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAeAB4AHgAeACsAKwArACsAUABQAFAAUABQAFAAHgAeABoAHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADgAOABMAEwArACsAKwArACsAKwArACsABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUAAeAB4AHgBQAA4AUAArACsAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAB4AWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYACsAKwArAAQAHgAeAB4AHgAeAB4ADQANAA0AHgAeAB4AHgArAFAASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArAB4AHgBcAFwAXABcAFwAKgBcAFwAXABcAFwAXABcAFwAXABcAEsASwBLAEsASwBLAEsASwBLAEsAXABcAFwAXABcACsAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAFAAUABQAAQAUABQAFAAUABQAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAHgANAA0ADQBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAKgAqACoAXABcACoAKgBcAFwAXABcAFwAKgAqAFwAKgBcACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAA0ADQBQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQADQAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAVABVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBUAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVACsAKwArACsAKwArACsAKwArACsAKwArAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAKwArACsAKwBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAKwArACsAKwAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArACsAKwArAFYABABWAFYAVgBWAFYAVgBWAFYAVgBWAB4AVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgArAFYAVgBWAFYAVgArAFYAKwBWAFYAKwBWAFYAKwBWAFYAVgBWAFYAVgBWAFYAVgBWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAEQAWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAaAB4AKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAGAARABEAGAAYABMAEwAWABEAFAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACUAJQAlACUAJQAWABEAFgARABYAEQAWABEAFgARABYAEQAlACUAFgARACUAJQAlACUAJQAlACUAEQAlABEAKwAVABUAEwATACUAFgARABYAEQAWABEAJQAlACUAJQAlACUAJQAlACsAJQAbABoAJQArACsAKwArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAcAKwATACUAJQAbABoAJQAlABYAEQAlACUAEQAlABEAJQBXAFcAVwBXAFcAVwBXAFcAVwBXABUAFQAlACUAJQATACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXABYAJQARACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAWACUAEQAlABYAEQARABYAEQARABUAVwBRAFEAUQBRAFEAUQBRAFEAUQBRAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcARwArACsAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXACsAKwBXAFcAVwBXAFcAVwArACsAVwBXAFcAKwArACsAGgAbACUAJQAlABsAGwArAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAAQAB0AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsADQANAA0AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQBQAFAAUABQACsAKwArACsAUABQAFAAUABQAFAAUABQAA0AUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQACsAKwArAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgBQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwBQAFAAUABQAFAABAAEAAQAKwAEAAQAKwArACsAKwArAAQABAAEAAQAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsABAAEAAQAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsADQANAA0ADQANAA0ADQANAB4AKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AUABQAFAAUABQAFAAUABQAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwArACsAUABQAFAAUABQAA0ADQANAA0ADQANABQAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwANAA0ADQANAA0ADQANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQAeAB4AHgAeAB4AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsASwBLAEsASwBLAEsASwBLAEsASwANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAeAA4AUAArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAADQANAB4ADQAeAAQABAAEAB4AKwArAEsASwBLAEsASwBLAEsASwBLAEsAUAAOAFAADQANAA0AKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAA0AHgANAA0AHgAEACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAA0AKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAUAArACsAKwArACsAKwAEACsAKwArACsAKwBQAFAAUABQAFAABAAEACsAKwAEAAQABAAEAAQABAAEACsAKwArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABABQAFAAUABQAA0ADQANAA0AHgBLAEsASwBLAEsASwBLAEsASwBLACsADQArAB4AKwArAAQABAAEAAQAUABQAB4AUAArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEACsAKwAEAAQABAAEAAQABAAEAAQABAAOAA0ADQATABMAHgAeAB4ADQANAA0ADQANAA0ADQANAA0ADQANAA0ADQANAA0AUABQAFAAUAAEAAQAKwArAAQADQANAB4AUAArACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAKwAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAXABcAA0ADQANACoASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAOAB4ADQANAA0ADQAOAB4ABAArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAFAAUAArACsAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAA0ADQANACsADgAOAA4ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAFAADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAOABMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAArACsAKwAEACsABAAEACsABAAEAAQABAAEAAQABABQAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABIAEgAQwBDAEMAUABQAFAAUABDAFAAUABQAEgAQwBIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABDAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwANAA0AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAANACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQANAB4AHgAeAB4AHgAeAFAAUABQAFAADQAeACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEcARwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwArACsAKwArACsAKwArACsAKwArACsAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQACsAKwAeAAQABAANAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAHgAeAAQABAAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAEAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUAArACsAUAArACsAUABQACsAKwBQAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQACsAUABQAFAAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwAeAB4AUABQAFAAUABQACsAUAArACsAKwBQAFAAUABQAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AKwArAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAEAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAeAB4ADQANAA0ADQAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABAArAAQABAArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAEAAQABAAEAAQABAAEACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAFgAWAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArAFAAKwArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArAFAAKwBQACsAKwArACsAKwArAFAAKwArACsAKwBQACsAUAArAFAAKwBQAFAAUAArAFAAUAArAFAAKwArAFAAKwBQACsAUAArAFAAKwBQACsAUABQACsAUAArACsAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAUABQAFAAUAArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUA
vendor: 4,701 bytes, lines 32796-32806
32796BQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwBQAFAAUAArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAlACUAJQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeACUAJQAlACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeACUAJQAlACUAJQAeACUAJQAlACUAJQAgACAAIAAlACUAIAAlACUAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIQAhACEAIQAhACUAJQAgACAAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAgACAAIAAlACUAJQAlACAAJQAgACAAIAAgACAAIAAgACAAIAAlACUAJQAgACUAJQAlACUAIAAgACAAJQAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeACUAHgAlAB4AJQAlACUAJQAlACAAJQAlACUAJQAeACUAHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAgACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAlACUAJQAlACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAIAAgACAAJQAlACUAIAAgACAAIAAgAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFwAXABcAFQAVABUAHgAeAB4AHgAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAgACAAJQAlACUAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAlACAAIAAlACUAJQAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAIAAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsA';
32797
32798var LineBreak = createCommonjsModule(function (module, exports) {
32799Object.defineProperty(exports, "__esModule", {
32800    value: true
32801});
32802exports.LineBreaker = exports.inlineBreakOpportunities = exports.lineBreakAtIndex = exports.codePointsToCharacterClasses = exports.UnicodeTrie = exports.BREAK_ALLOWED = exports.BREAK_NOT_ALLOWED = exports.BREAK_MANDATORY = exports.classes = exports.LETTER_NUMBER_MODIFIER = undefined;
32803
32804var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
32805
32806var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); }
32806 else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
32807
32808
32809
32810
32811
32812var _linebreakTrie2 = _interopRequireDefault(linebreakTrie);
32813
32814
32815
32816function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
32817
32818function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
32819
32820function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
32821
32822var LETTER_NUMBER_MODIFIER = exports.LETTER_NUMBER_MODIFIER = 50;
32823
32824// Non-tailorable Line Breaking Classes
32825var BK = 1; //  Cause a line break (after)
32826var CR = 2; //  Cause a line break (after), except between CR and LF
32827var LF = 3; //  Cause a line break (after)
32828var CM = 4; //  Prohibit a line break between the character and the preceding character
32829var NL = 5; //  Cause a line break (after)
32830var SG = 6; //  Do not occur in well-formed text
32831var WJ = 7; //  Prohibit line breaks before and after
32832var ZW = 8; //  Provide a break opportunity
32833var GL = 9; //  Prohibit line breaks before and after
32834var SP = 10; // Enable indirect line breaks
32835var ZWJ = 11; // Prohibit line breaks within joiner sequences
32836// Break Opportunities
32837var B2 = 12; //  Provide a line break opportunity before and after the character
32838var BA = 13; //  Generally provide a line break opportunity after the character
32839var BB = 14; //  Generally provide a line break opportunity before the character
32840var HY = 15; //  Provide a line break opportunity after the character, except in numeric context
32841var CB = 16; //   Provide a line break opportunity contingent on additional information
32842// Characters Prohibiting Certain Breaks
32843var CL = 17; //  Prohibit line breaks before
32844var CP = 18; //  Prohibit line breaks before
32845var EX = 19; //  Prohibit line breaks before
32846var IN = 20; //  Allow only indirect line breaks between pairs
32847var NS = 21; //  Allow only indirect line breaks before
32848var OP = 22; //  Prohibit line breaks after
32849var QU = 23; //  Act like they are both opening and closing
32850// Numeric Context
32851var IS = 24; //  Prevent breaks after any and before numeric
32852var NU = 25; //  Form numeric expressions for line breaking purposes
32853var PO = 26; //  Do not break following a numeric expression
32854var PR = 27; //  Do not break in front of a numeric expression
32855var SY = 28; //  Prevent a break before; and allow a break after
32856// Other Characters
32857var AI = 29; //  Act like AL when the resolvedEAW is N; otherwise; act as ID
32858var AL = 30; //  Are alphabetic characters or symbols that are used with alphabetic characters
32859var CJ = 31; //  Treat as NS or ID for strict or normal breaking.
32860var EB = 32; //  Do not break from following Emoji Modifier
32861var EM = 33; //  Do not break from preceding Emoji Base
32862var H2 = 34; //  Form Korean syllable blocks
32863var H3 = 35; //  Form Korean syllable blocks
32864var HL = 36; //  Do not break around a following hyphen; otherwise act as Alphabetic
32865var ID = 37; //  Break before or after; except in some numeric context
32866var JL = 38; //  Form Korean syllable blocks
32867var JV = 39; //  Form Korean syllable blocks
32868var JT = 40; //  Form Korean syllable blocks
32869var RI = 41; //  Keep pairs together. For pairs; break before and after other classes
32870var SA = 42; //  Provide a line break opportunity contingent on additional, language-specific context analysis
32871var XX = 43; //  Have as yet unknown line breaking behavior or unassigned code positions
32872
32873var classes = exports.classes = {
32874    BK: BK,
32875    CR: CR,
32876    LF: LF,
32877    CM: CM,
32878    NL: NL,
32879    SG: SG,
32880    WJ: WJ,
32881    ZW: ZW,
32882    GL: GL,
32883    SP: SP,
32884    ZWJ: ZWJ,
32885    B2: B2,
32886    BA: BA,
32887    BB: BB,
32888    HY: HY,
32889    CB: CB,
32890    CL: CL,
32891    CP: CP,
32892    EX: EX,
32893    IN: IN,
32894    NS: NS,
32895    OP: OP,
32896    QU: QU,
32897    IS: IS,
32898    NU: NU,
32899    PO: PO,
32900    PR: PR,
32901    SY: SY,
32902    AI: AI,
32903    AL: AL,
32904    CJ: CJ,
32905    EB: EB,
32906    EM: EM,
32907    H2: H2,
32908    H3: H3,
32909    HL: HL,
32910    ID: ID,
32911    JL: JL,
32912    JV: JV,
32913    JT: JT,
32914    RI: RI,
32915    SA: SA,
32916    XX: XX
32917};
32918
32919var BREAK_MANDATORY = exports.BREAK_MANDATORY = '!';
32920var BREAK_NOT_ALLOWED = exports.BREAK_NOT_ALLOWED = '×';
32921var BREAK_ALLOWED = exports.BREAK_ALLOWED = '÷';
32922var UnicodeTrie = exports.UnicodeTrie = (0, Trie_1.createTrieFromBase64)(_linebreakTrie2.default);
32923
32924var ALPHABETICS = [AL, HL];
32925var HARD_LINE_BREAKS = [BK, CR, LF, NL];
32926var SPACE = [SP, ZW];
32927var PREFIX_POSTFIX = [PR, PO];
32928var LINE_BREAKS = HARD_LINE_BREAKS.concat(SPACE);
32929var KOREAN_SYLLABLE_BLOCK = [JL, JV, JT, H2, H3];
32930var HYPHEN = [HY, BA];
32931
vendor: 5,126 bytes, lines 32932-33097
32932var codePointsToCharacterClasses = exports.codePointsToCharacterClasses = function codePointsToCharacterClasses(codePoints) {
32933    var lineBreak = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'strict';
32934
32935    var types = [];
32936    var indicies = [];
32937    var categories = [];
32938    codePoints.forEach(function (codePoint, index) {
32939        var classType = UnicodeTrie.get(codePoint);
32940        if (classType > LETTER_NUMBER_MODIFIER) {
32941            categories.push(true);
32942            classType -= LETTER_NUMBER_MODIFIER;
32943        } else {
32944            categories.push(false);
32945        }
32946
32947        if (['normal', 'auto', 'loose'].indexOf(lineBreak) !== -1) {
32948            // U+2010, – U+2013, 〜 U+301C, ゠ U+30A0
32949            if ([0x2010, 0x2013, 0x301c, 0x30a0].indexOf(codePoint) !== -1) {
32950                indicies.push(index);
32951                return types.push(CB);
32952            }
32953        }
32954
32955        if (classType === CM || classType === ZWJ) {
32956            // LB10 Treat any remaining combining mark or ZWJ as AL.
32957            if (index === 0) {
32958                indicies.push(index);
32959                return types.push(AL);
32960            }
32961
32962            // LB9 Do not break a combining character sequence; treat it as if it has the line breaking class of
32963            // the base character in all of the following rules. Treat ZWJ as if it were CM.
32964            var prev = types[index - 1];
32965            if (LINE_BREAKS.indexOf(prev) === -1) {
32966                indicies.push(indicies[index - 1]);
32967                return types.push(prev);
32968            }
32969            indicies.push(index);
32970            return types.push(AL);
32971        }
32972
32973        indicies.push(index);
32974
32975        if (classType === CJ) {
32976            return types.push(lineBreak === 'strict' ? NS : ID);
32977        }
32978
32979        if (classType === SA) {
32980            return types.push(AL);
32981        }
32982
32983        if (classType === AI) {
32984            return types.push(AL);
32985        }
32986
32987        // For supplementary characters, a useful default is to treat characters in the range 10000..1FFFD as AL
32988        // and characters in the ranges 20000..2FFFD and 30000..3FFFD as ID, until the implementation can be revised
32989        // to take into account the actual line breaking properties for these characters.
32990        if (classType === XX) {
32991            if (codePoint >= 0x20000 && codePoint <= 0x2fffd || codePoint >= 0x30000 && codePoint <= 0x3fffd) {
32992                return types.push(ID);
32993            } else {
32994                return types.push(AL);
32995            }
32996        }
32997
32998        types.push(classType);
32999    });
33000
33001    return [indicies, types, categories];
33002};
33003
33004var isAdjacentWithSpaceIgnored = function isAdjacentWithSpaceIgnored(a, b, currentIndex, classTypes) {
33005    var current = classTypes[currentIndex];
33006    if (Array.isArray(a) ? a.indexOf(current) !== -1 : a === current) {
33007        var i = currentIndex;
33008        while (i <= classTypes.length) {
33009            i++;
33010            var next = classTypes[i];
33011
33012            if (next === b) {
33013                return true;
33014            }
33015
33016            if (next !== SP) {
33017                break;
33018            }
33019        }
33020    }
33021
33022    if (current === SP) {
33023        var _i = currentIndex;
33024
33025        while (_i > 0) {
33026            _i--;
33027            var prev = classTypes[_i];
33028
33029            if (Array.isArray(a) ? a.indexOf(prev) !== -1 : a === prev) {
33030                var n = currentIndex;
33031                while (n <= classTypes.length) {
33032                    n++;
33033                    var _next = classTypes[n];
33034
33035                    if (_next === b) {
33036                        return true;
33037                    }
33038
33039                    if (_next !== SP) {
33040                        break;
33041                    }
33042                }
33043            }
33044
33045            if (prev !== SP) {
33046                break;
33047            }
33048        }
33049    }
33050    return false;
33051};
33052
33053var previousNonSpaceClassType = function previousNonSpaceClassType(currentIndex, classTypes) {
33054    var i = currentIndex;
33055    while (i >= 0) {
33056        var type = classTypes[i];
33057        if (type === SP) {
33058            i--;
33059        } else {
33060            return type;
33061        }
33062    }
33063    return 0;
33064};
33065
33066var _lineBreakAtIndex = function _lineBreakAtIndex(codePoints, classTypes, indicies, index, forbiddenBreaks) {
33067    if (indicies[index] === 0) {
33068        return BREAK_NOT_ALLOWED;
33069    }
33070
33071    var currentIndex = index - 1;
33072    if (Array.isArray(forbiddenBreaks) && forbiddenBreaks[currentIndex] === true) {
33073        return BREAK_NOT_ALLOWED;
33074    }
33075
33076    var beforeIndex = currentIndex - 1;
33077    var afterIndex = currentIndex + 1;
33078    var current = classTypes[currentIndex];
33079
33080    // LB4 Always break after hard line breaks.
33081    // LB5 Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks.
33082    var before = beforeIndex >= 0 ? classTypes[beforeIndex] : 0;
33083    var next = classTypes[afterIndex];
33084
33085    if (current === CR && next === LF) {
33086        return BREAK_NOT_ALLOWED;
33087    }
33088
33089    if (HARD_LINE_BREAKS.indexOf(current) !== -1) {
33090        return BREAK_MANDATORY;
33091    }
33092
33093    // LB6 Do not break before hard line breaks.
33094    if (HARD_LINE_BREAKS.indexOf(next) !== -1) {
33095        return BREAK_NOT_ALLOWED;
33096    }
33097
33098    // LB7 Do not break before spaces or zero width space.
33099    if (SPACE.indexOf(next) !== -1) {
33100        return BREAK_NOT_ALLOWED;
33101    }
33102
33103    // LB8 Break before any character following a zero-width space, even if one or more spaces intervene.
33104    if (previousNonSpaceClassType(currentIndex, classTypes) === ZW) {
33105        return BREAK_ALLOWED;
33106    }
33107
33108    // LB8a Do not break between a zero width joiner and an ideograph, emoji base or emoji modifier.
33109    if (UnicodeTrie.get(codePoints[currentIndex]) === ZWJ && (next === ID || next === EB || next === EM)) {
33110        return BREAK_NOT_ALLOWED;
33111    }
33112
33113    // LB11 Do not break before or after Word joiner and related characters.
33114    if (current === WJ || next === WJ) {
33115        return BREAK_NOT_ALLOWED;
33116    }
33117
33118    // LB12 Do not break after NBSP and related characters.
33119    if (current === GL) {
33120        return BREAK_NOT_ALLOWED;
33121    }
33122
33123    // LB12a Do not break before NBSP and related characters, except after spaces and hyphens.
33124    if ([SP, BA, HY].indexOf(current) === -1 && next === GL) {
33125        return BREAK_NOT_ALLOWED;
33126    }
33127
33128    // LB13 Do not break before ‘]’ or ‘!’ or ‘;’ or ‘/’, even after spaces.
33129    if ([CL, CP, EX, IS, SY].indexOf(next) !== -1) {
33130        return BREAK_NOT_ALLOWED;
33131    }
33132
33133    // LB14 Do not break after ‘[’, even after spaces.
33134    if (previousNonSpaceClassType(currentIndex, classTypes) === OP) {
33135        return BREAK_NOT_ALLOWED;
33136    }
33137
33138    // LB15 Do not break within ‘”[’, even with intervening spaces.
33139    if (isAdjacentWithSpaceIgnored(QU, OP, currentIndex, classTypes)) {
33140        return BREAK_NOT_ALLOWED;
33141    }
33142
33143    // LB16 Do not break between closing punctuation and a nonstarter (lb=NS), even with intervening spaces.
33144    if (isAdjacentWithSpaceIgnored([CL, CP], NS, currentIndex, classTypes)) {
33145        return BREAK_NOT_ALLOWED;
33146    }
33147
33148    // LB17 Do not break within ‘——’, even with intervening spaces.
33149    if (isAdjacentWithSpaceIgnored(B2, B2, currentIndex, classTypes)) {
33150        return BREAK_NOT_ALLOWED;
33151    }
33152
33153    // LB18 Break after spaces.
33154    if (current === SP) {
33155        return BREAK_ALLOWED;
33156    }
33157
33158    // LB19 Do not break before or after quotation marks, such as ‘ ” ’.
33159    if (current === QU || next === QU) {
33160        return BREAK_NOT_ALLOWED;
33161    }
33162
33163    // LB20 Break before and after unresolved CB.
33164    if (next === CB || current === CB) {
33165        return BREAK_ALLOWED;
33166    }
33167
33168    // LB21 Do not break before hyphen-minus, other hyphens, fixed-width spaces, small kana, and other non-starters, or after acute accents.
33169    if ([BA, HY, NS].indexOf(next) !== -1 || current === BB) {
33170        return BREAK_NOT_ALLOWED;
33171    }
33172
33173    // LB21a Don't break after Hebrew + Hyphen.
33174    if (before === HL && HYPHEN.indexOf(current) !== -1) {
33175        return BREAK_NOT_ALLOWED;
33176    }
33177
33178    // LB21b Don’t break between Solidus and Hebrew letters.
33179    if (current === SY && next === HL) {
33180        return BREAK_NOT_ALLOWED;
33181    }
33182
33183    // LB22 Do not break between two ellipses, or between letters, numbers or exclamations and ellipsis.
33184    if (next === IN && ALPHABETICS.concat(IN, EX, NU, ID, EB, EM).indexOf(current) !== -1) {
33185        return BREAK_NOT_ALLOWED;
33186    }
33187
33188    // LB23 Do not break between digits and letters.
33189    if (ALPHABETICS.indexOf(next) !== -1 && current === NU || ALPHABETICS.indexOf(current) !== -1 && next === NU) {
33190        return BREAK_NOT_ALLOWED;
33191    }
33192
33193    // LB23a Do not break between numeric prefixes and ideographs, or between ideographs and numeric postfixes.
33194    if (current === PR && [ID, EB, EM].indexOf(next) !== -1 || [ID, EB, EM].indexOf(current) !== -1 && next === PO) {
33195        return BREAK_NOT_ALLOWED;
33196    }
33197
33198    // LB24 Do not break between numeric prefix/postfix and letters, or between letters and prefix/postfix.
33199    if (ALPHABETICS.indexOf(current) !== -1 && PREFIX_POSTFIX.indexOf(next) !== -1 || PREFIX_POSTFIX.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) {
33200        return BREAK_NOT_ALLOWED;
33201    }
33202
33203    // LB25 Do not break between the following pairs of classes relevant to numbers:
33204    if (
33205    // (PR | PO) × ( OP | HY )? NU
33206    [PR, PO].indexOf(current) !== -1 && (next === NU || [OP, HY].indexOf(next) !== -1 && classTypes[afterIndex + 1] === NU) ||
33207    // ( OP | HY ) × NU
33208    [OP, HY].indexOf(current) !== -1 && next === NU ||
33209    // NU ×	(NU | SY | IS)
33210    current === NU && [NU, SY, IS].indexOf(next) !== -1) {
33211        return BREAK_NOT_ALLOWED;
33212    }
33213
33214    // NU (NU | SY | IS)* × (NU | SY | IS | CL | CP)
33215    if ([NU, SY, IS, CL, CP].indexOf(next) !== -1) {
33216        var prevIndex = currentIndex;
33217        while (prevIndex >= 0) {
33218            var type = classTypes[prevIndex];
33219            if (type === NU) {
33220                return BREAK_NOT_ALLOWED;
33221            } else if ([SY, IS].indexOf(type) !== -1) {
33222                prevIndex--;
33223            } else {
33224                break;
33225            }
33226        }
33227    }
33228
33229    // NU (NU | SY | IS)* (CL | CP)? × (PO | PR))
33230    if ([PR, PO].indexOf(next) !== -1) {
33231        var _prevIndex = [CL, CP].indexOf(current) !== -1 ? beforeIndex : currentIndex;
33232        while (_prevIndex >= 0) {
33233            var _type = classTypes[_prevIndex];
33234            if (_type === NU) {
33235                return BREAK_NOT_ALLOWED;
33236            } else if ([SY, IS].indexOf(_type) !== -1) {
33237                _prevIndex--;
33238            } else {
33239                break;
33240            }
33241        }
33242    }
33243
33244    // LB26 Do not break a Korean syllable.
33245    if (JL === current && [JL, JV, H2, H3].indexOf(next) !== -1 || [JV, H2].indexOf(current) !== -1 && [JV, JT].indexOf(next) !== -1 || [JT, H3].indexOf(current) !== -1 && next === JT) {
33246        return BREAK_NOT_ALLOWED;
33247    }
33248
33249    // LB27 Treat a Korean Syllable Block the same as ID.
33250    if (KOREAN_SYLLABLE_BLOCK.indexOf(current) !== -1 && [IN, PO].indexOf(next) !== -1 || KOREAN_SYLLABLE_BLOCK.indexOf(next) !== -1 && current === PR) {
33251        return BREAK_NOT_ALLOWED;
33252    }
33253
33254    // LB28 Do not break between alphabetics (“at”).
33255    if (ALPHABETICS.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) {
33256        return BREAK_NOT_ALLOWED;
33257    }
33258
33259    // LB29 Do not break between numeric punctuation and alphabetics (“e.g.”).
33260    if (current === IS && ALPHABETICS.indexOf(next) !== -1) {
33261        return BREAK_NOT_ALLOWED;
33262    }
33263
33264    // LB30 Do not break between letters, numbers, or ordinary symbols and opening or closing parentheses.
33265    if (ALPHABETICS.concat(NU).indexOf(current) !== -1 && next === OP || ALPHABETICS.concat(NU).indexOf(next) !== -1 && current === CP) {
33266        return BREAK_NOT_ALLOWED;
33267    }
33268
33269    // LB30a Break between two regional indicator symbols if and only if there are an even number of regional
33270    // indicators preceding the position of the break.
33271    if (current === RI && next === RI) {
33272        var i = indicies[currentIndex];
33273        var count = 1;
33274        while (i > 0) {
33275            i--;
33276            if (classTypes[i] === RI) {
33277                count++;
33278            } else {
33279                break;
33280            }
33281        }
33282        if (count % 2 !== 0) {
33283            return BREAK_NOT_ALLOWED;
33284        }
33285    }
33286
33287    // LB30b Do not break between an emoji base and an emoji modifier.
33288    if (current === EB && next === EM) {
33289        return BREAK_NOT_ALLOWED;
33290    }
33291
33292    return BREAK_ALLOWED;
33293};
33294
33295var lineBreakAtIndex = exports.lineBreakAtIndex = function lineBreakAtIndex(codePoints, index) {
33296    // LB2 Never break at the start of text.
33297    if (index === 0) {
33298        return BREAK_NOT_ALLOWED;
33299    }
33300
33301    // LB3 Always break at the end of text.
33302    if (index >= codePoints.length) {
33303        return BREAK_MANDATORY;
33304    }
33305
33306    var _codePointsToCharacte = codePointsToCharacterClasses(codePoints),
33307        _codePointsToCharacte2 = _slicedToArray(_codePointsToCharacte, 2),
33308        indicies = _codePointsToCharacte2[0],
33309        classTypes = _codePointsToCharacte2[1];
33310
33311    return _lineBreakAtIndex(codePoints, classTypes, indicies, index);
33312};
33313
33314var cssFormattedClasses = function cssFormattedClasses(codePoints, options) {
33315    if (!options) {
33316        options = { lineBreak: 'normal', wordBreak: 'normal' };
33317    }
33318
33319    var _codePointsToCharacte3 = codePointsToCharacterClasses(codePoints, options.lineBreak),
33320        _codePointsToCharacte4 = _slicedToArray(_codePointsToCharacte3, 3),
33321        indicies = _codePointsToCharacte4[0],
33322        classTypes = _codePointsToCharacte4[1],
33323        isLetterNumber = _codePointsToCharacte4[2];
33324
33325    if (options.wordBreak === 'break-all' || options.wordBreak === 'break-word') {
33326        classTypes = classTypes.map(function (type) {
33327            return [NU, AL, SA].indexOf(type) !== -1 ? ID : type;
33328        });
33329    }
33330
33331    var forbiddenBreakpoints = options.wordBreak === 'keep-all' ? isLetterNumber.map(function (isLetterNumber, i) {
33332        return isLetterNumber && codePoints[i] >= 0x4e00 && codePoints[i] <= 0x9fff;
33333    }) : null;
33334
33335    return [indicies, classTypes, forbiddenBreakpoints];
33336};
33337
33338var inlineBreakOpportunities = exports.inlineBreakOpportunities = function inlineBreakOpportunities(str, options) {
33339    var codePoints = (0, Util$2.toCodePoints)(str);
33340    var output = BREAK_NOT_ALLOWED;
33341
33342    var _cssFormattedClasses = cssFormattedClasses(codePoints, options),
33343        _cssFormattedClasses2 = _slicedToArray(_cssFormattedClasses, 3),
33344        indicies = _cssFormattedClasses2[0],
33345        classTypes = _cssFormattedClasses2[1],
33346        forbiddenBreakpoints = _cssFormattedClasses2[2];
33347
33348    codePoints.forEach(function (codePoint, i) {
33349        output += (0, Util$2.fromCodePoint)(codePoint) + (i >= codePoints.length - 1 ? BREAK_MANDATORY : _lineBreakAtIndex(codePoints, classTypes, indicies, i + 1, forbiddenBreakpoints));
33350    });
33351
33352    return output;
33353};
33354
33355var Break = function () {
33356    function Break(codePoints, lineBreak, start, end) {
33357        _classCallCheck(this, Break);
33358
33359        this._codePoints = codePoints;
33360        this.required = lineBreak === BREAK_MANDATORY;
33361        this.start = start;
33362        this.end = end;
33363    }
33364
33365    _createClass(Break, [{
33366        key: 'slice',
33367        value: function slice() {
33368            return Util$2.fromCodePoint.apply(undefined, _toConsumableArray(this._codePoints.slice(this.start, this.end)));
33369        }
33370    }]);
33371
33372    return Break;
33373}();
33374
33375var LineBreaker = exports.LineBreaker = function LineBreaker(str, options) {
33376    var codePoints = (0, Util$2.toCodePoints)(str);
33377
33378    var _cssFormattedClasses3 = cssFormattedClasses(codePoints, options),
33379        _cssFormattedClasses4 = _slicedToArray(_cssFormattedClasses3, 3),
33380        indicies = _cssFormattedClasses4[0],
33381        classTypes = _cssFormattedClasses4[1],
33382        forbiddenBreakpoints = _cssFormattedClasses4[2];
33383
33384    var length = codePoints.length;
33385    var lastEnd = 0;
33386    var nextIndex = 0;
33387
33388    return {
33389        next: function next() {
33390            if (nextIndex >= length) {
33391                return { done: true };
33392            }
33393            var lineBreak = BREAK_NOT_ALLOWED;
33394            while (nextIndex < length && (lineBreak = _lineBreakAtIndex(codePoints, classTypes, indicies, ++nextIndex, forbiddenBreakpoints)) === BREAK_NOT_ALLOWED) {}
33395
33396            if (lineBreak !== BREAK_NOT_ALLOWED || nextIndex === length) {
33397                var value = new Break(codePoints, lineBreak, lastEnd, nextIndex);
33398                lastEnd = nextIndex;
33399                return { value: value, done: false };
33400            }
33401
33402            return { done: true };
33403        }
33404    };
33405};
33406});
33407
33408unwrapExports(LineBreak);
33409var LineBreak_1 = LineBreak.LineBreaker;
33410var LineBreak_2 = LineBreak.inlineBreakOpportunities;
33411var LineBreak_3 = LineBreak.lineBreakAtIndex;
33412var LineBreak_4 = LineBreak.codePointsToCharacterClasses;
33413var LineBreak_5 = LineBreak.UnicodeTrie;
33414var LineBreak_6 = LineBreak.BREAK_ALLOWED;
33415var LineBreak_7 = LineBreak.BREAK_NOT_ALLOWED;
33416var LineBreak_8 = LineBreak.BREAK_MANDATORY;
33417var LineBreak_9 = LineBreak.classes;
33418var LineBreak_10 = LineBreak.LETTER_NUMBER_MODIFIER;
33419
33420var dist = createCommonjsModule(function (module, exports) {
33421Object.defineProperty(exports, "__esModule", {
33422  value: true
33423});
33424
33425
33426
33427Object.defineProperty(exports, 'toCodePoints', {
33428  enumerable: true,
33429  get: function get() {
33430    return Util$2.toCodePoints;
33431  }
33432});
33433Object.defineProperty(exports, 'fromCodePoint', {
33434  enumerable: true,
33435  get: function get() {
33436    return Util$2.fromCodePoint;
33437  }
33438});
33439
33440
33441
33442Object.defineProperty(exports, 'LineBreaker', {
33443  enumerable: true,
33444  get: function get() {
33445    return LineBreak.LineBreaker;
33446  }
33447});
33448});
33449
33450unwrapExports(dist);
33451
33452var Unicode = createCommonjsModule(function (module, exports) {
33453Object.defineProperty(exports, "__esModule", {
33454    value: true
33455});
33456exports.breakWords = exports.fromCodePoint = exports.toCodePoints = undefined;
33457
33458
33459
33460Object.defineProperty(exports, 'toCodePoints', {
33461    enumerable: true,
33462    get: function get() {
33463        return dist.toCodePoints;
33464    }
33465});
33466Object.defineProperty(exports, 'fromCodePoint', {
33467    enumerable: true,
33468    get: function get() {
33469        return dist.fromCodePoint;
33470    }
33471});
33472
33473
33474
33475var _NodeContainer2 = _interopRequireDefault(NodeContainer_1);
33476
33477
33478
33479function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
33480
33481var breakWords = exports.breakWords = function breakWords(str, parent) {
33482    var breaker = (0, dist.LineBreaker)(str, {
33483        lineBreak: parent.style.lineBreak,
33484        wordBreak: parent.style.overflowWrap === overflowWrap.OVERFLOW_WRAP.BREAK_WORD ? 'break-word' : parent.style.wordBreak
33485    });
33486
33487    var words = [];
33488    var bk = void 0;
33489
33490    while (!(bk = breaker.next()).done) {
33491        words.push(bk.value.slice());
33492    }
33493
33494    return words;
33495};
33496});
33497
33498unwrapExports(Unicode);
33499var Unicode_1 = Unicode.breakWords;
33500var Unicode_2 = Unicode.fromCodePoint;
33501var Unicode_3 = Unicode.toCodePoints;
33502
33503var TextBounds_1 = createCommonjsModule(function (module, exports) {
33504Object.defineProperty(exports, "__esModule", {
33505    value: true
33506});
33507exports.parseTextBounds = exports.TextBounds = undefined;
33508
33509
33510
33511
33512
33513
33514
33515var _Feature2 = _interopRequireDefault(Feature);
33516
33517
33518
33519function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
33520
33521function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
33522
33523var TextBounds = exports.TextBounds = function TextBounds(text, bounds) {
33524    _classCallCheck(this, TextBounds);
33525
33526    this.text = text;
33527    this.bounds = bounds;
33528};
33529
33530var parseTextBounds = exports.parseTextBounds = function parseTextBounds(value, parent, node) {
33531    var letterRendering = parent.style.letterSpacing !== 0;
33532    var textList = letterRendering ? (0, Unicode.toCodePoints)(value).map(function (i) {
33533        return (0, Unicode.fromCodePoint)(i);
33534    }) : (0, Unicode.breakWords)(value, parent);
33535    var length = textList.length;
33536    var defaultView = node.parentNode ? node.parentNode.ownerDocument.defaultView : null;
33537    var scrollX = defaultView ? defaultView.pageXOffset : 0;
33538    var scrollY = defaultView ? defaultView.pageYOffset : 0;
33539    var textBounds = [];
33540    var offset = 0;
33541    for (var i = 0; i < length; i++) {
33542        var text = textList[i];
33543        if (parent.style.textDecoration !== textDecoration.TEXT_DECORATION.NONE || text.trim().length > 0) {
33544            if (_Feature2.default.SUPPORT_RANGE_BOUNDS) {
33545                textBounds.push(new TextBounds(text, getRangeBounds(node, offset, text.length, scrollX, scrollY)));
33546            } else {
33547                var replacementNode = node.splitText(text.length);
33548                textBounds.push(new TextBounds(text, getWrapperBounds(node, scrollX, scrollY)));
33549                node = replacementNode;
33550            }
33551        } else if (!_Feature2.default.SUPPORT_RANGE_BOUNDS) {
33552            node = node.splitText(text.length);
33553        }
33554        offset += text.length;
33555    }
33556    return textBounds;
33557};
33558
33559var getWrapperBounds = function getWrapperBounds(node, scrollX, scrollY) {
33560    var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
33561    wrapper.appendChild(node.cloneNode(true));
33562    var parentNode = node.parentNode;
33563    if (parentNode) {
33564        parentNode.replaceChild(wrapper, node);
33565        var bounds = (0, Bounds_1.parseBounds)(wrapper, scrollX, scrollY);
33566        if (wrapper.firstChild) {
33567            parentNode.replaceChild(wrapper.firstChild, wrapper);
33568        }
33569        return bounds;
33570    }
33571    return new Bounds_1.Bounds(0, 0, 0, 0);
33572};
33573
33574var getRangeBounds = function getRangeBounds(node, offset, length, scrollX, scrollY) {
33575    var range = node.ownerDocument.createRange();
33576    range.setStart(node, offset);
33577    range.setEnd(node, offset + length);
33578    return Bounds_1.Bounds.fromClientRect(range.getBoundingClientRect(), scrollX, scrollY);
33579};
33580});
33581
33582unwrapExports(TextBounds_1);
33583var TextBounds_2 = TextBounds_1.parseTextBounds;
33584var TextBounds_3 = TextBounds_1.TextBounds;
33585
33586var TextContainer_1 = createCommonjsModule(function (module, exports
33586) {
33587Object.defineProperty(exports, "__esModule", {
33588    value: true
33589});
33590
33591var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
33592
33593
33594
33595
33596
33597function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
33598
33599var TextContainer = function () {
33600    function TextContainer(text, parent, bounds) {
33601        _classCallCheck(this, TextContainer);
33602
33603        this.text = text;
33604        this.parent = parent;
33605        this.bounds = bounds;
33606    }
33607
33608    _createClass(TextContainer, null, [{
33609        key: 'fromTextNode',
33610        value: function fromTextNode(node, parent) {
33611            var text = transform(node.data, parent.style.textTransform);
33612            return new TextContainer(text, parent, (0, TextBounds_1.parseTextBounds)(text, parent, node));
33613        }
33614    }]);
33615
33616    return TextContainer;
33617}();
33618
33619exports.default = TextContainer;
33620
33621
33622var CAPITALIZE = /(^|\s|:|-|\(|\))([a-z])/g;
33623
33624var transform = function transform(text, _transform) {
33625    switch (_transform) {
33626        case textTransform.TEXT_TRANSFORM.LOWERCASE:
33627            return text.toLowerCase();
33628        case textTransform.TEXT_TRANSFORM.CAPITALIZE:
33629            return text.replace(CAPITALIZE, capitalize);
33630        case textTransform.TEXT_TRANSFORM.UPPERCASE:
33631            return text.toUpperCase();
33632        default:
33633            return text;
33634    }
33635};
33636
33637function capitalize(m, p1, p2) {
33638    if (m.length > 0) {
33639        return p1 + p2.toUpperCase();
33640    }
33641
33642    return m;
33643}
33644});
33645
33646unwrapExports(TextContainer_1);
33647
33648var Circle_1 = createCommonjsModule(function (module, exports) {
33649Object.defineProperty(exports, "__esModule", {
33650    value: true
33651});
33652
33653
33654
33655function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
33656
33657var Circle = function Circle(x, y, radius) {
33658    _classCallCheck(this, Circle);
33659
33660    this.type = Path.PATH.CIRCLE;
33661    this.x = x;
33662    this.y = y;
33663    this.radius = radius;
33664    
33665};
33666
33667exports.default = Circle;
33668});
33669
33670unwrapExports(Circle_1);
33671
33672var Input = createCommonjsModule(function (module, exports) {
33673Object.defineProperty(exports, "__esModule", {
33674    value: true
33675});
33676exports.reformatInputBounds = exports.inlineSelectElement = exports.inlineTextAreaElement = exports.inlineInputElement = exports.getInputBorderRadius = exports.INPUT_BACKGROUND = exp
33676orts.INPUT_BORDERS = exports.INPUT_COLOR = undefined;
33677
33678
33679
33680var _TextContainer2 = _interopRequireDefault(TextContainer_1);
33681
33682
33683
33684
33685
33686
33687
33688var _Circle2 = _interopRequireDefault(Circle_1);
33689
33690
33691
33692var _Vector2 = _interopRequireDefault(Vector_1);
33693
33694
33695
33696var _Color2 = _interopRequireDefault(Color_1);
33697
33698
33699
33700var _Length2 = _interopRequireDefault(Length_1);
33701
33702
33703
33704
33705
33706
33707
33708function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
33709
33710var INPUT_COLOR = exports.INPUT_COLOR = new _Color2.default([42, 42, 42]);
33711var INPUT_BORDER_COLOR = new _Color2.default([165, 165, 165]);
33712var INPUT_BACKGROUND_COLOR = new _Color2.default([222, 222, 222]);
33713var INPUT_BORDER = {
33714    borderWidth: 1,
33715    borderColor: INPUT_BORDER_COLOR,
33716    borderStyle: border.BORDER_STYLE.SOLID
33717};
33718var INPUT_BORDERS = exports.INPUT_BORDERS = [INPUT_BORDER, INPUT_BORDER, INPUT_BORDER, INPUT_BORDER];
33719var INPUT_BACKGROUND = exports.INPUT_BACKGROUND = {
33720    backgroundColor: INPUT_BACKGROUND_COLOR,
33721    backgroundImage: [],
33722    backgroundClip: background.BACKGROUND_CLIP.PADDING_BOX,
33723    backgroundOrigin: background.BACKGROUND_ORIGIN.PADDING_BOX
33724};
33725
33726var RADIO_BORDER_RADIUS = new _Length2.default('50%');
33727var RADIO_BORDER_RADIUS_TUPLE = [RADIO_BORDER_RADIUS, RADIO_BORDER_RADIUS];
33728var INPUT_RADIO_BORDER_RADIUS = [RADIO_BORDER_RADIUS_TUPLE, RADIO_BORDER_RADIUS_TUPLE, RADIO_BORDER_RADIUS_TUPLE, RADIO_BORDER_RADIUS_TUPLE];
33729
33730var CHECKBOX_BORDER_RADIUS = new _Length2.default('3px');
33731var CHECKBOX_BORDER_RADIUS_TUPLE = [CHECKBOX_BORDER_RADIUS, CHECKBOX_BORDER_RADIUS];
33732var INPUT_CHECKBOX_BORDER_RADIUS = [CHECKBOX_BORDER_RADIUS_TUPLE, CHECKBOX_BORDER_RADIUS_TUPLE, CHECKBOX_BORDER_RADIUS_TUPLE, CHECKBOX_BORDER_RADIUS_TUPLE];
33733
33734var getInputBorderRadius = exports.getInputBorderRadius = function getInputBorderRadius(node) {
33735    return node.type === 'radio' ? INPUT_RADIO_BORDER_RADIUS : INPUT_CHECKBOX_BORDER_RADIUS;
33736};
33737
33738var inlineInputElement = exports.inlineInputElement = function inlineInputElement(node, container) {
33739    if (node.type === 'radio' || node.type === 'checkbox') {
33740        if (node.checked) {
33741            var size = Math.min(container.bounds.width, container.bounds.height);
33742            container.childNodes.push(node.type === 'checkbox' ? [new _Vector2.default(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79), new _Vector2.default(container.bounds.left + size * 0.16, container.bounds.top + size * 0.5549), new _Vector2.default(container.bounds.left + size * 0.27347, container.bounds.top + size * 0.44071), new _Vector2.default(container.bounds.left + size * 0.39694, container.bounds.top + size * 0.5649), new _Vector2.default(container.bounds.left + size * 0.72983, container.bounds.top + size * 0.23), new _Vector2.default(container.bounds.left + size * 0.84, container.bounds.top + size * 0.34085), new _Vector2.default(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79)] : new _Circle2.default(container.bounds.left + size / 4, container.bounds.top + size / 4, size / 4));
33743        }
33744    } else {
33745        inlineFormElement(getInputValue(node), node, container, false);
33746    }
33747};
33748
33749var inlineTextAreaElement = exports.inlineTextAreaElement = function inlineTextAreaElement(node, container) {
33750    inlineFormElement(node.value, node, container, true);
33751};
33752
33753var inlineSelectElement = exports.inlineSelectElement = function inlineSelectElement(node, container) {
33754    var option = node.options[node.selectedIndex || 0];
33755    inlineFormElement(option ? option.text || '' : '', node, container, false);
33756};
33757
33758var reformatInputBounds = exports.reformatInputBounds = function reformatInputBounds(bounds) {
33759    if (bounds.width > bounds.height) {
33760        bounds.left += (bounds.width - bounds.height) / 2;
33761        bounds.width = bounds.height;
33762    } else if (bounds.width < bounds.height) {
33763        bounds.top += (bounds.height - bounds.width) / 2;
33764        bounds.height = bounds.width;
33765    }
33766    return bounds;
33767};
33768
33769var inlineFormElement = function inlineFormElement(value, node, container, allowLinebreak) {
33770    var body = node.ownerDocument.body;
33771    if (value.length > 0 && body) {
33772        var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
33773        (0, Util.copyCSSStyles)(node.ownerDocument.defaultView.getComputedStyle(node, null), wrapper);
33774        wrapper.style.position = 'absolute';
33775        wrapper.style.left = container.bounds.left + 'px';
33776        wrapper.style.top = container.bounds.top + 'px';
33777        if (!allowLinebreak) {
33778            wrapper.style.whiteSpace = 'nowrap';
33779        }
33780        var text = node.ownerDocument.createTextNode(value);
33781        wrapper.appendChild(text);
33782        body.appendChild(wrapper);
33783        container.childNodes.push(_TextContainer2.default.fromTextNode(text, container));
33784        body.removeChild(wrapper);
33785    }
33786};
33787
33788var getInputValue = function getInputValue(node) {
33789    var value = node.type === 'password' ? new Array(node.value.length + 1).join('\u2022') : node.value;
33790
33791    return value.length === 0 ? node.placeholder || '' : value;
33792};
33793});
33794
33795unwrapExports(Input);
33796var Input_1 = Input.reformatInputBounds;
33797var Input_2 = Input.inlineSelectElement;
33798var Input_3 = Input.inlineTextAreaElement;
33799var Input_4 = Input.inlineInputElement;
33800var Input_5 = Input.getInputBorderRadius;
33801var Input_6 = Input.INPUT_BACKGROUND;
33802var Input_7 = Input.INPUT_BORDERS;
33803var Input_8 = Input.INPUT_COLOR;
33804
33805var ListItem = createCommonjsModule(function (module, exports) {
33806Object.defineProperty(exports, "__esModule", {
33807    value: true
33808});
33809exports.createCounterText = exports.inlineListItemElement = exports.getListOwner = undefined;
33810
33811
33812
33813
33814
33815var _NodeContainer2 = _interopRequireDefault(NodeContainer_1);
33816
33817
33818
33819var _TextContainer2 = _interopRequireDefault(TextContainer_1);
33820
33821
33822
33823
33824
33825function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
33826
33827// Margin between the enumeration and the list item content
33828var MARGIN_RIGHT = 7;
33829
33830var ancestorTypes = ['OL', 'UL', 'MENU'];
33831
33832var getListOwner = exports.getListOwner = function getListOwner(container) {
33833    var parent = container.parent;
33834    if (!parent) {
33835        return null;
33836    }
33837
33838    do {
33839        var isAncestor = ancestorTypes.indexOf(parent.tagName) !== -1;
33840        if (isAncestor) {
33841            return parent;
33842        }
33843        parent = parent.parent;
33844    } while (parent);
33845
33846    return container.parent;
33847};
33848
33849var inlineListItemElement = exports.inlineListItemElement = function inlineListItemElement(node, container, resourceLoader) {
33850    var listStyle$$1 = container.style.listStyle;
33851
33852    if (!listStyle$$1) {
33853        return;
33854    }
33855
33856    var style = node.ownerDocument.defaultView.getComputedStyle(node, null);
33857    var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
33858    (0, Util.copyCSSStyles)(style, wrapper);
33859
33860    wrapper.style.position = 'absolute';
33861    wrapper.style.bottom = 'auto';
33862    wrapper.style.display = 'block';
33863    wrapper.style.letterSpacing = 'normal';
33864
33865    switch (listStyle$$1.listStylePosition) {
33866        case listStyle.LIST_STYLE_POSITION.OUTSIDE:
33867            wrapper.style.left = 'auto';
33868            wrapper.style.right = node.ownerDocument.defaultView.innerWidth - container.bounds.left - container.style.margin[1].getAbsoluteValue(container.bounds.width) + MARGIN_RIGHT + 'px';
33869            wrapper.style.textAlign = 'right';
33870            break;
33871        case listStyle.LIST_STYLE_POSITION.INSIDE:
33872            wrapper.style.left = container.bounds.left - container.style.margin[3].getAbsoluteValue(container.bounds.width) + 'px';
33873            wrapper.style.right = 'auto';
33874            wrapper.style.textAlign = 'left';
33875            break;
33876    }
33877
33878    var text = void 0;
33879    var MARGIN_TOP = container.style.margin[0].getAbsoluteValue(container.bounds.width);
33880    var styleImage = listStyle$$1.listStyleImage;
33881    if (styleImage) {
33882        if (styleImage.method === 'url') {
33883            var image = node.ownerDocument.createElement('img');
33884            image.src = styleImage.args[0];
33885            wrapper.style.top = container.bounds.top - MARGIN_TOP + 'px';
33886            wrapper.style.width = 'auto';
33887            wrapper.style.height = 'auto';
33888            wrapper.appendChild(image);
33889        } else {
33890            var size = parseFloat(container.style.font.fontSize) * 0.5;
33891            wrapper.style.top = container.bounds.top - MARGIN_TOP + container.bounds.height - 1.5 * size + 'px';
33892            wrapper.style.width = size + 'px';
33893            wrapper.style.height = size + 'px';
33894            wrapper.style.backgroundImage = style.listStyleImage;
33895        }
33896    } else if (typeof container.listIndex === 'number') {
33897        text = node.ownerDocument.createTextNode(createCounterText(container.listIndex, listStyle$$1.listStyleType, true));
33898        wrapper.appendChild(text);
33899        wrapper.style.top = container.bounds.top - MARGIN_TOP + 'px';
33900    }
33901
33902    // $FlowFixMe
33903    var body = node.ownerDocument.body;
33904    body.appendChild(wrapper);
33905
33906    if (text) {
33907        container.childNodes.push(_TextContainer2.default.fromTextNode(text, container));
33908        body.removeChild(wrapper);
33909    } else {
33910        // $FlowFixMe
33911        container.childNodes.push(new _NodeContainer2.default(wrapper, container, resourceLoader, 0));
33912    }
33913};
33914
33915var ROMAN_UPPER = {
33916    integers: [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
33917    values: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
33918};
33919
33920var ARMENIAN = {
33921    integers: [9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
33922    values: ['Ք', 'Փ', 'Ւ', 'Ց', 'Ր', 'Տ', 'Վ', 'Ս', 'Ռ', 'Ջ', 'Պ', 'Չ', 'Ո', 'Շ', 'Ն', 'Յ', 'Մ', 'Ճ', 'Ղ', 'Ձ', 'Հ', 'Կ', 'Ծ', 'Խ', 'Լ', 'Ի', 'Ժ', 'Թ', 'Ը', 'Է', 'Զ', 'Ե', 'Դ', 'Գ', 'Բ', 'Ա']
33923};
33924
33925var HEBREW = {
33926    integers: [10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
33927    values: ['י׳', 'ט׳', 'ח׳', 'ז׳', 'ו׳', 'ה׳', 'ד׳', 'ג׳', 'ב׳', 'א׳', 'ת', 'ש', 'ר', 'ק', 'צ', 'פ', 'ע', 'ס', 'נ', 'מ', 'ל', 'כ', 'יט', 'יח', 'יז', 'טז', 'טו', 'י', 'ט', 'ח', 'ז', 'ו', 'ה', 'ד', 'ג', 'ב', 'א']
33928};
33929
33930var GEORGIAN = {
33931    integers: [10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
33932    values: ['ჵ', 'ჰ', 'ჯ', 'ჴ', 'ხ', 'ჭ', 'წ', 'ძ', 'ც', 'ჩ', 'შ', 'ყ', 'ღ', 'ქ', 'ფ', 'ჳ', 'ტ', 'ს', 'რ', 'ჟ', 'პ', 'ო', 'ჲ', 'ნ', 'მ', 'ლ', 'კ', 'ი', 'თ', 'ჱ', 'ზ', 'ვ', 'ე', 'დ', 'გ', 'ბ', 'ა']
33933};
33934
33935var createAdditiveCounter = function createAdditiveCounter(value, min, max, symbols, fallback, suffix) {
33936    if (value < min || value > max) {
33937        return createCounterText(value, fallback, suffix.length > 0);
33938    }
33939
33940    return symbols.integers.reduce(function (string, integer, index) {
33941        while (value >= integer) {
33942            value -= integer;
33943            string += symbols.values[index];
33944        }
33945        return string;
33946    }, '') + suffix;
33947};
33948
33949var createCounterStyleWithSymbolResolver = function createCounterStyleWithSymbolResolver(value, codePointRangeLength, isNumeric, resolver) {
33950    var string = '';
33951
33952    do {
33953        if (!isNumeric) {
33954            value--;
33955        }
33956        string = resolver(value) + string;
33957        value /= codePointRangeLength;
33958    } while (value * codePointRangeLength >= codePointRangeLength);
33959
33960    return string;
33961};
33962
33963var createCounterStyleFromRange = function createCounterStyleFromRange(value, codePointRangeStart, codePointRangeEnd, isNumeric, suffix) {
33964    var codePointRangeLength = codePointRangeEnd - codePointRangeStart + 1;
33965
33966    return (value < 0 ? '-' : '') + (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, isNumeric, function (codePoint) {
33967        return (0, Unicode.fromCodePoint)(Math.floor(codePoint % codePointRangeLength) + codePointRangeStart);
33968    }) + suffix);
33969};
33970
33971var createCounterStyleFromSymbols = function createCounterStyleFromSymbols(value, symbols) {
33972    var suffix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '. ';
33973
33974    var codePointRangeLength = symbols.length;
33975    return createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, false, function (codePoint) {
33976        return symbols[Math.floor(codePoint % codePointRangeLength)];
33977    }) + suffix;
33978};
33979
33980var CJK_ZEROS = 1 << 0;
33981var CJK_TEN_COEFFICIENTS = 1 << 1;
33982var CJK_TEN_HIGH_COEFFICIENTS = 1 << 2;
33983var CJK_HUNDRED_COEFFICIENTS = 1 << 3;
33984
33985var createCJKCounter = function createCJKCounter(value, numbers, multipliers, negativeSign, suffix, flags) {
33986    if (value < -9999 || value > 9999) {
33987        return createCounterText(value, listStyle.LIST_STYLE_TYPE.CJK_DECIMAL, suffix.length > 0);
33988    }
33989    var tmp = Math.abs(value);
33990    var string = suffix;
33991
33992    if (tmp === 0) {
33993        return numbers[0] + string;
33994    }
33995
33996    for (var digit = 0; tmp > 0 && digit <= 4; digit++) {
33997        var coefficient = tmp % 10;
33998
33999        if (coefficient === 0 && (0, Util.contains)(flags, CJK_ZEROS) && string !== '') {
34000            string = numbers[coefficient] + string;
34001        } else if (coefficient > 1 || coefficient === 1 && digit === 0 || coefficient === 1 && digit === 1 && (0, Util.contains)(flags, CJK_TEN_COEFFICIENTS) || coefficient === 1 && digit === 1 && (0, Util.contains)(flags, CJK_TEN_HIGH_COEFFICIENTS) && value > 100 || coefficient === 1 && digit > 1 && (0, Util.contains)(flags, CJK_HUNDRED_COEFFICIENTS)) {
34002            string = numbers[coefficient] + (digit > 0 ? multipliers[digit - 1] : '') + string;
34003        } else if (coefficient === 1 && digit > 0) {
34004            string = multipliers[digit - 1] + string;
34005        }
34006        tmp = Math.floor(tmp / 10);
34007    }
34008
34009    return (value < 0 ? negativeSign : '') + string;
34010};
34011
34012var CHINESE_INFORMAL_MULTIPLIERS = '十百千萬';
34013var CHINESE_FORMAL_MULTIPLIERS = '拾佰仟萬';
34014var JAPANESE_NEGATIVE = 'マイナス';
34015var KOREAN_NEGATIVE = '마이너스 ';
34016
34017var createCounterText = exports.createCounterText = function createCounterText(value, type, appendSuffix) {
34018    var defaultSuffix = appendSuffix ? '. ' : '';
34019    var cjkSuffix = appendSuffix ? '、' : '';
34020    var koreanSuffix = appendSuffix ? ', ' : '';
34021    switch (type) {
34022        case listStyle.LIST_STYLE_TYPE.DISC:
34023            return '•';
34024        case listStyle.LIST_STYLE_TYPE.CIRCLE:
34025            return '◦';
34026        case listStyle.LIST_STYLE_TYPE.SQUARE:
34027            return '◾';
34028        case listStyle.LIST_STYLE_TYPE.DECIMAL_LEADING_ZERO:
34029            var string = createCounterStyleFromRange(value, 48, 57, true, defaultSuffix);
34030            return string.length < 4 ? '0' + string : string;
34031        case listStyle.LIST_STYLE_TYPE.CJK_DECIMAL:
34032            return createCounterStyleFromSymbols(value, '〇一二三四五六七八九', cjkSuffix);
34033        case listStyle.LIST_STYLE_TYPE.LOWER_ROMAN:
34034            return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, listStyle.LIST_STYLE_TYPE.DECIMAL, defaultSuffix).toLowerCase();
34035        case listStyle.LIST_STYLE_TYPE.UPPER_ROMAN:
34036            return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, listStyle.LIST_STYLE_TYPE.DECIMAL, defaultSuffix);
34037        case listStyle.LIST_STYLE_TYPE.LOWER_GREEK:
34038            return createCounterStyleFromRange(value, 945, 969, false, defaultSuffix);
34039        case listStyle.LIST_STYLE_TYPE.LOWER_ALPHA:
34040            return createCounterStyleFromRange(value, 97, 122, false, defaultSuffix);
34041        case listStyle.LIST_STYLE_TYPE.UPPER_ALPHA:
34042            return createCounterStyleFromRange(value, 65, 90, false, defaultSuffix);
34043        case listStyle.LIST_STYLE_TYPE.ARABIC_INDIC:
34044            return createCounterStyleFromRange(value, 1632, 1641, true, defaultSuffix);
34045        case listStyle.LIST_STYLE_TYPE.ARMENIAN:
34046        case listStyle.LIST_STYLE_TYPE.UPPER_ARMENIAN:
34047            return createAdditiveCounter(value, 1, 9999, ARMENIAN, listStyle.LIST_STYLE_TYPE.DECIMAL, defaultSuffix);
34048        case listStyle.LIST_STYLE_TYPE.LOWER_ARMENIAN:
34049            return createAdditiveCounter(value, 1, 9999, ARMENIAN, listStyle.LIST_STYLE_TYPE.DECIMAL, defaultSuffix).toLowerCase();
34050        case listStyle.LIST_STYLE_TYPE.BENGALI:
34051            return createCounterStyleFromRange(value, 2534, 2543, true, defaultSuffix);
34052        case listStyle.LIST_STYLE_TYPE.CAMBODIAN:
34053        case listStyle.LIST_STYLE_TYPE.KHMER:
34054            return createCounterStyleFromRange(value, 6112, 6121, true, defaultSuffix);
34055        case listStyle.LIST_STYLE_TYPE.CJK_EARTHLY_BRANCH:
34056            return createCounterStyleFromSymbols(value, '子丑寅卯辰巳午未申酉戌亥', cjkSuffix);
34057        case listStyle.LIST_STYLE_TYPE.CJK_HEAVENLY_STEM:
34058            return createCounterStyleFromSymbols(value, '甲乙丙丁戊己庚辛壬癸', cjkSuffix);
34059        case listStyle.LIST_STYLE_TYPE.CJK_IDEOGRAPHIC:
34060        case listStyle.LIST_STYLE_TYPE.TRAD_CHINESE_INFORMAL:
34061            return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
34062        case listStyle.LIST_STYLE_TYPE.TRAD_CHINESE_FORMAL:
34063            return createCJKCounter(value, '零壹貳參肆伍陸柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
34064        case listStyle.LIST_STYLE_TYPE.SIMP_CHINESE_INFORMAL:
34065            return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
34066        case listStyle.LIST_STYLE_TYPE.SIMP_CHINESE_FORMAL:
34067            return createCJKCounter(value, '零壹贰叁肆伍陆柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
34068        case listStyle.LIST_STYLE_TYPE.JAPANESE_INFORMAL:
34069            return createCJKCounter(value, '〇一二三四五六七八九', '十百千万', JAPANESE_NEGATIVE, cjkSuffix, 0);
34070        case listStyle.LIST_STYLE_TYPE.JAPANESE_FORMAL:
34071            return createCJKCounter(value, '零壱弐参四伍六七八九', '拾百千万', JAPANESE_NEGATIVE, cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
34072        case listStyle.LIST_STYLE_TYPE.KOREAN_HANGUL_FORMAL:
34073            return createCJKCounter(value, '영일이삼사오육칠팔구', '십백천만', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
34074        case listStyle.LIST_STYLE_TYPE.KOREAN_HANJA_INFORMAL:
34075            return createCJKCounter(value, '零一二三四五六七八九', '十百千萬', KOREAN_NEGATIVE, koreanSuffix, 0);
34076        case listStyle.LIST_STYLE_TYPE.KOREAN_HANJA_FORMAL:
34077            return createCJKCounter(value, '零壹貳參四五六七八九', '拾百千', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
34078        case listStyle.LIST_STYLE_TYPE.DEVANAGARI:
34079            return createCounterStyleFromRange(value, 0x966, 0x96f, true, defaultSuffix);
34080        case listStyle.LIST_STYLE_TYPE.GEORGIAN:
34081            return createAdditiveCounter(value, 1, 19999, GEORGIAN, listStyle.LIST_STYLE_TYPE.DECIMAL, defaultSuffix);
34082        case listStyle.LIST_STYLE_TYPE.GUJARATI:
34083            return createCounterStyleFromRange(value, 0xae6, 0xaef, true, defaultSuffix);
34084        case listStyle.LIST_STYLE_TYPE.GURMUKHI:
34085            return createCounterStyleFromRange(value, 0xa66, 0xa6f, true, defaultSuffix);
34086        case listStyle.LIST_STYLE_TYPE.HEBREW:
34087            return createAdditiveCounter(value, 1, 10999, HEBREW, listStyle.LIST_STYLE_TYPE.DECIMAL, defaultSuffix);
34088        case listStyle.LIST_STYLE_TYPE.HIRAGANA:
34089            return createCounterStyleFromSymbols(value, 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん');
34090        case listStyle.LIST_STYLE_TYPE.HIRAGANA_IROHA:
34091            return createCounterStyleFromSymbols(value, 'いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす');
34092        case listStyle.LIST_STYLE_TYPE.KANNADA:
34093            return createCounterStyleFromRange(value, 0xce6, 0xcef, true, defaultSuffix);
34094        case listStyle.LIST_STYLE_TYPE.KATAKANA:
34095            return createCounterStyleFromSymbols(value, 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン', cjkSuffix);
34096        case listStyle.LIST_STYLE_TYPE.KATAKANA_IROHA:
34097            return createCounterStyleFromSymbols(value, 'イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス', cjkSuffix);
34098        case listStyle.LIST_STYLE_TYPE.LAO:
34099            return createCounterStyleFromRange(value, 0xed0, 0xed9, true, defaultSuffix);
34100        case listStyle.LIST_STYLE_TYPE.MONGOLIAN:
34101            return createCounterStyleFromRange(value, 0x1810, 0x1819, true, defaultSuffix);
34102        case listStyle.LIST_STYLE_TYPE.MYANMAR:
34103            return createCounterStyleFromRange(value, 0x1040, 0x1049, true, defaultSuffix);
34104        case listStyle.LIST_STYLE_TYPE.ORIYA:
34105            return createCounterStyleFromRange(value, 0xb66, 0xb6f, true, defaultSuffix);
34106        case listStyle.LIST_STYLE_TYPE.PERSIAN:
34107            return createCounterStyleFromRange(value, 0x6f0, 0x6f9, true, defaultSuffix);
34108        case listStyle.LIST_STYLE_TYPE.TAMIL:
34109            return createCounterStyleFromRange(value, 0xbe6, 0xbef, true, defaultSuffix);
34110        case listStyle.LIST_STYLE_TYPE.TELUGU:
34111            return createCounterStyleFromRange(value, 0xc66, 0xc6f, true, defaultSuffix);
34112        case listStyle.LIST_STYLE_TYPE.THAI:
34113            return createCounterStyleFromRange(value, 0xe50, 0xe59, true, defaultSuffix);
34114        case listStyle.LIST_STYLE_TYPE.TIBETAN:
34115            return createCounterStyleFromRange(value, 0xf20, 0xf29, true, defaultSuffix);
34116        case listStyle.LIST_STYLE_TYPE.DECIMAL:
34117        default:
34118            return createCounterStyleFromRange(value, 48, 57, true, defaultSuffix);
34119    }
34120};
34121});
34122
34123unwrapExports(ListItem);
34124var ListItem_1 = ListItem.createCounterText;
34125var ListItem_2 = ListItem.inlineListItemElement;
34126var ListItem_3 = ListItem.getListOwner;
34127
34128var NodeContainer_1 = createCommonjsModule(function (module, exports) {
34129Object.defineProperty(exports, "__esModule", {
34130    value: true
34131});
34132
34133var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
34134
34135
34136
34137var _Color2 = _interopRequireDefault(Color_1);
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
34190
34191function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
34192
34193var INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];
34194
34195var NodeContainer = function () {
34196    function NodeContainer(node, parent, resourceLoader, index) {
34197        var _this = this;
34198
34199        _classCallCheck(this, NodeContainer);
34200
34201        this.parent = parent;
34202        this.tagName = node.tagName;
34203        this.index = index;
34204        this.childNodes = [];
34205        this.listItems = [];
34206        if (typeof node.start === 'number') {
34207            this.listStart = node.start;
34208        }
34209        var defaultView = node.ownerDocument.defaultView;
34210        var scrollX = defaultView.pageXOffset;
34211        var scrollY = defaultView.pageYOffset;
34212        var style = defaultView.getComputedStyle(node, null);
34213        var display$$1 = (0, display.parseDisplay)(style.display);
34214
34215        var IS_INPUT = node.type === 'radio' || node.type === 'checkbox';
34216
34217        var position$$1 = (0, position.parsePosition)(style.position);
34218
34219        this.style = {
34220            background: IS_INPUT ? Input.INPUT_BACKGROUND : (0, background.parseBackgroun
34220d)(style, resourceLoader),
34221            border: IS_INPUT ? Input.INPUT_BORDERS : (0, border.parseBorder)(style),
34222            borderRadius: (node instanceof defaultView.HTMLInputElement || node instanceof HTMLInputElement) && IS_INPUT ? (0, Input.getInputBorderRadius)(node) : (0, borderRadius.parseBorderRadius)(style),
34223            color: IS_INPUT ? Input.INPUT_COLOR : new _Color2.default(style.color),
34224            display: display$$1,
34225            float: (0, float_1.parseCSSFloat)(style.float),
34226            font: (0, font.parseFont)(style),
34227            letterSpacing: (0, letterSpacing.parseLetterSpacing)(style.letterSpacing),
34228            listStyle: display$$1 === display.DISPLAY.LIST_ITEM ? (0, listStyle.parseListStyle)(style) : null,
34229            lineBreak: (0, lineBreak.parseLineBreak)(style.lineBreak),
34230            margin: (0, margin.parseMargin)(style),
34231            opacity: parseFloat(style.opacity),
34232            overflow: INPUT_TAGS.indexOf(node.tagName) === -1 ? (0, overflow.parseOverflow)(style.overflow) : overflow.OVERFLOW.HIDDEN,
34233            overflowWrap: (0, overflowWrap.parseOverflowWrap)(style.overflowWrap ? style.overflowWrap : style.wordWrap),
34234            padding: (0, padding.parsePadding)(style),
34235            position: position$$1,
34236            textDecoration: (0, textDecoration.parseTextDecoration)(style),
34237            textShadow: (0, textShadow.parseTextShadow)(style.textShadow),
34238            textTransform: (0, textTransform.parseTextTransform)(style.textTransform),
34239            transform: (0, transform.parseTransform)(style),
34240            visibility: (0, visibility.parseVisibility)(style.visibility),
34241            wordBreak: (0, wordBreak.parseWordBreak)(style.wordBreak),
34242            zIndex: (0, zIndex.parseZIndex)(position$$1 !== position.POSITION.STATIC ? style.zIndex : 'auto')
34243        };
34244
34245        if (this.isTransformed()) {
34246            // getBoundingClientRect provides values post-transform, we want them without the transformation
34247            node.style.transform = 'matrix(1,0,0,1,0,0)';
34248        }
34249
34250        if (display$$1 === display.DISPLAY.LIST_ITEM) {
34251            var listOwner = (0, ListItem.getListOwner)(this);
34252            if (listOwner) {
34253                var listIndex = listOwner.listItems.length;
34254                listOwner.listItems.push(this);
34255                this.listIndex = node.hasAttribute('value') && typeof node.value === 'number' ? node.value : listIndex === 0 ? typeof listOwner.listStart === 'number' ? listOwner.listStart : 1 : listOwner.listItems[listIndex - 1].listIndex + 1;
34256            }
34257        }
34258
34259        // TODO move bound retrieval for all nodes to a later stage?
34260        if (node.tagName === 'IMG') {
34261            node.addEventListener('load', function () {
34262                _this.bounds = (0, Bounds_1.parseBounds)(node, scrollX, scrollY);
34263                _this.curvedBounds = (0, Bounds_1.parseBoundCurves)(_this.bounds, _this.style.border, _this.style.borderRadius);
34264            });
34265        }
34266        this.image = getImage(node, resourceLoader);
34267        this.bounds = IS_INPUT ? (0, Input.reformatInputBounds)((0, Bounds_1.parseBounds)(node, scrollX, scrollY)) : (0, Bounds_1.parseBounds)(node, scrollX, scrollY);
34268        this.curvedBounds = (0, Bounds_1.parseBoundCurves)(this.bounds, this.style.border, this.style.borderRadius);
34269
34270        
34271    }
34272
34273    _createClass(NodeContainer, [{
34274        key: 'getClipPaths',
34275        value: function getClipPaths() {
34276            var parentClips = this.parent ? this.parent.getClipPaths() : [];
34277            var isClipped = this.style.overflow !== overflow.OVERFLOW.VISIBLE;
34278
34279            return isClipped ? parentClips.concat([(0, Bounds_1.calculatePaddingBoxPath)(this.curvedBounds)]) : parentClips;
34280        }
34281    }, {
34282        key: 'isInFlow',
34283        value: function isInFlow() {
34284            return this.isRootElement() && !this.isFloating() && !this.isAbsolutelyPositioned();
34285        }
34286    }, {
34287        key: 'isVisible',
34288        value: function isVisible() {
34289            return !(0, Util.contains)(this.style.display, display.DISPLAY.NONE) && this.style.opacity >
34289 0 && this.style.visibility === visibility.VISIBILITY.VISIBLE;
34290        }
34291    }, {
34292        key: 'isAbsolutelyPositioned',
34293        value: function isAbsolutelyPositioned() {
34294            return this.style.position !== position.POSITION.STATIC && this.style.position !== position.POSITION.RELATIVE;
34295        }
34296    }, {
34297        key: 'isPositioned',
34298        value: function isPositioned() {
34299            return this.style.position !== position.POSITION.STATIC;
34300        }
34301    }, {
34302        key: 'isFloating',
34303        value: function isFloating() {
34304            return this.style.float !== float_1.FLOAT.NONE;
34305        }
34306    }, {
34307        key: 'isRootElement',
34308        value: function isRootElement() {
34309            return this.parent === null;
34310        }
34311    }, {
34312        key: 'isTransformed',
34313        value: function isTransformed() {
34314            return this.style.transform !== null;
34315        }
34316    }, {
34317        key: 'isPositionedWithZIndex',
34318        value: function isPositionedWithZIndex() {
34319            return this.isPositioned() && !this.style.zIndex.auto;
34320        }
34321    }, {
34322        key: 'isInlineLevel',
34323        value: function isInlineLevel() {
34324            return (0, Util.contains)(this.style.display, display.DISPLAY.INLINE) || (0, Util.contains)(this.style.display, display.DISPLAY.INLINE_BLOCK) || (0, Util.contains)(this.style.display, display.DISPLAY.INLINE_FLEX) || (0, Util.contains)(this.style.display, display.DISPLAY.INLINE_GRID) || (0, Util.contains)(this.style.display, display.DISPLAY.INLINE_LIST_ITEM) || (0, Util.contains)(this.style.display, display.DISPLAY.INLINE_TABLE);
34325        }
34326    }, {
34327        key: 'isInlineBlockOrInlineTable',
34328        value: function isInlineBlockOrInlineTable() {
34329            return (0, Util.contains)(this.style.display, display.DISPLAY.INLINE_BLOCK) || (0, Util.contains)(this.style.display, display.DISPLAY.INLINE_TABLE);
34330        }
34331    }]);
34332
34333    return NodeContainer;
34334}();
34335
34336exports.default = NodeContainer;
34337
34338
34339var getImage = function getImage(node, resourceLoader) {
34340    if (node instanceof node.ownerDocument.defaultView.SVGSVGElement || node instanceof SVGSVGElement) {
34341        var s = new XMLSerializer();
34342        return resourceLoader.loadImage('data:image/svg+xml,' + encodeURIComponent(s.serializeToString(node)));
34343    }
34344    switch (node.tagName) {
34345        case 'IMG':
34346            // $FlowFixMe
34347            var img = node;
34348            return resourceLoader.loadImage(img.currentSrc || img.src);
34349        case 'CANVAS':
34350            // $FlowFixMe
34351            var canvas = node;
34352            return resourceLoader.loadCanvas(canvas);
34353        case 'IFRAME':
34354            var iframeKey = node.getAttribute('data-html2canvas-internal-iframe-key');
34355            if (iframeKey) {
34356                return iframeKey;
34357            }
34358            break;
34359    }
34360
34361    return null;
34362};
34363});
34364
34365unwrapExports(NodeContainer_1);
34366
34367var StackingContext_1 = createCommonjsModule(function (module, exports) {
34368Object.defineProperty(exports, "__esModule", {
34369    value: true
34370});
34371
34372var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
34373
34374
34375
34376var _NodeContainer2 = _interopRequireDefault(NodeContainer_1);
34377
34378
34379
34380function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
34381
34382function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
34383
34384var StackingContext = function () {
34385    function StackingContext(container, parent, treatAsRealStackingContext) {
34386        _classCallCheck(this, StackingContext);
34387
34388        this.container = container;
34389        this.parent = parent;
34390        this.contexts = [];
34391        this.children = [];
34392        this.treatAsRealStackingContext = treatAsRealStackingContext;
34393    }
34394
34395    _createClass(StackingContext, [{
34396        key: 'getOpacity',
34397        value: function getOpacity() {
34398            return this.parent ? this.container.style.opacity * this.parent.getOpacity() : this.container.style.opacity;
34399        }
34400    }, {
34401        key: 'getRealParentStackingContext',
34402        value: function getRealParentStackingContext() {
34403            return !this.parent || this.treatAsRealStackingContext ? this : this.parent.getRealParentStackingContext();
34404        }
34405    }]);
34406
34407    return StackingContext;
34408}();
34409
34410exports.default = StackingContext;
34411});
34412
34413unwrapExports(StackingContext_1);
34414
34415var NodeParser_1 = createCommonjsModule(function (module, exports) {
34416Object.defineProperty(exports, "__esModule", {
34417    value: true
34418});
34419exports.NodeParser = undefined;
34420
34421
34422
34423var _StackingContext2 = _interopRequireDefault(StackingContext_1);
34424
34425
34426
34427var _NodeContainer2 = _interopRequireDefault(NodeContainer_1);
34428
34429
34430
34431var _TextContainer2 = _interopRequireDefault(TextContainer_1);
34432
34433
34434
34435
34436
34437
34438
34439function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
34440
34441var NodeParser = exports.NodeParser = function NodeParser(node, resourceLoader, logger) {
34442    var index = 0;
34443
34444    var container = new _NodeContainer2.default(node, null, resourceLoader, index++);
34445    var stack = new _StackingContext2.default(container, null, true);
34446
34447    parseNodeTree(node, container, stack, resourceLoader, index);
34448
34449    return stack;
34450};
34451
34452var IGNORED_NODE_NAMES = ['SCRIPT', 'HEAD', 'TITLE', 'OBJECT', 'BR', 'OPTION'];
34453
34454var parseNodeTree = function parseNodeTree(node, parent, stack, resourceLoader, index) {
34455    for (var childNode = node.firstChild, nextNode; childNode; childNode = nextNode) {
34456        nextNode = childNode.nextSibling;
34457        var defaultView = childNode.ownerDocument.defaultView;
34458        if (childNode instanceof defaultView.Text || childNode instanceof Text || defaultView.parent && childNode instanceof defaultView.parent.Text) {
34459            if (childNode.data.trim().length > 0) {
34460                parent.childNodes.push(_TextContainer2.default.fromTextNode(childNode, parent));
34461            }
34462        } else if (childNode instanceof defaultView.HTMLElement || childNode instanceof HTMLElement || defaultView.parent && childNode instanceof defaultView.parent.HTMLElement) {
34463            if (IGNORED_NODE_NAMES.indexOf(childNode.nodeName) === -1) {
34464                var container = new _NodeContainer2.default(childNode, parent, resourceLoader, index++);
34465                if (container.isVisible()) {
34466                    if (childNode.tagName === 'INPUT') {
34467                        // $FlowFixMe
34468                        (0, Input.inlineInputElement)(childNode, container);
34469                    } else if (childNode.tagName === 'TEXTAREA') {
34470                        // $FlowFixMe
34471                        (0, Input.inlineTextAreaElement)(childNode, container);
34472                    } else if (childNode.tagName === 'SELECT') {
34473                        // $FlowFixMe
34474                        (0, Input.inlineSelectElement)(childNode, container);
34475                    } else if (container.style.listStyle && container.style.listStyle.listStyleType !== listStyle.LIST_STYLE_TYPE.NONE) {
34476                        (0, ListItem.inlineListItemElement)(childNode, container, resourceLoader);
34477                    }
34478
34479                    var SHOULD_TRAVERSE_CHILDREN = childNode.tagName !== 'TEXTAREA';
34480                    var treatAsRealStackingContext = createsRealStackingContext(container, childNode);
34481                    if (treatAsRealStackingContext || createsStackingContext(container)) {
34482                        // for treatAsRealStackingContext:false, any positioned descendants and descendants
34483                        // which actually create a new stacking context should be considered part of the parent stacking context
34484                        var parentStack = treatAsRealStackingContext || container.isPositioned() ? stack.getRealParentStackingContext() : stack;
34485                        var childStack = new _StackingContext2.default(container, parentStack, treatAsRealStackingContext);
34486                        parentStack.contexts.push(childStack);
34487                        if (SHOULD_TRAVERSE_CHILDREN) {
34488                            parseNodeTree(childNode, container, childStack, resourceLoader, index);
34489                        }
34490                    } else {
34491                        stack.children.push(container);
34492                        if (SHOULD_TRAVERSE_CHILDREN) {
34493                            parseNodeTree(childNode, container, stack, resourceLoader, index);
34494                        }
34495                    }
34496                }
34497            }
34498        } else if (childNode instanceof defaultView.SVGSVGElement || childNode instanceof SVGSVGElement || defaultView.parent && childNode instanceof defaultView.parent.SVGSVGElement) {
34499            var _container = new _NodeContainer2.default(childNode, parent, resourceLoader, index++);
34500            var _treatAsRealStackingContext = createsRealStackingContext(_container, childNode);
34501            if (_treatAsRealStackingContext || createsStackingContext(_container)) {
34502                // for treatAsRealStackingContext:false, any positioned descendants and desce
34502ndants
34503                // which actually create a new stacking context should be considered part of the parent stacking context
34504                var _parentStack = _treatAsRealStackingContext || _container.isPositioned() ? stack.getRealParentStackingContext() : stack;
34505                var _childStack = new _StackingContext2.default(_container, _parentStack, _treatAsRealStackingContext);
34506                _parentStack.contexts.push(_childStack);
34507            } else {
34508                stack.children.push(_container);
34509            }
34510        }
34511    }
34512};
34513
34514var createsRealStackingContext = function createsRealStackingContext(container, node) {
34515    return container.isRootElement() || container.isPositionedWithZIndex() || container.style.opacity < 1 || container.isTransformed() || isBodyWithTransparentRoot(container, node);
34516};
34517
34518var createsStackingContext = function createsStackingContext(container) {
34519    return container.isPositioned() || container.isFloating();
34520};
34521
34522var isBodyWithTransparentRoot = function isBodyWithTransparentRoot(container, node) {
34523    return node.nodeName === 'BODY' && container.parent instanceof _NodeContainer2.default && container.parent.style.background.backgroundColor.isTransparent();
34524};
34525});
34526
34527unwrapExports(NodeParser_1);
34528var NodeParser_2 = NodeParser_1.NodeParser;
34529
34530var Font = createCommonjsModule(function (module, exports) {
34531Object.defineProperty(exports, "__esModule", {
34532    value: true
34533});
34534exports.FontMetrics = undefined;
34535
34536var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
34537
34538
34539
34540function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
34541
34542var SAMPLE_TEXT = 'Hidden Text';
34543
34544var FontMetrics = exports.FontMetrics = function () {
34545    function FontMetrics(document) {
34546        _classCallCheck(this, FontMetrics);
34547
34548        this._data = {};
34549        this._document = document;
34550    }
34551
34552    _createClass(FontMetrics, [{
34553        key: '_parseMetrics',
34554        value: function _parseMetrics(font) {
34555            var container = this._document.createElement('div');
34556            var img = this._document.createElement('img');
34557            var span = this._document.createElement('span');
34558
34559            var body = this._document.body;
34560            if (!body) {
34561                throw new Error('');
34562            }
34563
34564            container.style.visibility = 'hidden';
34565            container.style.fontFamily = font.fontFamily;
34566            container.style.fontSize = font.fontSize;
34567            container.style.margin = '0';
34568            container.style.padding = '0';
34569
34570            body.appendChild(container);
34571
34572            img.src = Util.SMALL_IMAGE;
34573            img.width = 1;
34574            img.height = 1;
34575
34576            img.style.margin = '0';
34577            img.style.padding = '0';
34578            img.style.verticalAlign = 'baseline';
34579
34580            span.style.fontFamily = font.fontFamily;
34581            span.style.fontSize = font.fontSize;
34582            span.style.margin = '0';
34583            span.style.padding = '0';
34584
34585            span.appendChild(this._document.createTextNode(SAMPLE_TEXT));
34586            container.appendChild(span);
34587            container.appendChild(img);
34588            var baseline = img.offsetTop - span.offsetTop + 2;
34589
34590            container.removeChild(span);
34591            container.appendChild(this._document.createTextNode(SAMPLE_TEXT));
34592
34593            container.style.lineHeight = 'normal';
34594            img.style.verticalAlign = 'super';
34595
34596            var middle = img.offsetTop - container.offsetTop + 2;
34597
34598            body.removeChild(container);
34599
34600            return { baseline: baseline, middle: middle };
34601        }
34602    }, {
34603        key: 'getMetrics',
34604        value: function getMetrics(font) {
34605            var key = font.fontFamily + ' ' + font.fontSize;
34606            if (this._data[key] === undefined) {
34607                this._data[key] = this._parseMetrics(font);
34608            }
34609
34610            return this._data[key];
34611        }
34612    }]);
34613
34614    return FontMetrics;
34615}();
34616});
34617
34618unwrapExports(Font);
34619var Font_1 = Font.FontMetrics;
34620
34621var Angle = createCommonjsModule(function (module, exports) {
34622Object.defineProperty(exports, "__esModule", {
34623    value: true
34624});
34625var ANGLE = /([+-]?\d*\.?\d+)(deg|grad|rad|turn)/i;
34626
34627var parseAngle = exports.parseAngle = function parseAngle(angle) {
34628    var match = angle.match(ANGLE);
34629
34630    if (match) {
34631        var value = parseFloat(match[1]);
34632        switch (match[2].toLowerCase()) {
34633            case 'deg':
34634                return Math.PI * value / 180;
34635            case 'grad':
34636                return Math.PI / 200 * value;
34637            case 'rad':
34638                return value;
34639            case 'turn':
34640                return Math.PI * 2 * value;
34641        }
34642    }
34643
34644    return null;
34645};
34646});
34647
34648unwrapExports(Angle);
34649var Angle_1 = Angle.parseAngle;
34650
34651var Gradient = createCommonjsModule(function (module, exports) {
34652Object.defineProperty(exports, "__esModule", {
34653    value: true
34654});
34655exports.transformWebkitRadialGradientArgs = exports.parseGradient = exports.RadialGradient = exports.LinearGradient = exports.RADIAL_GRADIENT_SHAPE = exports.GRADIENT_TYPE = undefined;
34656
34657var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
34658
34659
34660
34661var _NodeContainer2 = _interopRequireDefault(NodeContainer_1);
34662
34663
34664
34665
34666
34667var _Color2 = _interopRequireDefault(Color_1);
34668
34669
34670
34671var _Length2 = _interopRequireDefault(Length_1);
34672
34673
34674
34675function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
34676
34677function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
34678
34679var SIDE_OR_CORNER = /^(to )?(left|top|right|bottom)( (left|top|right|bottom))?$/i;
34680var PERCENTAGE_ANGLES = /^([+-]?\d*\.?\d+)% ([+-]?\d*\.?\d+)%$/i;
34681var ENDS_WITH_LENGTH = /(px)|%|( 0)$/i;
34682var FROM_TO_COLORSTOP = /^(from|to|color-stop)\((?:([\d.]+)(%)?,\s*)?(.+?)\)$/i;
34683var RADIAL_SHAPE_DEFINITION = /^\s*(circle|ellipse)?\s*((?:([\d.]+)(px|r?em|%)\s*(?:([\d.]+)(px|r?em|%))?)|closest-side|closest-corner|farthest-side|farthest-corner)?\s*(?:at\s*(?:(left|center|right)|([\d.]+)(px|r?em|%))\s+(?:(top|center|bottom)|([\d.]+)(px|r?em|%)))?(?:\s|$)/i;
34684
34685var GRADIENT_TYPE = exports.GRADIENT_TYPE = {
34686    LINEAR_GRADIENT: 0,
34687    RADIAL_GRADIENT: 1
34688};
34689
34690var RADIAL_GRADIENT_SHAPE = exports.RADIAL_GRADIENT_SHAPE = {
34691    CIRCLE: 0,
34692    ELLIPSE: 1
34693};
34694
34695var LENGTH_FOR_POSITION = {
34696    left: new _Length2.default('0%'),
34697    top: new _Length2.default('0%'),
34698    center: new _Length2.default('50%'),
34699    right: new _Length2.default('100%'),
34700    bottom: new _Length2.default('100%')
34701};
34702
34703var LinearGradient = exports.LinearGradient = function LinearGradient(colorStops, direction) {
34704    _classCallCheck(this, LinearGradient);
34705
34706    this.type = GRADIENT_TYPE.LINEAR_GRADIENT;
34707    this.colorStops = colorStops;
34708    this.direction = direction;
34709};
34710
34711var RadialGradient = exports.RadialGradient = function RadialGradient(colorStops, shape, center, radius) {
34712    _classCallCheck(this, RadialGradient);
34713
34714    this.type = GRADIENT_TYPE.RADIAL_GRADIENT;
34715    this.colorStops = colorStops;
34716    this.shape = shape;
34717    this.center = center;
34718    this.radius = radius;
34719};
34720
34721var parseGradient = exports.parseGradient = function parseGradient(container, _ref, bounds) {
34722    var args = _ref.args,
34723        method = _ref.method,
34724        prefix = _ref.prefix;
34725
34726    if (method === 'linear-gradient') {
34727        return parseLinearGradient(args, bounds, !!prefix);
34728    } else if (method === 'gradient' && args[0] === 'linear') {
34729        // TODO handle correct angle
34730        return parseLinearGradient(['to bottom'].concat(transformObsoleteColorStops(args.slice(3))), bounds, !!prefix);
34731    } else if (method === 'radial-gradient') {
34732        return parseRadialGradient(container, prefix === '-webkit-' ? transformWebkitRadialGradientArgs(args) : args, bounds);
34733    } else if (method === 'gradient' && args[0] === 'radial') {
34734        return parseRadialGradient(container, transformObsoleteColorStops(transformWebkitRadialGradientArgs(args.slice(1))), bounds);
34735    }
34736};
34737
34738var parseColorStops = function parseColorStops(args, firstColorStopIndex, lineLength) {
34739    var colorStops = [];
34740
34741    for (var i = firstColorStopIndex; i < args.length; i++) {
34742        var value = args[i];
34743        var HAS_LENGTH = ENDS_WITH_LENGTH.test(value);
34744        var lastSpaceIndex = value.lastIndexOf(' ');
34745        var _color = new _Color2.default(HAS_LENGTH ? value.substring(0, lastSpaceIndex) : value);
34746        var _stop = HAS_LENGTH ? new _Length2.default(value.substring(lastSpaceIndex + 1)) : i === firstColorStopIndex ? new _Length2.default('0%') : i === args.length - 1 ? new _Length2.default('100%') : null;
34747        colorStops.push({ color: _color, stop: _stop });
34748    }
34749
34750    var absoluteValuedColorStops = colorStops.map(function (_ref2) {
34751        var color = _ref2.color,
34752            stop = _ref2.stop;
34753
34754        var absoluteStop = lineLength === 0 ? 0 : stop ? stop.getAbsoluteValue(lineLength) / lineLength : null;
34755
34756        return {
34757            color: color,
34758            // $FlowFixMe
34759            stop: absoluteStop
34760        };
34761    });
34762
34763    var previousColorStop = absoluteValuedColorStops[0].stop;
34764    for (var _i = 0; _i < absoluteValuedColorStops.length; _i++) {
34765        if (previousColorStop !== null) {
34766            var _stop2 = absoluteValuedColorStops[_i].stop;
34767            if (_stop2 === null) {
34768                var n = _i;
34769                while (absoluteValuedColorStops[n].stop === null) {
34770                    n++;
34771                }
34772                var steps = n - _i + 1;
34773                var nextColorStep = absoluteValuedColorStops[n].stop;
34774                var stepSize = (nextColorStep - previousColorStop) / steps;
34775                for (; _i < n; _i++) {
34776                    previousColorStop = absoluteValuedColorStops[_i].stop = previousColorStop + stepSize;
34777                }
34778            } else {
34779                previousColorStop = _stop2;
34780            }
34781        }
34782    }
34783
34784    return absoluteValuedColorStops;
34785};
34786
34787var parseLinearGradient = function parseLinearGradient(args, bounds, hasPrefix) {
34788    var angle = (0, Angle.parseAngle)(args[0]);
34789    var HAS_SIDE_OR_CORNER = SIDE_OR_CORNER.test(args[0]);
34790    var HAS_DIRECTION = HAS_SIDE_OR_CORNER || angle !== null || PERCENTAGE_ANGLES.test(args[0]);
34791    var direction = HAS_DIRECTION ? angle !== null ? calculateGradientDirection(
34792    // if there is a prefix, the 0° angle points due East (instead of North per W3C)
34793    hasPrefix ? angle - Math.PI * 0.5 : angle, bounds) : HAS_SIDE_OR_CORNER ? parseSideOrCorner(args[0], bounds) : parsePercentageAngle(args[0], bounds) : calculateGradientDirection(Math.PI, bounds);
34794    var firstColorStopIndex = HAS_DIRECTION ? 1 : 0;
34795
34796    // TODO: Fix some inaccuracy with color stops with px values
34797    var lineLength = Math.min((0, Util.distance)(Math.abs(direction.x0) + Math.abs(direction.x1), Math.abs(direction.y0) + Math.abs(direction.y1)), bounds.width * 2, bounds.height * 2);
34798
34799    return new LinearGradient(parseColorStops(args, firstColorStopIndex, lineLength), direction);
34800};
34801
34802var parseRadialGradient = function parseRadialGradient(container, args, bounds) {
34803    var m = args[0].match(RADIAL_SHAPE_DEFINITION);
34804    var shape = m && (m[1] === 'circle' || // explicit shape specification
34805    m[3] !== undefined && m[5] === undefined) // only one radius coordinate
34806    ? RADIAL_GRADIENT_SHAPE.CIRCLE : RADIAL_GRADIENT_SHAPE.ELLIPSE;
34807    var radius = {};
34808    var center = {};
34809
34810    if (m) {
34811        // Radius
34812        if (m[3] !== undefined) {
34813            radius.x = (0, Length_1.calculateLengthFromValueWithUnit)(container, m[3], m[4]).getAbsoluteValue(bounds.width);
34814        }
34815
34816        if (m[5] !== undefined) {
34817            radius.y = (0, Length_1.calculateLengthFromValueWithUnit)(container, m[5], m[6]).getAbsoluteValue(bounds.height);
34818        }
34819
34820        // Position
34821        if (m[7]) {
34822            center.x = LENGTH_FOR_POSITION[m[7].toLowerCase()];
34823        } else if (m[8] !== undefined) {
34824            center.x = (0, Length_1.calculateLengthFromValueWithUnit)(container, m[8], m[9]);
34825        }
34826
34827        if (m[10]) {
34828            center.y = LENGTH_FOR_POSITION[m[10].toLowerCase()];
34829        } else if (m[11] !== undefined) {
34830            center.y = (0, Length_1.calculateLengthFromValueWithUnit)(container, m[11], m[12]);
34831        }
34832    }
34833
34834    var gradientCenter = {
34835        x: center.x === undefined ? bounds.width / 2 : center.x.getAbsoluteValue(bounds.width),
34836        y: center.y === undefined ? bounds.height / 2 : center.y.getAbsoluteValue(bounds.height)
34837    };
34838    var gradientRadius = calculateRadius(m && m[2] || 'farthest-corner', shape, gradientCenter, radius, bounds);
34839
34840    return new RadialGradient(parseColorStops(args, m ? 1 : 0, Math.min(gradientRadius.x, gradientRadius.y)), shape, gradientCenter, gradientRadius);
34841};
34842
34843var calculateGradientDirection = function calculateGradientDirection(radian, bounds) {
34844    var width = bounds.width;
34845    var height = bounds.height;
34846    var HALF_WIDTH = width * 0.5;
34847    var HALF_HEIGHT = height * 0.5;
34848    var lineLength = Math.abs(width * Math.sin(radian)) + Math.abs(height * Math.cos(radian));
34849    var HALF_LINE_LENGTH = lineLength / 2;
34850
34851    var x0 = HALF_WIDTH + Math.sin(radian) * HALF_LINE_LENGTH;
34852    var y0 = HALF_HEIGHT - Math.cos(radian) * HALF_LINE_LENGTH;
34853    var x1 = width - x0;
34854    var y1 = height - y0;
34855
34856    return { x0: x0, x1: x1, y0: y0, y1: y1 };
34857};
34858
34859var parseTopRight = function parseTopRight(bounds) {
34860    return Math.acos(bounds.width / 2 / ((0, Util.distance)(bounds.width, bounds.height) / 2));
34861};
34862
34863var parseSideOrCorner = function parseSideOrCorner(side, bounds) {
34864    switch (side) {
34865        case 'bottom':
34866        case 'to top':
34867            return calculateGradientDirection(0, bounds);
34868        case 'left':
34869        case 'to right':
34870            return calculateGradientDirection(Math.PI / 2, bounds);
34871        case 'right':
34872        case 'to left':
34873            return calculateGradientDirection(3 * Math.PI / 2, bounds);
34874        case 'top right':
34875        case 'right top':
34876        case 'to bottom left':
34877        case 'to left bottom':
34878            return calculateGradientDirection(Math.PI + parseTopRight(bounds), bounds);
34879        case 'top left':
34880        case 'left top':
34881        case 'to bottom right':
34882        case 'to right bottom':
34883            return calculateGradientDirection(Math.PI - parseTopRight(bounds), bounds);
34884        case 'bottom left':
34885        case 'left bottom':
34886        case 'to top right':
34887        case 'to right top':
34888            return calculateGradientDirection(parseTopRight(bounds), bounds);
34889        case 'bottom right':
34890        case 'right bottom':
34891        case 'to top left':
34892        case 'to left top':
34893            return calculateGradientDirection(2 * Math.PI - parseTopRight(bounds), bounds);
34894        case 'top':
34895        case 'to bottom':
34896        default:
34897            return calculateGradientDirection(Math.PI, bounds);
34898    }
34899};
34900
34901var parsePercentageAngle = function parsePercentageAngle(angle, bounds) {
34902    var _angle$split$map = angle.split(' ').map(parseFloat),
34903        _angle$split$map2 = _slicedToArray(_angle$split$map, 2),
34904        left = _angle$split$map2[0],
34905        top = _angle$split$map2[1];
34906
34907    var ratio = left / 100 * bounds.width / (top / 100 * bounds.height);
34908
34909    return calculateGradientDirection(Math.atan(isNaN(ratio) ? 1 : ratio) + Math.PI / 2, bounds);
34910};
34911
34912var findCorner = function findCorner(bounds, x, y, closest) {
34913    var corners = [{ x: 0, y: 0 }, { x: 0, y: bounds.height }, { x: bounds.width, y: 0 }, { x: bounds.width, y: bounds.height }];
34914
34915    // $FlowFixMe
34916    return corners.reduce(function (stat, corner) {
34917        var d = (0, Util.distance)(x - corner.x, y - corner.y);
34918        if (closest ? d < stat.optimumDistance : d > stat.optimumDistance) {
34919            return {
34920                optimumCorner: corner,
34921                optimumDistance: d
34922            };
34923        }
34924
34925        return stat;
34926    }, {
34927        optimumDistance: closest ? Infinity : -Infinity,
34928        optimumCorner: null
34929    }).optimumCorner;
34930};
34931
34932var calculateRadius = function calculateRadius(extent, shape, center, radius, bounds) {
34933    var x = center.x;
34934    var y = center.y;
34935    var rx = 0;
34936    var ry = 0;
34937
34938    switch (extent) {
34939        case 'closest-side':
34940            // The ending shape is sized so that that it exactly meets the side of the gradient box closest to the gradient’s center.
34941            // If the shape is an ellipse, it exactly meets the closest side in each dimension.
34942            if (shape === RADIAL_GRADIENT_SHAPE.CIRCLE) {
34943                rx = ry = Math.min(Math.abs(x), Math.abs(x - bounds.width), Math.abs(y), Math.abs(y - bounds.height));
34944            } else if (shape === RADIAL_GRADIENT_SHAPE.ELLIPSE) {
34945                rx = Math.min(Math.abs(x), Math.abs(x - bounds.width));
34946                ry = Math.min(Math.abs(y), Math.abs(y - bounds.height));
34947            }
34948            break;
34949
34950        case 'closest-corner':
34951            // The ending shape is sized so that that it passes through the corner of the gradient box closest to the gradient’s center.
34952            // If the shape is an ellipse, the ending shape is given the same aspect-ratio it would have if closest-side were specified.
34953            if (shape === RADIAL_GRADIENT_SHAPE.CIRCLE) {
34954                rx = ry = Math.min((0, Util.distance)(x, y), (0, Util.distance)(x, y - bounds.height), (0, Util.distance)(x - bounds.width, y), (0, Util.distance)(x - bounds.width, y - bounds.height));
34955            } else if (shape === RADIAL_GRADIENT_SHAPE.ELLIPSE) {
34956                // Compute the ratio ry/rx (which is to be the same as for "closest-side")
34957                var c = Math.min(Math.abs(y), Math.abs(y - bounds.height)) / Math.min(Math.abs(x), Math.abs(x - bounds.width));
34958                var corner = findCorner(bounds, x, y, true);
34959                rx = (0, Util.distance)(corner.x - x, (corner.y - y) / c);
34960                ry = c * rx;
34961            }
34962            break;
34963
34964        case 'farthest-side':
34965            // Same as closest-side, except the ending shape is sized based on the farthest side(s)
34966            if (shape === RADIAL_GRADIENT_SHAPE.CIRCLE) {
34967                rx = ry = Math.max(Math.abs(x), Math.abs(x - bounds.width), Math.abs(y), Math.abs(y - bounds.height));
34968            } else if (shape === RADIAL_GRADIENT_SHAPE.ELLIPSE) {
34969                rx = Math.max(Math.abs(x), Math.abs(x - bounds.width));
34970                ry = Math.max(Math.abs(y), Math.abs(y - bounds.height));
34971            }
34972            break;
34973
34974        case 'farthest-corner':
34975            // Same as closest-corner, except the ending shape is sized based on the farthest corner.
34976            // If the shape is an ellipse, the ending shape is given the same aspect ratio it would have if farthest-side were specified.
34977            if (shape === RADIAL_GRADIENT_SHAPE.CIRCLE) {
34978                rx = ry = Math.max((0, Util.distance)(x, y), (0, Util.distance)(x, y - bounds.height), (0, Util.distance)(x - bounds.width, y), (0, Util.distance)(x - bounds.width, y - bounds.height));
34979            } else if (shape === RADIAL_GRADIENT_SHAPE.ELLIPSE) {
34980                // Compute the ratio ry/rx (which is to be the same as for "farthest-side")
34981                var _c = Math.max(Math.abs(y), Math.abs(y - bounds.height)) / Math.max(Math.abs(x), Math.abs(x - bounds.width));
34982                var _corner = findCorner(bounds, x, y, false);
34983                rx = (0, Util.distance)(_corner.x - x, (_corner.y - y) / _c);
34984                ry = _c * rx;
34985            }
34986            break;
34987
34988        default:
34989            // pixel or percentage values
34990            rx = radius.x || 0;
34991            ry = radius.y !== undefined ? radius.y : rx;
34992            break;
34993    }
34994
34995    return {
34996        x: rx,
34997        y: ry
34998    };
34999};
35000
35001var transformWebkitRadialGradientArgs = exports.transformWebkitRadialGradientArgs = function transformWebkitRadialGradientArgs(args) {
35002    var shape = '';
35003    var radius = '';
35004    var extent = '';
35005    var position = '';
35006    var idx = 0;
35007
35008    var POSITION = /^(left|center|right|\d+(?:px|r?em|%)?)(?:\s+(top|center|bottom|\d+(?:px|r?em|%)?))?$/i;
35009    var SHAPE_AND_EXTENT = /^(circle|ellipse)?\s*(closest-side|closest-corner|farthest-side|farthest-corner|contain|cover)?$/i;
35010    var RADIUS = /^\d+(px|r?em|%)?(?:\s+\d+(px|r?em|%)?)?$/i;
35011
35012    var matchStartPosition = args[idx].match(POSITION);
35013    if (matchStartPosition) {
35014        idx++;
35015    }
35016
35017    var matchShapeExtent = args[idx].match(SHAPE_AND_EXTENT);
35018    if (matchShapeExtent) {
35019        shape = matchShapeExtent[1] || '';
35020        extent = matchShapeExtent[2] || '';
35021        if (extent === 'contain') {
35022            extent = 'closest-side';
35023        } else if (extent === 'cover') {
35024            extent = 'farthest-corner';
35025        }
35026        idx++;
35027    }
35028
35029    var matchStartRadius = args[idx].match(RADIUS);
35030    if (matchStartRadius) {
35031        idx++;
35032    }
35033
35034    var matchEndPosition = args[idx].match(POSITION);
35035    if (matchEndPosition) {
35036        idx++;
35037    }
35038
35039    var matchEndRadius = args[idx].match(RADIUS);
35040    if (matchEndRadius) {
35041        idx++;
35042    }
35043
35044    var matchPosition = matchEndPosition || matchStartPosition;
35045    if (matchPosition && matchPosition[1]) {
35046        position = matchPosition[1] + (/^\d+$/.test(matchPosition[1]) ? 'px' : '');
35047        if (matchPosition[2]) {
35048            position += ' ' + matchPosition[2] + (/^\d+$/.test(matchPosition[2]) ? 'px' : '');
35049        }
35050    }
35051
35052    var matchRadius = matchEndRadius || matchStartRadius;
35053    if (matchRadius) {
35054        radius = matchRadius[0];
35055        if (!matchRadius[1]) {
35056            radius += 'px';
35057        }
35058    }
35059
35060    if (position && !shape && !radius && !extent) {
35061        radius = position;
35062        position = '';
35063    }
35064
35065    if (position) {
35066        position = 'at ' + position;
35067    }
35068
35069    return [[shape, extent, radius, position].filter(function (s) {
35070        return !!s;
35071    }).join(' ')].concat(args.slice(idx));
35072};
35073
35074var transformObsoleteColorStops = function transformObsoleteColorStops(args) {
35075    return args.map(function (color) {
35076        return color.match(FROM_TO_COLORSTOP);
35077    })
35078    // $FlowFixMe
35079    .map(function (v, index) {
35080        if (!v) {
35081            return args[index];
35082        }
35083
35084        switch (v[1]) {
35085            case 'from':
35086                return v[4] + ' 0%';
35087            case 'to':
35088                return v[4] + ' 100%';
35089            case 'color-stop':
35090                if (v[3] === '%') {
35091                    return v[4] + ' ' + v[2];
35092                }
35093                return v[4] + ' ' + parseFloat(v[2]) * 100 + '%';
35094        }
35095    });
35096};
35097});
35098
35099unwrapExports(Gradient);
35100var Gradient_1 = Gradient.transformWebkitRadialGradientArgs;
35101var Gradient_2 = Gradient.parseGradient;
35102var Gradient_3 = Gradient.RadialGradient;
35103var Gradient_4 = Gradient.LinearGradient;
35104var Gradient_5 = Gradient.RADIAL_GRADIENT_SHAPE;
35105var Gradient_6 = Gradient.GRADIENT_TYPE;
35106
35107var Renderer_1 = createCommonjsModule(function (module, exports) {
35108Object.defineProperty(exports, "__esModule", {
35109    value: true
35110});
35111
35112var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
35113
35114var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124var _TextContainer2 = _interopRequireDefault(TextContainer_1);
35125
35126
35127
35128
35129
35130function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
35131
35132function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
35133
35134var Renderer = function () {
35135    function Renderer(target, options) {
35136        _classCallCheck(this, Renderer);
35137
35138        this.target = target;
35139        this.options = options;
35140        target.render(options);
35141    }
35142
35143    _createClass(Renderer, [{
35144        key: 'renderNode',
35145        value: function renderNode(container) {
35146            if (container.isVisible()) {
35147                this.renderNodeBackgroundAndBorders(container);
35148                this.renderNodeContent(container);
35149            }
35150        }
35151    }, {
35152        key: 'renderNodeContent',
35153        value: function renderNodeContent(container) {
35154            var _this = this;
35155
35156            var callback = function callback() {
35157                if (container.childNodes.length) {
35158                    container.childNodes.forEach(function (child) {
35159                        if (child instanceof _TextContainer2.default) {
35160                            var style = child.parent.style;
35161                            _this.target.renderTextNode(child.bounds, style.color, style.font, style.textDecoration, style.textShadow);
35162                        } else {
35163                            _this.target.drawShape(child, container.style.color);
35164                        }
35165                    });
35166                }
35167
35168                if (container.image) {
35169                    var _image = _this.options.imageStore.get(container.image);
35170                    if (_image) {
35171                        var contentBox = (0, Bounds_1.calculateContentBox)(container.bounds, container.style.padding, container.style.border);
35172                        var _width = typeof _image.width === 'number' && _image.width > 0 ? _image.width : contentBox.width;
35173                        var _height = typeof _image.height === 'number' && _image.height > 0 ? _image.height : contentBox.height;
35174                        if (_width > 0 && _height > 0) {
35175                            _this.target.clip([(0, Bounds_1.calculatePaddingBoxPath)(container.curvedBounds)], function () {
35176                                _this.target.drawImage(_image, new Bounds_1.Bounds(0, 0, _width, _height), contentBox);
35177                            });
35178                        }
35179                    }
35180                }
35181            };
35182            var paths = container.getClipPaths();
35183            if (paths.length) {
35184                this.target.clip(paths, callback);
35185            } else {
35186                callback();
35187            }
35188        }
35189    }, {
35190        key: 'renderNodeBackgroundAndBorders',
35191        value: function renderNodeBackgroundAndBorders(container) {
35192            var _this2 = this;
35193
35194            var HAS_BACKGROUND = !container.style.background.backgroundColor.isTransparent() || container.style.background.backgroundImage.length;
35195
35196            var hasRenderableBorders = container.style.border.some(function (border$$2) {
35197                return border$$2.borderStyle !== border.BORDER_STYLE.NONE && !border$$2.borderColor.isTransparent();
35198            });
35199
35200            var callback = function callback() {
35201                var backgroundPaintingArea = (0, background.calculateBackgroungPaintingArea)(container.curvedBounds, container.style.background.backgroundClip);
35202
35203                if (HAS_BACKGROUND) {
35204                    _this2.target.clip([backgroundPaintingArea], function () {
35205                        if (!container.style.background.backgroundColor.isTransparent()) {
35206                            _this2.target.fill(container.style.background.backgroundColor);
35207                        }
35208
35209                        _this2.renderBackgroundImage(container);
35210                    });
35211                }
35212
35213                container.style.border.forEach(function (border$$2, side) {
35214                    if (border$$2.borderStyle !== border.BORDER_STYLE.NONE && !border$$2.borderColor.isTransparent()) {
35215                        _this2.renderBorder(border$$2, side, container.curvedBounds);
35216                    }
35217                });
35218            };
35219
35220            if (HAS_BACKGROUND || hasRenderableBorders) {
35221                var paths = container.parent ? container.parent.getClipPaths() : [];
35222                if (paths.length) {
35223                    this.target.clip(paths, callback);
35224                } else {
35225                    callback();
35226                }
35227            }
35228        }
35229    }, {
35230        key: 'renderBackgroundImage',
35231        value: function renderBackgroundImage(container) {
35232            var _this3 = this;
35233
35234            container.style.background.backgroundImage.slice(0).reverse().forEach(function (backgroundImage) {
35235                if (backgroundImage.source.method === 'url' && backgroundImage.source.args.length) {
35236                    _this3.renderBackgroundRepeat(container, backgroundImage);
35237                } else if (/gradient/i.test(backgroundImage.source.method)) {
35238                    _this3.renderBackgroundGradient(container, backgroundImage);
35239                }
35240            });
35241        }
35242    }, {
35243        key: 'renderBackgroundRepeat',
35244        value: function renderBackgroundRepeat(container, background$$2) {
35245            var image = this.options.imageStore.get(background$$2.source.args[0]);
35246            if (image) {
35247                var backgroundPositioningArea = (0, background.calculateBackgroungPositioningArea)(container.style.background.backgroundOrigin, container.bounds, container.style.padding, container.style.border);
35248                var backgroundImageSize = (0, background.calculateBackgroundSize)(background$$2, image, backgroundPositioningArea);
35249                var position = (0, background.calculateBackgroundPosition)(background$$2.position, backgroundImageSize, backgroundPositioningArea);
35250                var _path = (0, background.calculateBackgroundRepeatPath)(background$$2, position, backgroundImageSize, backgroundPositioningArea, container.bounds);
35251
35252                var _offsetX = Math.round(backgroundPositioningArea.left + position.x);
35253                var _offsetY = Math.round(backgroundPositioningArea.top + position.y);
35254                this.target.renderRepeat(_path, image, backgroundImageSize, _offsetX, _offsetY);
35255            }
35256        }
35257    }, {
35258        key: 'renderBackgroundGradient',
35259        value: function renderBackgroundGradient(container, background$$2) {
35260            var backgroundPositioningArea = (0, background.calculateBackgroungPositioningArea)(container.style.background.backgroundOrigin, container.bounds, container.style.padding, container.style.border);
35261            var backgroundImageSize = (0, background.calculateGradientBackgroundSize)(background$$2, backgroundPositioningArea);
35262            var position = (0, background.calculateBackgroundPosition)(background$$2.position, backgroundImageSize, backgroundPositioningArea);
35263            var gradientBounds = new Bounds_1.Bounds(Math.round(backgroundPositioningArea.left + position.x), Math.round(backgroundPositioningArea.top + position.y), backgroundImageSize.width, backgroundImageSize.height);
35264
35265            var gradient = (0, Gradient.parseGradient)(container, background$$2.source, gradientBounds);
35266            if (gradient) {
35267                switch (gradient.type) {
35268                    case Gradient.GRADIENT_TYPE.LINEAR_GRADIENT:
35269                        // $FlowFixMe
35270                        this.target.renderLinearGradient(gradientBounds, gradient);
35271                        break;
35272                    case Gradient.GRADIENT_TYPE.RADIAL_GRADIENT:
35273                        // $FlowFixMe
35274                        this.target.renderRadialGradient(gradientBounds, gradient);
35275                        break;
35276                }
35277            }
35278        }
35279    }, {
35280        key: 'renderBorder',
35281        value: function renderBorder(border$$2, side, curvePoints) {
35282            this.target.drawShape((0, Bounds_1.parsePathForBorder)(curvePoints, side), border$$2.borderColor);
35283        }
35284    }, {
35285        key: 'renderStack',
35286        value: function renderStack(stack) {
35287            var _this4 = this;
35288
35289            if (stack.container.isVisible()) {
35290                var _opacity = stack.getOpacity();
35291                if (_opacity !== this._opacity) {
35292                    this.target.setOpacity(stack.getOpacity());
35293                    this._opacity = _opacity;
35294                }
35295
35296                var _transform = stack.container.style.transform;
35297                if (_transform !== null) {
35298                    this.target.transform(stack.container.bounds.left + _transform.transformOrigin[0].value, stack.container.bounds.top + _transform.transformOrigin[1].value, _transform.transform, function () {
35299                        return _this4.renderStackContent(stack);
35300                    });
35301                } else {
35302                    this.renderStackContent(stack);
35303                }
35304            }
35305        }
35306    }, {
35307        key: 'renderStackContent',
35308        value: function renderStackContent(stack) {
35309            var _splitStackingContext = splitStackingContexts(stack),
35310                _splitStackingContext2 = _slicedToArray(_splitStackingContext, 5),
35311                negativeZIndex = _splitStackingContext2[0],
35312                zeroOrAutoZIndexOrTransformedOrOpacity = _splitStackingContext2[1],
35313                positiveZIndex = _splitStackingContext2[2],
35314                nonPositionedFloats = _splitStackingContext2[3],
35315                nonPositionedInlineLevel = _splitStackingContext2[4];
35316
35317            var _splitDescendants = splitDescendants(stack),
35318                _splitDescendants2 = _slicedToArray(_splitDescendants, 2),
35319                inlineLevel = _splitDescendants2[0],
35320                nonInlineLevel = _splitDescendants2[1];
35321
35322            // https://www.w3.org/TR/css-position-3/#painting-order
35323            // 1. the background and borders of the element forming the stacking context.
35324
35325
35326            this.renderNodeBackgroundAndBorders(stack.container);
35327            // 2. the child stacking contexts with negative stack levels (most negative first).
35328            negativeZIndex.sort(sortByZIndex).forEach(this.renderStack, this);
35329            // 3. For all its in-flow, non-positioned, block-level descendants in tree order:
35330            this.renderNodeContent(stack.container);
35331            nonInlineLevel.forEach(this.renderNode, this);
35332            // 4. All non-positioned floating descendants, in tree order. For each one of these,
35333            // treat the element as if it created a new stacking context, but any positioned descendants and descendants
35334            // which actually create a new stacking context should be considered part of the parent stacking context,
35335            // not this new one.
35336            nonPositionedFloats.forEach(this.renderStack, this);
35337            // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
35338            nonPositionedInlineLevel.forEach(this.renderStack, this);
35339            inlineLevel.forEach(this.renderNode, this);
35340            // 6. All positioned, opacity or transform descendants, in tree order that fall into the following categories:
35341            //  All positioned descendants with 'z-index: auto' or 'z-index: 0', in tree order.
35342            //  For those with 'z-index: auto', treat the element as if it created a new stacking context,
35343            //  but any positioned descendants and descendants which actually create a new stacking context should be
35344            //  considered part of the parent stacking context, not this new one. For those with 'z-index: 0',
35345            //  treat the stacking context generated atomically.
35346            //
35347            //  All opacity descendants with opacity less than 1
35348            //
35349            //  All transform descendants with transform other than none
35350            zeroOrAutoZIndexOrTransformedOrOpacity.forEach(this.renderStack, this);
35351            // 7. Stacking contexts formed by positioned descendants with z-indices greater than or equal to 1 in z-index
35352            // order (smallest first) then tree order.
35353            positiveZIndex.sort(sortByZIndex).forEach(this.renderStack, this);
35354        }
35355    }, {
35356        key: 'render',
35357        value: function render(stack) {
35358            if (this.options.backgroundColor) {
35359                this.target.rectangle(this.options.x, this.options.y, this.options.width, this.options.height, this.options.backgroundColor);
35360            }
35361            this.renderStack(stack);
35362            var target = this.target.getTarget();
35363            return target;
35364        }
35365    }]);
35366
35367    return Renderer;
35368}();
35369
35370exports.default = Renderer;
35371
35372
35373var splitDescendants = function splitDescendants(stack) {
35374    var inlineLevel = [];
35375    var nonInlineLevel = [];
35376
35377    var length = stack.children.length;
35378    for (var i = 0; i < length; i++) {
35379        var child = stack.children[i];
35380        if (child.isInlineLevel()) {
35381            inlineLevel.push(child);
35382        } else {
35383            nonInlineLevel.push(child);
35384        }
35385    }
35386    return [inlineLevel, nonInlineLevel];
35387};
35388
35389var splitStackingContexts = function splitStackingContexts(stack) {
35390    var negativeZIndex = [];
35391    var zeroOrAutoZIndexOrTransformedOrOpacity = [];
35392    var positiveZIndex = [];
35393    var nonPositionedFloats = [];
35394    var nonPositionedInlineLevel = [];
35395    var length = stack.contexts.length;
35396    for (var i = 0; i < length; i++) {
35397        var child = stack.contexts[i];
35398        if (child.container.isPositioned() || child.container.style.opacity < 1 || child.container.isTransformed()) {
35399            if (child.container.style.zIndex.order < 0) {
35400                negativeZIndex.push(child);
35401            } else if (child.container.style.zIndex.order > 0) {
35402                positiveZIndex.push(child);
35403            } else {
35404                zeroOrAutoZIndexOrTransformedOrOpacity.push(child);
35405            }
35406        } else {
35407            if (child.container.isFloating()) {
35408                nonPositionedFloats.push(child);
35409            } else {
35410                nonPositionedInlineLevel.push(child);
35411            }
35412        }
35413    }
35414    return [negativeZIndex, zeroOrAutoZIndexOrTransformedOrOpacity, positiveZIndex, nonPositionedFloats, nonPositionedInlineLevel];
35415};
35416
35417var sortByZIndex = function sortByZIndex(a, b) {
35418    if (a.container.style.zIndex.order > b.container.style.zIndex.order) {
35419        return 1;
35420    } else if (a.container.style.zIndex.order < b.container.style.zIndex.order) {
35421        return -1;
35422    }
35423
35424    return a.container.index > b.container.index ? 1 : -1;
35425};
35426});
35427
35428unwrapExports(Renderer_1);
35429
35430var _Proxy = createCommonjsModule(function (module, exports) {
35431Object.defineProperty(exports, "__esModule", {
35432    value: true
35433});
35434exports.Proxy = undefined;
35435
35436
35437
35438var _Feature2 = _interopRequireDefault(Feature);
35439
35440function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
35441
35442var Proxy = exports.Proxy = function Proxy(src, options) {
35443    if (!options.proxy) {
35444        return Promise.reject(null);
35445    }
35446    var proxy = options.proxy;
35447
35448    return new Promise(function (resolve, reject) {
35449        var responseType = _Feature2.default.SUPPORT_CORS_XHR && _Feature2.default.SUPPORT_RESPONSE_TYPE ? 'blob' : 'text';
35450        var xhr = _Feature2.default.SUPPORT_CORS_XHR ? new XMLHttpRequest() : new XDomainRequest();
35451        xhr.onload = function () {
35452            if (xhr instanceof XMLHttpRequest) {
35453                if (xhr.status === 200) {
35454                    if (responseType === 'text') {
35455                        resolve(xhr.response);
35456                    } else {
35457                        var reader = new FileReader();
35458                        // $FlowFixMe
35459                        reader.addEventListener('load', function () {
35460                            return resolve(reader.result);
35461                        }, false);
35462                        // $FlowFixMe
35463                        reader.addEventListener('error', function (e) {
35464                            return reject(e);
35465                        }, false);
35466                        reader.readAsDataURL(xhr.response);
35467                    }
35468                } else {
35469                    reject('');
35470                }
35471            } else {
35472                resolve(xhr.responseText);
35473            }
35474        };
35475
35476        xhr.onerror = reject;
35477        xhr.open('GET', proxy + '?url=' + encodeURIComponent(src) + '&responseType=' + responseType);
35478
35479        if (responseType !== 'text' && xhr instanceof XMLHttpRequest) {
35480            xhr.responseType = responseType;
35481        }
35482
35483        if (options.imageTimeout) {
35484            var timeout = options.imageTimeout;
35485            xhr.timeout = timeout;
35486            xhr.ontimeout = function () {
35487                return reject('');
35488            };
35489        }
35490
35491        xhr.send();
35492    });
35493};
35494});
35495
35496unwrapExports(_Proxy);
35497var _Proxy_1 = _Proxy.Proxy;
35498
35499var ResourceLoader_1 = createCommonjsModule(function (module, exports
35499) {
35500Object.defineProperty(exports, "__esModule", {
35501    value: true
35502});
35503exports.ResourceStore = undefined;
35504
35505var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
35506
35507
35508
35509var _Feature2 = _interopRequireDefault(Feature);
35510
35511
35512
35513function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
35514
35515function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
35516
35517var ResourceLoader = function () {
35518    function ResourceLoader(options, logger, window) {
35519        _classCallCheck(this, ResourceLoader);
35520
35521        this.options = options;
35522        this._window = window;
35523        this.origin = this.getOrigin(window.location.href);
35524        this.cache = {};
35525        this.logger = logger;
35526        this._index = 0;
35527    }
35528
35529    _createClass(ResourceLoader, [{
35530        key: 'loadImage',
35531        value: function loadImage(src) {
35532            var _this = this;
35533
35534            if (this.hasResourceInCache(src)) {
35535                return src;
35536            }
35537            if (isBlobImage(src)) {
35538                this.cache[src] = _loadImage(src, this.options.imageTimeout || 0);
35539                return src;
35540            }
35541
35542            if (!isSVG(src) || _Feature2.default.SUPPORT_SVG_DRAWING) {
35543                if (this.options.allowTaint === true || isInlineImage(src) || this.isSameOrigin(src)) {
35544                    return this.addImage(src, src, false);
35545                } else if (!this.isSameOrigin(src)) {
35546                    if (typeof this.options.proxy === 'string') {
35547                        this.cache[src] = (0, _Proxy.Proxy)(src, this.options).then(function (src) {
35548                            return _loadImage(src, _this.options.imageTimeout || 0);
35549                        });
35550                        return src;
35551                    } else if (this.options.useCORS === true && _Feature2.default.SUPPORT_CORS_IMAGES) {
35552                        return this.addImage(src, src, true);
35553                    }
35554                }
35555            }
35556        }
35557    }, {
35558        key: 'inlineImage',
35559        value: function inlineImage(src) {
35560            var _this2 = this;
35561
35562            if (isInlineImage(src)) {
35563                return _loadImage(src, this.options.imageTimeout || 0);
35564            }
35565            if (this.hasResourceInCache(src)) {
35566                return this.cache[src];
35567            }
35568            if (!this.isSameOrigin(src) && typeof this.options.proxy === 'string') {
35569                return this.cache[src] = (0, _Proxy.Proxy)(src, this.options).then(function (src) {
35570                    return _loadImage(src, _this2.options.imageTimeout || 0);
35571                });
35572            }
35573
35574            return this.xhrImage(src);
35575        }
35576    }, {
35577        key: 'xhrImage',
35578        value: function xhrImage(src) {
35579            var _this3 = this;
35580
35581            this.cache[src] = new Promise(function (resolve, reject) {
35582                var xhr = new XMLHttpRequest();
35583                xhr.onreadystatechange = function () {
35584                    if (xhr.readyState === 4) {
35585                        if (xhr.status !== 200) {
35586                            reject('Failed to fetch image ' + src.substring(0, 256) + ' with status code ' + xhr.status);
35587                        } else {
35588                            var reader = new FileReader();
35589                            reader.addEventListener('load', function () {
35590                                // $FlowFixMe
35591                                var result = reader.result;
35592                                resolve(result);
35593                            }, false);
35594                            reader.addEventListener('error', function (e) {
35595                                return reject(e);
35596                            }, false);
35597                            reader.readAsDataURL(xhr.response);
35598                        }
35599                    }
35600                };
35601                xhr.responseType = 'blob';
35602                if (_this3.options.imageTimeout) {
35603                    var timeout = _this3.options.imageTimeout;
35604                    xhr.timeout = timeout;
35605                    xhr.ontimeout = function () {
35606                        return reject('');
35607                    };
35608                }
35609                xhr.open('GET', src, true);
35610                xhr.send();
35611            }).then(function (src) {
35612                return _loadImage(src, _this3.options.imageTimeout || 0);
35613            });
35614
35615            return this.cache[src];
35616        }
35617    }, {
35618        key: 'loadCanvas',
35619        value: function loadCanvas(node) {
35620            var key = String(this._index++);
35621            this.cache[key] = Promise.resolve(node);
35622            return key;
35623        }
35624    }, {
35625        key: 'hasResourceInCache',
35626        value: function hasResourceInCache(key) {
35627            return typeof this.cache[key] !== 'undefined';
35628        }
35629    }, {
35630        key: 'addImage',
35631        value: function addImage(key, src, useCORS) {
35632            var _this4 = this;
35633
35634            var imageLoadHandler = function imageLoadHandler(supportsDataImages) {
35635                return new Promise(function (resolve, reject) {
35636                    var img = new Image();
35637                    img.onload = function () {
35638                        return resolve(img);
35639                    };
35640                    //ios safari 10.3 taints canvas with data urls unless crossOrigin is set to anonymous
35641                    if (!supportsDataImages || useCORS) {
35642                        img.crossOrigin = 'anonymous';
35643                    }
35644
35645                    img.onerror = reject;
35646                    img.src = src;
35647                    if (img.complete === true) {
35648                        // Inline XML images may fail to parse, throwing an Error later on
35649                        setTimeout(function () {
35650                            resolve(img);
35651                        }, 500);
35652                    }
35653                    if (_this4.options.imageTimeout) {
35654                        var timeout = _this4.options.imageTimeout;
35655                        setTimeout(function () {
35656                            return reject('');
35657                        }, timeout);
35658                    }
35659                });
35660            };
35661
35662            this.cache[key] = isInlineBase64Image(src) && !isSVG(src) ? // $FlowFixMe
35663            _Feature2.default.SUPPORT_BASE64_DRAWING(src).then(imageLoadHandler) : imageLoadHandler(true);
35664            return key;
35665        }
35666    }, {
35667        key: 'isSameOrigin',
35668        value: function isSameOrigin(url) {
35669            return this.getOrigin(url) === this.origin;
35670        }
35671    }, {
35672        key: 'getOrigin',
35673        value: function getOrigin(url) {
35674            var link = this._link || (this._link = this._window.document.createElement('a'));
35675            link.href = url;
35676            link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
35677            return link.protocol + link.hostname + link.port;
35678        }
35679    }, {
35680        key: 'ready',
35681        value: function ready() {
35682            var _this5 = this;
35683
35684            var keys = Object.keys(this.cache);
35685            var values = keys.map(function (str) {
35686                return _this5.cache[str].catch(function (e) {
35687                    return null;
35688                });
35689            });
35690            return Promise.all(values).then(function (images) {
35691                return new ResourceStore(keys, images);
35692            });
35693        }
35694    }]);
35695
35696    return ResourceLoader;
35697}();
35698
35699exports.default = ResourceLoader;
35700
35701var ResourceStore = exports.ResourceStore = function () {
35702    function ResourceStore(keys, resources) {
35703        _classCallCheck(this, ResourceStore);
35704
35705        this._keys = keys;
35706        this._resources = resources;
35707    }
35708
35709    _createClass(ResourceStore, [{
35710        key: 'get',
35711        value: function get(key) {
35712            var index = this._keys.indexOf(key);
35713            return index === -1 ? null : this._resources[index];
35714        }
35715    }]);
35716
35717    return ResourceStore;
35718}();
35719
35720var INLINE_SVG = /^data:image\/svg\+xml/i;
35721var INLINE_BASE64 = /^data:image\/.*;base64,/i;
35722var INLINE_IMG = /^data:image\/.*/i;
35723
35724var isInlineImage = function isInlineImage(src) {
35725    return INLINE_IMG.test(src);
35726};
35727var isInlineBase64Image = function isInlineBase64Image(src) {
35728    return INLINE_BASE64.test(src);
35729};
35730var isBlobImage = function isBlobImage(src) {
35731    return src.substr(0, 4) === 'blob';
35732};
35733
35734var isSVG = function isSVG(src) {
35735    return src.substr(-3).toLowerCase() === 'svg' || INLINE_SVG.test(src);
35736};
35737
35738var _loadImage = function _loadImage(src, timeout) {
35739    return new Promise(function (resolve, reject) {
35740        var img = new Image();
35741        img.onload = function () {
35742            return resolve(img);
35743        };
35744        img.onerror = reject;
35745        img.src = src;
35746        if (img.complete === true) {
35747            // Inline XML images may fail to parse, throwing an Error later on
35748            setTimeout(function () {
35749                resolve(img);
35750            }, 500);
35751        }
35752        if (timeout) {
35753            setTimeout(function () {
35754                return reject('');
35755            }, timeout);
35756        }
35757    });
35758};
35759});
35760
35761unwrapExports(ResourceLoader_1);
35762var ResourceLoader_2 = ResourceLoader_1.ResourceStore;
35763
35764var PseudoNodeContent = createCommonjsModule(function (module, exports
35764) {
35765Object.defineProperty(exports, "__esModule", {
35766    value: true
35767});
35768exports.parseContent = exports.resolvePseudoContent = exports.popCounters = exports.parseCounterReset = exports.TOKEN_TYPE = exports.PSEUDO_CONTENT_ITEM_TYPE = undefined;
35769
35770var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
35771
35772
35773
35774
35775
35776var PSEUDO_CONTENT_ITEM_TYPE = exports.PSEUDO_CONTENT_ITEM_TYPE = {
35777    TEXT: 0,
35778    IMAGE: 1
35779};
35780
35781var TOKEN_TYPE = exports.TOKEN_TYPE = {
35782    STRING: 0,
35783    ATTRIBUTE: 1,
35784    URL: 2,
35785    COUNTER: 3,
35786    COUNTERS: 4,
35787    OPENQUOTE: 5,
35788    CLOSEQUOTE: 6
35789};
35790
35791var parseCounterReset = exports.parseCounterReset = function parseCounterReset(style, data) {
35792    if (!style || !style.counterReset || style.counterReset === 'none') {
35793        return [];
35794    }
35795
35796    var counterNames = [];
35797    var counterResets = style.counterReset.split(/\s*,\s*/);
35798    var lenCounterResets = counterResets.length;
35799
35800    for (var i = 0; i < lenCounterResets; i++) {
35801        var _counterResets$i$spli = counterResets[i].split(/\s+/),
35802            _counterResets$i$spli2 = _slicedToArray(_counterResets$i$spli, 2),
35803            counterName = _counterResets$i$spli2[0],
35804            initialValue = _counterResets$i$spli2[1];
35805
35806        counterNames.push(counterName);
35807        var counter = data.counters[counterName];
35808        if (!counter) {
35809            counter = data.counters[counterName] = [];
35810        }
35811        counter.push(parseInt(initialValue || 0, 10));
35812    }
35813
35814    return counterNames;
35815};
35816
35817var popCounters = exports.popCounters = function popCounters(counterNames, data) {
35818    var lenCounters = counterNames.length;
35819    for (var i = 0; i < lenCounters; i++) {
35820        data.counters[counterNames[i]].pop();
35821    }
35822};
35823
35824var resolvePseudoContent = exports.resolvePseudoContent = function resolvePseudoContent(node, style, data) {
35825    if (!style || !style.content || style.content === 'none' || style.content === '-moz-alt-content' || style.display === 'none') {
35826        return null;
35827    }
35828
35829    var tokens = parseContent(style.content);
35830
35831    var len = tokens.length;
35832    var contentItems = [];
35833    var s = '';
35834
35835    // increment the counter (if there is a "counter-increment" declaration)
35836    var counterIncrement = style.counterIncrement;
35837    if (counterIncrement && counterIncrement !== 'none') {
35838        var _counterIncrement$spl = counterIncrement.split(/\s+/),
35839            _counterIncrement$spl2 = _slicedToArray(_counterIncrement$spl, 2),
35840            counterName = _counterIncrement$spl2[0],
35841            incrementValue = _counterIncrement$spl2[1];
35842
35843        var counter = data.counters[counterName];
35844        if (counter) {
35845            counter[counter.length - 1] += incrementValue === undefined ? 1 : parseInt(incrementValue, 10);
35846        }
35847    }
35848
35849    // build the content string
35850    for (var i = 0; i < len; i++) {
35851        var token = tokens[i];
35852        switch (token.type) {
35853            case TOKEN_TYPE.STRING:
35854                s += token.value || '';
35855                break;
35856
35857            case TOKEN_TYPE.ATTRIBUTE:
35858                if (node instanceof HTMLElement && token.value) {
35859                    s += node.getAttribute(token.value) || '';
35860                }
35861                break;
35862
35863            case TOKEN_TYPE.COUNTER:
35864                var _counter = data.counters[token.name || ''];
35865                if (_counter) {
35866                    s += formatCounterValue([_counter[_counter.length - 1]], '', token.format);
35867                }
35868                break;
35869
35870            case TOKEN_TYPE.COUNTERS:
35871                var _counters = data.counters[token.name || ''];
35872                if (_counters) {
35873                    s += formatCounterValue(_counters, token.glue, token.format);
35874                }
35875                break;
35876
35877            case TOKEN_TYPE.OPENQUOTE:
35878                s += getQuote(style, true, data.quoteDepth);
35879                data.quoteDepth++;
35880                break;
35881
35882            case TOKEN_TYPE.CLOSEQUOTE:
35883                data.quoteDepth--;
35884                s += getQuote(style, false, data.quoteDepth);
35885                break;
35886
35887            case TOKEN_TYPE.URL:
35888                if (s) {
35889                    contentItems.push({ type: PSEUDO_CONTENT_ITEM_TYPE.TEXT, value: s });
35890                    s = '';
35891                }
35892                contentItems.push({ type: PSEUDO_CONTENT_ITEM_TYPE.IMAGE, value: token.value || '' });
35893                break;
35894        }
35895    }
35896
35897    if (s) {
35898        contentItems.push({ type: PSEUDO_CONTENT_ITEM_TYPE.TEXT, value: s });
35899    }
35900
35901    return contentItems;
35902};
35903
35904var parseContent = exports.parseContent = function parseContent(content, cache) {
35905    if (cache && cache[content]) {
35906        return cache[content];
35907    }
35908
35909    var tokens = [];
35910    var len = content.length;
35911
35912    var isString = false;
35913    var isEscaped = false;
35914    var isFunction = false;
35915    var str = '';
35916    var functionName = '';
35917    var args = [];
35918
35919    for (var i = 0; i < len; i++) {
35920        var c = content.charAt(i);
35921
35922        switch (c) {
35923            case "'":
35924            case '"':
35925                if (isEscaped) {
35926                    str += c;
35927                } else {
35928                    isString = !isString;
35929                    if (!isFunction && !isString) {
35930                        tokens.push({ type: TOKEN_TYPE.STRING, value: str });
35931                        str = '';
35932                    }
35933                }
35934                break;
35935
35936            case '\\':
35937                if (isEscaped) {
35938                    str += c;
35939                    isEscaped = false;
35940                } else {
35941                    isEscaped = true;
35942                }
35943                break;
35944
35945            case '(':
35946                if (isString) {
35947                    str += c;
35948                } else {
35949                    isFunction = true;
35950                    functionName = str;
35951                    str = '';
35952                    args = [];
35953                }
35954                break;
35955
35956            case ')':
35957                if (isString) {
35958                    str += c;
35959                } else if (isFunction) {
35960                    if (str) {
35961                        args.push(str);
35962                    }
35963
35964                    switch (functionName) {
35965                        case 'attr':
35966                            if (args.length > 0) {
35967                                tokens.push({ type: TOKEN_TYPE.ATTRIBUTE, value: args[0] });
35968                            }
35969                            break;
35970
35971                        case 'counter':
35972                            if (args.length > 0) {
35973                                var counter = {
35974                                    type: TOKEN_TYPE.COUNTER,
35975                                    name: args[0]
35976                                };
35977                                if (args.length > 1) {
35978                                    counter.format = args[1];
35979                                }
35980                                tokens.push(counter);
35981                            }
35982                            break;
35983
35984                        case 'counters':
35985                            if (args.length > 0) {
35986                                var _counters2 = {
35987                                    type: TOKEN_TYPE.COUNTERS,
35988                                    name: args[0]
35989                                };
35990                                if (args.length > 1) {
35991                                    _counters2.glue = args[1];
35992                                }
35993                                if (args.length > 2) {
35994                                    _counters2.format = args[2];
35995                                }
35996                                tokens.push(_counters2);
35997                            }
35998                            break;
35999
36000                        case 'url':
36001                            if (args.length > 0) {
36002                                tokens.push({ type: TOKEN_TYPE.URL, value: args[0] });
36003                            }
36004                            break;
36005                    }
36006
36007                    isFunction = false;
36008                    str = '';
36009                }
36010                break;
36011
36012            case ',':
36013                if (isString) {
36014                    str += c;
36015                } else if (isFunction) {
36016                    args.push(str);
36017                    str = '';
36018                }
36019                break;
36020
36021            case ' ':
36022            case '\t':
36023                if (isString) {
36024                    str += c;
36025                } else if (str) {
36026                    addOtherToken(tokens, str);
36027                    str = '';
36028                }
36029                break;
36030
36031            default:
36032                str += c;
36033        }
36034
36035        if (c !== '\\') {
36036            isEscaped = false;
36037        }
36038    }
36039
36040    if (str) {
36041        addOtherToken(tokens, str);
36042    }
36043
36044    if (cache) {
36045        cache[content] = tokens;
36046    }
36047
36048    return tokens;
36049};
36050
36051var addOtherToken = function addOtherToken(tokens, identifier) {
36052    switch (identifier) {
36053        case 'open-quote':
36054            tokens.push({ type: TOKEN_TYPE.OPENQUOTE });
36055            break;
36056        case 'close-quote':
36057            tokens.push({ type: TOKEN_TYPE.CLOSEQUOTE });
36058            break;
36059    }
36060};
36061
36062var getQuote = function getQuote(style, isOpening, quoteDepth) {
36063    var quotes = style.quotes ? style.quotes.split(/\s+/) : ["'\"'", "'\"'"];
36064    var idx = quoteDepth * 2;
36065    if (idx >= quotes.length) {
36066        idx = quotes.length - 2;
36067    }
36068    if (!isOpening) {
36069        ++idx;
36070    }
36071    return quotes[idx].replace(/^["']|["']$/g, '');
36072};
36073
36074var formatCounterValue = function formatCounterValue(counter, glue, format) {
36075    var len = counter.length;
36076    var result = '';
36077
36078    for (var i = 0; i < len; i++) {
36079        if (i > 0) {
36080            result += glue || '';
36081        }
36082        result += (0, ListItem.createCounterText)(counter[i], (0, listStyle.parseListStyleType)(format || 'decimal'), false);
36083    }
36084
36085    return result;
36086};
36087});
36088
36089unwrapExports(PseudoNodeContent);
36090var PseudoNodeContent_1 = PseudoNodeContent.parseContent;
36091var PseudoNodeContent_2 = PseudoNodeContent.resolvePseudoContent;
36092var PseudoNodeContent_3 = PseudoNodeContent.popCounters;
36093var PseudoNodeContent_4 = PseudoNodeContent.parseCounterReset;
36094var PseudoNodeContent_5 = PseudoNodeContent.TOKEN_TYPE;
36095var PseudoNodeContent_6 = PseudoNodeContent.PSEUDO_CONTENT_ITEM_TYPE;
36096
36097var Clone = createCommonjsModule(function (module, exports) {
36098Object.defineProperty(exports, "__esModule", {
36099    value: true
36100});
36101exports.cloneWindow = exports.DocumentCloner = undefined;
36102
36103var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
36104
36105var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
36106
36107
36108
36109
36110
36111
36112
36113var _ResourceLoader2 = _interopRequireDefault(ResourceLoader_1);
36114
36115
36116
36117
36118
36119
36120
36121var _CanvasRenderer2 = _interopRequireDefault(CanvasRenderer_1);
36122
36123
36124
36125function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36126
36127function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
36128
36129var IGNORE_ATTRIBUTE = 'data-html2canvas-ignore';
36130
36131var DocumentCloner = exports.DocumentCloner = function () {
36132    function DocumentCloner(element, options, logger, copyInline, renderer) {
36133        _classCallCheck(this, DocumentCloner);
36134
36135        this.referenceElement = element;
36136        this.scrolledElements = [];
36137        this.copyStyles = copyInline;
36138        this.inlineImages = copyInline;
36139        this.logger = logger;
36140        this.options = options;
36141        this.renderer = renderer;
36142        this.resourceLoader = new _ResourceLoader2.default(options, logger, window);
36143        this.pseudoContentData = {
36144            counters: {},
36145            quoteDepth: 0
36146        };
36147        // $FlowFixMe
36148        this.documentElement = this.cloneNode(element.ownerDocument.documentElement);
36149    }
36150
36151    _createClass(DocumentCloner, [{
36152        key: 'inlineAllImages',
36153        value: function inlineAllImages(node) {
36154            var _this = this;
36155
36156            if (this.inlineImages && node) {
36157                var style = node.style;
36158                Promise.all((0, background.parseBackgroundImage)(style.backgroundImage).map(function (backgroundImage) {
36159                    if (backgroundImage.method === 'url') {
36160                        return _this.resourceLoader.inlineImage(backgroundImage.args[0]).then(function (img) {
36161                            return img && typeof img.src === 'string' ? 'url("' + img.src + '")' : 'none';
36162                        }).catch(function (e) {
36163                            
36164                        });
36165                    }
36166                    return Promise.resolve('' + backgroundImage.prefix + backgroundImage.method + '(' + backgroundImage.args.join(',') + ')');
36167                })).then(function (backgroundImages) {
36168                    if (backgroundImages.length > 1) {
36169                        // TODO Multiple backgrounds somehow broken in Chrome
36170                        style.backgroundColor = '';
36171                    }
36172                    style.backgroundImage = backgroundImages.join(',');
36173                });
36174
36175                if (node instanceof HTMLImageElement) {
36176                    this.resourceLoader.inlineImage(node.src).then(function (img) {
36177                        if (img && node instanceof HTMLImageElement && node.parentNode) {
36178                            var parentNode = node.parentNode;
36179                            var clonedChild = (0, Util.copyCSSStyles)(node.style, img.cloneNode(false));
36180                            parentNode.replaceChild(clonedChild, node);
36181                        }
36182                    }).catch(function (e) {
36183                        
36184                    });
36185                }
36186            }
36187        }
36188    }, {
36189        key: 'inlineFonts',
36190        value: function inlineFonts(document) {
36191            var _this2 = this;
36192
36193            return Promise.all(Array.from(document.styleSheets).map(function (sheet) {
36194                if (sheet.href) {
36195                    return fetch(sheet.href).then(function (res) {
36196                        return res.text();
36197                    }).then(function (text) {
36198                        return createStyleSheetFontsFromText(text, sheet.href);
36199                    }).catch(function (e) {
36200                        return [];
36201                    });
36202                }
36203                return getSheetFonts(sheet, document);
36204            })).then(function (fonts) {
36205                return fonts.reduce(function (acc, font) {
36206                    return acc.concat(font);
36207                }, []);
36208            }).then(function (fonts) {
36209                return Promise.all(fonts.map(function (font) {
36210                    return fetch(font.formats[0].src).then(function (response) {
36211                        return response.blob();
36212                    }).then(function (blob) {
36213                        return new Promise(function (resolve, reject) {
36214                            var reader = new FileReader();
36215                            reader.onerror = reject;
36216                            reader.onload = function () {
36217                                // $FlowFixMe
36218                                var result = reader.result;
36219                                resolve(result);
36220                            };
36221                            reader.readAsDataURL(blob);
36222                        });
36223                    }).then(function (dataUri) {
36224                        font.fontFace.setProperty('src', 'url("' + dataUri + '")');
36225                        return '@font-face {' + font.fontFace.cssText + ' ';
36226                    });
36227                }));
36228            }).then(function (fontCss) {
36229                var style = document.createElement('style');
36230                style.textContent = fontCss.join('\n');
36231                _this2.documentElement.appendChild(style);
36232            });
36233        }
36234    }, {
36235        key: 'createElementClone',
36236        value: function createElementClone(node) {
36237            var _this3 = this;
36238
36239            if (this.copyStyles && node instanceof HTMLCanvasElement) {
36240                var img = node.ownerDocument.createElement('img');
36241                try {
36242                    img.src = node.toDataURL();
36243                    return img;
36244                } catch (e) {
36245                    
36246                }
36247            }
36248
36249            if (node instanceof HTMLIFrameElement) {
36250                var tempIframe = node.cloneNode(false);
36251                var iframeKey = generateIframeKey();
36252                tempIframe.setAttribute('data-html2canvas-internal-iframe-key', iframeKey);
36253
36254                var _parseBounds = (0, Bounds_1.parseBounds)(node, 0, 0),
36255                    width = _parseBounds.width,
36256                    height = _parseBounds.height;
36257
36258                this.resourceLoader.cache[iframeKey] = getIframeDocumentElement(node, this.options).then(function (documentElement) {
36259                    return _this3.renderer(documentElement, {
36260                        async: _this3.options.async,
36261                        allowTaint: _this3.options.allowTaint,
36262                        backgroundColor: '#ffffff',
36263                        canvas: null,
36264                        imageTimeout: _this3.options.imageTimeout,
36265                        logging: _this3.options.logging,
36266                        proxy: _this3.options.proxy,
36267                        removeContainer: _this3.options.removeContainer,
36268                        scale: _this3.options.scale,
36269                        foreignObjectRendering: _this3.options.foreignObjectRendering,
36270                        useCORS: _this3.options.useCORS,
36271                        target: new _CanvasRenderer2.default(),
36272                        width: width,
36273                        height: height,
36274                        x: 0,
36275                        y: 0,
36276                        windowWidth: documentElement.ownerDocument.defaultView.innerWidth,
36277                        windowHeight: documentElement.ownerDocument.defaultView.innerHeight,
36278                        scrollX: documentElement.ownerDocument.defaultView.pageXOffset,
36279                        scrollY: documentElement.ownerDocument.defaultView.pageYOffset
36280                    }, _this3.logger.child(iframeKey));
36281                }).then(function (canvas) {
36282                    return new Promise(function (resolve, reject) {
36283                        var iframeCanvas = document.createElement('img');
36284                        iframeCanvas.onload = function () {
36285                            return resolve(canvas);
36286                        };
36287                        iframeCanvas.onerror = reject;
36288                        iframeCanvas.src = canvas.toDataURL();
36289                        if (tempIframe.parentNode) {
36290                            tempIframe.parentNode.replaceChild((0, Util.copyCSSStyles)(node.ownerDocument.defaultView.getComputedStyle(node), iframeCanvas), tempIframe);
36291                        }
36292                    });
36293                });
36294                return tempIframe;
36295            }
36296
36297            if (node instanceof HTMLStyleElement && node.sheet && node.sheet.cssRules) {
36298                var css = [].slice.call(node.sheet.cssRules, 0).reduce(function (css, rule) {
36299                    try {
36300                        if (rule && rule.cssText) {
36301                            return css + rule.cssText;
36302                        }
36303                        return css;
36304                    } catch (err) {
36305                        _this3.logger.log('Unable to access cssText property', rule.name);
36306                        return css;
36307                    }
36308                }, '');
36309                var style = node.cloneNode(false);
36310                style.textContent = css;
36311                return style;
36312            }
36313
36314            return node.cloneNode(false);
36315        }
36316    }, {
36317        key: 'cloneNode',
36318        value: function cloneNode(node) {
36319            var clone = node.nodeType === Node.TEXT_NODE ? document.createTextNode(node.nodeValue) : this.createElementClone(node);
36320
36321            var window = node.ownerDocument.defaultView;
36322            var style = node instanceof window.HTMLElement ? window.getComputedStyle(node) : null;
36323            var styleBefore = node instanceof window.HTMLElement ? window.getComputedStyle(node, ':before') : null;
36324            var styleAfter = node instanceof window.HTMLElement ? window.getComputedStyle(node, ':after') : null;
36325
36326            if (this.referenceElement === node && clone instanceof window.HTMLElement) {
36327                this.clonedReferenceElement = clone;
36328            }
36329
36330            if (clone instanceof window.HTMLBodyElement) {
36331                createPseudoHideStyles(clone);
36332            }
36333
36334            var counters = (0, PseudoNodeContent.parseCounterReset)(style, this.pseudoContentData);
36335            var contentBefore = (0, PseudoNodeContent.resolvePseudoContent)(node, styleBefore, this.pseudoContentData);
36336
36337            for (var child = node.firstChild; child; child = child.nextSibling) {
36338                if (child.nodeType !== Node.ELEMENT_NODE || child.nodeName !== 'SCRIPT' &&
36339                // $FlowFixMe
36340                !child.hasAttribute(IGNORE_ATTRIBUTE) && (typeof this.options.ignoreElements !== 'function' ||
36341                // $FlowFixMe
36342                !this.options.ignoreElements(child))) {
36343                    if (!this.copyStyles || child.nodeName !== 'STYLE') {
36344                        clone.appendChild(this.cloneNode(child));
36345                    }
36346                }
36347            }
36348
36349            var contentAfter = (0, PseudoNodeContent.resolvePseudoContent)(node, styleAfter, this.pseudoContentData);
36350            (0, PseudoNodeContent.popCounters)(counters, this.pseudoContentData);
36351
36352            if (node instanceof window.HTMLElement && clone instanceof window.HTMLElement) {
36353                if (styleBefore) {
36354                    this.inlineAllImages(inlinePseudoElement(node, clone, styleBefore, contentBefore, PSEUDO_BEFORE));
36355                }
36356                if (styleAfter) {
36357                    this.inlineAllImages(inlinePseudoElement(node, clone, styleAfter, contentAfter, PSEUDO_AFTER));
36358                }
36359                if (style && this.copyStyles && !(node instanceof HTMLIFrameElement)) {
36360                    (0, Util.copyCSSStyles)(style, clone);
36361                }
36362                this.inlineAllImages(clone);
36363                if (node.scrollTop !== 0 || node.scrollLeft !== 0) {
36364                    this.scrolledElements.push([clone, node.scrollLeft, node.scrollTop]);
36365                }
36366                switch (node.nodeName) {
36367                    case 'CANVAS':
36368                        if (!this.copyStyles) {
36369                            cloneCanvasContents(node, clone);
36370                        }
36371                        break;
36372                    case 'TEXTAREA':
36373                    case 'SELECT':
36374                        clone.value = node.value;
36375                        break;
36376                }
36377            }
36378            return clone;
36379        }
36380    }]);
36381
36382    return DocumentCloner;
36383}();
36384
36385var getSheetFonts = function getSheetFonts(sheet, document) {
36386    // $FlowFixMe
36387    return (sheet.cssRules ? Array.from(sheet.cssRules) : []).filter(function (rule) {
36388        return rule.type === CSSRule.FONT_FACE_RULE;
36389    }).map(function (rule) {
36390        var src = (0, background.parseBackgroundImage)(rule.style.getPropertyValue('src'));
36391        var formats = [];
36392        for (var i = 0; i < src.length; i++) {
36393            if (src[i].method === 'url' && src[i + 1] && src[i + 1].method === 'format') {
36394                var a = document.createElement('a');
36395                a.href = src[i].args[0];
36396                if (document.body) {
36397                    document.body.appendChild(a);
36398                }
36399
36400                var font = {
36401                    src: a.href,
36402                    format: src[i + 1].args[0]
36403                };
36404                formats.push(font);
36405            }
36406        }
36407
36408        return {
36409            // TODO select correct format for browser),
36410
36411            formats: formats.filter(function (font) {
36412                return (/^woff/i.test(font.format)
36413                );
36414            }),
36415            fontFace: rule.style
36416        };
36417    }).filter(function (font) {
36418        return font.formats.length;
36419    });
36420};
36421
36422var createStyleSheetFontsFromText = function createStyleSheetFontsFromText(text, baseHref) {
36423    var doc = document.implementation.createHTMLDocument('');
36424    var base = document.createElement('base');
36425    // $FlowFixMe
36426    base.href = baseHref;
36427    var style = document.createElement('style');
36428
36429    style.textContent = text;
36430    if (doc.head) {
36431        doc.head.appendChild(base);
36432    }
36433    if (doc.body) {
36434        doc.body.appendChild(style);
36435    }
36436
36437    return style.sheet ? getSheetFonts(style.sheet, doc) : [];
36438};
36439
36440var restoreOwnerScroll = function restoreOwnerScroll(ownerDocument, x, y) {
36441    if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
36442        ownerDocument.defaultView.scrollTo(x, y);
36443    }
36444};
36445
36446var cloneCanvasContents = function cloneCanvasContents(canvas, clonedCanvas) {
36447    try {
36448        if (clonedCanvas) {
36449            clonedCanvas.width = canvas.width;
36450            clonedCanvas.height = canvas.height;
36451            var ctx = canvas.getContext('2d');
36452            var clonedCtx = clonedCanvas.getContext('2d');
36453            if (ctx) {
36454                clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
36455            } else {
36456                clonedCtx.drawImage(canvas, 0, 0);
36457            }
36458        }
36459    } catch (e) {}
36460};
36461
36462var inlinePseudoElement = function inlinePseudoElement(node, clone, style, contentItems, pseudoElt) {
36463    if (!style || !style.content || style.content === 'none' || style.content === '-moz-alt-content' || style.display === 'none') {
36464        return;
36465    }
36466
36467    var anonymousReplacedElement = clone.ownerDocument.createElement('html2canvaspseudoelement');
36468    (0, Util.copyCSSStyles)(style, anonymousReplacedElement);
36469
36470    if (contentItems) {
36471        var len = contentItems.length;
36472        for (var i = 0; i < len; i++) {
36473            var item = contentItems[i];
36474            switch (item.type) {
36475                case PseudoNodeContent.PSEUDO_CONTENT_ITEM_TYPE.IMAGE:
36476                    var img = clone.ownerDocument.createElement('img');
36477                    img.src = (0, background.parseBackgroundImage)('url(' + item.value + ')')[0].args[0];
36478                    img.style.opacity = '1';
36479                    anonymousReplacedElement.appendChild(img);
36480                    break;
36481                case PseudoNodeContent.PSEUDO_CONTENT_ITEM_TYPE.TEXT:
36482                    anonymousReplacedElement.appendChild(clone.ownerDocument.createTextNode(item.value));
36483                    break;
36484            }
36485        }
36486    }
36487
36488    anonymousReplacedElement.className = PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ' ' + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
36489    clone.className += pseudoElt === PSEUDO_BEFORE ? ' ' + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE : ' ' + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
36490    if (pseudoElt === PSEUDO_BEFORE) {
36491        clone.insertBefore(anonymousReplacedElement, clone.firstChild);
36492    } else {
36493        clone.appendChild(anonymousReplacedElement);
36494    }
36495
36496    return anonymousReplacedElement;
36497};
36498
36499var PSEUDO_BEFORE = ':before';
36500var PSEUDO_AFTER = ':after';
36501var PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = '___html2canvas___pseudoelement_before';
36502var PSEUDO_HIDE_ELEMENT_CLASS_AFTER = '___html2canvas___pseudoelement_after';
36503
36504var PSEUDO_HIDE_ELEMENT_STYLE = '{\n    content: "" !important;\n    display: none !important;\n}';
36505
36506var createPseudoHideStyles = function createPseudoHideStyles(body) {
36507    createStyles(body, '.' + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + PSEUDO_BEFORE + PSEUDO_HIDE_ELEMENT_STYLE + '\n         .' + PSEUDO_HIDE_ELEMENT_CLASS_AFTER + PSEUDO_AFTER + PSEUDO_HIDE_ELEMENT_STYLE);
36508};
36509
36510var createStyles = function createStyles(body, styles) {
36511    var style = body.ownerDocument.createElement('style');
36512    style.innerHTML = styles;
36513    body.appendChild(style);
36514};
36515
36516var initNode = function initNode(_ref) {
36517    var _ref2 = _slicedToArray(_ref, 3),
36518        element = _ref2[0],
36519        x = _ref2[1],
36520        y = _ref2[2];
36521
36522    element.scrollLeft = x;
36523    element.scrollTop = y;
36524};
36525
36526var generateIframeKey = function generateIframeKey() {
36527    return Math.ceil(Date.now() + Math.random() * 10000000).toString(16);
36528};
36529
36530var DATA_URI_REGEXP = /^data:text\/(.+);(base64)?,(.*)$/i;
36531
36532var getIframeDocumentElement = function getIframeDocumentElement(node, options) {
36533    try {
36534        return Promise.resolve(node.contentWindow.document.documentElement);
36535    } catch (e) {
36536        return options.proxy ? (0, _Proxy.Proxy)(node.src, options).then(function (html) {
36537            var match = html.match(DATA_URI_REGEXP);
36538            if (!match) {
36539                return Promise.reject();
36540            }
36541
36542            return match[2] === 'base64' ? window.atob(decodeURIComponent(match[3])) : decodeURIComponent(match[3]);
36543        }).then(function (html) {
36544            return createIframeContainer(node.ownerDocument, (0, Bounds_1.parseBounds)(node, 0, 0)).then(function (cloneIframeContainer) {
36545                var cloneWindow = cloneIframeContainer.contentWindow;
36546                var documentClone = cloneWindow.document;
36547
36548                documentClone.open();
36549                documentClone.write(html);
36550                var iframeLoad = iframeLoader(cloneIframeContainer).then(function () {
36551                    return documentClone.documentElement;
36552                });
36553
36554                documentClone.close();
36555                return iframeLoad;
36556            });
36557        }) : Promise.reject();
36558    }
36559};
36560
36561var createIframeContainer = function createIframeContainer(ownerDocument, bounds) {
36562    var cloneIframeContainer = ownerDocument.createElement('iframe');
36563
36564    cloneIframeContainer.className = 'html2canvas-container';
36565    cloneIframeContainer.style.visibility = 'hidden';
36566    cloneIframeContainer.style.position = 'fixed';
36567    cloneIframeContainer.style.left = '-10000px';
36568    cloneIframeContainer.style.top = '0px';
36569    cloneIframeContainer.style.border = '0';
36570    cloneIframeContainer.width = bounds.width.toString();
36571    cloneIframeContainer.height = bounds.height.toString();
36572    cloneIframeContainer.scrolling = 'no'; // ios won't scroll without it
36573    cloneIframeContainer.setAttribute(IGNORE_ATTRIBUTE, 'true');
36574    if (!ownerDocument.body) {
36575        return Promise.reject('');
36576    }
36577
36578    ownerDocument.body.appendChild(cloneIframeContainer);
36579
36580    return Promise.resolve(cloneIframeContainer);
36581};
36582
36583var iframeLoader = function iframeLoader(cloneIframeContainer) {
36584    var cloneWindow = cloneIframeContainer.contentWindow;
36585    var documentClone = cloneWindow.document;
36586
36587    return new Promise(function (resolve, reject) {
36588        cloneWindow.onload = cloneIframeContainer.onload = documentClone.onreadystatechange = function () {
36589            var interval = setInterval(function () {
36590                if (documentClone.body.childNodes.length > 0 && documentClone.readyState === 'complete') {
36591                    clearInterval(interval);
36592                    resolve(cloneIframeContainer);
36593                }
36594            }, 50);
36595        };
36596    });
36597};
36598
36599var cloneWindow = exports.cloneWindow = function cloneWindow(ownerDocument, bounds, referenceElement, options, logger, renderer) {
36600    var cloner = new DocumentCloner(referenceElement, options, logger, false, renderer);
36601    var scrollX = ownerDocument.defaultView.pageXOffset;
36602    var scrollY = ownerDocument.defaultView.pageYOffset;
36603
36604    return createIframeContainer(ownerDocument, bounds).then(function (cloneIframeContainer) {
36605        var cloneWindow = cloneIframeContainer.contentWindow;
36606        var documentClone = cloneWindow.document;
36607
36608        /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
36609             if window url is about:blank, we can assign the url to current by writing onto the document
36610             */
36611
36612        var iframeLoad = iframeLoader(cloneIframeContainer).then(function () {
36613            cloner.scrolledElements.forEach(initNode);
36614            cloneWindow.scrollTo(bounds.left, bounds.top);
36615            if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent) && (cloneWindow.scrollY !== bounds.top || cloneWindow.scrollX !== bounds.left)) {
36616                documentClone.documentElement.style.top = -bounds.top + 'px';
36617                documentClone.documentElement.style.left = -bounds.left + 'px';
36618                documentClone.documentElement.style.position = 'absolute';
36619            }
36620
36621            var result = Promise.resolve([cloneIframeContainer, cloner.clonedReferenceElement, cloner.resourceLoader]);
36622
36623            var onclone = options.onclone;
36624
36625            return cloner.clonedReferenceElement instanceof cloneWindow.HTMLElement || cloner.clonedReferenceElement instanceof ownerDocument.defaultView.HTMLElement || cloner.clonedReferenceElement instanceof HTMLElement ? typeof onclone === 'function' ? Promise.resolve().then(function () {
36626                return onclone(documentClone);
36627            }).then(function () {
36628                return result;
36629            }) : result : Promise.reject('');
36630        });
36631
36632        documentClone.open();
36633        documentClone.write(serializeDoctype(document.doctype) + '<html></html>');
36634        // Chrome scrolls the parent document for some reason after the write to the cloned window???
36635        restoreOwnerScroll(referenceElement.ownerDocument, scrollX, scrollY);
36636        documentClone.replaceChild(documentClone.adoptNode(cloner.documentElement), documentClone.documentElement);
36637        documentClone.close();
36638
36639        return iframeLoad;
36640    });
36641};
36642
36643var serializeDoctype = function serializeDoctype(doctype) {
36644    var str = '';
36645    if (doctype) {
36646        str += '<!DOCTYPE ';
36647        if (doctype.name) {
36648            str += doctype.name;
36649        }
36650
36651        if (doctype.internalSubset) {
36652            str += doctype.internalSubset;
36653        }
36654
36655        if (doctype.publicId) {
36656            str += '"' + doctype.publicId + '"';
36657        }
36658
36659        if (doctype.systemId) {
36660            str += '"' + doctype.systemId + '"';
36661        }
36662
36663        str += '>';
36664    }
36665
36666    return str;
36667};
36668});
36669
36670unwrapExports(Clone);
36671var Clone_1 = Clone.cloneWindow;
36672var Clone_2 = Clone.DocumentCloner;
36673
36674var Window = createCommonjsModule(function (module, exports) {
36675Object.defineProperty(exports, "__esModule", {
36676    value: true
36677});
36678exports.renderElement = undefined;
36679
36680var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
36681
36682
36683
36684var _Logger2 = _interopRequireDefault(Logger_1);
36685
36686
36687
36688
36689
36690var _Renderer2 = _interopRequireDefault(Renderer_1);
36691
36692
36693
36694var _ForeignObjectRenderer2 = _interopRequireDefault(ForeignObjectRenderer_1);
36695
36696
36697
36698var _Feature2 = _interopRequireDefault(Feature);
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708var _Color2 = _interopRequireDefault(Color_1);
36709
36710function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36711
36712var renderElement = exports.renderElement = function renderElement(element, options, logger) {
36713    var ownerDocument = element.ownerDocument;
36714
36715    var windowBounds = new Bounds_1.Bounds(options.scrollX, options.scrollY, options.windowWidth, options.windowHeight);
36716
36717    // http://www.w3.org/TR/css3-background/#special-backgrounds
36718    var documentBackgroundColor = ownerDocument.documentElement ? new _Color2.default(getComputedStyle(ownerDocument.documentElement).backgroundColor) : Color_1.TRANSPARENT;
36719    var bodyBackgroundColor = ownerDocument.body ? new _Color2.default(getComputedStyle(ownerDocument.body).backgroundColor) : Color_1.TRANSPARENT;
36720
36721    var backgroundColor = element === ownerDocument.documentElement ? documentBackgroun
36721dColor.isTransparent() ? bodyBackgroundColor.isTransparent() ? options.backgroundColor ? new _Color2.default(options.backgroundColor) : null : bodyBackgroundColor : documentBackgroundColor : options.backgroundColor ? new _Color2.default(options.backgroundColor) : null;
36722
36723    return (options.foreignObjectRendering ? // $FlowFixMe
36724    _Feature2.default.SUPPORT_FOREIGNOBJECT_DRAWING : Promise.resolve(false)).then(function (supportForeignObject) {
36725        return supportForeignObject ? function (cloner) {
36726            return cloner.inlineFonts(ownerDocument).then(function () {
36727                return cloner.resourceLoader.ready();
36728            }).then(function () {
36729                var renderer = new _ForeignObjectRenderer2.default(cloner.documentElement);
36730
36731                var defaultView = ownerDocument.defaultView;
36732                var scrollX = defaultView.pageXOffset;
36733                var scrollY = defaultView.pageYOffset;
36734
36735                var isDocument = element.tagName === 'HTML' || element.tagName === 'BODY';
36736
36737                var _ref = isDocument ? (0, Bounds_1.parseDocumentSize)(ownerDocument) : (0, Bounds_1.parseBounds)(element, scrollX, scrollY),
36738                    width = _ref.width,
36739                    height = _ref.height,
36740                    left = _ref.left,
36741                    top = _ref.top;
36742
36743                return renderer.render({
36744                    backgroundColor: backgroundColor,
36745                    logger: logger,
36746                    scale: options.scale,
36747                    x: typeof options.x === 'number' ? options.x : left,
36748                    y: typeof options.y === 'number' ? options.y : top,
36749                    width: typeof options.width === 'number' ? options.width : Math.ceil(width),
36750                    height: typeof options.height === 'number' ? options.height : Math.ceil(height),
36751                    windowWidth: options.windowWidth,
36752                    windowHeight: options.windowHeight,
36753                    scrollX: options.scrollX,
36754                    scrollY: options.scrollY
36755                });
36756            });
36757        }(new Clone.DocumentCloner(element, options, logger, true, renderElement)) : (0, Clone.cloneWindow)(ownerDocument, windowBounds, element, options, logger, renderElement).then(function (_ref2) {
36758            var _ref3 = _slicedToArray(_ref2, 3),
36759                container = _ref3[0],
36760                clonedElement = _ref3[1],
36761                resourceLoader = _ref3[2];
36762
36763            var stack = (0, NodeParser_1.NodeParser)(clonedElement, resourceLoader, logger);
36764            var clonedDocument = clonedElement.ownerDocument;
36765
36766            if (backgroundColor === stack.container.style.background.backgroundColor) {
36767                stack.container.style.background.backgroundColor = Color_1.TRANSPARENT;
36768            }
36769
36770            return resourceLoader.ready().then(function (imageStore) {
36771                var fontMetrics = new Font.FontMetrics(clonedDocument);
36772                var defaultView = clonedDocument.defaultView;
36773                var scrollX = defaultView.pageXOffset;
36774                var scrollY = defaultView.pageYOffset;
36775
36776                var isDocument = clonedElement.tagName === 'HTML' || clonedElement.tagName === 'BODY';
36777
36778                var _ref4 = isDocument ? (0, Bounds_1.parseDocumentSize)(ownerDocument) : (0, Bounds_1.parseBounds)(clonedElement, scrollX, scrollY),
36779                    width = _ref4.width,
36780                    height = _ref4.height,
36781                    left = _ref4.left,
36782                    top = _ref4.top;
36783
36784                var renderOptions = {
36785                    backgroundColor: backgroundColor,
36786                    fontMetrics: fontMetrics,
36787                    imageStore: imageStore,
36788                    logger: logger,
36789                    scale: options.scale,
36790                    x: typeof options.x === 'number' ? options.x : left,
36791                    y: typeof options.y === 'number' ? options.y : top,
36792                    width: typeof options.width === 'number' ? options.width : Math.ceil(width),
36793                    height: typeof options.height === 'number' ? options.height : Math.
36793ceil(height)
36794                };
36795
36796                if (Array.isArray(options.target)) {
36797                    return Promise.all(options.target.map(function (target) {
36798                        var renderer = new _Renderer2.default(target, renderOptions);
36799                        return renderer.render(stack);
36800                    }));
36801                } else {
36802                    var renderer = new _Renderer2.default(options.target, renderOptions);
36803                    var canvas = renderer.render(stack);
36804                    if (options.removeContainer === true) {
36805                        if (container.parentNode) {
36806                            container.parentNode.removeChild(container);
36807                        } else {}
36808                    }
36809
36810                    return canvas;
36811                }
36812            });
36813        });
36814    });
36815};
36816});
36817
36818unwrapExports(Window);
36819var Window_1 = Window.renderElement;
36820
36821var npm = createCommonjsModule(function (module) {
36822var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
36823
36824
36825
36826var _CanvasRenderer2 = _interopRequireDefault(CanvasRenderer_1);
36827
36828
36829
36830var _Logger2 = _interopRequireDefault(Logger_1);
36831
36832
36833
36834function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36835
36836var html2canvas = function html2canvas(element, conf) {
36837    var config = conf || {};
36838    var logger = new _Logger2.default(typeof config.logging === 'boolean' ? config.logging : true);
36839    logger.log('html2canvas ' + "$npm_package_version");
36840
36841    var ownerDocument = element.ownerDocument;
36842    if (!ownerDocument) {
36843        return Promise.reject('Provided element is not within a Document');
36844    }
36845    var defaultView = ownerDocument.defaultView;
36846
36847    var defaultOptions = {
36848        async: true,
36849        allowTaint: false,
36850        backgroundColor: '#ffffff',
36851        imageTimeout: 15000,
36852        logging: true,
36853        proxy: null,
36854        removeContainer: true,
36855        foreignObjectRendering: false,
36856        scale: defaultView.devicePixelRatio || 1,
36857        target: new _CanvasRenderer2.default(config.canvas),
36858        useCORS: false,
36859        windowWidth: defaultView.innerWidth,
36860        windowHeight: defaultView.innerHeight,
36861        scrollX: defaultView.pageXOffset,
36862        scrollY: defaultView.pageYOffset
36863    };
36864
36865    var result = (0, Window.renderElement)(element, _extends({}, defaultOptions, config), logger);
36866
36867    return result;
36868};
36869
36870html2canvas.CanvasRenderer = _CanvasRenderer2.default;
36871
36872module.exports = html2canvas;
36873});
36874
36875var html2canvas$1 = unwrapExports(npm);
36876
36877var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
36878  return typeof obj;
36879} : function (obj) {
36880  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
36881};
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903var _extends = Object.assign || function (target) {
36904  for (var i = 1; i < arguments.length; i++) {
36905    var source = arguments[i];
36906
36907    for (var key in source) {
36908      if (Object.prototype.hasOwnProperty.call(source, key)) {
36909        target[key] = source[key];
36910      }
36911    }
36912  }
36913
36914  return target;
36915};
36916
36917// Determine the type of a variable/object.
36918var objType = function objType(obj) {
36919  var type = typeof obj === 'undefined' ? 'undefined' : _typeof(obj);
36920  if (type === 'undefined') return 'undefined';else if (type === 'string' || obj instanceof String) return 'string';else if (type === 'number' || obj instanceof Number) return 'number';else if (type === 'function' || obj instanceof Function) return 'function';else if (!!obj && obj.constructor === Array) return 'array';else if (obj && obj.nodeType === 1) return 'element';else if (type === 'object') return 'object';else return 'unknown';
36921};
36922
36923// Create an HTML element with optional className, innerHTML, and style.
36924var createElement = function createElement(tagName, opt) {
36925  var el = document.createElement(tagName);
36926  if (opt.className) el.className = opt.className;
36927  if (opt.innerHTML) {
36928    el.innerHTML = opt.innerHTML;
36929    var scripts = el.getElementsByTagName('script');
36930    for (var i = scripts.length; i-- > 0; null) {
36931      scripts[i].parentNode.removeChild(scripts[i]);
36932    }
36933  }
36934  for (var key in opt.style) {
36935    el.style[key] = opt.style[key];
36936  }
36937  return el;
36938};
36939
36940// Deep-clone a node and preserve contents/properties.
36941var cloneNode = function cloneNode(node, javascriptEnabled) {
36942  // Recursively clone the node.
36943  var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
36944  for (var child = node.firstChild; child; child = child.nextSibling) {
36945    if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
36946      clone.appendChild(cloneNode(child, javascriptEnabled));
36947    }
36948  }
36949
36950  if (node.nodeType === 1) {
36951    // Preserve contents/properties of special nodes.
36952    if (node.nodeName === 'CANVAS') {
36953      clone.width = node.width;
36954      clone.height = node.height;
36955      clone.getContext('2d').drawImage(node, 0, 0);
36956    } else if (node.nodeName === 'TEXTAREA' || node.nodeName === 'SELECT') {
36957      clone.value = node.value;
36958    }
36959
36960    // Preserve the node's scroll position when it loads.
36961    clone.addEventListener('load', function () {
36962      clone.scrollTop = node.scrollTop;
36963      clone.scrollLeft = node.scrollLeft;
36964    }, true);
36965  }
36966
36967  // Return the cloned node.
36968  return clone;
36969};
36970
36971// Convert units from px using the conversion value 'k' from jsPDF.
36972var unitConvert = function unitConvert(obj, k) {
36973  if (objType(obj) === 'number') {
36974    return obj * 72 / 96 / k;
36975  } else {
36976    var newObj = {};
36977    for (var key in obj) {
36978      newObj[key] = obj[key] * 72 / 96 / k;
36979    }
36980    return newObj;
36981  }
36982};
36983
36984// Convert units to px using the conversion value 'k' from jsPDF.
36985var toPx = function toPx(val, k) {
36986  return Math.floor(val * k / 72 * 96);
36987};
36988
36989var es6Promise = createCommonjsModule(function (module, exports) {
36990/*!
36991 * @overview es6-promise - a tiny implementation of Promises/A+.
36992 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
36993 * @license   Licensed under MIT license
36994 *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
36995 * @version   v4.2.5+7f2b526d
36996 */
36997
36998(function (global, factory) {
36999	module.exports = factory();
37000}(commonjsGlobal, (function () { function objectOrFunction(x) {
37001  var type = typeof x;
37002  return x !== null && (type === 'object' || type === 'function');
37003}
37004
37005function isFunction(x) {
37006  return typeof x === 'function';
37007}
37008
37009
37010
37011var _isArray = void 0;
37012if (Array.isArray) {
37013  _isArray = Array.isArray;
37014} else {
37015  _isArray = function (x) {
37016    return Object.prototype.toString.call(x) === '[object Array]';
37017  };
37018}
37019
37020var isArray = _isArray;
37021
37022var len = 0;
37023var vertxNext = void 0;
37024var customSchedulerFn = void 0;
37025
37026var asap = function asap(callback, arg) {
37027  queue[len] = callback;
37028  queue[len + 1] = arg;
37029  len += 2;
37030  if (len === 2) {
37031    // If len is 2, that means that we need to schedule an async flush.
37032    // If additional callbacks are queued before the queue is flushed, they
37033    // will be processed by this flush that we are scheduling.
37034    if (customSchedulerFn) {
37035      customSchedulerFn(flush);
37036    } else {
37037      scheduleFlush();
37038    }
37039  }
37040};
37041
37042function setScheduler(scheduleFn) {
37043  customSchedulerFn = scheduleFn;
37044}
37045
37046function setAsap(asapFn) {
37047  asap = asapFn;
37048}
37049
37050var browserWindow = typeof window !== 'undefined' ? window : undefined;
37051var browserGlobal = browserWindow || {};
37052var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
37053var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
37054
37055// test for web worker but not in IE10
37056var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
37057
37058// node
37059function useNextTick() {
37060  // node version 0.10.x displays a deprecation warning when nextTick is used recursively
37061  // see https://github.com/cujojs/when/issues/410 for details
37062  return function () {
37063    return process.nextTick(flush);
37064  };
37065}
37066
37067// vertx
37068function useVertxTimer() {
37069  if (typeof vertxNext !== 'undefined') {
37070    return function () {
37071      vertxNext(flush);
37072    };
37073  }
37074
37075  return useSetTimeout();
37076}
37077
37078function useMutationObserver() {
37079  var iterations = 0;
37080  var observer = new BrowserMutationObserver(flush);
37081  var node = document.createTextNode('');
37082  observer.observe(node, { characterData: true });
37083
37084  return function () {
37085    node.data = iterations = ++iterations % 2;
37086  };
37087}
37088
37089// web worker
37090function useMessageChannel() {
37091  var channel = new MessageChannel();
37092  channel.port1.onmessage = flush;
37093  return function () {
37094    return channel.port2.postMessage(0);
37095  };
37096}
37097
37098function useSetTimeout() {
37099  // Store setTimeout reference so es6-promise will be unaffected by
37100  // other code modifying setTimeout (like sinon.useFakeTimers())
37101  var globalSetTimeout = setTimeout;
37102  return function () {
37103    return globalSetTimeout(flush, 1);
37104  };
37105}
37106
37107var queue = new Array(1000);
37108function flush() {
37109  for (var i = 0; i < len; i += 2) {
37110    var callback = queue[i];
37111    var arg = queue[i + 1];
37112
37113    callback(arg);
37114
37115    queue[i] = undefined;
37116    queue[i + 1] = undefined;
37117  }
37118
37119  len = 0;
37120}
37121
37122function attemptVertx() {
37123  try {
37124    var vertx = Function('return this')().require('vertx');
37125    vertxNext = vertx.runOnLoop || vertx.runOnContext;
37126    return useVertxTimer();
37127  } catch (e) {
37128    return useSetTimeout();
37129  }
37130}
37131
37132var scheduleFlush = void 0;
37133// Decide what async method to use to triggering processing of queued callbacks:
37134if (isNode) {
37135  scheduleFlush = useNextTick();
37136} else if (BrowserMutationObserver) {
37137  scheduleFlush = useMutationObserver();
37138} else if (isWorker) {
37139  scheduleFlush = useMessageChannel();
37140} else if (browserWindow === undefined && typeof commonjsRequire
vendor: 8,702 bytes, lines 37140-37521
37140 === 'function') {
37141  scheduleFlush = attemptVertx();
37142} else {
37143  scheduleFlush = useSetTimeout();
37144}
37145
37146function then(onFulfillment, onRejection) {
37147  var parent = this;
37148
37149  var child = new this.constructor(noop);
37150
37151  if (child[PROMISE_ID] === undefined) {
37152    makePromise(child);
37153  }
37154
37155  var _state = parent._state;
37156
37157
37158  if (_state) {
37159    var callback = arguments[_state - 1];
37160    asap(function () {
37161      return invokeCallback(_state, child, callback, parent._result);
37162    });
37163  } else {
37164    subscribe(parent, child, onFulfillment, onRejection);
37165  }
37166
37167  return child;
37168}
37169
37170/**
37171  `Promise.resolve` returns a promise that will become resolved with the
37172  passed `value`. It is shorthand for the following:
37173
37174  ```javascript
37175  let promise = new Promise(function(resolve, reject){
37176    resolve(1);
37177  });
37178
37179  promise.then(function(value){
37180    // value === 1
37181  });
37182  ```
37183
37184  Instead of writing the above, your code now simply becomes the following:
37185
37186  ```javascript
37187  let promise = Promise.resolve(1);
37188
37189  promise.then(function(value){
37190    // value === 1
37191  });
37192  ```
37193
37194  @method resolve
37195  @static
37196  @param {Any} value value that the returned promise will be resolved with
37197  Useful for tooling.
37198  @return {Promise} a promise that will become fulfilled with the given
37199  `value`
37200*/
37201function resolve$1(object) {
37202  /*jshint validthis:true */
37203  var Constructor = this;
37204
37205  if (object && typeof object === 'object' && object.constructor === Constructor) {
37206    return object;
37207  }
37208
37209  var promise = new Constructor(noop);
37210  resolve(promise, object);
37211  return promise;
37212}
37213
37214var PROMISE_ID = Math.random().toString(36).substring(2);
37215
37216function noop() {}
37217
37218var PENDING = void 0;
37219var FULFILLED = 1;
37220var REJECTED = 2;
37221
37222var TRY_CATCH_ERROR = { error: null };
37223
37224function selfFulfillment() {
37225  return new TypeError("You cannot resolve a promise with itself");
37226}
37227
37228function cannotReturnOwn() {
37229  return new TypeError('A promises callback cannot return that same promise.');
37230}
37231
37232function getThen(promise) {
37233  try {
37234    return promise.then;
37235  } catch (error) {
37236    TRY_CATCH_ERROR.error = error;
37237    return TRY_CATCH_ERROR;
37238  }
37239}
37240
37241function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
37242  try {
37243    then$$1.call(value, fulfillmentHandler, rejectionHandler);
37244  } catch (e) {
37245    return e;
37246  }
37247}
37248
37249function handleForeignThenable(promise, thenable, then$$1) {
37250  asap(function (promise) {
37251    var sealed = false;
37252    var error = tryThen(then$$1, thenable, function (value) {
37253      if (sealed) {
37254        return;
37255      }
37256      sealed = true;
37257      if (thenable !== value) {
37258        resolve(promise, value);
37259      } else {
37260        fulfill(promise, value);
37261      }
37262    }, function (reason) {
37263      if (sealed) {
37264        return;
37265      }
37266      sealed = true;
37267
37268      reject(promise, reason);
37269    }, 'Settle: ' + (promise._label || ' unknown promise'));
37270
37271    if (!sealed && error) {
37272      sealed = true;
37273      reject(promise, error);
37274    }
37275  }, promise);
37276}
37277
37278function handleOwnThenable(promise, thenable) {
37279  if (thenable._state === FULFILLED) {
37280    fulfill(promise, thenable._result);
37281  } else if (thenable._state === REJECTED) {
37282    reject(promise, thenable._result);
37283  } else {
37284    subscribe(thenable, undefined, function (value) {
37285      return resolve(promise, value);
37286    }, function (reason) {
37287      return reject(promise, reason);
37288    });
37289  }
37290}
37291
37292function handleMaybeThenable(promise, maybeThenable, then$$1) {
37293  if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
37294    handleOwnThenable(promise, maybeThenable);
37295  } else {
37296    if (then$$1 === TRY_CATCH_ERROR) {
37297      reject(promise, TRY_CATCH_ERROR.error);
37298      TRY_CATCH_ERROR.error = null;
37299    } else if (then$$1 === undefined) {
37300      fulfill(promise, maybeThenable);
37301    } else if (isFunction(then$$1)) {
37302      handleForeignThenable(promise, maybeThenable, then$$1);
37303    } else {
37304      fulfill(promise, maybeThenable);
37305    }
37306  }
37307}
37308
37309function resolve(promise, value) {
37310  if (promise === value) {
37311    reject(promise, selfFulfillment());
37312  } else if (objectOrFunction(value)) {
37313    handleMaybeThenable(promise, value, getThen(value));
37314  } else {
37315    fulfill(promise, value);
37316  }
37317}
37318
37319function publishRejection(promise) {
37320  if (promise._onerror) {
37321    promise._onerror(promise._result);
37322  }
37323
37324  publish(promise);
37325}
37326
37327function fulfill(promise, value) {
37328  if (promise._state !== PENDING) {
37329    return;
37330  }
37331
37332  promise._result = value;
37333  promise._state = FULFILLED;
37334
37335  if (promise._subscribers.length !== 0) {
37336    asap(publish, promise);
37337  }
37338}
37339
37340function reject(promise, reason) {
37341  if (promise._state !== PENDING) {
37342    return;
37343  }
37344  promise._state = REJECTED;
37345  promise._result = reason;
37346
37347  asap(publishRejection, promise);
37348}
37349
37350function subscribe(parent, child, onFulfillment, onRejection) {
37351  var _subscribers = parent._subscribers;
37352  var length = _subscribers.length;
37353
37354
37355  parent._onerror = null;
37356
37357  _subscribers[length] = child;
37358  _subscribers[length + FULFILLED] = onFulfillment;
37359  _subscribers[length + REJECTED] = onRejection;
37360
37361  if (length === 0 && parent._state) {
37362    asap(publish, parent);
37363  }
37364}
37365
37366function publish(promise) {
37367  var subscribers = promise._subscribers;
37368  var settled = promise._state;
37369
37370  if (subscribers.length === 0) {
37371    return;
37372  }
37373
37374  var child = void 0,
37375      callback = void 0,
37376      detail = promise._result;
37377
37378  for (var i = 0; i < subscribers.length; i += 3) {
37379    child = subscribers[i];
37380    callback = subscribers[i + settled];
37381
37382    if (child) {
37383      invokeCallback(settled, child, callback, detail);
37384    } else {
37385      callback(detail);
37386    }
37387  }
37388
37389  promise._subscribers.length = 0;
37390}
37391
37392function tryCatch(callback, detail) {
37393  try {
37394    return callback(detail);
37395  } catch (e) {
37396    TRY_CATCH_ERROR.error = e;
37397    return TRY_CATCH_ERROR;
37398  }
37399}
37400
37401function invokeCallback(settled, promise, callback, detail) {
37402  var hasCallback = isFunction(callback),
37403      value = void 0,
37404      error = void 0,
37405      succeeded = void 0,
37406      failed = void 0;
37407
37408  if (hasCallback) {
37409    value = tryCatch(callback, detail);
37410
37411    if (value === TRY_CATCH_ERROR) {
37412      failed = true;
37413      error = value.error;
37414      value.error = null;
37415    } else {
37416      succeeded = true;
37417    }
37418
37419    if (promise === value) {
37420      reject(promise, cannotReturnOwn());
37421      return;
37422    }
37423  } else {
37424    value = detail;
37425    succeeded = true;
37426  }
37427
37428  if (promise._state !== PENDING) {
37429    // noop
37430  } else if (hasCallback && succeeded) {
37431    resolve(promise, value);
37432  } else if (failed) {
37433    reject(promise, error);
37434  } else if (settled === FULFILLED) {
37435    fulfill(promise, value);
37436  } else if (settled === REJECTED) {
37437    reject(promise, value);
37438  }
37439}
37440
37441function initializePromise(promise, resolver) {
37442  try {
37443    resolver(function resolvePromise(value) {
37444      resolve(promise, value);
37445    }, function rejectPromise(reason) {
37446      reject(promise, reason);
37447    });
37448  } catch (e) {
37449    reject(promise, e);
37450  }
37451}
37452
37453var id = 0;
37454function nextId() {
37455  return id++;
37456}
37457
37458function makePromise(promise) {
37459  promise[PROMISE_ID] = id++;
37460  promise._state = undefined;
37461  promise._result = undefined;
37462  promise._subscribers = [];
37463}
37464
37465function validationError() {
37466  return new Error('Array Methods must be provided an Array');
37467}
37468
37469var Enumerator = function () {
37470  function Enumerator(Constructor, input) {
37471    this._instanceConstructor = Constructor;
37472    this.promise = new Constructor(noop);
37473
37474    if (!this.promise[PROMISE_ID]) {
37475      makePromise(this.promise);
37476    }
37477
37478    if (isArray(input)) {
37479      this.length = input.length;
37480      this._remaining = input.length;
37481
37482      this._result = new Array(this.length);
37483
37484      if (this.length === 0) {
37485        fulfill(this.promise, this._result);
37486      } else {
37487        this.length = this.length || 0;
37488        this._enumerate(input);
37489        if (this._remaining === 0) {
37490          fulfill(this.promise, this._result);
37491        }
37492      }
37493    } else {
37494      reject(this.promise, validationError());
37495    }
37496  }
37497
37498  Enumerator.prototype._enumerate = function _enumerate(input) {
37499    for (var i = 0; this._state === PENDING && i < input.length; i++) {
37500      this._eachEntry(input[i], i);
37501    }
37502  };
37503
37504  Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
37505    var c = this._instanceConstructor;
37506    var resolve$$1 = c.resolve;
37507
37508
37509    if (resolve$$1 === resolve$1) {
37510      var _then = getThen(entry);
37511
37512      if (_then === then && entry._state !== PENDING) {
37513        this._settledAt(entry._state, i, entry._result);
37514      } else if (typeof _then !== 'function') {
37515        this._remaining--;
37516        this._result[i] = entry;
37517      } else if (c === Promise$1) {
37518        var promise = new c(noop);
37519        handleMaybeThenable(promise, entry, _then);
37520        this._willSettleAt(promise, i);
37521      } else {
vendor: 15,768 bytes, lines 37522-38128
37522        this._willSettleAt(new c(function (resolve$$1) {
37523          return resolve$$1(entry);
37524        }), i);
37525      }
37526    } else {
37527      this._willSettleAt(resolve$$1(entry), i);
37528    }
37529  };
37530
37531  Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
37532    var promise = this.promise;
37533
37534
37535    if (promise._state === PENDING) {
37536      this._remaining--;
37537
37538      if (state === REJECTED) {
37539        reject(promise, value);
37540      } else {
37541        this._result[i] = value;
37542      }
37543    }
37544
37545    if (this._remaining === 0) {
37546      fulfill(promise, this._result);
37547    }
37548  };
37549
37550  Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
37551    var enumerator = this;
37552
37553    subscribe(promise, undefined, function (value) {
37554      return enumerator._settledAt(FULFILLED, i, value);
37555    }, function (reason) {
37556      return enumerator._settledAt(REJECTED, i, reason);
37557    });
37558  };
37559
37560  return Enumerator;
37561}();
37562
37563/**
37564  `Promise.all` accepts an array of promises, and returns a new promise which
37565  is fulfilled with an array of fulfillment values for the passed promises, or
37566  rejected with the reason of the first passed promise to be rejected. It casts all
37567  elements of the passed iterable to promises as it runs this algorithm.
37568
37569  Example:
37570
37571  ```javascript
37572  let promise1 = resolve(1);
37573  let promise2 = resolve(2);
37574  let promise3 = resolve(3);
37575  let promises = [ promise1, promise2, promise3 ];
37576
37577  Promise.all(promises).then(function(array){
37578    // The array here would be [ 1, 2, 3 ];
37579  });
37580  ```
37581
37582  If any of the `promises` given to `all` are rejected, the first promise
37583  that is rejected will be given as an argument to the returned promises's
37584  rejection handler. For example:
37585
37586  Example:
37587
37588  ```javascript
37589  let promise1 = resolve(1);
37590  let promise2 = reject(new Error("2"));
37591  let promise3 = reject(new Error("3"));
37592  let promises = [ promise1, promise2, promise3 ];
37593
37594  Promise.all(promises).then(function(array){
37595    // Code here never runs because there are rejected promises!
37596  }, function(error) {
37597    // error.message === "2"
37598  });
37599  ```
37600
37601  @method all
37602  @static
37603  @param {Array} entries array of promises
37604  @param {String} label optional string for labeling the promise.
37605  Useful for tooling.
37606  @return {Promise} promise that is fulfilled when all `promises` have been
37607  fulfilled, or rejected if any of them become rejected.
37608  @static
37609*/
37610function all(entries) {
37611  return new Enumerator(this, entries).promise;
37612}
37613
37614/**
37615  `Promise.race` returns a new promise which is settled in the same way as the
37616  first passed promise to settle.
37617
37618  Example:
37619
37620  ```javascript
37621  let promise1 = new Promise(function(resolve, reject){
37622    setTimeout(function(){
37623      resolve('promise 1');
37624    }, 200);
37625  });
37626
37627  let promise2 = new Promise(function(resolve, reject){
37628    setTimeout(function(){
37629      resolve('promise 2');
37630    }, 100);
37631  });
37632
37633  Promise.race([promise1, promise2]).then(function(result){
37634    // result === 'promise 2' because it was resolved before promise1
37635    // was resolved.
37636  });
37637  ```
37638
37639  `Promise.race` is deterministic in that only the state of the first
37640  settled promise matters. For example, even if other promises given to the
37641  `promises` array argument are resolved, but the first settled promise has
37642  become rejected before the other promises became fulfilled, the returned
37643  promise will become rejected:
37644
37645  ```javascript
37646  let promise1 = new Promise(function(resolve, reject){
37647    setTimeout(function(){
37648      resolve('promise 1');
37649    }, 200);
37650  });
37651
37652  let promise2 = new Promise(function(resolve, reject){
37653    setTimeout(function(){
37654      reject(new Error('promise 2'));
37655    }, 100);
37656  });
37657
37658  Promise.race([promise1, promise2]).then(function(result){
37659    // Code here never runs
37660  }, function(reason){
37661    // reason.message === 'promise 2' because promise 2 became rejected before
37662    // promise 1 became fulfilled
37663  });
37664  ```
37665
37666  An example real-world use case is implementing timeouts:
37667
37668  ```javascript
37669  Promise.race([ajax('foo.json'), timeout(5000)])
37670  ```
37671
37672  @method race
37673  @static
37674  @param {Array} promises array of promises to observe
37675  Useful for tooling.
37676  @return {Promise} a promise which settles in the same way as the first passed
37677  promise to settle.
37678*/
37679function race(entries) {
37680  /*jshint validthis:true */
37681  var Constructor = this;
37682
37683  if (!isArray(entries)) {
37684    return new Constructor(function (_, reject) {
37685      return reject(new TypeError('You must pass an array to race.'));
37686    });
37687  } else {
37688    return new Constructor(function (resolve, reject) {
37689      var length = entries.length;
37690      for (var i = 0; i < length; i++) {
37691        Constructor.resolve(entries[i]).then(resolve, reject);
37692      }
37693    });
37694  }
37695}
37696
37697/**
37698  `Promise.reject` returns a promise rejected with the passed `reason`.
37699  It is shorthand for the following:
37700
37701  ```javascript
37702  let promise = new Promise(function(resolve, reject){
37703    reject(new Error('WHOOPS'));
37704  });
37705
37706  promise.then(function(value){
37707    // Code here doesn't run because the promise is rejected!
37708  }, function(reason){
37709    // reason.message === 'WHOOPS'
37710  });
37711  ```
37712
37713  Instead of writing the above, your code now simply becomes the following:
37714
37715  ```javascript
37716  let promise = Promise.reject(new Error('WHOOPS'));
37717
37718  promise.then(function(value){
37719    // Code here doesn't run because the promise is rejected!
37720  }, function(reason){
37721    // reason.message === 'WHOOPS'
37722  });
37723  ```
37724
37725  @method reject
37726  @static
37727  @param {Any} reason value that the returned promise will be rejected with.
37728  Useful for tooling.
37729  @return {Promise} a promise rejected with the given `reason`.
37730*/
37731function reject$1(reason) {
37732  /*jshint validthis:true */
37733  var Constructor = this;
37734  var promise = new Constructor(noop);
37735  reject(promise, reason);
37736  return promise;
37737}
37738
37739function needsResolver() {
37740  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
37741}
37742
37743function needsNew() {
37744  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
37745}
37746
37747/**
37748  Promise objects represent the eventual result of an asynchronous operation. The
37749  primary way of interacting with a promise is through its `then` method, which
37750  registers callbacks to receive either a promise's eventual value or the reason
37751  why the promise cannot be fulfilled.
37752
37753  Terminology
37754  -----------
37755
37756  - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
37757  - `thenable` is an object or function that defines a `then` method.
37758  - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
37759  - `exception` is a value that is thrown using the throw statement.
37760  - `reason` is a value that indicates why a promise was rejected.
37761  - `settled` the final resting state of a promise, fulfilled or rejected.
37762
37763  A promise can be in one of three states: pending, fulfilled, or rejected.
37764
37765  Promises that are fulfilled have a fulfillment value and are in the fulfilled
37766  state.  Promises that are rejected have a rejection reason and are in the
37767  rejected state.  A fulfillment value is never a thenable.
37768
37769  Promises can also be said to *resolve* a value.  If this value is also a
37770  promise, then the original promise's settled state will match the value's
37771  settled state.  So a promise that *resolves* a promise that rejects will
37772  itself reject, and a promise that *resolves* a promise that fulfills will
37773  itself fulfill.
37774
37775
37776  Basic Usage:
37777  ------------
37778
37779  ```js
37780  let promise = new Promise(function(resolve, reject) {
37781    // on success
37782    resolve(value);
37783
37784    // on failure
37785    reject(reason);
37786  });
37787
37788  promise.then(function(value) {
37789    // on fulfillment
37790  }, function(reason) {
37791    // on rejection
37792  });
37793  ```
37794
37795  Advanced Usage:
37796  ---------------
37797
37798  Promises shine when abstracting away asynchronous interactions such as
37799  `XMLHttpRequest`s.
37800
37801  ```js
37802  function getJSON(url) {
37803    return new Promise(function(resolve, reject){
37804      let xhr = new XMLHttpRequest();
37805
37806      xhr.open('GET', url);
37807      xhr.onreadystatechange = handler;
37808      xhr.responseType = 'json';
37809      xhr.setRequestHeader('Accept', 'application/json');
37810      xhr.send();
37811
37812      function handler() {
37813        if (this.readyState === this.DONE) {
37814          if (this.status === 200) {
37815            resolve(this.response);
37816          } else {
37817            reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
37818          }
37819        }
37820      };
37821    });
37822  }
37823
37824  getJSON('/posts.json').then(function(json) {
37825    // on fulfillment
37826  }, function(reason) {
37827    // on rejection
37828  });
37829  ```
37830
37831  Unlike callbacks, promises are great composable primitives.
37832
37833  ```js
37834  Promise.all([
37835    getJSON('/posts'),
37836    getJSON('/comments')
37837  ]).then(function(values){
37838    values[0] // => postsJSON
37839    values[1] // => commentsJSON
37840
37841    return values;
37842  });
37843  ```
37844
37845  @class Promise
37846  @param {Function} resolver
37847  Useful for tooling.
37848  @constructor
37849*/
37850
37851var Promise$1 = function () {
37852  function Promise(resolver) {
37853    this[PROMISE_ID] = nextId();
37854    this._result = this._state = undefined;
37855    this._subscribers = [];
37856
37857    if (noop !== resolver) {
37858      typeof resolver !== 'function' && needsResolver();
37859      this instanceof Promise ? initializePromise(this, resolver) : needsNew();
37860    }
37861  }
37862
37863  /**
37864  The primary way of interacting with a promise is through its `then` method,
37865  which registers callbacks to receive either a promise's eventual value or the
37866  reason why the promise cannot be fulfilled.
37867   ```js
37868  findUser().then(function(user){
37869    // user is available
37870  }, function(reason){
37871    // user is unavailable, and you are given the reason why
37872  });
37873  ```
37874   Chaining
37875  --------
37876   The return value of `then` is itself a promise.  This second, 'downstream'
37877  promise is resolved with the return value of the first promise's fulfillment
37878  or rejection handler, or rejected if the handler throws an exception.
37879   ```js
37880  findUser().then(function (user) {
37881    return user.name;
37882  }, function (reason) {
37883    return 'default name';
37884  }).then(function (userName) {
37885    // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
37886    // will be `'default name'`
37887  });
37888   findUser().then(function (user) {
37889    throw new Error('Found user, but still unhappy');
37890  }, function (reason) {
37891    throw new Error('`findUser` rejected and we're unhappy');
37892  }).then(function (value) {
37893    // never reached
37894  }, function (reason) {
37895    // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
37896    // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
37897  });
37898  ```
37899  If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
37900   ```js
37901  findUser().then(function (user) {
37902    throw new PedagogicalException('Upstream error');
37903  }).then(function (value) {
37904    // never reached
37905  }).then(function (value) {
37906    // never reached
37907  }, function (reason) {
37908    // The `PedgagocialException` is propagated all the way down to here
37909  });
37910  ```
37911   Assimilation
37912  ------------
37913   Sometimes the value you want to propagate to a downstream promise can only be
37914  retrieved asynchronously. This can be achieved by returning a promise in the
37915  fulfillment or rejection handler. The downstream promise will then be pending
37916  until the returned promise is settled. This is called *assimilation*.
37917   ```js
37918  findUser().then(function (user) {
37919    return findCommentsByAuthor(user);
37920  }).then(function (comments) {
37921    // The user's comments are now available
37922  });
37923  ```
37924   If the assimliated promise rejects, then the downstream promise will also reject.
37925   ```js
37926  findUser().then(function (user) {
37927    return findCommentsByAuthor(user);
37928  }).then(function (comments) {
37929    // If `findCommentsByAuthor` fulfills, we'll have the value here
37930  }, function (reason) {
37931    // If `findCommentsByAuthor` rejects, we'll have the reason here
37932  });
37933  ```
37934   Simple Example
37935  --------------
37936   Synchronous Example
37937   ```javascript
37938  let result;
37939   try {
37940    result = findResult();
37941    // success
37942  } catch(reason) {
37943    // failure
37944  }
37945  ```
37946   Errback Example
37947   ```js
37948  findResult(function(result, err){
37949    if (err) {
37950      // failure
37951    } else {
37952      // success
37953    }
37954  });
37955  ```
37956   Promise Example;
37957   ```javascript
37958  findResult().then(function(result){
37959    // success
37960  }, function(reason){
37961    // failure
37962  });
37963  ```
37964   Advanced Example
37965  --------------
37966   Synchronous Example
37967   ```javascript
37968  let author, books;
37969   try {
37970    author = findAuthor();
37971    books  = findBooksByAuthor(author);
37972    // success
37973  } catch(reason) {
37974    // failure
37975  }
37976  ```
37977   Errback Example
37978   ```js
37979   function foundBooks(books) {
37980   }
37981   function failure(reason) {
37982   }
37983   findAuthor(function(author, err){
37984    if (err) {
37985      failure(err);
37986      // failure
37987    } else {
37988      try {
37989        findBoooksByAuthor(author, function(books, err) {
37990          if (err) {
37991            failure(err);
37992          } else {
37993            try {
37994              foundBooks(books);
37995            } catch(reason) {
37996              failure(reason);
37997            }
37998          }
37999        });
38000      } catch(error) {
38001        failure(err);
38002      }
38003      // success
38004    }
38005  });
38006  ```
38007   Promise Example;
38008   ```javascript
38009  findAuthor().
38010    then(findBooksByAuthor).
38011    then(function(books){
38012      // found books
38013  }).catch(function(reason){
38014    // something went wrong
38015  });
38016  ```
38017   @method then
38018  @param {Function} onFulfilled
38019  @param {Function} onRejected
38020  Useful for tooling.
38021  @return {Promise}
38022  */
38023
38024  /**
38025  `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
38026  as the catch block of a try/catch statement.
38027  ```js
38028  function findAuthor(){
38029  throw new Error('couldn't find that author');
38030  }
38031  // synchronous
38032  try {
38033  findAuthor();
38034  } catch(reason) {
38035  // something went wrong
38036  }
38037  // async with promises
38038  findAuthor().catch(function(reason){
38039  // something went wrong
38040  });
38041  ```
38042  @method catch
38043  @param {Function} onRejection
38044  Useful for tooling.
38045  @return {Promise}
38046  */
38047
38048
38049  Promise.prototype.catch = function _catch(onRejection) {
38050    return this.then(null, onRejection);
38051  };
38052
38053  /**
38054    `finally` will be invoked regardless of the promise's fate just as native
38055    try/catch/finally behaves
38056  
38057    Synchronous example:
38058  
38059    ```js
38060    findAuthor() {
38061      if (Math.random() > 0.5) {
38062        throw new Error();
38063      }
38064      return new Author();
38065    }
38066  
38067    try {
38068      return findAuthor(); // succeed or fail
38069    } catch(error) {
38070      return findOtherAuther();
38071    } finally {
38072      // always runs
38073      // doesn't affect the return value
38074    }
38075    ```
38076  
38077    Asynchronous example:
38078  
38079    ```js
38080    findAuthor().catch(function(reason){
38081      return findOtherAuther();
38082    }).finally(function(){
38083      // author was either found, or not
38084    });
38085    ```
38086  
38087    @method finally
38088    @param {Function} callback
38089    @return {Promise}
38090  */
38091
38092
38093  Promise.prototype.finally = function _finally(callback) {
38094    var promise = this;
38095    var constructor = promise.constructor;
38096
38097    if (isFunction(callback)) {
38098      return promise.then(function (value) {
38099        return constructor.resolve(callback()).then(function () {
38100          return value;
38101        });
38102      }, function (reason) {
38103        return constructor.resolve(callback()).then(function () {
38104          throw reason;
38105        });
38106      });
38107    }
38108
38109    return promise.then(callback, callback);
38110  };
38111
38112  return Promise;
38113}();
38114
38115Promise$1.prototype.then = then;
38116Promise$1.all = all;
38117Promise$1.race = race;
38118Promise$1.resolve = resolve$1;
38119Promise$1.reject = reject$1;
38120Promise$1._setScheduler = setScheduler;
38121Promise$1._setAsap = setAsap;
38122Promise$1._asap = asap;
38123
38124/*global self*/
38125function polyfill() {
38126  var local = void 0;
38127
38128  if (typeof 
vendor: 748 bytes, lines 38128-38170
38128commonjsGlobal !== 'undefined') {
38129    local = commonjsGlobal;
38130  } else if (typeof self !== 'undefined') {
38131    local = self;
38132  } else {
38133    try {
38134      local = Function('return this')();
38135    } catch (e) {
38136      throw new Error('polyfill failed because global object is unavailable in this environment');
38137    }
38138  }
38139
38140  var P = local.Promise;
38141
38142  if (P) {
38143    var promiseToString = null;
38144    try {
38145      promiseToString = Object.prototype.toString.call(P.resolve());
38146    } catch (e) {
38147      // silently ignored
38148    }
38149
38150    if (promiseToString === '[object Promise]' && !P.cast) {
38151      return;
38152    }
38153  }
38154
38155  local.Promise = Promise$1;
38156}
38157
38158// Strange compat..
38159Promise$1.polyfill = polyfill;
38160Promise$1.Promise = Promise$1;
38161
38162return Promise$1;
38163
38164})));
38165
38166
38167
38168
38169});
38170
38171var Promise$1 = es6Promise.Promise;
38172
38173/* ----- CONSTRUCTOR ----- */
38174
38175var Worker = function Worker(opt) {
38176  // Create the root parent for the proto chain, and the starting Worker.
38177  var root = _extends(Worker.convert(Promise$1.resolve()), JSON.parse(JSON.stringify(Worker.template)));
38178  var self = Worker.convert(Promise$1.resolve(), root);
38179
38180  // Set progress, optional settings, and return.
38181  self = self.setProgress(1, Worker, 1, [Worker]);
38182  self = self.set(opt);
38183  return self;
38184};
38185
38186// Boilerplate for subclassing Promise.
38187Worker.prototype = Object.create(Promise$1.prototype);
38188Worker.prototype.constructor = Worker;
38189
38190// Converts/casts promises into Workers.
38191Worker.convert = function convert(promise, inherit) {
38192  // Uses prototypal inheritance to receive changes made to ancestors' properties.
38193  promise.__proto__ = inherit || Worker.prototype;
38194  return promise;
38195};
38196
38197Worker.template = {
38198  prop: {
38199    src: null,
38200    container: null,
38201    overlay: null,
38202    canvas: null,
38203    img: null,
38204    pdf: null,
38205    pageSize: null
38206  },
38207  progress: {
38208    val: 0,
38209    state: null,
38210    n: 0,
38211    stack: []
38212  },
38213  opt: {
38214    filename: 'file.pdf',
38215    margin: [0, 0, 0, 0],
38216    image: { type: 'jpeg', quality: 0.95 },
38217    enableLinks: true,
38218    html2canvas: {},
38219    jsPDF: {}
38220  }
38221};
38222
38223/* ----- FROM / TO ----- */
38224
38225Worker.prototype.from = function from(src, type) {
38226  function getType(src) {
38227    switch (objType(src)) {
38228      case 'string':
38229        return 'string';
38230      case 'element':
38231        return src.nodeName.toLowerCase === 'canvas' ? 'canvas' : 'element';
38232      default:
38233        return 'unknown';
38234    }
38235  }
38236
38237  return this.then(function from_main() {
38238    type = type || getType(src);
38239    switch (type) {
38240      case 'string':
38241        return this.set({ src: createElement('div', { innerHTML: src }) });
38242      case 'element':
38243        return this.set({ src: src });
38244      case 'canvas':
38245        return this.set({ canvas: src });
38246      case 'img':
38247        return this.set({ img: src });
38248      default:
38249        return this.error('Unknown source type.');
38250    }
38251  });
38252};
38253
38254Worker.prototype.to = function to(target) {
38255  // Route the 'to' request to the appropriate method.
38256  switch (target) {
38257    case 'container':
38258      return this.toContainer();
38259    case 'canvas':
38260      return this.toCanvas();
38261    case 'img':
38262      return this.toImg();
38263    case 'pdf':
38264      return this.toPdf();
38265    default:
38266      return this.error('Invalid target.');
38267  }
38268};
38269
38270Worker.prototype.toContainer = function toContainer() {
38271  // Set up function prerequisites.
38272  var prereqs = [function checkSrc() {
38273    return this.prop.src || this.error('Cannot duplicate - no source HTML.');
38274  }, function checkPageSize() {
38275    return this.prop.pageSize || this.setPageSize();
38276  }];
38277
38278  return this.thenList(prereqs).then(function toContainer_main() {
38279    // Define the CSS styles for the container and its overlay parent.
38280    var overlayCSS = {
38281      position: 'fixed', overflow: 'hidden', zIndex: 1000,
38282      left: 0, right: 0, bottom: 0, top: 0,
38283      backgroundColor: 'rgba(0,0,0,0.8)'
38284    };
38285    var containerCSS = {
38286      position: 'absolute', width: this.prop.pageSize.inner.width + this.prop.pageSize.unit,
38287      left: 0, right: 0, top: 0, height: 'auto', margin: 'auto',
38288      backgroundColor: 'white'
38289    };
38290
38291    // Set the overlay to hidden (could be changed in the future to provide a print preview).
38292    overlayCSS.opacity = 0;
38293
38294    // Create and attach the elements.
38295    var source = cloneNode(this.prop.src, this.opt.html2canvas.javascriptEnabled);
38296    this.prop.overlay = createElement('div', { className: 'html2pdf__overlay', style: overlayCSS });
38297    this.prop.container = createElement('div', { className: 'html2pdf__container', style: containerCSS });
38298    this.prop.container.appendChild(source);
38299    this.prop.overlay.appendChild(this.prop.container);
38300    document.body.appendChild(this.prop.overlay);
38301  });
38302};
38303
38304Worker.prototype.toCanvas = function toCanvas() {
38305  // Set up function prerequisites.
38306  var prereqs = [function checkContainer() {
38307    return document.body.contains(this.prop.container) || this.toContainer();
38308  }];
38309
38310  // Fulfill prereqs then create the canvas.
38311  return this.thenList(prereqs).then(function toCanvas_main() {
38312    // Handle old-fashioned 'onrendered' argument.
38313    var options = _extends({}, this.opt.html2canvas);
38314    delete options.onrendered;
38315
38316    return html2canvas$1(this.prop.container, options);
38317  }).then(function toCanvas_post(canvas) {
38318    // Handle old-fashioned 'onrendered' argument.
38319    var onRendered = this.opt.html2canvas.onrendered || function () {};
38320    onRendered(canvas);
38321
38322    this.prop.canvas = canvas;
38323    document.body.removeChild(this.prop.overlay);
38324  });
38325};
38326
38327Worker.prototype.toImg = function toImg() {
38328  // Set up function prerequisites.
38329  var prereqs = [function checkCanvas() {
38330    return this.prop.canvas || this.toCanvas();
38331  }];
38332
38333  // Fulfill prereqs then create the image.
38334  return this.thenList(prereqs).then(function toImg_main() {
38335    var imgData = this.prop.canvas.toDataURL('image/' + this.opt.image.type, this.opt.image.quality);
38336    this.prop.img = document.createElement('img');
38337    this.prop.img.src = imgData;
38338  });
38339};
38340
38341Worker.prototype.toPdf = function toPdf() {
38342  // Set up function prerequisites.
38343  var prereqs = [function checkCanvas() {
38344    return this.prop.canvas || this.toCanvas();
38345  }];
38346
38347  // Fulfill prereqs then create the image.
38348  return this.thenList(prereqs).then(function toPdf_main() {
38349    // Create local copies of frequently used properties.
38350    var canvas = this.prop.canvas;
38351    var opt = this.opt;
38352
38353    // Calculate the number of pages.
38354    var pxFullHeight = canvas.height;
38355    var pxPageHeight = Math.floor(canvas.width * this.prop.pageSize.inner.ratio);
38356    var nPages = Math.ceil(pxFullHeight / pxPageHeight);
38357
38358    // Define pageHeight separately so it can be trimmed on the final page.
38359    var pageHeight = this.prop.pageSize.inner.height;
38360
38361    // Create a one-page canvas to split up the full image.
38362    var pageCanvas = document.createElement('canvas');
38363    var pageCtx = pageCanvas.getContext('2d');
38364    pageCanvas.width = canvas.width;
38365    pageCanvas.height = pxPageHeight;
38366
38367    // Initialize the PDF.
38368    this.prop.pdf = this.prop.pdf || new jspdf_min(opt.jsPDF);
38369
38370    for (var page = 0; page < nPages; page++) {
38371      // Trim the final page to reduce file size.
38372      if (page === nPages - 1 && pxFullHeight % pxPageHeight !== 0) {
38373        pageCanvas.height = pxFullHeight % pxPageHeight;
38374        pageHeight = pageCanvas.height * this.prop.pageSize.inner.width / pageCanvas.width;
38375      }
38376
38377      // Display the page.
38378      var w = pageCanvas.width;
38379      var h = pageCanvas.height;
38380      pageCtx.fillStyle = 'white';
38381      pageCtx.fillRect(0, 0, w, h);
38382      pageCtx.drawImage(canvas, 0, page * pxPageHeight, w, h, 0, 0, w, h);
38383
38384      // Add the page to the PDF.
38385      if (page) this.prop.pdf.addPage();
38386      var imgData = pageCanvas.toDataURL('image/' + opt.image.type, opt.image.quality);
38387      this.prop.pdf.addImage(imgData, opt.image.type, opt.margin[1], opt.margin[0], this.prop.pageSize.inner.width, pageHeight);
38388    }
38389  });
38390};
38391
38392/* ----- OUTPUT / SAVE ----- */
38393
38394Worker.prototype.output = function output(type, options, src) {
38395  // Redirect requests to the correct function (outputPdf / outputImg).
38396  src = src || 'pdf';
38397  if (src.toLowerCase() === 'img' || src.toLowerCase() === 'image') {
38398    return this.outputImg(type, options);
38399  } else {
38400    return this.outputPdf(type, options);
38401  }
38402};
38403
38404Worker.prototype.outputPdf = function outputPdf(type, options) {
38405  // Set up function prerequisites.
38406  var prereqs = [function checkPdf() {
38407    return this.prop.pdf || this.toPdf();
38408  }];
38409
38410  // Fulfill prereqs then perform the appropriate output.
38411  return this.thenList(prereqs).then(function outputPdf_main() {
38412    /* Currently implemented output types:
38413     *    https://rawgit.com/MrRio/jsPDF/master/docs/jspdf.js.html#line992
38414     *  save(options), arraybuffer, blob, bloburi/bloburl,
38415     *  datauristring/dataurlstring, dataurlnewwindow, datauri/dataurl
38416     */
38417    return this.prop.pdf.output(type, options);
38418  });
38419};
38420
38421Worker.prototype.outputImg = function outputImg(type, options) {
38422  // Set up function prerequisites.
38423  var prereqs = [function checkImg() {
38424    return this.prop.img || this.toImg();
38425  }];
38426
38427  // Fulfill prereqs then perform the appropriate output.
38428  return this.thenList(prereqs).then(function outputImg_main() {
38429    switch (type) {
38430      case undefined:
38431      case 'img':
38432        return this.prop.img;
38433      case 'datauristring':
38434      case 'dataurlstring':
38435        return this.prop.img.src;
38436      case 'datauri':
38437      case 'dataurl':
38438        return document.location.href = this.prop.img.src;
38439      default:
38440        throw 'Image output type "' + type + '" is not supported.';
38441    }
38442  });
38443};
38444
38445Worker.prototype.save = function save(filename) {
38446  // Set up function prerequisites.
38447  var prereqs = [function checkPdf() {
38448    return this.prop.pdf || this.toPdf();
38449  }];
38450
38451  // Fulfill prereqs, update the filename (if provided), and save the PDF.
38452  return this.thenList(prereqs).set(filename ? { filename: filename } : null).then(function save_main() {
38453    this.prop.pdf.save(this.opt.filename);
38454  });
38455};
38456
38457/* ----- SET / GET ----- */
38458
38459Worker.prototype.set = function set$$1(opt) {
38460  // TODO: Implement ordered pairs?
38461
38462  // Silently ignore invalid or empty input.
38463  if (objType(opt) !== 'object') {
38464    return this;
38465  }
38466
38467  // Build an array of setter functions to queue.
38468  var fns = Object.keys(opt || {}).map(function (key) {
38469    if (key in Worker.template.prop) {
38470      // Set pre-defined properties.
38471      return function set_prop() {
38472        this.prop[key] = opt[key];
38473      };
38474    } else {
38475      switch (key) {
38476        case 'margin':
38477          return this.setMargin.bind(this, opt.margin);
38478        case 'jsPDF':
38479          return function set_jsPDF() {
38480            this.opt.jsPDF = opt.jsPDF;return this.setPageSize();
38481          };
38482        case 'pageSize':
38483          return this.setPageSize.bind(this, opt.pageSize);
38484        default:
38485          // Set any other properties in opt.
38486          return function set_opt() {
38487            this.opt[key] = opt[key];
38488          };
38489      }
38490    }
38491  }, this);
38492
38493  // Set properties within the promise chain.
38494  return this.then(function set_main() {
38495    return this.thenList(fns);
38496  });
38497};
38498
38499Worker.prototype.get = function get$$1(key, cbk) {
38500  return this.then(function get_main() {
38501    // Fetch the requested property, either as a predefined prop or in opt.
38502    var val = key in Worker.template.prop ? this.prop[key] : this.opt[key];
38503    return cbk ? cbk(val) : val;
38504  });
38505};
38506
38507Worker.prototype.setMargin = function setMargin(margin) {
38508  return this.then(function setMargin_main() {
vendor: 5,907 bytes, lines 38509-38674
38509    // Parse the margin property: [top, left, bottom, right].
38510    switch (objType(margin)) {
38511      case 'number':
38512        margin = [margin, margin, margin, margin];
38513      case 'array':
38514        if (margin.length === 2) {
38515          margin = [margin[0], margin[1], margin[0], margin[1]];
38516        }
38517        if (margin.length === 4) {
38518          break;
38519        }
38520      default:
38521        return this.error('Invalid margin array.');
38522    }
38523
38524    // Set the margin property, then update pageSize.
38525    this.opt.margin = margin;
38526  }).then(this.setPageSize);
38527};
38528
38529Worker.prototype.setPageSize = function setPageSize(pageSize) {
38530  return this.then(function setPageSize_main() {
38531    // Retrieve page-size based on jsPDF settings, if not explicitly provided.
38532    pageSize = pageSize || jspdf_min.getPageSize(this.opt.jsPDF);
38533
38534    // Add 'inner' field if not present.
38535    if (!pageSize.hasOwnProperty('inner')) {
38536      pageSize.inner = {
38537        width: pageSize.width - this.opt.margin[1] - this.opt.margin[3],
38538        height: pageSize.height - this.opt.margin[0] - this.opt.margin[2]
38539      };
38540      pageSize.inner.px = {
38541        width: toPx(pageSize.inner.width, pageSize.k),
38542        height: toPx(pageSize.inner.height, pageSize.k)
38543      };
38544      pageSize.inner.ratio = pageSize.inner.height / pageSize.inner.width;
38545    }
38546
38547    // Attach pageSize to this.
38548    this.prop.pageSize = pageSize;
38549  });
38550};
38551
38552Worker.prototype.setProgress = function setProgress(val, state, n, stack) {
38553  // Immediately update all progress values.
38554  if (val != null) this.progress.val = val;
38555  if (state != null) this.progress.state = state;
38556  if (n != null) this.progress.n = n;
38557  if (stack != null) this.progress.stack = stack;
38558  this.progress.ratio = this.progress.val / this.progress.state;
38559
38560  // Return this for command chaining.
38561  return this;
38562};
38563
38564Worker.prototype.updateProgress = function updateProgress(val, state, n, stack) {
38565  // Immediately update all progress values, using setProgress.
38566  return this.setProgress(val ? this.progress.val + val : null, state ? state : null, n ? this.progress.n + n : null, stack ? this.progress.stack.concat(stack) : null);
38567};
38568
38569/* ----- PROMISE MAPPING ----- */
38570
38571Worker.prototype.then = function then(onFulfilled, onRejected) {
38572  // Wrap `this` for encapsulation.
38573  var self = this;
38574
38575  return this.thenCore(onFulfilled, onRejected, function then_main(onFulfilled, onRejected) {
38576    // Update progress while queuing, calling, and resolving `then`.
38577    self.updateProgress(null, null, 1, [onFulfilled]);
38578    return Promise$1.prototype.then.call(this, function then_pre(val) {
38579      self.updateProgress(null, onFulfilled);
38580      return val;
38581    }).then(onFulfilled, onRejected).then(function then_post(val) {
38582      self.updateProgress(1);
38583      return val;
38584    });
38585  });
38586};
38587
38588Worker.prototype.thenCore = function thenCore(onFulfilled, onRejected, thenBase) {
38589  // Handle optional thenBase parameter.
38590  thenBase = thenBase || Promise$1.prototype.then;
38591
38592  // Wrap `this` for encapsulation and bind it to the promise handlers.
38593  var self = this;
38594  if (onFulfilled) {
38595    onFulfilled = onFulfilled.bind(self);
38596  }
38597  if (onRejected) {
38598    onRejected = onRejected.bind(self);
38599  }
38600
38601  // Cast self into a Promise to avoid polyfills recursively defining `then`.
38602  var isNative = Promise$1.toString().indexOf('[native code]') !== -1 && Promise$1.name === 'Promise';
38603  var selfPromise = isNative ? self : Worker.convert(_extends({}, self), Promise$1.prototype);
38604
38605  // Return the promise, after casting it into a Worker and preserving props.
38606  var returnVal = thenBase.call(selfPromise, onFulfilled, onRejected);
38607  return Worker.convert(returnVal, self.__proto__);
38608};
38609
38610Worker.prototype.thenExternal = function thenExternal(onFulfilled, onRejected) {
38611  // Call `then` and return a standard promise (exits the Worker chain).
38612  return Promise$1.prototype.then.call(this, onFulfilled, onRejected);
38613};
38614
38615Worker.prototype.thenList = function thenList(fns) {
38616  // Queue a series of promise 'factories' into the promise chain.
38617  var self = this;
38618  fns.forEach(function thenList_forEach(fn) {
38619    self = self.thenCore(fn);
38620  });
38621  return self;
38622};
38623
38624Worker.prototype['catch'] = function (onRejected) {
38625  // Bind `this` to the promise handler, call `catch`, and return a Worker.
38626  if (onRejected) {
38627    onRejected = onRejected.bind(this);
38628  }
38629  var returnVal = Promise$1.prototype['catch'].call(this, onRejected);
38630  return Worker.convert(returnVal, this);
38631};
38632
38633Worker.prototype.catchExternal = function catchExternal(onRejected) {
38634  // Call `catch` and return a standard promise (exits the Worker chain).
38635  return Promise$1.prototype['catch'].call(this, onRejected);
38636};
38637
38638Worker.prototype.error = function error(msg) {
38639  // Throw the error in the Promise chain.
38640  return this.then(function error_main() {
38641    throw new Error(msg);
38642  });
38643};
38644
38645/* ----- ALIASES ----- */
38646
38647Worker.prototype.using = Worker.prototype.set;
38648Worker.prototype.saveAs = Worker.prototype.save;
38649Worker.prototype.export = Worker.prototype.output;
38650Worker.prototype.run = Worker.prototype.then;
38651
38652// Import dependencies.
38653// Get dimensions of a PDF page, as determined by jsPDF.
38654jspdf_min.getPageSize = function (orientation, unit, format) {
38655  // Decode options object
38656  if ((typeof orientation === 'undefined' ? 'undefined' : _typeof(orientation)) === 'object') {
38657    var options = orientation;
38658    orientation = options.orientation;
38659    unit = options.unit || unit;
38660    format = options.format || format;
38661  }
38662
38663  // Default options
38664  unit = unit || 'mm';
38665  format = format || 'a4';
38666  orientation = ('' + (orientation || 'P')).toLowerCase();
38667  var format_as_string = ('' + format).toLowerCase();
38668
38669  // Size in pt of various paper formats
38670  var pageFormats = {
38671    'a0': [2383.94, 3370.39], 'a1': [1683.78, 2383.94],
38672    'a2': [1190.55, 1683.78], 'a3': [841.89, 1190.55],
38673    'a4': [595.28, 841.89], 'a5': [419.53, 595.28],
38674    'a6': [297.64, 419.53], 'a7': [209.76, 297.64],
38675    'a8': [147.40, 209.76], 'a9': [104.88, 147.40],
38676    'a10': [73.70, 104.88], 'b0': [2834.65, 4008.19],
38677    'b1': [2004.09, 2834.65], 'b2': [1417.32, 2004.09],
38678    'b3': [1000.63, 1417.32], 'b4': [708.66, 1000.63],
38679    'b5': [498.90, 708.66], 'b6': [354.33, 498.90],
38680    'b7': [249.45, 354.33], 'b8': [175.75, 249.45],
38681    'b9': [124.72, 175.75], 'b10': [87.87, 124.72],
38682    'c0': [2599.37, 3676.54], 'c1': [1836.85, 2599.37],
38683    'c2': [1298.27, 1836.85], 'c3': [918.43, 1298.27],
38684    'c4': [649.13, 918.43], 'c5': [459.21, 649.13],
38685    'c6': [323.15, 459.21], 'c7': [229.61, 323.15],
38686    'c8': [161.57, 229.61], 'c9': [113.39, 161.57],
38687    'c10': [79.37, 113.39], 'dl': [311.81, 623.62],
38688    'letter': [612, 792],
38689    'government-letter': [576, 756],
38690    'legal': [612, 1008],
38691    'junior-legal': [576, 360],
38692    'ledger': [1224, 792],
38693    'tabloid': [792, 1224],
38694    'credit-card': [153, 243]
38695  };
38696
38697  // Unit conversion
38698  switch (unit) {
38699    case 'pt':
38700      var k = 1;break;
38701    case 'mm':
38702      var k = 72 / 25.4;break;
38703    case 'cm':
38704      var k = 72 / 2.54;break;
38705    case 'in':
38706      var k = 72;break;
38707    case 'px':
38708      var k = 72 / 96;break;
38709    case 'pc':
38710      var k = 12;break;
38711    case 'em':
38712      var k = 12;break;
38713    case 'ex':
38714      var k = 6;break;
38715    default:
38716      throw 'Invalid unit: ' + unit;
38717  }
38718
38719  // Dimensions are stored as user units and converted to points on output
38720  if (pageFormats.hasOwnProperty(format_as_string)) {
38721    var pageHeight = pageFormats[format_as_string][1] / k;
38722    var pageWidth = pageFormats[format_as_string][0] / k;
38723  } else {
38724    try {
38725      var pageHeight = format[1];
38726      var pageWidth = format[0];
38727    } catch (err) {
38728      throw new Error('Invalid format: ' + format);
38729    }
38730  }
38731
38732  // Handle page orientation
38733  if (orientation === 'p' || orientation === 'portrait') {
38734    orientation = 'p';
38735    if (pageWidth > pageHeight) {
38736      var tmp = pageWidth;
38737      pageWidth = pageHeight;
38738      pageHeight = tmp;
38739    }
38740  } else if (orientation === 'l' || orientation === 'landscape') {
38741    orientation = 'l';
38742    if (pageHeight > pageWidth) {
38743      var tmp = pageWidth;
38744      pageWidth = pageHeight;
38745      pageHeight = tmp;
38746    }
38747  } else {
38748    throw 'Invalid orientation: ' + orientation;
38749  }
38750
38751  // Return information (k is the unit conversion ratio from pts)
38752  var info = { 'width': pageWidth, 'height': pageHeight, 'unit': unit, 'k': k };
38753  return info;
38754};
38755
38756/* Pagebreak plugin:
38757
38758    Adds page-break functionality to the html2pdf library. Page-breaks can be
38759    enabled by CSS styles, set on individual elements using selectors, or
38760    avoided from breaking inside all elements.
38761
38762    Options on the `opt.pagebreak` object:
38763
38764    mode:   String or array of strings: 'avoid-all', 'css', and/or 'legacy'
38765            Default: ['css', 'legacy']
38766
38767    before: String or array of CSS selectors for which to add page-breaks
38768            before each element. Can be a specific element with an ID
38769            ('#myID'), all elements of a type (e.g. 'img'), all of a class
38770            ('.myClass'), or even '*' to match every element.
38771
38772    after:  Like 'before', but adds a page-break immediately after the element.
38773
38774    avoid:  Like 'before', but avoids page-breaks on these elements. You can
38775            enable this feature on every element using the 'avoid-all' mode.
38776*/
38777
38778// Refs to original functions.
38779var orig = {
38780  toContainer: Worker.prototype.toContainer
38781};
38782
38783// Add pagebreak default options to the Worker template.
38784Worker.template.opt.pagebreak = {
38785  mode: ['css', 'legacy'],
38786  before: [],
38787  after: [],
38788  avoid: []
38789};
38790
38791Worker.prototype.toContainer = function toContainer() {
38792  return orig.toContainer.call(this).then(function toContainer_pagebreak() {
38793    // Setup root element and inner page height.
38794    var root = this.prop.container;
38795    var pxPageHeight = this.prop.pageSize.inner.px.height;
38796
38797    // Check all requested modes.
38798    var modeSrc = [].concat(this.opt.pagebreak.mode);
38799    var mode = {
38800      avoidAll: modeSrc.indexOf('avoid-all') !== -1,
38801      css: modeSrc.indexOf('css') !== -1,
38802      legacy: modeSrc.indexOf('legacy') !== -1
38803    };
38804
38805    // Get arrays of all explicitly requested elements.
38806    var select = {};
38807    var self = this;
38808    ['before', 'after', 'avoid'].forEach(function (key) {
38809      var all = mode.avoidAll && key === 'avoid';
38810      select[key] = all ? [] : [].concat(self.opt.pagebreak[key] || []);
38811      if (select[key].length > 0) {
38812        select[key] = Array.prototype.slice.call(root.querySelectorAll(select[key].join(', ')));
38813      }
38814    });
38815
38816    // Get all legacy page-break elements.
38817    var legacyEls = root.querySelectorAll('.html2pdf__page-break');
38818    legacyEls = Array.prototype.slice.call(legacyEls);
38819
38820    // Loop through all elements.
38821    var els = root.querySelectorAll('*');
38822    Array.prototype.forEach.call(els, function pagebreak_loop(el) {
38823      // Setup pagebreak rules based on legacy and avoidAll modes.
38824      var rules = {
38825        before: false,
38826        after: mode.legacy && legacyEls.indexOf(el) !== -1,
38827        avoid: mode.avoidAll
38828      };
38829
38830      // Add rules for css mode.
38831      if (mode.css) {
38832        // TODO: Check if this is valid with iFrames.
38833        var style = window.getComputedStyle(el);
38834        // TODO: Handle 'left' and 'right' correctly.
38835        // TODO: Add support for 'avoid' on breakBefore/After.
38836        var breakOpt = ['always', 'page', 'left', 'right'];
38837        var avoidOpt = ['avoid', 'avoid-page'];
38838        rules = {
38839          before: rules.before || breakOpt.indexOf(style.breakBefore || style.pageBreakBefore) !== -1,
38840          after: rules.after || breakOpt.indexOf(style.breakAfter || style.pageBreakAfter) !== -1,
38841          avoid: rules.avoid || avoidOpt.indexOf(style.breakInside || style.pageBreakInside) !== -1
38842        };
38843      }
38844
38845      // Add rules for explicit requests.
38846      Object.keys(rules).forEach(function (key) {
38847        rules[key] = rules[key] || select[key].indexOf(el) !== -1;
38848      });
38849
38850      // Get element position on the screen.
38851      // TODO: Subtract the top of the container from clientRect.top/bottom?
38852      var clientRect = el.getBoundingClientRect();
38853
38854      // Avoid: Check if a break happens mid-element.
38855      if (rules.avoid && !rules.before) {
38856        var startPage = Math.floor(clientRect.top / pxPageHeight);
38857        var endPage = Math.floor(clientRect.bottom / pxPageHeight);
38858        var nPages = Math.abs(clientRect.bottom - clientRect.top) / pxPageHeight;
38859
38860        // Turn on rules.before if the el is broken and is at most one page long.
38861        if (endPage !== startPage && nPages <= 1) {
38862          rules.before = true;
38863        }
38864      }
38865
38866      // Before: Create a padding div to push the element to the next page.
38867      if (rules.before) {
38868        var pad = createElement('div', { style: {
38869            display: 'block',
38870            height: pxPageHeight - clientRect.top % pxPageHeight + 'px'
38871          } });
38872        el.parentNode.insertBefore(pad, el);
38873      }
38874
38875      // After: Create a padding div to fill the remaining page.
38876      if (rules.after) {
38877        var pad = createElement('div', { style: {
38878            display: 'block',
38879            height: pxPageHeight - clientRect.bottom % pxPageHeight + 'px'
38880          } });
38881        el.parentNode.insertBefore(pad, el.nextSibling);
38882      }
38883    });
38884  });
38885};
38886
38887// Add hyperlink functionality to the PDF creation.
38888
38889// Main link array, and refs to original functions.
38890var linkInfo = [];
38891var orig$1 = {
38892  toContainer: Worker.prototype.toContainer,
38893  toPdf: Worker.prototype.toPdf
38894};
38895
38896Worker.prototype.toContainer = function toContainer() {
38897  return orig$1.toContainer.call(this).then(function toContainer_hyperlink() {
38898    // Retrieve hyperlink info if the option is enabled.
38899    if (this.opt.enableLinks) {
38900      // Find all anchor tags and get the container's bounds for reference.
38901      var container = this.prop.container;
38902      var links = container.querySelectorAll('a');
38903      var containerRect = unitConvert(container.getBoundingClientRect(), this.prop.pageSize.k);
38904      linkInfo = [];
38905
38906      // Loop through each anchor tag.
38907      Array.prototype.forEach.call(links, function (link) {
38908        // Treat each client rect as a separate link (for text-wrapping).
38909        var clientRects = link.getClientRects();
38910        for (var i = 0; i < clientRects.length; i++) {
38911          var clientRect = unitConvert(clientRects[i], this.prop.pageSize.k);
38912          clientRect.left -= containerRect.left;
38913          clientRect.top -= containerRect.top;
38914
38915          var page = Math.floor(clientRect.top / this.prop.pageSize.inner.height) + 1;
38916          var top = this.opt.margin[0] + clientRect.top % this.prop.pageSize.inner.height;
38917          var left = this.opt.margin[1] + clientRect.left;
38918
38919          linkInfo.push({ page: page, top: top, left: left, clientRect: clientRect, link: link });
38920        }
38921      }, this);
38922    }
38923  });
38924};
38925
38926Worker.prototype.toPdf = function toPdf() {
38927  return orig$1.toPdf.call(this).then(function toPdf_hyperlink() {
38928    // Add hyperlinks if the option is enabled.
38929    if (this.opt.enableLinks) {
38930      // Attach each anchor tag based on info from toContainer().
38931      linkInfo.forEach(function (l) {
38932        this.prop.pdf.setPage(l.page);
38933        this.prop.pdf.link(l.left, l.top, l.clientRect.width, l.clientRect.height, { url: l.link.href });
38934      }, this);
38935
38936      // Reset the active page of the PDF to the final page.
38937      var nPages = this.prop.pdf.internal.getNumberOfPages();
38938      this.prop.pdf.setPage(nPages);
38939    }
38940  });
38941};
38942
38943/**
38944 * Generate a PDF from an HTML element or string using html2canvas and jsPDF.
38945 *
38946 * @param {Element|string} source The source element or HTML string.
38947 * @param {Object=} opt An object of optional settings: 'margin', 'filename',
38948 *    'image' ('type' and 'quality'), and 'html2canvas' / 'jspdf', which are
38949 *    sent as settings to their corresponding functions.
38950 */
38951var html2pdf = function html2pdf(src, opt) {
38952  // Create a new worker with the given options.
38953  var worker = new html2pdf.Worker(opt);
38954
38955  if (src) {
38956    // If src is specified, perform the traditional 'simple' operation.
38957    return worker.from(src).save();
38958  } else {
38959    // Otherwise, return the worker for new Promise-based operation.
38960    return worker;
38961  }
38962};
38963html2pdf.Worker = Worker;
38964
38965return html2pdf;
38966
38967})));
38968
38969!function(t){function e(n){if(a[n])return a[n].exports;
38969var i=a[n]={exports:{},id:n,loaded:!1};return t[n].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var a={};return e.m=t,e.c=a,e.p="dist/",e(0)}([function(t,e,a){"use strict";var n=a(1),i=a(19);!function(){var t=HTMLCanvasElement.prototype.toDataURL;window.CanvasPngCompression={Base64Writer:i.Base64Writer,PngWriter:n.PngWriter,replaceToDataURL:function(e){e=e||{},HTMLCanvasElement.prototype.toDataURL=function(a,r){var s=this;if("undefined"==typeof a||"image/png"===a){var o=s.getContext("2d");"undefined"==typeof r&&(r=1);var l=Math.max(Math.min(Math.round(9-r/(1/9)),9),0);return(new i.Base64Writer).bytesToBase64("data:image/png;base64,",(new n.PngWriter).write(o.getImageData(0,0,s.width,s.height),Object.assign({},e,{level:l})))}return t.apply(this,arguments)}},revertToDataURL:function(){HTMLCanvasElement.prototype.toDataURL=t}}}()},function(t,e,a){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e["default"]=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var a=0;a<e.length;a++){var n=e[a];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,a,n){return a&&t(e.prototype,a),n&&t(e,n),e}}(),s=a(2),o=n(s),l=a(8),h=n(l),d=a(18),u=function(){function t(){i(this,t)}return r(t,[{key:"write",value:function(e,a){a=a||{};var n=[];n.push(new Uint8Array(t.PNG_SIGNATURE)),n.push(this.writeIHDRChunk(e.width,e.height));var i=(0,d.filter)(e),r=o.deflate(i,Object.assign({level:0,windowBits:15,chunkSize:32768,strategy:3},a));n.push(this.writeIDATChunk(r)),n.push(this.writeIENDChunk());var s=n.reduce(function(t,e){return e.length+t},0),l=0;return n.reduce(function(t,e){return t.set(e,l),l+=e.length,t},new Uint8Array(s))}},{key:"writeIHDRChunk",value:function(e,a){var n=new Uint8Array(13);return t._writeAsBigEndian(n,e,0),t._writeAsBigEndian(n,a,4),n[8]=8,n[9]=6,n[10]=0,n[11]=0,n[12]=0,this._writeChunk(t.TYPE_IHDR,n)}},{key:"writeIDATChunk",value:function(e){return this._writeChunk(t.TYPE_IDAT,e)}},{key:"writeIENDChunk",value:function(){return this._writeChunk(t.TYPE_IEND,null)}},{key:"_filterData",value:function(e){for(var a=0,n=e.width,i=e.height,r=e.data,s=4*n,o=new Uint8Array((s+1)*i),l=0,h=0,d=0;i>d;d++)o[l]=a,t.copy(r,o,l+1,s,h),l+=s+1,h+=s;return o}},{key:"_writeChunk",value:function(e,a){var n=null!==a?a:{length:0},i=n.length,r=new Uint8Array(i+12);t._writeAsBigEndian(r,i,0),t._writeAsBigEndian(r,e,4),null!==a&&t.copy(a,r,8);var s=r.slice(4,r.length-4);return t._writeAsBigEndian(r,h["default"](0,s,s.length,0),r.length-4),r}}
38969],[{key:"_writeAsBigEndian",value:function(t,e,a){t[a]=e>>>24,t[a+1]=e>>>16,t[a+2]=e>>>8,t[a+3]=e>>>0}},{key:"copy",value:function(t,e,a,n,i){n="undefined"==typeof n||null===n?t.length:n,i="undefined"==typeof i||null===i?0:i,e.set(t.subarray(i,i+n),a)}}]),t}();e.PngWriter=u,u.PNG_SIGNATURE=[137,80,78,71,13,10,26,10],u.TYPE_IHDR=1229472850,u.TYPE_IEND=1229278788,u.TYPE_IDAT=1229209940},function(t,e,a){"use strict";var n=a(3).assign,i=a(4),r=a(12),s=a(16),o={};n(o,i,r,s),t.exports=o},function(t,e){"use strict";var a="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;e.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var a=e.shift();if(a){if("object"!=typeof a)throw new TypeError(a+"must be non-object");for(var n in a)a.hasOwnProperty(n)&&(t[n]=a[n])}}return t},e.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var n={arraySet:function(t,e,a,n,i){if(e.subarray&&t.subarray)return void t.set(e.subarray(a,a+n),i);for(var r=0;n>r;r++)t[i+r]=e[a+r]},flattenChunks:function(t){var e,a,n,i,r,s;for(n=0,e=0,a=t.length;a>e;e++)n+=t[e].length;for(s=new Uint8Array(n),i=0,e=0,a=t.length;a>e;e++)r=t[e],s.set(r,i),i+=r.length;return s}},i={arraySet:function(t,e,a,n,i){for(var r=0;n>r;r++)t[i+r]=e[a+r]},flattenChunks:function(t){return[].concat.apply([],t)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,n)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,i))},e.setTyped(a)},function(t,e,a){"use strict";function n(t,e){var a=new m(e);if(a.push(t,!0),a.err)throw a.msg;return a.result}function i(t,e){return e=e||{},e.raw=!0,n(t,e)}function r(t,e){return e=e||{},e.gzip=!0,n(t,e)}var s=a(5),o=a(3),l=a(10),h=a(9),d=a(11),u=Object.prototype.toString,f=0,_=4,c=0,g=1,w=2,b=-1,p=0,v=8,m=function(t){this.options=o.assign({level:b,method:v,chunkSize:16384,windowBits:15,memLevel:8,strategy:p,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d,this.strm.avail_out=0;var a=s.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==c)throw new Error(h[a]);e.header&&s.deflateSetHeader(this.strm,e.header)};m.prototype.push=function(t,e){var a,n,i=this.strm,r=this.options.chunkSize;if(this.ended)return!1;n=e===~~e?e:e===!0?_:f,"string"==typeof t?i.input=l.string2buf(t):"[object ArrayBuffer]"===u.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;do{if(0===i.avail_out&&(i.output=new o.Buf8(r),i.next_out=0,i.avail_out=r),a=s.deflate(i,n),a!==g&&a!==c)return this.onEnd(a),this.ended=!0,!1;(0===i.avail_out||0===i.avail_in&&(n===_||n===w))&&("string"===this.options.to?this.onData(l.buf2binstring(o.shrinkBuf(i.output,i.next_out))):this.onData(o.shrinkBuf(i.output,i.next_out)))}while((i.avail_in>0||0===i.avail_out)&&a!==g);return n===_?(a=s.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===c):n===w?(this.onEnd(c),i.avail_out=0,!0):!0},m.prototype.onData=function(t){this.chunks.push(t)},m.prototype.onEnd=function(t){t===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Deflate=m,e.deflate=n,e.deflateRaw=i,e.gzip=r},function(t,e,a){"use strict";function n(t,e){return t.msg=I[e],e}function i(t){return(t<<1)-(t>4?9:0)}function r(t){for(var e=t.length;--e>=0;)t[e]=0}function s(t){var e=t.state,a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(S.arraySet(t.output,e.pending_buf,e.pending_out,a,t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))}function o(t,e){C._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,s(t.strm)}function l(t,e){t.pending_buf[t.pending++]=e}function h(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function d(t,e,a,n){var i=t.avail_in;return i>n&&(i=n),0===i?0:(t.avail_in-=i,S.arraySet(e,t.input,t.next_in,i,a),1===t.state.wrap?t.adler=R(t.adler,e,i,a):2===t.state.wrap&&(t.adler=Z(t.adler,e,i,a)),t.next_in+=i,t.total_in+=i,i)}function u(t,e){var a,n,i=t.max_chain_length,r=t.strstart,s=t.prev_length,o=t.nice_match,l=t.strstart>t.w_size-ht?t.strstart-(t.w_size-ht):0,h=t.window,d=t.w_mask,u=t.prev,f
38969=t.strstart+lt,_=h[r+s-1],c=h[r+s];t.prev_length>=t.good_match&&(i>>=2),o>t.lookahead&&(o=t.lookahead);do if(a=e,h[a+s]===c&&h[a+s-1]===_&&h[a]===h[r]&&h[++a]===h[r+1]){r+=2,a++;do;while(h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&h[++r]===h[++a]&&f>r);if(n=lt-(f-r),r=f-lt,n>s){if(t.match_start=e,s=n,n>=o)break;_=h[r+s-1],c=h[r+s]}}while((e=u[e&d])>l&&0!==--i);return s<=t.lookahead?s:t.lookahead}function f(t){var e,a,n,i,r,s=t.w_size;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=s+(s-ht)){S.arraySet(t.window,t.window,s,s,0),t.match_start-=s,t.strstart-=s,t.block_start-=s,a=t.hash_size,e=a;do n=t.head[--e],t.head[e]=n>=s?n-s:0;while(--a);a=s,e=a;do n=t.prev[--e],t.prev[e]=n>=s?n-s:0;while(--a);i+=s}if(0===t.strm.avail_in)break;if(a=d(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=ot)for(r=t.strstart-t.insert,t.ins_h=t.window[r],t.ins_h=(t.ins_h<<t.hash_shift^t.window[r+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[r+ot-1])&t.hash_mask,t.prev[r&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=r,r++,t.insert--,!(t.lookahead+t.insert<ot)););}while(t.lookahead<ht&&0!==t.strm.avail_in)}function _(t,e){var a=65535;for(a>t.pending_buf_size-5&&(a=t.pending_buf_size-5);;){if(t.lookahead<=1){if(f(t),0===t.lookahead&&e===T)return pt;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+a;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,o(t,!1),0===t.strm.avail_out))return pt;if(t.strstart-t.block_start>=t.w_size-ht&&(o(t,!1),0===t.strm.avail_out))return pt}return t.insert=0,e===O?(o(t,!0),0===t.strm.avail_out?mt:kt):t.strstart>t.block_start&&(o(t,!1),0===t.strm.avail_out)?pt:pt}function c(t,e){for(var a,n;;){if(t.lookahead<ht){if(f(t),t.lookahead<ht&&e===T)return pt;if(0===t.lookahead)break}if(a=0,t.lookahead>=ot&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ot-1])&t.hash_mask,a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-ht&&(t.match_length=u(t,a)),t.match_length>=ot)if(n=C._tr_tally(t,t.strstart-t.match_start,t.match_length-ot),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=ot){t.match_length--;do t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ot-1])&t.hash_mask,a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart;while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else n=C._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(o(t,!1),0===t.strm.avail_out))return pt}return t.insert=t.strstart<ot-1?t.strstart:ot-1,e===O?(o(t,!0),0===t.strm.avail_out?mt:kt):t.last_lit&&(o(t,!1),0===t.strm.avail_out)?pt:vt}function g(t,e){for(var a,n,i;;){if(t.lookahead<ht){if(f(t),t.lookahead<ht&&e===T)return pt;if(0===t.lookahead)break}if(a=0,t.lookahead>=ot&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ot-1])&t.hash_mask,a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=ot-1,0!==a&&t.prev_length<t.max_lazy_match&&t.strstart-a<=t.w_size-ht&&(t.match_length=u(t,a),t.match_length<=5&&(t.strategy===Y||t.match_length===ot&&t.strstart-t.match_start>4096)&&(t.match_length=ot-1)),t.prev_length>=ot&&t.match_length<=t.prev_length){i=t.strstart+t.lookahead-ot,n=C._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-ot),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=i&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+ot-1])&t.hash_mask,a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart);while(0!==--t.prev_length);if(t.match_available=0,t.match_length=ot-1,t.strstart++,n&&(o(t,!1),0===t.strm.avail_out))return pt}else if(t.match_available){if(n=C._tr_tally(t,0,t.window[t.strstart-1]),n&&o(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return pt}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=C._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<ot-1?t.strstart:ot-1,e===O?(o(t,!0),0===t.strm.avail_out?mt:kt):t.last_lit&&(o(t,!1),0===t.strm.avail_out)?pt:vt}function w(t,e){for(var a,n,i,r,s=t.window;;){if(t.lookahead<=lt){if(f(t),t.lookahead<=lt&&e===T)return pt;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=ot&&t.strstart>0&&(i=t.strstart-1,n=s[i],n===s[++i]&&n===s[++i]&&n===s[++i])){r=t.strstart+lt;do;while(n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&r>i);t.match_length=lt-(r-i),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=ot?(a=C._tr_tally(t,1,t.match_length-ot),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=C._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(o(t,!1),0===t.strm.avail_out))return pt}return t.insert=0,e===O?(o(t,!0),0===t.strm.avail_out?mt:kt):t.last_lit&&(o(t,!1),0===t.strm.avail_out)?pt:vt}function b(t,e){for(var a;;){if(0===t.lookahead&&(f(t),0===t.lookahead)){if(e===T)return pt;break}if(t.match_length=0,a=C._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(o(t,!1),0===t.strm.avail_out))return pt}return t.insert=0,e===O?(o(t,!0),0===t.strm.avail_out?mt:kt):t.last_lit&&(o(t,!1),0===t.strm.avail_out)?pt:vt}function p(t){t.window_size=2*t.w_size,r(t.head),t.max_lazy_match=A[t.level].max_lazy,t.good_match=A[t.level].good_length,t.nice_match=A[t.level].nice_length,t.max_chain_length=A[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=ot-1,t.match_available=0,t.ins_h=0}function v(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=J,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new S.Buf16(2*rt),this.dyn_dtree=new S.Buf16(2*(2*nt+1)),this.bl_tree=new S.Buf16(2*(2*it+1)),r(this.dyn_ltree),r(this.dyn_dtree),r(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new S.Buf16(st+1),this.heap=new S.Buf16(2*at+1),r(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new S.Buf16(2*at+1),r(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function m(t){var e;
38969return t&&t.state?(t.total_in=t.total_out=0,t.data_type=q,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?ut:wt,t.adler=2===e.wrap?0:1,e.last_flush=T,C._tr_init(e),L):n(t,P)}function k(t){var e=m(t);return e===L&&p(t.state),e}function y(t,e){return t&&t.state?2!==t.state.wrap?P:(t.state.gzhead=e,L):P}function x(t,e,a,i,r,s){if(!t)return P;var o=1;if(e===j&&(e=6),0>i?(o=0,i=-i):i>15&&(o=2,i-=16),1>r||r>Q||a!==J||8>i||i>15||0>e||e>9||0>s||s>G)return n(t,P);8===i&&(i=9);var l=new v;return t.state=l,l.strm=t,l.wrap=o,l.gzhead=null,l.w_bits=i,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=r+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+ot-1)/ot),l.window=new S.Buf8(2*l.w_size),l.head=new S.Buf16(l.hash_size),l.prev=new S.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new S.Buf8(l.pending_buf_size),l.d_buf=l.lit_bufsize>>1,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=s,l.method=a,k(t)}function z(t,e){return x(t,e,J,V,$,X)}function B(t,e){var a,o,d,u;if(!t||!t.state||e>U||0>e)return t?n(t,P):P;if(o=t.state,!t.output||!t.input&&0!==t.avail_in||o.status===bt&&e!==O)return n(t,0===t.avail_out?F:P);if(o.strm=t,a=o.last_flush,o.last_flush=e,o.status===ut)if(2===o.wrap)t.adler=0,l(o,31),l(o,139),l(o,8),o.gzhead?(l(o,(o.gzhead.text?1:0)+(o.gzhead.hcrc?2:0)+(o.gzhead.extra?4:0)+(o.gzhead.name?8:0)+(o.gzhead.comment?16:0)),l(o,255&o.gzhead.time),l(o,o.gzhead.time>>8&255),l(o,o.gzhead.time>>16&255),l(o,o.gzhead.time>>24&255),l(o,9===o.level?2:o.strategy>=K||o.level<2?4:0),l(o,255&o.gzhead.os),o.gzhead.extra&&o.gzhead.extra.length&&(l(o,255&o.gzhead.extra.length),l(o,o.gzhead.extra.length>>8&255)),o.gzhead.hcrc&&(t.adler=Z(t.adler,o.pending_buf,o.pending,0)),o.gzindex=0,o.status=ft):(l(o,0),l(o,0),l(o,0),l(o,0),l(o,0),l(o,9===o.level?2:o.strategy>=K||o.level<2?4:0),l(o,yt),o.status=wt);else{var f=J+(o.w_bits-8<<4)<<8,_=-1;_=o.strategy>=K||o.level<2?0:o.level<6?1:6===o.level?2:3,f|=_<<6,0!==o.strstart&&(f|=dt),f+=31-f%31,o.status=wt,h(o,f),0!==o.strstart&&(h(o,t.adler>>>16),h(o,65535&t.adler)),t.adler=1}if(o.status===ft)if(o.gzhead.extra){for(d=o.pending;o.gzindex<(65535&o.gzhead.extra.length)&&(o.pending!==o.pending_buf_size||(o.gzhead.hcrc&&o.pending>d&&(t.adler=Z(t.adler,o.pending_buf,o.pending-d,d)),s(t),d=o.pending,o.pending!==o.pending_buf_size));)l(o,255&o.gzhead.extra[o.gzindex]),o.gzindex++;o.gzhead.hcrc&&o.pending>d&&(t.adler=Z(t.adler,o.pending_buf,o.pending-d,d)),o.gzindex===o.gzhead.extra.length&&(o.gzindex=0,o.status=_t)}else o.status=_t;if(o.status===_t)if(o.gzhead.name){d=o.pending;do{if(o.pending===o.pending_buf_size&&(o.gzhead.hcrc&&o.pending>d&&(t.adler=Z(t.adler,o.pending_buf,o.pending-d,d)),s(t),d=o.pending,o.pending===o.pending_buf_size)){u=1;break}u=o.gzindex<o.gzhead.name.length?255&o.gzhead.name.charCodeAt(o.gzindex++):0,l(o,u)}while(0!==u);o.gzhead.hcrc&&o.pending>d&&(t.adler=Z(t.adler,o.pending_buf,o.pending-d,d)),0===u&&(o.gzindex=0,o.status=ct)}else o.status=ct;
38969if(o.status===ct)if(o.gzhead.comment){d=o.pending;do{if(o.pending===o.pending_buf_size&&(o.gzhead.hcrc&&o.pending>d&&(t.adler=Z(t.adler,o.pending_buf,o.pending-d,d)),s(t),d=o.pending,o.pending===o.pending_buf_size)){u=1;break}u=o.gzindex<o.gzhead.comment.length?255&o.gzhead.comment.charCodeAt(o.gzindex++):0,l(o,u)}while(0!==u);o.gzhead.hcrc&&o.pending>d&&(t.adler=Z(t.adler,o.pending_buf,o.pending-d,d)),0===u&&(o.status=gt)}else o.status=gt;if(o.status===gt&&(o.gzhead.hcrc?(o.pending+2>o.pending_buf_size&&s(t),o.pending+2<=o.pending_buf_size&&(l(o,255&t.adler),l(o,t.adler>>8&255),t.adler=0,o.status=wt)):o.status=wt),0!==o.pending){if(s(t),0===t.avail_out)return o.last_flush=-1,L}else if(0===t.avail_in&&i(e)<=i(a)&&e!==O)return n(t,F);if(o.status===bt&&0!==t.avail_in)return n(t,F);if(0!==t.avail_in||0!==o.lookahead||e!==T&&o.status!==bt){var c=o.strategy===K?b(o,e):o.strategy===W?w(o,e):A[o.level].func(o,e);if((c===mt||c===kt)&&(o.status=bt),c===pt||c===mt)return 0===t.avail_out&&(o.last_flush=-1),L;if(c===vt&&(e===D?C._tr_align(o):e!==U&&(C._tr_stored_block(o,0,0,!1),e===N&&(r(o.head),0===o.lookahead&&(o.strstart=0,o.block_start=0,o.insert=0))),s(t),0===t.avail_out))return o.last_flush=-1,L}return e!==O?L:o.wrap<=0?M:(2===o.wrap?(l(o,255&t.adler),l(o,t.adler>>8&255),l(o,t.adler>>16&255),l(o,t.adler>>24&255),l(o,255&t.total_in),l(o,t.total_in>>8&255),l(o,t.total_in>>16&255),l(o,t.total_in>>24&255)):(h(o,t.adler>>>16),h(o,65535&t.adler)),s(t),o.wrap>0&&(o.wrap=-o.wrap),0!==o.pending?L:M)}function E(t){var e;return t&&t.state?(e=t.state.status,e!==ut&&e!==ft&&e!==_t&&e!==ct&&e!==gt&&e!==wt&&e!==bt?n(t,P):(t.state=null,e===wt?n(t,H):L)):P}var A,S=a(3),C=a(6),R=a(7),Z=a(8),I=a(9),T=0,D=1,N=3,O=4,U=5,L=0,M=1,P=-2,H=-3,F=-5,j=-1,Y=1,K=2,W=3,G=4,X=0,q=2,J=8,Q=9,V=15,$=8,tt=29,et=256,at=et+1+tt,nt=30,it=19,rt=2*at+1,st=15,ot=3,lt=258,ht=lt+ot+1,dt=32,ut=42,ft=69,_t=73,ct=91,gt=103,wt=113,bt=666,pt=1,vt=2,mt=3,kt=4,yt=3,xt=function(t,e,a,n,i){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=n,this.func=i};A=[new xt(0,0,0,0,_),new xt(4,4,8,4,c),new xt(4,5,16,8,c),new xt(4,6,32,32,c),new xt(4,4,16,16,g),new xt(8,16,32,32,g),new xt(8,16,128,128,g),new xt(8,32,128,256,g),new xt(32,128,258,1024,g),new xt(32,258,258,4096,g)],e.deflateInit=z,e.deflateInit2=x,e.deflateReset=k,e.deflateResetKeep=m,e.deflateSetHeader=y,e.deflate=B,e.deflateEnd=E,e.deflateInfo="pako deflate (from Nodeca project)"},function(t,e,a){"use strict";function n(t){for(var e=t.length;--e>=0;)t[e]=0}function i(t){return 256>t?st[t]:st[256+(t>>>7)]}function r(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function s(t,e,a){t.bi_valid>G-a?(t.bi_buf|=e<<t.bi_valid&65535,r(t,t.bi_buf),t.bi_buf=e>>G-t.bi_valid,t.bi_valid+=a-G):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=a)}function o(t,e,a){s(t,a[2*e],a[2*e+1])}function l(t,e){var a=0;do a|=1&t,t>>>=1,a<<=1;while(--e>0);return a>>>1}function h(t){16===t.bi_valid?(r(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}function d(t,e){var a,n,i,r,s,o,l=e.dyn_tree,h=e.max_code,d=e.stat_desc.static_tree,u=e.stat_desc.has_stree,f=e.stat_desc.extra_bits,_=e.stat_desc.extra_base,c=e.stat_desc.max_length,g=0;for(r=0;W>=r;r++)t.bl_count[r]=0;for(l[2*t.heap[t.heap_max]+1]=0,a=t.heap_max+1;K>a;a++)n=t.heap[a],r=l[2*l[2*n+1]+1]+1,r>c&&(r=c,g++),l[2*n+1]=r,n>h||(t.bl_count[r]++,s=0,n>=_&&(s=f[n-_]),o=l[2*n],t.opt_len+=o*(r+s),u&&(t.static_len+=o*(d[2*n+1]+s)));if(0!==g){do{for(r=c-1;0===t.bl_count[r];)r--;t.bl_count[r]--,t.bl_count[r+1]+=2,t.bl_count[c]--,g-=2}while(g>0);for(r=c;0!==r;r--)for(n=t.bl_count[r];0!==n;)i=t.heap[--a],i>h||(l[2*i+1]!==r&&(t.opt_len+=(r-l[2*i+1])*l[2*i],l[2*i+1]=r),n--)}}function u(t,e,a){var n,i,r=new Array(W+1),s=0;for(n=1;W>=n;n++)r[n]=s=s+a[n-1]<<1;for(i=0;e>=i;i++){var o=t[2*i+1];0!==o&&(t[2*i]=l(r[o]++,o))}}function f(){var t,e,a,n,i,r=new Array(W+1);for(a=0,n=0;P-1>n;n++)for(lt[n]=a,t=0;t<1<<$[n];t++)ot[a++]=n;for(ot[a-1]=n,i=0,n=0;16>n;n++)for(ht[n]=i,t=0;t<1<<tt[n];t++)st[i++]=n;for(i>>=7;j>n;n++)for(ht[n]=i<<7,t=0;t<1<<tt[n]-7;t++)st[256+i++]=n;for(e=0;W>=e;e++)r[e]=0;for(t=0;143>=t;)it[2*t+1]=8,t++,r[8]++;for(;255>=t;)it[2*t+1]=9,t++,r[9]++;for(;279>=t;)it[2*t+1]=7,t++,r[7]++;for(;287>=t;)it[2*t+1]=8,t++,r[8]++;for(u(it,F+1,r),t=0;j>t;t++)rt[2*t+1]=5,rt[2*t]=l(t,5);dt=new _t(it,$,H+1,F,W),ut=new _t(rt,tt,0,j,W),ft=new _t(new Array(0),et,0,Y,X)}function _(t){var e;
38969for(e=0;F>e;e++)t.dyn_ltree[2*e]=0;for(e=0;j>e;e++)t.dyn_dtree[2*e]=0;for(e=0;Y>e;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*q]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function c(t){t.bi_valid>8?r(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function g(t,e,a,n){c(t),n&&(r(t,a),r(t,~a)),R.arraySet(t.pending_buf,t.window,e,a,t.pending),t.pending+=a}function w(t,e,a,n){var i=2*e,r=2*a;return t[i]<t[r]||t[i]===t[r]&&n[e]<=n[a]}function b(t,e,a){for(var n=t.heap[a],i=a<<1;i<=t.heap_len&&(i<t.heap_len&&w(e,t.heap[i+1],t.heap[i],t.depth)&&i++,!w(e,n,t.heap[i],t.depth));)t.heap[a]=t.heap[i],a=i,i<<=1;t.heap[a]=n}function p(t,e,a){var n,r,l,h,d=0;if(0!==t.last_lit)do n=t.pending_buf[t.d_buf+2*d]<<8|t.pending_buf[t.d_buf+2*d+1],r=t.pending_buf[t.l_buf+d],d++,0===n?o(t,r,e):(l=ot[r],o(t,l+H+1,e),h=$[l],0!==h&&(r-=lt[l],s(t,r,h)),n--,l=i(n),o(t,l,a),h=tt[l],0!==h&&(n-=ht[l],s(t,n,h)));while(d<t.last_lit);o(t,q,e)}function v(t,e){var a,n,i,r=e.dyn_tree,s=e.stat_desc.static_tree,o=e.stat_desc.has_stree,l=e.stat_desc.elems,h=-1;for(t.heap_len=0,t.heap_max=K,a=0;l>a;a++)0!==r[2*a]?(t.heap[++t.heap_len]=h=a,t.depth[a]=0):r[2*a+1]=0;for(;t.heap_len<2;)i=t.heap[++t.heap_len]=2>h?++h:0,r[2*i]=1,t.depth[i]=0,t.opt_len--,o&&(t.static_len-=s[2*i+1]);for(e.max_code=h,a=t.heap_len>>1;a>=1;a--)b(t,r,a);i=l;do a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],b(t,r,1),n=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=n,r[2*i]=r[2*a]+r[2*n],t.depth[i]=(t.depth[a]>=t.depth[n]?t.depth[a]:t.depth[n])+1,r[2*a+1]=r[2*n+1]=i,t.heap[1]=i++,b(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],d(t,e),u(r,h,t.bl_count)}function m(t,e,a){var n,i,r=-1,s=e[1],o=0,l=7,h=4;for(0===s&&(l=138,h=3),e[2*(a+1)+1]=65535,n=0;a>=n;n++)i=s,s=e[2*(n+1)+1],++o<l&&i===s||(h>o?t.bl_tree[2*i]+=o:0!==i?(i!==r&&t.bl_tree[2*i]++,t.bl_tree[2*J]++):10>=o?t.bl_tree[2*Q]++:t.bl_tree[2*V]++,o=0,r=i,0===s?(l=138,h=3):i===s?(l=6,h=3):(l=7,h=4))}function k(t,e,a){var n,i,r=-1,l=e[1],h=0,d=7,u=4;for(0===l&&(d=138,u=3),n=0;a>=n;n++)if(i=l,l=e[2*(n+1)+1],!(++h<d&&i===l)){if(u>h){do o(t,i,t.bl_tree);while(0!==--h)}else 0!==i?(i!==r&&(o(t,i,t.bl_tree),h--),o(t,J,t.bl_tree),s(t,h-3,2)):10>=h?(o(t,Q,t.bl_tree),s(t,h-3,3)):(o(t,V,t.bl_tree),s(t,h-11,7));h=0,r=i,0===l?(d=138,u=3):i===l?(d=6,u=3):(d=7,u=4)}}function y(t){var e;for(m(t,t.dyn_ltree,t.l_desc.max_code),m(t,t.dyn_dtree,t.d_desc.max_code),v(t,t.bl_desc),e=Y-1;e>=3&&0===t.bl_tree[2*at[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}function x(t,e,a,n){var i;for(s(t,e-257,5),s(t,a-1,5),s(t,n-4,4),i=0;n>i;i++)s(t,t.bl_tree[2*at[i]+1],3);k(t,t.dyn_ltree,e-1),k(t,t.dyn_dtree,a-1)}function z(t){var e,a=4093624447;for(e=0;31>=e;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return I;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return T;for(e=32;H>e;e++)if(0!==t.dyn_ltree[2*e])return T;return I}function B(t){gt||(f(),gt=!0),t.l_desc=new ct(t.dyn_ltree,dt),t.d_desc=new ct(t.dyn_dtree,ut),t.bl_desc=new ct(t.bl_tree,ft),t.bi_buf=0,t.bi_valid=0,_(t)}function E(t,e,a,n){s(t,(N<<1)+(n?1:0),3),g(t,e,a,!0)}function A(t){s(t,O<<1,3),o(t,q,it),h(t)}function S(t,e,a,n){var i,r,o=0;t.level>0?(t.strm.data_type===D&&(t.strm.data_type=z(t)),v(t,t.l_desc),v(t,t.d_desc),o=y(t),i=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,i>=r&&(i=r)):i=r=a+5,i>=a+4&&-1!==e?E(t,e,a,n):t.strategy===Z||r===i?(s(t,(O<<1)+(n?1:0),3),p(t,it,rt)):(s(t,(U<<1)+(n?1:0),3),x(t,t.l_desc.max_code+1,t.d_desc.max_code+1,o+1),p(t,t.dyn_ltree,t.dyn_dtree)),_(t),n&&c(t)}function C(t,e,a){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&a,t.last_lit++,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(ot[a]+H+1)]++,t.dyn_dtree[2*i(e)]++),t.last_lit===t.lit_bufsize-1}var R=a(3),Z=4,I=0,T=1,D=2,N=0,O=1,U=2,L=3,M=258,P=29,H=256,F=H+1+P,j=30,Y=19,K=2*F+1,W=15,G=16,X=7,q=256,J=16,Q=17,V=18,$=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],tt=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],et=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],at=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],nt=512,it=new Array(2*(F+2));n(it);var rt=new Array(2*j);n(rt);var st=new Array(nt);n(st);var ot=new Array(M-L+1);n(ot);var lt=new Array(P);n(lt);var ht=new Array(j);n(ht);var dt,ut,ft,_t=function(t,e,a,n,i){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=n,this.max_length=i,this.has_stree=t&&t.length},ct=function(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e},gt=!1;e._tr_init=B,e._tr_stored_block=E,e._tr_flush_block=S,e._tr_tally=C,e._tr_align=A},function(t,e){"use strict";function a(t,e,a,n){for(var i=65535&t|0,r=t>>>16&65535|0,s=0;0!==a;){s=a>2e3?2e3:a,a-=s;do i=i+e[n++]|0,r=r+i|0;while(--s);i%=65521,r%=65521}return i|r<<16|0}t.exports=a},function(t,e){"use strict";function a(){for(var t,e=[],a=0;256>a;a++){t=a;for(var n=0;8>n;n++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e}function n(t,e,a,n){var r=i,s=n+a;t=-1^t;for(var o=n;s>o;o++)t=t>>>8^r[255&(t^e[o])];return-1^t}var i=a();t.exports=n},function(t,e){"use strict";
38969t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(t,e,a){"use strict";function n(t,e){if(65537>e&&(t.subarray&&s||!t.subarray&&r))return String.fromCharCode.apply(null,i.shrinkBuf(t,e));for(var a="",n=0;e>n;n++)a+=String.fromCharCode(t[n]);return a}var i=a(3),r=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch(o){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(o){s=!1}for(var l=new i.Buf8(256),h=0;256>h;h++)l[h]=h>=252?6:h>=248?5:h>=240?4:h>=224?3:h>=192?2:1;l[254]=l[254]=1,e.string2buf=function(t){var e,a,n,r,s,o=t.length,l=0;for(r=0;o>r;r++)a=t.charCodeAt(r),55296===(64512&a)&&o>r+1&&(n=t.charCodeAt(r+1),56320===(64512&n)&&(a=65536+(a-55296<<10)+(n-56320),r++)),l+=128>a?1:2048>a?2:65536>a?3:4;for(e=new i.Buf8(l),s=0,r=0;l>s;r++)a=t.charCodeAt(r),55296===(64512&a)&&o>r+1&&(n=t.charCodeAt(r+1),56320===(64512&n)&&(a=65536+(a-55296<<10)+(n-56320),r++)),128>a?e[s++]=a:2048>a?(e[s++]=192|a>>>6,e[s++]=128|63&a):65536>a?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},e.buf2binstring=function(t){return n(t,t.length)},e.binstring2buf=function(t){for(var e=new i.Buf8(t.length),a=0,n=e.length;n>a;a++)e[a]=t.charCodeAt(a);return e},e.buf2string=function(t,e){var a,i,r,s,o=e||t.length,h=new Array(2*o);for(i=0,a=0;o>a;)if(r=t[a++],128>r)h[i++]=r;else if(s=l[r],s>4)h[i++]=65533,a+=s-1;else{for(r&=2===s?31:3===s?15:7;s>1&&o>a;)r=r<<6|63&t[a++],s--;s>1?h[i++]=65533:65536>r?h[i++]=r:(r-=65536,h[i++]=55296|r>>10&1023,h[i++]=56320|1023&r)}return n(h,i)},e.utf8border=function(t,e){var a;for(e=e||t.length,e>t.length&&(e=t.length),a=e-1;a>=0&&128===(192&t[a]);)a--;return 0>a?e:0===a?e:a+l[t[a]]>e?a:e}},function(t,e){"use strict";function a(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}t.exports=a},function(t,e,a){"use strict";function n(t,e){var a=new _(e);if(a.push(t,!0),a.err)throw a.msg;return a.result}function i(t,e){return e=e||{},e.raw=!0,n(t,e)}var r=a(13),s=a(3),o=a(10),l=a(16),h=a(9),d=a(11),u=a(17),f=Object.prototype.toString,_=function(t){this.options=s.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0===(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d,this.strm.avail_out=0;var a=r.inflateInit2(this.strm,e.windowBits);if(a!==l.Z_OK)throw new Error(h[a]);this.header=new u,r.inflateGetHeader(this.strm,this.header)};_.prototype.push=function(t,e){var a,n,i,h,d,u=this.strm,_=this.options.chunkSize,c=!1;if(this.ended)return!1;n=e===~~e?e:e===!0?l.Z_FINISH:l.Z_NO_FLUSH,"string"==typeof t?u.input=o.binstring2buf(t):"[object ArrayBuffer]"===f.call(t)?u.input=new Uint8Array(t):u.input=t,u.next_in=0,u.avail_in=u.input.length;do{if(0===u.avail_out&&(u.output=new s.Buf8(_),u.next_out=0,u.avail_out=_),a=r.inflate(u,l.Z_NO_FLUSH),a===l.Z_BUF_ERROR&&c===!0&&(a=l.Z_OK,c=!1),a!==l.Z_STREAM_END&&a!==l.Z_OK)return this.onEnd(a),this.ended=!0,!1;u.next_out&&(0===u.avail_out||a===l.Z_STREAM_END||0===u.avail_in&&(n===l.Z_FINISH||n===l.Z_SYNC_FLUSH))&&("string"===this.options.to?(i=o.utf8border(u.output,u.next_out),h=u.next_out-i,d=o.buf2string(u.output,i),u.next_out=h,u.avail_out=_-h,h&&s.arraySet(u.output,u.output,i,h,0),this.onData(d)):this.onData(s.shrinkBuf(u.output,u.next_out))),0===u.avail_in&&0===u.avail_out&&(c=!0)}while((u.avail_in>0||0===u.avail_out)&&a!==l.Z_STREAM_END);return a===l.Z_STREAM_END&&(n=l.Z_FINISH),n===l.Z_FINISH?(a=r.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===l.Z_OK):n===l.Z_SYNC_FLUSH?(this.onEnd(l.Z_OK),u.avail_out=0,!0):!0},_.prototype.onData=function(t){this.chunks.push(t)},_.prototype.onEnd=function(t){t===l.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Inflate=_,e.inflate=n,e.inflateRaw=i,e.ungzip=n},function(t,e,a){"use strict";function n(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function i(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new b.Buf16(320),this.work=new b.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function r(t){var e;return t&&t.state?(e=t.state,
38970t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=O,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new b.Buf32(ct),e.distcode=e.distdyn=new b.Buf32(gt),e.sane=1,e.back=-1,S):Z}function s(t){var e;return t&&t.state?(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,r(t)):Z}function o(t,e){var a,n;return t&&t.state?(n=t.state,0>e?(a=0,e=-e):(a=(e>>4)+1,48>e&&(e&=15)),e&&(8>e||e>15)?Z:(null!==n.window&&n.wbits!==e&&(n.window=null),n.wrap=a,n.wbits=e,s(t))):Z}function l(t,e){var a,n;return t?(n=new i,t.state=n,n.window=null,a=o(t,e),a!==S&&(t.state=null),a):Z}function h(t){return l(t,bt)}function d(t){if(pt){var e;
38970for(g=new b.Buf32(512),w=new b.Buf32(32),e=0;144>e;)t.lens[e++]=8;for(;256>e;)t.lens[e++]=9;for(;280>e;)t.lens[e++]=7;for(;288>e;)t.lens[e++]=8;for(k(x,t.lens,0,288,g,0,t.work,{bits:9}),e=0;32>e;)t.lens[e++]=5;k(z,t.lens,0,32,w,0,t.work,{bits:5}),pt=!1}t.lencode=g,t.lenbits=9,t.distcode=w,t.distbits=5}function u(t,e,a,n){var i,r=t.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new b.Buf8(r.wsize)),n>=r.wsize?(b.arraySet(r.window,e,a-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(i=r.wsize-r.wnext,i>n&&(i=n),b.arraySet(r.window,e,a-n,i,r.wnext),n-=i,n?(b.arraySet(r.window,e,a-n,n,0),r.wnext=n,r.whave=r.wsize):(r.wnext+=i,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=i))),0}function f(t,e){var a,i,r,s,o,l,h,f,_,c,g,w,ct,gt,wt,bt,pt,vt,mt,kt,yt,xt,zt,Bt,Et=0,At=new b.Buf8(4),St=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return Z;a=t.state,a.mode===G&&(a.mode=X),o=t.next_out,r=t.output,h=t.avail_out,s=t.next_in,i=t.input,l=t.avail_in,f=a.hold,_=a.bits,c=l,g=h,xt=S;t:for(;;)switch(a.mode){case O:if(0===a.wrap){a.mode=X;break}for(;16>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}if(2&a.wrap&&35615===f){a.check=0,At[0]=255&f,At[1]=f>>>8&255,a.check=v(a.check,At,2,0),f=0,_=0,a.mode=U;break}if(a.flags=0,a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&f)<<8)+(f>>8))%31){t.msg="incorrect header check",a.mode=ut;break}if((15&f)!==N){t.msg="unknown compression method",a.mode=ut;break}if(f>>>=4,_-=4,yt=(15&f)+8,0===a.wbits)a.wbits=yt;else if(yt>a.wbits){t.msg="invalid window size",a.mode=ut;break}a.dmax=1<<yt,t.adler=a.check=1,a.mode=512&f?K:G,f=0,_=0;break;case U:for(;16>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}if(a.flags=f,(255&a.flags)!==N){t.msg="unknown compression method",a.mode=ut;break}if(57344&a.flags){t.msg="unknown header flags set",a.mode=ut;break}a.head&&(a.head.text=f>>8&1),512&a.flags&&(At[0]=255&f,At[1]=f>>>8&255,a.check=v(a.check,At,2,0)),f=0,_=0,a.mode=L;case L:for(;32>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}a.head&&(a.head.time=f),512&a.flags&&(At[0]=255&f,At[1]=f>>>8&255,At[2]=f>>>16&255,At[3]=f>>>24&255,a.check=v(a.check,At,4,0)),f=0,_=0,a.mode=M;case M:for(;16>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}a.head&&(a.head.xflags=255&f,a.head.os=f>>8),512&a.flags&&(At[0]=255&f,At[1]=f>>>8&255,a.check=v(a.check,At,2,0)),f=0,_=0,a.mode=P;case P:if(1024&a.flags){for(;16>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}a.length=f,a.head&&(a.head.extra_len=f),512&a.flags&&(At[0]=255&f,At[1]=f>>>8&255,a.check=v(a.check,At,2,0)),f=0,_=0}else a.head&&(a.head.extra=null);a.mode=H;case H:if(1024&a.flags&&(w=a.length,w>l&&(w=l),w&&(a.head&&(yt=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Array(a.head.extra_len)),b.arraySet(a.head.extra,i,s,w,yt)),512&a.flags&&(a.check=v(a.check,i,w,s)),l-=w,s+=w,a.length-=w),a.length))break t;a.length=0,a.mode=F;case F:if(2048&a.flags){if(0===l)break t;w=0;do yt=i[s+w++],a.head&&yt&&a.length<65536&&(a.head.name+=String.fromCharCode(yt));while(yt&&l>w);if(512&a.flags&&(a.check=v(a.check,i,w,s)),l-=w,s+=w,yt)break t}else a.head&&(a.head.name=null);a.length=0,a.mode=j;case j:if(4096&a.flags){if(0===l)break t;w=0;do yt=i[s+w++],a.head&&yt&&a.length<65536&&(a.head.comment+=String.fromCharCode(yt));while(yt&&l>w);if(512&a.flags&&(a.check=v(a.check,i,w,s)),l-=w,s+=w,yt)break t}else a.head&&(a.head.comment=null);a.mode=Y;case Y:if(512&a.flags){for(;16>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}if(f!==(65535&a.check)){t.msg="header crc mismatch",a.mode=ut;break}f=0,_=0}a.head&&(a.head.hcrc=a.flags>>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=G;break;case K:for(;32>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}t.adler=a.check=n(f),f=0,_=0,a.mode=W;case W:if(0===a.havedict)return t.next_out=o,t.avail_out=h,t.next_in=s,t.avail_in=l,a.hold=f,a.bits=_,R;t.adler=a.check=1,a.mode=G;case G:if(e===E||e===A)break t;case X:if(a.last){f>>>=7&_,_-=7&_,a.mode=lt;break}for(;3>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}switch(a.last=1&f,f>>>=1,_-=1,3&f){case 0:a.mode=q;break;case 1:if(d(a),a.mode=et,e===A){f>>>=2,_-=2;break t}break;case 2:a.mode=V;break;case 3:t.msg="invalid block type",a.mode=ut}f>>>=2,_-=2;break;case q:for(f>>>=7&_,_-=7&_;32>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}if((65535&f)!==(f>>>16^65535)){t.msg="invalid stored block lengths",a.mode=ut;break}if(a.length=65535&f,f=0,_=0,a.mode=J,e===A)break t;case J:a.mode=Q;case Q:if(w=a.length){if(w>l&&(w=l),w>h&&(w=h),0===w)break t;b.arraySet(r,i,s,w,o),l-=w,s+=w,h-=w,o+=w,a.length-=w;break}a.mode=G;break;case V:for(;14>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}if(a.nlen=(31&f)+257,f>>>=5,_-=5,a.ndist=(31&f)+1,f>>>=5,_-=5,a.ncode=(15&f)+4,f>>>=4,_-=4,a.nlen>286||a.ndist>30){t.msg="too many length or distance symbols",a.mode=ut;break}a.have=0,a.mode=$;case $:for(;a.have<a.ncode;){for(;3>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}
38970a.lens[St[a.have++]]=7&f,f>>>=3,_-=3}for(;a.have<19;)a.lens[St[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,zt={bits:a.lenbits},xt=k(y,a.lens,0,19,a.lencode,0,a.work,zt),a.lenbits=zt.bits,xt){t.msg="invalid code lengths set",a.mode=ut;break}a.have=0,a.mode=tt;case tt:for(;a.have<a.nlen+a.ndist;){for(;Et=a.lencode[f&(1<<a.lenbits)-1],wt=Et>>>24,bt=Et>>>16&255,pt=65535&Et,!(_>=wt);){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}if(16>pt)f>>>=wt,_-=wt,a.lens[a.have++]=pt;else{if(16===pt){for(Bt=wt+2;Bt>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}if(f>>>=wt,_-=wt,0===a.have){t.msg="invalid bit length repeat",a.mode=ut;break}yt=a.lens[a.have-1],w=3+(3&f),f>>>=2,_-=2}else if(17===pt){for(Bt=wt+3;Bt>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}f>>>=wt,_-=wt,yt=0,w=3+(7&f),f>>>=3,_-=3}else{for(Bt=wt+7;Bt>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}f>>>=wt,_-=wt,yt=0,w=11+(127&f),f>>>=7,_-=7}if(a.have+w>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=ut;break}for(;w--;)a.lens[a.have++]=yt}}if(a.mode===ut)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block",a.mode=ut;break}if(a.lenbits=9,zt={bits:a.lenbits},xt=k(x,a.lens,0,a.nlen,a.lencode,0,a.work,zt),a.lenbits=zt.bits,xt){t.msg="invalid literal/lengths set",a.mode=ut;break}if(a.distbits=6,a.distcode=a.distdyn,zt={bits:a.distbits},xt=k(z,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,zt),a.distbits=zt.bits,xt){t.msg="invalid distances set",a.mode=ut;break}if(a.mode=et,e===A)break t;case et:a.mode=at;case at:if(l>=6&&h>=258){t.next_out=o,t.avail_out=h,t.next_in=s,t.avail_in=l,a.hold=f,a.bits=_,m(t,g),o=t.next_out,r=t.output,h=t.avail_out,s=t.next_in,i=t.input,l=t.avail_in,f=a.hold,_=a.bits,a.mode===G&&(a.back=-1);break}for(a.back=0;Et=a.lencode[f&(1<<a.lenbits)-1],wt=Et>>>24,bt=Et>>>16&255,pt=65535&Et,!(_>=wt);){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}if(bt&&0===(240&bt)){for(vt=wt,mt=bt,kt=pt;Et=a.lencode[kt+((f&(1<<vt+mt)-1)>>vt)],wt=Et>>>24,bt=Et>>>16&255,pt=65535&Et,!(_>=vt+wt);){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}f>>>=vt,_-=vt,a.back+=vt}if(f>>>=wt,_-=wt,a.back+=wt,a.length=pt,0===bt){a.mode=ot;break}if(32&bt){a.back=-1,a.mode=G;break}if(64&bt){t.msg="invalid literal/length code",a.mode=ut;break}a.extra=15&bt,a.mode=nt;case nt:if(a.extra){for(Bt=a.extra;Bt>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}a.length+=f&(1<<a.extra)-1,f>>>=a.extra,_-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=it;case it:for(;Et=a.distcode[f&(1<<a.distbits)-1],wt=Et>>>24,bt=Et>>>16&255,pt=65535&Et,!(_>=wt);){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}if(0===(240&bt)){for(vt=wt,mt=bt,kt=pt;Et=a.distcode[kt+((f&(1<<vt+mt)-1)>>vt)],wt=Et>>>24,bt=Et>>>16&255,pt=65535&Et,!(_>=vt+wt);){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}f>>>=vt,_-=vt,a.back+=vt}if(f>>>=wt,_-=wt,a.back+=wt,64&bt){t.msg="invalid distance code",a.mode=ut;break}a.offset=pt,a.extra=15&bt,a.mode=rt;case rt:if(a.extra){for(Bt=a.extra;Bt>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}a.offset+=f&(1<<a.extra)-1,f>>>=a.extra,_-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=ut;break}a.mode=st;case st:if(0===h)break t;if(w=g-h,a.offset>w){if(w=a.offset-w,w>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=ut;break}w>a.wnext?(w-=a.wnext,ct=a.wsize-w):ct=a.wnext-w,w>a.length&&(w=a.length),gt=a.window}else gt=r,ct=o-a.offset,w=a.length;w>h&&(w=h),h-=w,a.length-=w;do r[o++]=gt[ct++];while(--w);0===a.length&&(a.mode=at);break;case ot:if(0===h)break t;r[o++]=a.length,h--,a.mode=at;break;case lt:if(a.wrap){for(;32>_;){if(0===l)break t;l--,f|=i[s++]<<_,_+=8}if(g-=h,t.total_out+=g,a.total+=g,g&&(t.adler=a.check=a.flags?v(a.check,r,g,o-g):p(a.check,r,g,o-g)),g=h,(a.flags?f:n(f))!==a.check){t.msg="incorrect data check",a.mode=ut;break}f=0,_=0}a.mode=ht;case ht:if(a.wrap&&a.flags){for(;32>_;){if(0===l)break t;l--,f+=i[s++]<<_,_+=8}if(f!==(4294967295&a.total)){t.msg="incorrect length check",a.mode=ut;break}f=0,_=0}a.mode=dt;case dt:xt=C;break t;case ut:xt=I;break t;case ft:return T;case _t:default:return Z}return t.next_out=o,t.avail_out=h,t.next_in=s,t.avail_in=l,a.hold=f,a.bits=_,(a.wsize||g!==t.avail_out&&a.mode<ut&&(a.mode<lt||e!==B))&&u(t,t.output,t.next_out,g-t.avail_out)?(a.mode=ft,T):(c-=t.avail_in,g-=t.avail_out,t.total_in+=c,t.total_out+=g,a.total+=g,a.wrap&&g&&(t.adler=a.check=a.flags?v(a.check,r,g,t.next_out-g):p(a.check,r,g,t.next_out-g)),t.data_type=a.bits+(a.last?64:0)+(a.mode===G?128:0)+(a.mode===et||a.mode===J?256:0),(0===c&&0===g||e===B)&&xt===S&&(xt=D),xt)}function _(t){if(!t||!t.state)return Z;var e=t.state;return e.window&&(e.window=null),t.state=null,S}function c(t,e){var a;return t&&t.state?(a=t.state,0===(2&a.wrap)?Z:(a.head=e,e.done=!1,S)
38970):Z}var g,w,b=a(3),p=a(7),v=a(8),m=a(14),k=a(15),y=0,x=1,z=2,B=4,E=5,A=6,S=0,C=1,R=2,Z=-2,I=-3,T=-4,D=-5,N=8,O=1,U=2,L=3,M=4,P=5,H=6,F=7,j=8,Y=9,K=10,W=11,G=12,X=13,q=14,J=15,Q=16,V=17,$=18,tt=19,et=20,at=21,nt=22,it=23,rt=24,st=25,ot=26,lt=27,ht=28,dt=29,ut=30,ft=31,_t=32,ct=852,gt=592,wt=15,bt=wt,pt=!0;e.inflateReset=s,e.inflateReset2=o,e.inflateResetKeep=r,e.inflateInit=h,e.inflateInit2=l,e.inflate=f,e.inflateEnd=_,e.inflateGetHeader=c,e.inflateInfo="pako inflate (from Nodeca project)"},function(t,e){"use strict";var a=30,n=12;t.exports=function(t,e){var i,r,s,o,l,h,d,u,f,_,c,g,w,b,p,v,m,k,y,x,z,B,E,A,S;i=t.state,r=t.next_in,A=t.input,s=r+(t.avail_in-5),o=t.next_out,S=t.output,l=o-(e-t.avail_out),h=o+(t.avail_out-257),d=i.dmax,u=i.wsize,f=i.whave,_=i.wnext,c=i.window,g=i.hold,w=i.bits,b=i.lencode,p=i.distcode,v=(1<<i.lenbits)-1,m=(1<<i.distbits)-1;t:do{15>w&&(g+=A[r++]<<w,w+=8,g+=A[r++]<<w,w+=8),k=b[g&v];e:for(;;){if(y=k>>>24,g>>>=y,w-=y,y=k>>>16&255,0===y)S[o++]=65535&k;else{if(!(16&y)){if(0===(64&y)){k=b[(65535&k)+(g&(1<<y)-1)];continue e}if(32&y){i.mode=n;break t}t.msg="invalid literal/length code",i.mode=a;break t}x=65535&k,y&=15,y&&(y>w&&(g+=A[r++]<<w,w+=8),x+=g&(1<<y)-1,g>>>=y,w-=y),15>w&&(g+=A[r++]<<w,w+=8,g+=A[r++]<<w,w+=8),k=p[g&m];a:for(;;){if(y=k>>>24,g>>>=y,w-=y,y=k>>>16&255,!(16&y)){if(0===(64&y)){k=p[(65535&k)+(g&(1<<y)-1)];continue a}t.msg="invalid distance code",i.mode=a;break t}if(z=65535&k,y&=15,y>w&&(g+=A[r++]<<w,w+=8,y>w&&(g+=A[r++]<<w,w+=8)),z+=g&(1<<y)-1,z>d){t.msg="invalid distance too far back",i.mode=a;break t}if(g>>>=y,w-=y,y=o-l,z>y){if(y=z-y,y>f&&i.sane){t.msg="invalid distance too far back",i.mode=a;break t}if(B=0,E=c,0===_){if(B+=u-y,x>y){x-=y;do S[o++]=c[B++];while(--y);B=o-z,E=S}}else if(y>_){if(B+=u+_-y,y-=_,x>y){x-=y;do S[o++]=c[B++];while(--y);if(B=0,x>_){y=_,x-=y;do S[o++]=c[B++];while(--y);B=o-z,E=S}}}else if(B+=_-y,x>y){x-=y;do S[o++]=c[B++];while(--y);B=o-z,E=S}for(;x>2;)S[o++]=E[B++],S[o++]=E[B++],S[o++]=E[B++],x-=3;x&&(S[o++]=E[B++],x>1&&(S[o++]=E[B++]))}else{B=o-z;do S[o++]=S[B++],S[o++]=S[B++],S[o++]=S[B++],x-=3;while(x>2);x&&(S[o++]=S[B++],x>1&&(S[o++]=S[B++]))}break}}break}}while(s>r&&h>o);x=w>>3,r-=x,w-=x<<3,g&=(1<<w)-1,t.next_in=r,t.next_out=o,t.avail_in=s>r?5+(s-r):5-(r-s),t.avail_out=h>o?257+(h-o):257-(o-h),i.hold=g,i.bits=w}},function(t,e,a){"use strict";var n=a(3),i=15,r=852,s=592,o=0,l=1,h=2,d=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],u=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],f=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],_=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(t,e,a,c,g,w,b,p){var v,m,k,y,x,z,B,E,A,S=p.bits,C=0,R=0,Z=0,I=0,T=0,D=0,N=0,O=0,U=0,L=0,M=null,P=0,H=new n.Buf16(i+1),F=new n.Buf16(i+1),j=null,Y=0;for(C=0;i>=C;C++)H[C]=0;for(R=0;c>R;R++)H[e[a+R]]++;for(T=S,I=i;I>=1&&0===H[I];I--);if(T>I&&(T=I),0===I)return g[w++]=20971520,g[w++]=20971520,p.bits=1,0;for(Z=1;I>Z&&0===H[Z];Z++);for(Z>T&&(T=Z),O=1,C=1;i>=C;C++)if(O<<=1,O-=H[C],0>O)return-1;if(O>0&&(t===o||1!==I))return-1;for(F[1]=0,C=1;i>C;C++)F[C+1]=F[C]+H[C];for(R=0;c>R;R++)0!==e[a+R]&&(b[F[e[a+R]]++]=R);if(t===o?(M=j=b,z=19):t===l?(M=d,P-=257,j=u,Y-=257,z=256):(M=f,j=_,z=-1),L=0,R=0,C=Z,x=w,D=T,N=0,k=-1,U=1<<T,y=U-1,t===l&&U>r||t===h&&U>s)return 1;for(var K=0;;){K++,B=C-N,b[R]<z?(E=0,A=b[R]):b[R]>z?(E=j[Y+b[R]],A=M[P+b[R]]):(E=96,A=0),v=1<<C-N,m=1<<D,Z=m;do m-=v,g[x+(L>>N)+m]=B<<24|E<<16|A|0;while(0!==m);for(v=1<<C-1;L&v;)v>>=1;if(0!==v?(L&=v-1,L+=v):L=0,R++,0===--H[C]){if(C===I)break;C=e[a+b[R]]}if(C>T&&(L&y)!==k){for(0===N&&(N=T),x+=Z,D=C-N,O=1<<D;I>D+N&&(O-=H[D+N],!(0>=O));)D++,O<<=1;if(U+=1<<D,t===l&&U>r||t===h&&U>s)return 1;k=L&y,g[k]=T<<24|D<<16|x-w|0}}return 0!==L&&(g[x+L]=C-N<<24|64<<16|0),p.bits=T,0}},function(t,e){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ER
38970ROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(t,e){"use strict";function a(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}t.exports=a},function(t,e,a){"use strict";function n(t,e,a){var n=t+e-a,i=Math.abs(n-t),r=Math.abs(n-e),s=Math.abs(n-a);return r>=i&&s>=i?t:s>=r?e:a}function i(t,e,a,n,i){g.PngWriter.copy(t,n,i,a,e)}function r(t,e,a){for(var n=0,i=e+a,r=e;i>r;r++)n+=Math.abs(t[r]);return n}function s(t,e,a,n,i,r){for(var s=0;a>s;s++){var o=s>=r?t[e+s-r]:0;n[i+s]=t[e+s]-o}}function o(t,e,a,n){for(var i=0,r=0;a>r;r++){var s=r>=n?t[e+r-n]:0,o=t[e+r]-s;i+=Math.abs(o)}return i}function l(t,e,a,n,i){for(var r=0;a>r;r++){var s=e>0?t[e+r-a]:0;n[i+r]=t[e+r]-s}}function h(t,e,a){for(var n=0,i=e+a,r=e;i>r;r++){var s=e>0?t[r-a]:0,o=t[r]-s;n+=Math.abs(o)}return n}function d(t,e,a,n,i,r){for(var s=0;a>s;s++){var o=s>=r?t[e+s-r]:0,l=e>0?t[e+s-a]:0;n[i+s]=t[e+s]-(o+l>>1)}}function u(t,e,a,n){for(var i=0,r=0;a>r;r++){var s=r>=n?t[e+r-n]:0,o=e>0?t[e+r-a]:0,l=t[e+r]-(s+o>>1);i+=Math.abs(l)}return i}function f(t,e,a,i,r,s){for(var o=0;a>o;o++){var l=o>=s?t[e+o-s]:0,h=e>0?t[e+o-a]:0,d=e>0&&o>=s?t[e+o-(a+s)]:0;i[r+o]=t[e+o]-n(l,h,d)}}function _(t,e,a,i){for(var r=0,s=0;a>s;s++){var o=s>=i?t[e+s-i]:0,l=e>0?t[e+s-a]:0,h=e>0&&s>=i?t[e+s-(a+i)]:0,d=t[e+s]-n(o,l,h);r+=Math.abs(d)}return r}function c(t){for(var e=t.width,a=t.height,n=t.data,i=4,r=e*i,s=new Uint8Array((r+1)*a),o=0,l=0,h=1,d=0;a>d;d++){for(var u=1/0,f=1;f<w.length;f++){var _=w[f].sum(n,l,r,i);u>_&&(u=_,h=f)}var c=w[h];s[o]=c.type,c.filter(n,l,r,s,o+1,i),o+=r+1,l+=r}return s}Object.defineProperty(e,"__esModule",{value:!0}),e.filter=c;var g=a(1),w=[{filter:i,sum:r,type:0},{filter:s,sum:o,type:1},{filter:l,sum:h,type:2},{filter:d,sum:u,type:3},{filter:f,sum:_,type:4}]},function(t,e){"use strict";function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(t,e){for(var a=0;a<e.length;a++){var n=e[a];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,a,n){return a&&t(e.prototype,a),n&&t(e,n),e}}(),i=function(){function t(){a(this,t)}return n(t,[{key:"bytesToBase64",value:function(t,e){for(var a="",n=0;n<e.byteLength;n++)a+=String.fromCharCode(e[n]);return t+btoa(a)}}]),t}();e.Base64Writer=i}]);
vendor: 44,287 bytes, lines 38971-40802
38971/*!
38972 * fancyBox - jQuery Plugin
38973 * version: 2.1.5 (Fri, 14 Jun 2013)
38974 * requires jQuery v1.6 or later
38975 *
38976 * Examples at http://fancyapps.com/fancybox/
38977 * License: www.fancyapps.com/fancybox/#license
38978 *
38979 * Copyright 2012 Janis Skarnelis - [email protected]
38980 *
38981 */
38982
38983;(function (window, document, $, undefined) {
38984	"use strict";
38985
38986	var H = $("html"),
38987		W = $(window),
38988		D = $(document),
38989		F = $.fancybox = function () {
38990			F.open.apply( this, arguments );
38991		},
38992		IE =  navigator.userAgent.match(/msie/i),
38993		didUpdate	= null,
38994		isTouch		= document.createTouch !== undefined,
38995
38996		isQuery	= function(obj) {
38997			return obj && obj.hasOwnProperty && obj instanceof $;
38998		},
38999		isString = function(str) {
39000			return str && $.type(str) === "string";
39001		},
39002		isPercentage = function(str) {
39003			return isString(str) && str.indexOf('%') > 0;
39004		},
39005		isScrollable = function(el) {
39006			return (el && !(el.style.overflow && el.style.overflow === 'hidden') && ((el.clientWidth && el.scrollWidth > el.clientWidth) || (el.clientHeight && el.scrollHeight > el.clientHeight)));
39007		},
39008		getScalar = function(orig, dim) {
39009			var value = parseInt(orig, 10) || 0;
39010
39011			if (dim && isPercentage(orig)) {
39012				value = F.getViewport()[ dim ] / 100 * value;
39013			}
39014
39015			return Math.ceil(value);
39016		},
39017		getValue = function(value, dim) {
39018			return getScalar(value, dim) + 'px';
39019		};
39020
39021	$.extend(F, {
39022		// The current version of fancyBox
39023		version: '2.1.5',
39024
39025		defaults: {
39026			padding : 15,
39027			margin  : 20,
39028
39029			width     : 800,
39030			height    : 600,
39031			minWidth  : 100,
39032			minHeight : 100,
39033			maxWidth  : 9999,
39034			maxHeight : 9999,
39035			pixelRatio: 1, // Set to 2 for retina display support
39036
39037			autoSize   : true,
39038			autoHeight : false,
39039			autoWidth  : false,
39040
39041			autoResize  : true,
39042			autoCenter  : !isTouch,
39043			fitToView   : true,
39044			aspectRatio : false,
39045			topRatio    : 0.5,
39046			leftRatio   : 0.5,
39047
39048			scrolling : 'auto', // 'auto', 'yes' or 'no'
39049			wrapCSS   : '',
39050
39051			arrows     : true,
39052			closeBtn   : true,
39053			closeClick : false,
39054			nextClick  : false,
39055			mouseWheel : true,
39056			autoPlay   : false,
39057			playSpeed  : 3000,
39058			preload    : 3,
39059			modal      : false,
39060			loop       : true,
39061
39062			ajax  : {
39063				dataType : 'html',
39064				headers  : { 'X-fancyBox': true }
39065			},
39066			iframe : {
39067				scrolling : 'auto',
39068				preload   : true
39069			},
39070			swf : {
39071				wmode: 'transparent',
39072				allowfullscreen   : 'true',
39073				allowscriptaccess : 'always'
39074			},
39075
39076			keys  : {
39077				next : {
39078					13 : 'left', // enter
39079					34 : 'up',   // page down
39080					39 : 'left', // right arrow
39081					40 : 'up'    // down arrow
39082				},
39083				prev : {
39084					8  : 'right',  // backspace
39085					33 : 'down',   // page up
39086					37 : 'right',  // left arrow
39087					38 : 'down'    // up arrow
39088				},
39089				close  : [27], // escape key
39090				play   : [32], // space - start/stop slideshow
39091				toggle : [70]  // letter "f" - toggle fullscreen
39092			},
39093
39094			direction : {
39095				next : 'left',
39096				prev : 'right'
39097			},
39098
39099			scrollOutside  : true,
39100
39101			// Override some properties
39102			index   : 0,
39103			type    : null,
39104			href    : null,
39105			content : null,
39106			title   : null,
39107
39108			// HTML templates
39109			tpl: {
39110				wrap     : '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',
39111				image    : '<img class="fancybox-image" src="{href}" alt="" />',
39112				iframe   : '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen' + (IE ? ' allowtransparency="true"' : '') + '></iframe>',
39113				error    : '<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>',
39114				closeBtn : '<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>',
39115				next     : '<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',
39116				prev     : '<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>',
39117				loading  : '<div id="fancybox-loading"><div></div></div>'
39118			},
39119
39120			// Properties for each animation type
39121			// Opening fancyBox
39122			openEffect  : 'fade', // 'elastic', 'fade' or 'none'
39123			openSpeed   : 250,
39124			openEasing  : 'swing',
39125			openOpacity : true,
39126			openMethod  : 'zoomIn',
39127
39128			// Closing fancyBox
39129			closeEffect  : 'fade', // 'elastic', 'fade' or 'none'
39130			closeSpeed   : 250,
39131			closeEasing  : 'swing',
39132			closeOpacity : true,
39133			closeMethod  : 'zoomOut',
39134
39135			// Changing next gallery item
39136			nextEffect : 'elastic', // 'elastic', 'fade' or 'none'
39137			nextSpeed  : 250,
39138			nextEasing : 'swing',
39139			nextMethod : 'changeIn',
39140
39141			// Changing previous gallery item
39142			prevEffect : 'elastic', // 'elastic', 'fade' or 'none'
39143			prevSpeed  : 250,
39144			prevEasing : 'swing',
39145			prevMethod : 'changeOut',
39146
39147			// Enable default helpers
39148			helpers : {
39149				overlay : true,
39150				title   : true
39151			},
39152
39153			// Callbacks
39154			onCancel     : $.noop, // If canceling
39155			beforeLoad   : $.noop, // Before loading
39156			afterLoad    : $.noop, // After loading
39157			beforeShow   : $.noop, // Before changing in current item
39158			afterShow    : $.noop, // After opening
39159			beforeChange : $.noop, // Before changing gallery item
39160			beforeClose  : $.noop, // Before closing
39161			afterClose   : $.noop  // After closing
39162		},
39163
39164		//Current state
39165		group    : {}, // Selected group
39166		opts     : {}, // Group options
39167		previous : null,  // Previous element
39168		coming   : null,  // Element being loaded
39169		current  : null,  // Currently loaded element
39170		isActive : false, // Is activated
39171		isOpen   : false, // Is currently open
39172		isOpened : false, // Have been fully opened at least once
39173
39174		wrap  : null,
39175		skin  : null,
39176		outer : null,
39177		inner : null,
39178
39179		player : {
39180			timer    : null,
39181			isActive : false
39182		},
39183
39184		// Loaders
39185		ajaxLoad   : null,
39186		imgPreload : null,
39187
39188		// Some collections
39189		transitions : {},
39190		helpers     : {},
39191
39192		/*
39193		 *	Static methods
39194		 */
39195
39196		open: function (group, opts) {
39197			if (!group) {
39198				return;
39199			}
39200
39201			if (!$.isPlainObject(opts)) {
39202				opts = {};
39203			}
39204
39205			// Close if already active
39206			if (false === F.close(true)) {
39207				return;
39208			}
39209
39210			// Normalize group
39211			if (!$.isArray(group)) {
39212				group = isQuery(group) ? $(group).get() : [group];
39213			}
39214
39215			// Recheck if the type of each element is `object` and set content type (image, ajax, etc)
39216			$.each(group, function(i, element) {
39217				var obj = {},
39218					href,
39219					title,
39220					content,
39221					type,
39222					rez,
39223					hrefParts,
39224					selector;
39225
39226				if ($.type(element) === "object") {
39227					// Check if is DOM element
39228					if (element.nodeType) {
39229						element = $(element);
39230					}
39231
39232					if (isQuery(element)) {
39233						obj = {
39234							href    : element.data('fancybox-href') || element.attr('href'),
39235							title   : $('<div/>').text( element.data('fancybox-title') || element.attr('title') || '' ).html(),
39236							isDom   : true,
39237							element : element
39238						};
39239
39240						if ($.metadata) {
39241							$.extend(true, obj, element.metadata());
39242						}
39243
39244					} else {
39245						obj = element;
39246					}
39247				}
39248
39249				href  = opts.href  || obj.href || (isString(element) ? element : null);
39250				title = opts.title !== undefined ? opts.title : obj.title || '';
39251
39252				content = opts.content || obj.content;
39253				type    = content ? 'html' : (opts.type  || obj.type);
39254
39255				if (!type && obj.isDom) {
39256					type = element.data('fancybox-type');
39257
39258					if (!type) {
39259						rez  = element.prop('class').match(/fancybox\.(\w+)/);
39260						type = rez ? rez[1] : null;
39261					}
39262				}
39263
39264				if (isString(href)) {
39265					// Try to guess the content type
39266					if (!type) {
39267						if (F.isImage(href)) {
39268							type = 'image';
39269
39270						} else if (F.isSWF(href)) {
39271							type = 'swf';
39272
39273						} else if (href.charAt(0) === '#') {
39274							type = 'inline';
39275
39276						} else if (isString(element)) {
39277							type    = 'html';
39278							content = element;
39279						}
39280					}
39281
39282					// Split url into two pieces with source url and content selector, e.g,
39283					// "/mypage.html #my_id" will load "/mypage.html" and display element having id "my_id"
39284					if (type === 'ajax') {
39285						hrefParts = href.split(/\s+/, 2);
39286						href      = hrefParts.shift();
39287						selector  = hrefParts.shift();
39288					}
39289				}
39290
39291				if (!content) {
39292					if (type === 'inline') {
39293						if (href) {
39294							content = $( isString(href) ? href.replace(/.*(?=#[^\s]+$)/, '') : href ); //strip for ie7
39295
39296						} else if (obj.isDom) {
39297							content = element;
39298						}
39299
39300					} else if (type === 'html') {
39301						content = href;
39302
39303					} else if (!type && !href && obj.isDom) {
39304						type    = 'inline';
39305						content = element;
39306					}
39307				}
39308
39309				$.extend(obj, {
39310					href     : href,
39311					type     : type,
39312					content  : content,
39313					title    : title,
39314					selector : selector
39315				});
39316
39317				group[ i ] = obj;
39318			});
39319
39320			// Extend the defaults
39321			F.opts = $.extend(true, {}, F.defaults, opts);
39322
39323			// All options are merged recursive except keys
39324			if (opts.keys !== undefined) {
39325				F.opts.keys = opts.keys ? $.extend({}, F.defaults.keys, opts.keys) : false;
39326			}
39327
39328			F.group = group;
39329
39330			return F._start(F.opts.index);
39331		},
39332
39333		// Cancel image loading or abort ajax request
39334		cancel: function () {
39335			var coming = F.coming;
39336
39337			if (coming && false === F.trigger('onCancel')) {
39338				return;
39339			}
39340
39341			F.hideLoading();
39342
39343			if (!coming) {
39344				return;
39345			}
39346
39347			if (F.ajaxLoad) {
39348				F.ajaxLoad.abort();
39349			}
39350
39351			F.ajaxLoad = null;
39352
39353			if (F.imgPreload) {
39354				F.imgPreload.onload = F.imgPreload.onerror = null;
39355			}
39356
39357			if (coming.wrap) {
39358				coming.wrap.stop(true, true).trigger('onReset').remove();
39359			}
39360
39361			F.coming = null;
39362
39363			// If the first item has been canceled, then clear everything
39364			if (!F.current) {
39365				F._afterZoomOut( coming );
39366			}
39367		},
39368
39369		// Start closing animation if is open; remove immediately if opening/closing
39370		close: function (event) {
39371			F.cancel();
39372
39373			if (false === F.trigger('beforeClose')) {
39374				return;
39375			}
39376
39377			F.unbindEvents();
39378
39379			if (!F.isActive) {
39380				return;
39381			}
39382
39383			if (!F.isOpen || event === true) {
39384				$('.fancybox-wrap').stop(true).trigger('onReset').remove();
39385
39386				F._afterZoomOut();
39387
39388			} else {
39389				F.isOpen = F.isOpened = false;
39390				F.isClosing = true;
39391
39392				$('.fancybox-item, .fancybox-nav').remove();
39393
39394				F.wrap.stop(true, true).removeClass('fancybox-opened');
39395
39396				F.transitions[ F.current.closeMethod ]();
39397			}
39398		},
39399
39400		// Manage slideshow:
39401		//   $.fancybox.play(); - toggle slideshow
39402		//   $.fancybox.play( true ); - start
39403		//   $.fancybox.play( false ); - stop
39404		play: function ( action ) {
39405			var clear = function () {
39406					clearTimeout(F.player.timer);
39407				},
39408				set = function () {
39409					clear();
39410
39411					if (F.current && F.player.isActive) {
39412						F.player.timer = setTimeout(F.next, F.current.playSpeed);
39413					}
39414				},
39415				stop = function () {
39416					clear();
39417
39418					D.unbind('.player');
39419
39420					F.player.isActive = false;
39421
39422					F.trigger('onPlayEnd');
39423				},
39424				start = function () {
39425					if (F.current && (F.current.loop || F.current.index < F.group.length - 1)) {
39426						F.player.isActive = true;
39427
39428						D.bind({
39429							'onCancel.player beforeClose.player' : stop,
39430							'onUpdate.player'   : set,
39431							'beforeLoad.player' : clear
39432						});
39433
39434						set();
39435
39436						F.trigger('onPlayStart');
39437					}
39438				};
39439
39440			if (action === true || (!F.player.isActive && action !== false)) {
39441				start();
39442			} else {
39443				stop();
39444			}
39445		},
39446
39447		// Navigate to next gallery item
39448		next: function ( direction ) {
39449			var current = F.current;
39450
39451			if (current) {
39452				if (!isString(direction)) {
39453					direction = current.direction.next;
39454				}
39455
39456				F.jumpto(current.index + 1, direction, 'next');
39457			}
39458		},
39459
39460		// Navigate to previous gallery item
39461		prev: function ( direction ) {
39462			var current = F.current;
39463
39464			if (current) {
39465				if (!isString(direction)) {
39466					direction = current.direction.prev;
39467				}
39468
39469				F.jumpto(current.index - 1, direction, 'prev');
39470			}
39471		},
39472
39473		// Navigate to gallery item by index
39474		jumpto: function ( index, direction, router ) {
39475			var current = F.current;
39476
39477			if (!current) {
39478				return;
39479			}
39480
39481			index = getScalar(index);
39482
39483			F.direction = direction || current.direction[ (index >= current.index ? 'next' : 'prev') ];
39484			F.router    = router || 'jumpto';
39485
39486			if (current.loop) {
39487				if (index < 0) {
39488					index = current.group.length + (index % current.group.length);
39489				}
39490
39491				index = index % current.group.length;
39492			}
39493
39494			if (current.group[ index ] !== undefined) {
39495				F.cancel();
39496
39497				F._start(index);
39498			}
39499		},
39500
39501		// Center inside viewport and toggle position type to fixed or absolute if needed
39502		reposition: function (e, onlyAbsolute) {
39503			var current = F.current,
39504				wrap    = current ? current.wrap : null,
39505				pos;
39506
39507			if (wrap) {
39508				pos = F._getPosition(onlyAbsolute);
39509
39510				if (e && e.type === 'scroll') {
39511					delete pos.position;
39512
39513					wrap.stop(true, true).animate(pos, 200);
39514
39515				} else {
39516					wrap.css(pos);
39517
39518					current.pos = $.extend({}, current.dim, pos);
39519				}
39520			}
39521		},
39522
39523		update: function (e) {
39524			var type = (e && e.originalEvent && e.originalEvent.type),
39525				anyway = !type || type === 'orientationchange';
39526
39527			if (anyway) {
39528				clearTimeout(didUpdate);
39529
39530				didUpdate = null;
39531			}
39532
39533			if (!F.isOpen || didUpdate) {
39534				return;
39535			}
39536
39537			didUpdate = setTimeout(function() {
39538				var current = F.current;
39539
39540				if (!current || F.isClosing) {
39541					return;
39542				}
39543
39544				F.wrap.removeClass('fancybox-tmp');
39545
39546				if (anyway || type === 'load' || (type === 'resize' && current.autoResize)) {
39547					F._setDimension();
39548				}
39549
39550				if (!(type === 'scroll' && current.canShrink)) {
39551					F.reposition(e);
39552				}
39553
39554				F.trigger('onUpdate');
39555
39556				didUpdate = null;
39557
39558			}, (anyway && !isTouch ? 0 : 300));
39559		},
39560
39561		// Shrink content to fit inside viewport or restore if resized
39562		toggle: function ( action ) {
39563			if (F.isOpen) {
39564				F.current.fitToView = $.type(action) === "boolean" ? action : !F.current.fitToView;
39565
39566				// Help browser to restore document dimensions
39567				if (isTouch) {
39568					F.wrap.removeAttr('style').addClass('fancybox-tmp');
39569
39570					F.trigger('onUpdate');
39571				}
39572
39573				F.update();
39574			}
39575		},
39576
39577		hideLoading: function () {
39578			D.unbind('.loading');
39579
39580			$('#fancybox-loading').remove();
39581		},
39582
39583		showLoading: function () {
39584			var el, viewport;
39585
39586			F.hideLoading();
39587
39588			el = $(F.opts.tpl.loading).click(F.cancel).appendTo('body');
39589
39590			// If user will press the escape-button, the request will be canceled
39591			D.bind('keydown.loading', function(e) {
39592				if ((e.which || e.keyCode) === 27) {
39593					e.preventDefault();
39594
39595					F.cancel();
39596				}
39597			});
39598
39599			if (!F.defaults.fixed) {
39600				viewport = F.getViewport();
39601
39602				el.css({
39603					position : 'absolute',
39604					top  : (viewport.h * 0.5) + viewport.y,
39605					left : (viewport.w * 0.5) + viewport.x
39606				});
39607			}
39608
39609			F.trigger('onLoading');
39610		},
39611
39612		getViewport: function () {
39613			var locked = (F.current && F.current.locked) || false,
39614				rez    = {
39615					x: W.scrollLeft(),
39616					y: W.scrollTop()
39617				};
39618
39619			if (locked && locked.length) {
39620				rez.w = locked[0].clientWidth;
39621				rez.h = locked[0].clientHeight;
39622
39623			} else {
39624				// See http://bugs.jquery.com/ticket/6724
39625				rez.w = isTouch && window.innerWidth  ? window.innerWidth  : W.width();
39626				rez.h = isTouch && window.innerHeight ? window.innerHeight : W.height();
39627			}
39628
39629			return rez;
39630		},
39631
39632		// Unbind the keyboard / clicking actions
39633		unbindEvents: function () {
39634			if (F.wrap && isQuery(F.wrap)) {
39635				F.wrap.unbind('.fb');
39636			}
39637
39638			D.unbind('.fb');
39639			W.unbind('.fb');
39640		},
39641
39642		bindEvents: function () {
39643			var current = F.current,
39644				keys;
39645
39646			if (!current) {
39647				return;
39648			}
39649
39650			// Changing document height on iOS devices triggers a 'resize' event,
39651			// that can change document height... repeating infinitely
39652			W.bind('orientationchange.fb' + (isTouch ? '' : ' resize.fb') + (current.autoCenter && !current.locked ? ' scroll.fb' : ''), F.update);
39653
39654			keys = current.keys;
39655
39656			if (keys) {
39657				D.bind('keydown.fb', function (e) {
39658					var code   = e.which || e.keyCode,
39659						target = e.target || e.srcElement;
39660
39661					// Skip esc key if loading, because showLoading will cancel preloading
39662					if (code === 27 && F.coming) {
39663						return false;
39664					}
39665
39666					// Ignore key combinations and key events within form elements
39667					if (!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey && !(target && (target.type || $(target).is('[contenteditable]')))) {
39668						$.each(keys, function(i, val) {
39669							if (current.group.length > 1 && val[ code ] !== undefined) {
39670								F[ i ]( val[ code ] );
39671
39672								e.preventDefault();
39673								return false;
39674							}
39675
39676							if ($.inArray(code, val) > -1) {
39677								F[ i ] ();
39678
39679								e.preventDefault();
39680								return false;
39681							}
39682						});
39683					}
39684				});
39685			}
39686
39687			if ($.fn.mousewheel && current.mouseWheel) {
39688				F.wrap.bind('mousewheel.fb', function (e, delta, deltaX, deltaY) {
39689					var target = e.target || null,
39690						parent = $(target),
39691						canScroll = false;
39692
39693					while (parent.length) {
39694						if (canScroll || parent.is('.fancybox-skin') || parent.is('.fancybox-wrap')) {
39695							break;
39696						}
39697
39698						canScroll = isScrollable( parent[0] );
39699						parent    = $(parent).parent();
39700					}
39701
39702					if (delta !== 0 && !canScroll) {
39703						if (F.group.length > 1 && !current.canShrink) {
39704							if (deltaY > 0 || deltaX > 0) {
39705								F.prev( deltaY > 0 ? 'down' : 'left' );
39706
39707							} else if (deltaY < 0 || deltaX < 0) {
39708								F.next( deltaY < 0 ? 'up' : 'right' );
39709							}
39710
39711							e.preventDefault();
39712						}
39713					}
39714				});
39715			}
39716		},
39717
39718		trigger: function (event, o) {
39719			var ret, obj = o || F.coming || F.current;
39720
39721			if (obj) {
39722				if ($.isFunction( obj[event] )) {
39723					ret = obj[event].apply(obj, Array.prototype.slice.call(arguments, 1));
39724				}
39725
39726				if (ret === false) {
39727					return false;
39728				}
39729
39730				if (obj.helpers) {
39731					$.each(obj.helpers, function (helper, opts) {
39732						if (opts && F.helpers[helper] && $.isFunction(F.helpers[helper][event])) {
39733							F.helpers[helper][event]($.extend(true, {}, F.helpers[helper].defaults, opts), obj);
39734						}
39735					});
39736				}
39737			}
39738
39739			D.trigger(event);
39740		},
39741
39742		isImage: function (str) {
39743			return isString(str) && str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i);
39744		},
39745
39746		isSWF: function (str) {
39747			return isString(str) && str.match(/\.(swf)((\?|#).*)?$/i);
39748		},
39749
39750		_start: function (index) {
39751			var coming = {},
39752				obj,
39753				href,
39754				type,
39755				margin,
39756				padding;
39757
39758			index = getScalar( index );
39759			obj   = F.group[ index ] || null;
39760
39761			if (!obj) {
39762				return false;
39763			}
39764
39765			coming = $.extend(true, {}, F.opts, obj);
39766
39767			// Convert margin and padding properties to array - top, right, bottom, left
39768			margin  = coming.margin;
39769			padding = coming.padding;
39770
39771			if ($.type(margin) === 'number') {
39772				coming.margin = [margin, margin, margin, margin];
39773			}
39774
39775			if ($.type(padding) === 'number') {
39776				coming.padding = [padding, padding, padding, padding];
39777			}
39778
39779			// 'modal' propery is just a shortcut
39780			if (coming.modal) {
39781				$.extend(true, coming, {
39782					closeBtn   : false,
39783					closeClick : false,
39784					nextClick  : false,
39785					arrows     : false,
39786					mouseWheel : false,
39787					keys       : null,
39788					helpers: {
39789						overlay : {
39790							closeClick : false
39791						}
39792					}
39793				});
39794			}
39795
39796			// 'autoSize' property is a shortcut, too
39797			if (coming.autoSize) {
39798				coming.autoWidth = coming.autoHeight = true;
39799			}
39800
39801			if (coming.width === 'auto') {
39802				coming.autoWidth = true;
39803			}
39804
39805			if (coming.height === 'auto') {
39806				coming.autoHeight = true;
39807			}
39808
39809			/*
39810			 * Add reference to the group, so it`s possible to access from callbacks, example:
39811			 * afterLoad : function() {
39812			 *     this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : '');
39813			 * }
39814			 */
39815
39816			coming.group  = F.group;
39817			coming.index  = index;
39818
39819			// Give a chance for callback or helpers to update coming item (type, title, etc)
39820			F.coming = coming;
39821
39822			if (false === F.trigger('beforeLoad')) {
39823				F.coming = null;
39824
39825				return;
39826			}
39827
39828			type = coming.type;
39829			href = coming.href;
39830
39831			if (!type) {
39832				F.coming = null;
39833
39834				//If we can not determine content type then drop silently or display next/prev item if looping through gallery
39835				if (F.current && F.router && F.router !== 'jumpto') {
39836					F.current.index = index;
39837
39838					return F[ F.router ]( F.direction );
39839				}
39840
39841				return false;
39842			}
39843
39844			F.isActive = true;
39845
39846			if (type === 'image' || type === 'swf') {
39847				coming.autoHeight = coming.autoWidth = false;
39848				coming.scrolling  = 'visible';
39849			}
39850
39851			if (type === 'image') {
39852				coming.aspectRatio = true;
39853			}
39854
39855			if (type === 'iframe' && isTouch) {
39856				coming.scrolling = 'scroll';
39857			}
39858
39859			// Build the neccessary markup
39860			coming.wrap = $(coming.tpl.wrap).addClass('fancybox-' + (isTouch ? 'mobile' : 'desktop') + ' fancybox-type-' + type + ' fancybox-tmp ' + coming.wrapCSS).appendTo( coming.parent || 'body' );
39861
39862			$.extend(coming, {
39863				skin  : $('.fancybox-skin',  coming.wrap),
39864				outer : $('.fancybox-outer', coming.wrap),
39865				inner : $('.fancybox-inner', coming.wrap)
39866			});
39867
39868			$.each(["Top", "Right", "Bottom", "Left"], function(i, v) {
39869				coming.skin.css('padding' + v, getValue(coming.padding[ i ]));
39870			});
39871
39872			F.trigger('onReady');
39873
39874			// Check before try to load; 'inline' and 'html' types need content, others - href
39875			if (type === 'inline' || type === 'html') {
39876				if (!coming.content || !coming.content.length) {
39877					return F._error( 'content' );
39878				}
39879
39880			} else if (!href) {
39881				return F._error( 'href' );
39882			}
39883
39884			if (type === 'image') {
39885				F._loadImage();
39886
39887			} else if (type === 'ajax') {
39888				F._loadAjax();
39889
39890			} else if (type === 'iframe') {
39891				F._loadIframe();
39892
39893			} else {
39894				F._afterLoad();
39895			}
39896		},
39897
39898		_error: function ( type ) {
39899			$.extend(F.coming, {
39900				type       : 'html',
39901				autoWidth  : true,
39902				autoHeight : true,
39903				minWidth   : 0,
39904				minHeight  : 0,
39905				scrolling  : 'no',
39906				hasError   : type,
39907				content    : F.coming.tpl.error
39908			});
39909
39910			F._afterLoad();
39911		},
39912
39913		_loadImage: function () {
39914			// Reset preload image so it is later possible to check "complete" property
39915			var img = F.imgPreload = new Image();
39916
39917			img.onload = function () {
39918				this.onload = this.onerror = null;
39919
39920				F.coming.width  = this.width / F.opts.pixelRatio;
39921				F.coming.height = this.height / F.opts.pixelRatio;
39922
39923				F._afterLoad();
39924			};
39925
39926			img.onerror = function () {
39927				this.onload = this.onerror = null;
39928
39929				F._error( 'image' );
39930			};
39931
39932			img.src = F.coming.href;
39933
39934			if (img.complete !== true) {
39935				F.showLoading();
39936			}
39937		},
39938
39939		_loadAjax: function () {
39940			var coming = F.coming;
39941
39942			F.showLoading();
39943
39944			F.ajaxLoad = $.ajax($.extend({}, coming.ajax, {
39945				url: coming.href,
39946				error: function (jqXHR, textStatus) {
39947					if (F.coming && textStatus !== 'abort') {
39948						F._error( 'ajax', jqXHR );
39949
39950					} else {
39951						F.hideLoading();
39952					}
39953				},
39954				success: function (data, textStatus) {
39955					if (textStatus === 'success') {
39956						coming.content = data;
39957
39958						F._afterLoad();
39959					}
39960				}
39961			}));
39962		},
39963
39964		_loadIframe: function() {
39965			var coming = F.coming,
39966				iframe = $(coming.tpl.iframe.replace(/\{rnd\}/g, new Date().getTime()))
39967					.attr('scrolling', isTouch ? 'auto' : coming.iframe.scrolling)
39968					.attr('src', coming.href);
39969
39970			// This helps IE
39971			$(coming.wrap).bind('onReset', function () {
39972				try {
39973					$(this).find('iframe').hide().attr('src', '//about:blank').end().empty();
39974				} catch (e) {}
39975			});
39976
39977			if (coming.iframe.preload) {
39978				F.showLoading();
39979
39980				iframe.one('load', function() {
39981					$(this).data('ready', 1);
39982
39983					// iOS will lose scrolling if we resize
39984					if (!isTouch) {
39985						$(this).bind('load.fb', F.update);
39986					}
39987
39988					// Without this trick:
39989					//   - iframe won't scroll on iOS devices
39990					//   - IE7 sometimes displays empty iframe
39991					$(this).parents('.fancybox-wrap').width('100%').removeClass('fancybox-tmp').show();
39992
39993					F._afterLoad();
39994				});
39995			}
39996
39997			coming.content = iframe.appendTo( coming.inner );
39998
39999			if (!coming.iframe.preload) {
40000				F._afterLoad();
40001			}
40002		},
40003
40004		_preloadImages: function() {
40005			var group   = F.group,
40006				current = F.current,
40007				len     = group.length,
40008				cnt     = current.preload ? Math.min(current.preload, len - 1) : 0,
40009				item,
40010				i;
40011
40012			for (i = 1; i <= cnt; i += 1) {
40013				item = group[ (current.index + i ) % len ];
40014
40015				if (item.type === 'image' && item.href) {
40016					new Image().src = item.href;
40017				}
40018			}
40019		},
40020
40021		_afterLoad: function () {
40022			var coming   = F.coming,
40023				previous = F.current,
40024				placeholder = 'fancybox-placeholder',
40025				current,
40026				content,
40027				type,
40028				scrolling,
40029				href,
40030				embed;
40031
40032			F.hideLoading();
40033
40034			if (!coming || F.isActive === false) {
40035				return;
40036			}
40037
40038			if (false === F.trigger('afterLoad', coming, previous)) {
40039				coming.wrap.stop(true).trigger('onReset').remove();
40040
40041				F.coming = null;
40042
40043				return;
40044			}
40045
40046			if (previous) {
40047				F.trigger('beforeChange', previous);
40048
40049				previous.wrap.stop(true).removeClass('fancybox-opened')
40050					.find('.fancybox-item, .fancybox-nav')
40051					.remove();
40052			}
40053
40054			F.unbindEvents();
40055
40056			current   = coming;
40057			content   = coming.content;
40058			type      = coming.type;
40059			scrolling = coming.scrolling;
40060
40061			$.extend(F, {
40062				wrap  : current.wrap,
40063				skin  : current.skin,
40064				outer : current.outer,
40065				inner : current.inner,
40066				current  : current,
40067				previous : previous
40068			});
40069
40070			href = current.href;
40071
40072			switch (type) {
40073				case 'inline':
40074				case 'ajax':
40075				case 'html':
40076					if (current.selector) {
40077						content = $('<div>').html(content).find(current.selector);
40078
40079					} else if (isQuery(content)) {
40080						if (!content.data(placeholder)) {
40081							content.data(placeholder, $('<div class="' + placeholder + '"></div>').insertAfter( content ).hide() );
40082						}
40083
40084						content = content.show().detach();
40085
40086						current.wrap.bind('onReset', function () {
40087							if ($(this).find(content).length) {
40088								content.hide().replaceAll( content.data(placeholder) ).data(placeholder, false);
40089							}
40090						});
40091					}
40092				break;
40093
40094				case 'image':
40095					content = current.tpl.image.replace(/\{href\}/g, href);
40096				break;
40097
40098				case 'swf':
40099					content = '<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="' + href + '"></param>';
40100					embed   = '';
40101
40102					$.each(current.swf, function(name, val) {
40103						content += '<param name="' + name + '" value="' + val + '"></param>';
40104						embed   += ' ' + name + '="' + val + '"';
40105					});
40106
40107					content += '<embed src="' + href + '" type="application/x-shockwave-flash" width="100%" height="100%"' + embed + '></embed></object>';
40108				break;
40109			}
40110
40111			if (!(isQuery(content) && content.parent().is(current.inner))) {
40112				current.inner.append( content );
40113			}
40114
40115			// Give a chance for helpers or callbacks to update elements
40116			F.trigger('beforeShow');
40117
40118			// Set scrolling before calculating dimensions
40119			current.inner.css('overflow', scrolling === 'yes' ? 'scroll' : (scrolling === 'no' ? 'hidden' : scrolling));
40120
40121			// Set initial dimensions and start position
40122			F._setDimension();
40123
40124			F.reposition();
40125
40126			F.isOpen = false;
40127			F.coming = null;
40128
40129			F.bindEvents();
40130
40131			if (!F.isOpened) {
40132				$('.fancybox-wrap').not( current.wrap ).stop(true).trigger('onReset').remove();
40133
40134			} else if (previous.prevMethod) {
40135				F.transitions[ previous.prevMethod ]();
40136			}
40137
40138			F.transitions[ F.isOpened ? current.nextMethod : current.openMethod ]();
40139
40140			F._preloadImages();
40141		},
40142
40143		_setDimension: function () {
40144			var viewport   = F.getViewport(),
40145				steps      = 0,
40146				canShrink  = false,
40147				canExpand  = false,
40148				wrap       = F.wrap,
40149				skin       = F.skin,
40150				inner      = F.inner,
40151				current    = F.current,
40152				width      = current.width,
40153				height     = current.height,
40154				minWidth   = current.minWidth,
40155				minHeight  = current.minHeight,
40156				maxWidth   = current.maxWidth,
40157				maxHeight  = current.maxHeight,
40158				scrolling  = current.scrolling,
40159				scrollOut  = current.scrollOutside ? current.scrollbarWidth : 0,
40160				margin     = current.margin,
40161				wMargin    = getScalar(margin[1] + margin[3]),
40162				hMargin    = getScalar(margin[0] + margin[2]),
40163				wPadding,
40164				hPadding,
40165				wSpace,
40166				hSpace,
40167				origWidth,
40168				origHeight,
40169				origMaxWidth,
40170				origMaxHeight,
40171				ratio,
40172				width_,
40173				height_,
40174				maxWidth_,
40175				maxHeight_,
40176				iframe,
40177				body;
40178
40179			// Reset dimensions so we could re-check actual size
40180			wrap.add(skin).add(inner).width('auto').height('auto').removeClass('fancybox-tmp');
40181
40182			wPadding = getScalar(skin.outerWidth(true)  - skin.width());
40183			hPadding = getScalar(skin.outerHeight(true) - skin.height());
40184
40185			// Any space between content and viewport (margin, padding, border, title)
40186			wSpace = wMargin + wPadding;
40187			hSpace = hMargin + hPadding;
40188
40189			origWidth  = isPercentage(width)  ? (viewport.w - wSpace) * getScalar(width)  / 100 : width;
40190			origHeight = isPercentage(height) ? (viewport.h - hSpace) * getScalar(height) / 100 : height;
40191
40192			if (current.type === 'iframe') {
40193				iframe = current.content;
40194
40195				if (current.autoHeight && iframe && iframe.data('ready') === 1) {
40196					try {
40197						if (iframe[0].contentWindow.document.location) {
40198							inner.width( origWidth ).height(9999);
40199
40200							body = iframe.contents().find('body');
40201
40202							if (scrollOut) {
40203								body.css('overflow-x', 'hidden');
40204							}
40205
40206							origHeight = body.outerHeight(true);
40207						}
40208
40209					} catch (e) {}
40210				}
40211
40212			} else if (current.autoWidth || current.autoHeight) {
40213				inner.addClass( 'fancybox-tmp' );
40214
40215				// Set width or height in case we need to calculate only one dimension
40216				if (!current.autoWidth) {
40217					inner.width( origWidth );
40218				}
40219
40220				if (!current.autoHeight) {
40221					inner.height( origHeight );
40222				}
40223
40224				if (current.autoWidth) {
40225					origWidth = inner.width();
40226				}
40227
40228				if (current.autoHeight) {
40229					origHeight = inner.height();
40230				}
40231
40232				inner.removeClass( 'fancybox-tmp' );
40233			}
40234
40235			width  = getScalar( origWidth );
40236			height = getScalar( origHeight );
40237
40238			ratio  = origWidth / origHeight;
40239
40240			// Calculations for the content
40241			minWidth  = getScalar(isPercentage(minWidth) ? getScalar(minWidth, 'w') - wSpace : minWidth);
40242			maxWidth  = getScalar(isPercentage(maxWidth) ? getScalar(maxWidth, 'w') - wSpace : maxWidth);
40243
40244			minHeight = getScalar(isPercentage(minHeight) ? getScalar(minHeight, 'h') - hSpace : minHeight);
40245			maxHeight = getScalar(isPercentage(maxHeight) ? getScalar(maxHeight, 'h') - hSpace : maxHeight);
40246
40247			// These will be used to determine if wrap can fit in the viewport
40248			origMaxWidth  = maxWidth;
40249			origMaxHeight = maxHeight;
40250
40251			if (current.fitToView) {
40252				maxWidth  = Math.min(viewport.w - wSpace, maxWidth);
40253				maxHeight = Math.min(viewport.h - hSpace, maxHeight);
40254			}
40255
40256			maxWidth_  = viewport.w - wMargin;
40257			maxHeight_ = viewport.h - hMargin;
40258
40259			if (current.aspectRatio) {
40260				if (width > maxWidth) {
40261					width  = maxWidth;
40262					height = getScalar(width / ratio);
40263				}
40264
40265				if (height > maxHeight) {
40266					height = maxHeight;
40267					width  = getScalar(height * ratio);
40268				}
40269
40270				if (width < minWidth) {
40271					width  = minWidth;
40272					height = getScalar(width / ratio);
40273				}
40274
40275				if (height < minHeight) {
40276					height = minHeight;
40277					width  = getScalar(height * ratio);
40278				}
40279
40280			} else {
40281				width = Math.max(minWidth, Math.min(width, maxWidth));
40282
40283				if (current.autoHeight && current.type !== 'iframe') {
40284					inner.width( width );
40285
40286					height = inner.height();
40287				}
40288
40289				height = Math.max(minHeight, Math.min(height, maxHeight));
40290			}
40291
40292			// Try to fit inside viewport (including the title)
40293			if (current.fitToView) {
40294				inner.width( width ).height( height );
40295
40296				wrap.width( width + wPadding );
40297
40298				// Real wrap dimensions
40299				width_  = wrap.width();
40300				height_ = wrap.height();
40301
40302				if (current.aspectRatio) {
40303					while ((width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight) {
40304						if (steps++ > 19) {
40305							break;
40306						}
40307
40308						height = Math.max(minHeight, Math.min(maxHeight, height - 10));
40309						width  = getScalar(height * ratio);
40310
40311						if (width < minWidth) {
40312							width  = minWidth;
40313							height = getScalar(width / ratio);
40314						}
40315
40316						if (width > maxWidth) {
40317							width  = maxWidth;
40318							height = getScalar(width / ratio);
40319						}
40320
40321						inner.width( width ).height( height );
40322
40323						wrap.width( width + wPadding );
40324
40325						width_  = wrap.width();
40326						height_ = wrap.height();
40327					}
40328
40329				} else {
40330					width  = Math.max(minWidth,  Math.min(width,  width  - (width_  - maxWidth_)));
40331					height = Math.max(minHeight, Math.min(height, height - (height_ - maxHeight_)));
40332				}
40333			}
40334
40335			if (scrollOut && scrolling === 'auto' && height < origHeight && (width + wPadding + scrollOut) < maxWidth_) {
40336				width += scrollOut;
40337			}
40338
40339			inner.width( width ).height( height );
40340
40341			wrap.width( width + wPadding );
40342
40343			width_  = wrap.width();
40344			height_ = wrap.height();
40345
40346			canShrink = (width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight;
40347			canExpand = current.aspectRatio ? (width < origMaxWidth && height < origMaxHeight && width < origWidth && height < origHeight) : ((width < origMaxWidth || height < origMaxHeight) && (width < origWidth || height < origHeight));
40348
40349			$.extend(current, {
40350				dim : {
40351					width	: getValue( width_ ),
40352					height	: getValue( height_ )
40353				},
40354				origWidth  : origWidth,
40355				origHeight : origHeight,
40356				canShrink  : canShrink,
40357				canExpand  : canExpand,
40358				wPadding   : wPadding,
40359				hPadding   : hPadding,
40360				wrapSpace  : height_ - skin.outerHeight(true),
40361				skinSpace  : skin.height() - height
40362			});
40363
40364			if (!iframe && current.autoHeight && height > minHeight && height < maxHeight && !canExpand) {
40365				inner.height('auto');
40366			}
40367		},
40368
40369		_getPosition: function (onlyAbsolute) {
40370			var current  = F.current,
40371				viewport = F.getViewport(),
40372				margin   = current.margin,
40373				width    = F.wrap.width()  + margin[1] + margin[3],
40374				height   = F.wrap.height() + margin[0] + margin[2],
40375				rez      = {
40376					position: 'absolute',
40377					top  : margin[0],
40378					left : margin[3]
40379				};
40380
40381			if (current.autoCenter && current.fixed && !onlyAbsolute && height <= viewport.h && width <= viewport.w) {
40382				rez.position = 'fixed';
40383
40384			} else if (!current.locked) {
40385				rez.top  += viewport.y;
40386				rez.left += viewport.x;
40387			}
40388
40389			rez.top  = getValue(Math.max(rez.top,  rez.top  + ((viewport.h - height) * current.topRatio)));
40390			rez.left = getValue(Math.max(rez.left, rez.left + ((viewport.w - width)  * current.leftRatio)));
40391
40392			return rez;
40393		},
40394
40395		_afterZoomIn: function () {
40396			var current = F.current;
40397
40398			if (!current) {
40399				return;
40400			}
40401
40402			F.isOpen = F.isOpened = true;
40403
40404			F.wrap.css('overflow', 'visible').addClass('fancybox-opened').hide().show(0);
40405
40406			F.update();
40407
40408			// Assign a click event
40409			if ( current.closeClick || (current.nextClick && F.group.length > 1) ) {
40410				F.inner.css('cursor', 'pointer').bind('click.fb', function(e) {
40411					if (!$(e.target).is('a') && !$(e.target).parent().is('a')) {
40412						e.preventDefault();
40413
40414						F[ current.closeClick ? 'close' : 'next' ]();
40415					}
40416				});
40417			}
40418
40419			// Create a close button
40420			if (current.closeBtn) {
40421				$(current.tpl.closeBtn).appendTo(F.skin).bind('click.fb', function(e) {
40422					e.preventDefault();
40423
40424					F.close();
40425				});
40426			}
40427
40428			// Create navigation arrows
40429			if (current.arrows && F.group.length > 1) {
40430				if (current.loop || current.index > 0) {
40431					$(current.tpl.prev).appendTo(F.outer).bind('click.fb', F.prev);
40432				}
40433
40434				if (current.loop || current.index < F.group.length - 1) {
40435					$(current.tpl.next).appendTo(F.outer).bind('click.fb', F.next);
40436				}
40437			}
40438
40439			F.trigger('afterShow');
40440
40441			// Stop the slideshow if this is the last item
40442			if (!current.loop && current.index === current.group.length - 1) {
40443
40444				F.play( false );
40445
40446			} else if (F.opts.autoPlay && !F.player.isActive) {
40447				F.opts.autoPlay = false;
40448
40449				F.play(true);
40450			}
40451		},
40452
40453		_afterZoomOut: function ( obj ) {
40454			obj = obj || F.current;
40455
40456			$('.fancybox-wrap').trigger('onReset').remove();
40457
40458			$.extend(F, {
40459				group  : {},
40460				opts   : {},
40461				router : false,
40462				current   : null,
40463				isActive  : false,
40464				isOpened  : false,
40465				isOpen    : false,
40466				isClosing : false,
40467				wrap   : null,
40468				skin   : null,
40469				outer  : null,
40470				inner  : null
40471			});
40472
40473			F.trigger('afterClose', obj);
40474		}
40475	});
40476
40477	/*
40478	 *	Default transitions
40479	 */
40480
40481	F.transitions = {
40482		getOrigPosition: function () {
40483			var current  = F.current,
40484				element  = current.element,
40485				orig     = current.orig,
40486				pos      = {},
40487				width    = 50,
40488				height   = 50,
40489				hPadding = current.hPadding,
40490				wPadding = current.wPadding,
40491				viewport = F.getViewport();
40492
40493			if (!orig && current.isDom && element.is(':visible')) {
40494				orig = element.find('img:first');
40495
40496				if (!orig.length) {
40497					orig = element;
40498				}
40499			}
40500
40501			if (isQuery(orig)) {
40502				pos = orig.offset();
40503
40504				if (orig.is('img')) {
40505					width  = orig.outerWidth();
40506					height = orig.outerHeight();
40507				}
40508
40509			} else {
40510				pos.top  = viewport.y + (viewport.h - height) * current.topRatio;
40511				pos.left = viewport.x + (viewport.w - width)  * current.leftRatio;
40512			}
40513
40514			if (F.wrap.css('position') === 'fixed' || current.locked) {
40515				pos.top  -= viewport.y;
40516				pos.left -= viewport.x;
40517			}
40518
40519			pos = {
40520				top     : getValue(pos.top  - hPadding * current.topRatio),
40521				left    : getValue(pos.left - wPadding * current.leftRatio),
40522				width   : getValue(width  + wPadding),
40523				height  : getValue(height + hPadding)
40524			};
40525
40526			return pos;
40527		},
40528
40529		step: function (now, fx) {
40530			var ratio,
40531				padding,
40532				value,
40533				prop       = fx.prop,
40534				current    = F.current,
40535				wrapSpace  = current.wrapSpace,
40536				skinSpace  = current.skinSpace;
40537
40538			if (prop === 'width' || prop === 'height') {
40539				ratio = fx.end === fx.start ? 1 : (now - fx.start) / (fx.end - fx.start);
40540
40541				if (F.isClosing) {
40542					ratio = 1 - ratio;
40543				}
40544
40545				padding = prop === 'width' ? current.wPadding : current.hPadding;
40546				value   = now - padding;
40547
40548				F.skin[ prop ](  getScalar( prop === 'width' ?  value : value - (wrapSpace * ratio) ) );
40549				F.inner[ prop ]( getScalar( prop === 'width' ?  value : value - (wrapSpace * ratio) - (skinSpace * ratio) ) );
40550			}
40551		},
40552
40553		zoomIn: function () {
40554			var current  = F.current,
40555				startPos = current.pos,
40556				effect   = current.openEffect,
40557				elastic  = effect === 'elastic',
40558				endPos   = $.extend({opacity : 1}, startPos);
40559
40560			// Remove "position" property that breaks older IE
40561			delete endPos.position;
40562
40563			if (elastic) {
40564				startPos = this.getOrigPosition();
40565
40566				if (current.openOpacity) {
40567					startPos.opacity = 0.1;
40568				}
40569
40570			} else if (effect === 'fade') {
40571				startPos.opacity = 0.1;
40572			}
40573
40574			F.wrap.css(startPos).animate(endPos, {
40575				duration : effect === 'none' ? 0 : current.openSpeed,
40576				easing   : current.openEasing,
40577				step     : elastic ? this.step : null,
40578				complete : F._afterZoomIn
40579			});
40580		},
40581
40582		zoomOut: function () {
40583			var current  = F.current,
40584				effect   = current.closeEffect,
40585				elastic  = effect === 'elastic',
40586				endPos   = {opacity : 0.1};
40587
40588			if (elastic) {
40589				endPos = this.getOrigPosition();
40590
40591				if (current.closeOpacity) {
40592					endPos.opacity = 0.1;
40593				}
40594			}
40595
40596			F.wrap.animate(endPos, {
40597				duration : effect === 'none' ? 0 : current.closeSpeed,
40598				easing   : current.closeEasing,
40599				step     : elastic ? this.step : null,
40600				complete : F._afterZoomOut
40601			});
40602		},
40603
40604		changeIn: function () {
40605			var current   = F.current,
40606				effect    = current.nextEffect,
40607				startPos  = current.pos,
40608				endPos    = { opacity : 1 },
40609				direction = F.direction,
40610				distance  = 200,
40611				field;
40612
40613			startPos.opacity = 0.1;
40614
40615			if (effect === 'elastic') {
40616				field = direction === 'down' || direction === 'up' ? 'top' : 'left';
40617
40618				if (direction === 'down' || direction === 'right') {
40619					startPos[ field ] = getValue(getScalar(startPos[ field ]) - distance);
40620					endPos[ field ]   = '+=' + distance + 'px';
40621
40622				} else {
40623					startPos[ field ] = getValue(getScalar(startPos[ field ]) + distance);
40624					endPos[ field ]   = '-=' + distance + 'px';
40625				}
40626			}
40627
40628			// Workaround for http://bugs.jquery.com/ticket/12273
40629			if (effect === 'none') {
40630				F._afterZoomIn();
40631
40632			} else {
40633				F.wrap.css(startPos).animate(endPos, {
40634					duration : current.nextSpeed,
40635					easing   : current.nextEasing,
40636					complete : F._afterZoomIn
40637				});
40638			}
40639		},
40640
40641		changeOut: function () {
40642			var previous  = F.previous,
40643				effect    = previous.prevEffect,
40644				endPos    = { opacity : 0.1 },
40645				direction = F.direction,
40646				distance  = 200;
40647
40648			if (effect === 'elastic') {
40649				endPos[ direction === 'down' || direction === 'up' ? 'top' : 'left' ] = ( direction === 'up' || direction === 'left' ? '-' : '+' ) + '=' + distance + 'px';
40650			}
40651
40652			previous.wrap.animate(endPos, {
40653				duration : effect === 'none' ? 0 : previous.prevSpeed,
40654				easing   : previous.prevEasing,
40655				complete : function () {
40656					$(this).trigger('onReset').remove();
40657				}
40658			});
40659		}
40660	};
40661
40662	/*
40663	 *	Overlay helper
40664	 */
40665
40666	F.helpers.overlay = {
40667		defaults : {
40668			closeClick : true,      // if true, fancyBox will be closed when user clicks on the overlay
40669			speedOut   : 200,       // duration of fadeOut animation
40670			showEarly  : true,      // indicates if should be opened immediately or wait until the content is ready
40671			css        : {},        // custom CSS properties
40672			locked     : !isTouch,  // if true, the content will be locked into overlay
40673			fixed      : true       // if false, the overlay CSS position property will not be set to "fixed"
40674		},
40675
40676		overlay : null,      // current handle
40677		fixed   : false,     // indicates if the overlay has position "fixed"
40678		el      : $('html'), // element that contains "the lock"
40679
40680		// Public methods
40681		create : function(opts) {
40682			var parent;
40683
40684			opts = $.extend({}, this.defaults, opts);
40685
40686			if (this.overlay) {
40687				this.close();
40688			}
40689
40690			parent = F.coming ? F.coming.parent : opts.parent;
40691
40692			this.overlay = $('<div class="fancybox-overlay"></div>').appendTo( parent && parent.length ? parent : 'body' );
40693			this.fixed   = false;
40694
40695			if (opts.fixed && F.defaults.fixed) {
40696				this.overlay.addClass('fancybox-overlay-fixed');
40697
40698				this.fixed = true;
40699			}
40700		},
40701
40702		open : function(opts) {
40703			var that = this;
40704
40705			opts = $.extend({}, this.defaults, opts);
40706
40707			if (this.overlay) {
40708				this.overlay.unbind('.overlay').width('auto').height('auto');
40709
40710			} else {
40711				this.create(opts);
40712			}
40713
40714			if (!this.fixed) {
40715				W.bind('resize.overlay', $.proxy( this.update, this) );
40716
40717				this.update();
40718			}
40719
40720			if (opts.closeClick) {
40721				this.overlay.bind('click.overlay', function(e) {
40722					if ($(e.target).hasClass('fancybox-overlay')) {
40723						if (F.isActive) {
40724							F.close();
40725						} else {
40726							that.close();
40727						}
40728
40729						return false;
40730					}
40731				});
40732			}
40733
40734			this.overlay.css( opts.css ).show();
40735		},
40736
40737		close : function() {
40738			W.unbind('resize.overlay');
40739
40740			if (this.el.hasClass('fancybox-lock')) {
40741				$('.fancybox-margin').removeClass('fancybox-margin');
40742
40743				this.el.removeClass('fancybox-lock');
40744
40745				W.scrollTop( this.scrollV ).scrollLeft( this.scrollH );
40746			}
40747
40748			$('.fancybox-overlay').remove().hide();
40749
40750			$.extend(this, {
40751				overlay : null,
40752				fixed   : false
40753			});
40754		},
40755
40756		// Private, callbacks
40757
40758		update : function () {
40759			var width = '100%', offsetWidth;
40760
40761			// Reset width/height so it will not mess
40762			this.overlay.width(width).height('100%');
40763
40764			// jQuery does not return reliable result for IE
40765			if (IE) {
40766				offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth);
40767
40768				if (D.width() > offsetWidth) {
40769					width = D.width();
40770				}
40771
40772			} else if (D.width() > W.width()) {
40773				width = D.width();
40774			}
40775
40776			this.overlay.width(width).height(D.height());
40777		},
40778
40779		// This is where we can manipulate DOM, because later it would cause iframes to reload
40780		onReady : function (opts, obj) {
40781			var overlay = this.overlay;
40782
40783			$('.fancybox-overlay').stop(true, true);
40784
40785			if (!overlay) {
40786				this.create(opts);
40787			}
40788
40789			if (opts.locked && this.fixed && obj.fixed) {
40790				obj.locked = this.overlay.append( obj.wrap );
40791				obj.fixed  = false;
40792			}
40793
40794			if (opts.showEarly === true) {
40795				this.beforeShow.apply(this, arguments);
40796			}
40797		},
40798
40799		beforeShow : function(opts, obj) {
40800			if (obj.locked && !this.el.hasClass('fancybox-lock')) {
40801				if (this.fixPosition !== false) {
40802					$('*
vendor: 1,346 bytes, lines 40802-40860
40802:not(object)').filter(function(){
40803						return ($(this).css('position') === 'fixed' && !$(this).hasClass("fancybox-overlay") && !$(this).hasClass("fancybox-wrap") );
40804					}).addClass('fancybox-margin');
40805				}
40806
40807				this.el.addClass('fancybox-margin');
40808
40809				this.scrollV = W.scrollTop();
40810				this.scrollH = W.scrollLeft();
40811
40812				this.el.addClass('fancybox-lock');
40813
40814				W.scrollTop( this.scrollV ).scrollLeft( this.scrollH );
40815			}
40816
40817			this.open(opts);
40818		},
40819
40820		onUpdate : function() {
40821			if (!this.fixed) {
40822				this.update();
40823			}
40824		},
40825
40826		afterClose: function (opts) {
40827			// Remove overlay if exists and fancyBox is not opening
40828			// (e.g., it is not being open using afterClose callback)
40829			if (this.overlay && !F.coming) {
40830				this.overlay.fadeOut(opts.speedOut, $.proxy( this.close, this ));
40831			}
40832		}
40833	};
40834
40835	/*
40836	 *	Title helper
40837	 */
40838
40839	F.helpers.title = {
40840		defaults : {
40841			type     : 'float', // 'float', 'inside', 'outside' or 'over',
40842			position : 'bottom' // 'top' or 'bottom'
40843		},
40844
40845		beforeShow: function (opts) {
40846			var current = F.current,
40847				text    = current.title,
40848				type    = opts.type,
40849				title,
40850				target;
40851
40852			if ($.isFunction(text)) {
40853				text = text.call(current.element, current);
40854			}
40855
40856			if (!isString(text) || $.trim(text) === '') {
40857				return;
40858			}
40859
40860			title = $('<div class="fancybox-title fancybox-title-' + type + '-wrap">
vendor: 4,225 bytes, lines 40860-41034
40860' + text + '</div>');
40861
40862			switch (type) {
40863				case 'inside':
40864					target = F.skin;
40865				break;
40866
40867				case 'outside':
40868					target = F.wrap;
40869				break;
40870
40871				case 'over':
40872					target = F.inner;
40873				break;
40874
40875				default: // 'float'
40876					target = F.skin;
40877
40878					title.appendTo('body');
40879
40880					if (IE) {
40881						title.width( title.width() );
40882					}
40883
40884					title.wrapInner('<span class="child"></span>');
40885
40886					//Increase bottom margin so this title will also fit into viewport
40887					F.current.margin[2] += Math.abs( getScalar(title.css('margin-bottom')) );
40888				break;
40889			}
40890
40891			title[ (opts.position === 'top' ? 'prependTo'  : 'appendTo') ](target);
40892		}
40893	};
40894
40895	// jQuery plugin initialization
40896	$.fn.fancybox = function (options) {
40897		var index,
40898			that     = $(this),
40899			selector = this.selector || '',
40900			run      = function(e) {
40901				var what = $(this).blur(), idx = index, relType, relVal;
40902
40903				if (!(e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) && !what.is('.fancybox-wrap')) {
40904					relType = options.groupAttr || 'data-fancybox-group';
40905					relVal  = what.attr(relType);
40906
40907					if (!relVal) {
40908						relType = 'rel';
40909						relVal  = what.get(0)[ relType ];
40910					}
40911
40912					if (relVal && relVal !== '' && relVal !== 'nofollow') {
40913						what = selector.length ? $(selector) : that;
40914						what = what.filter('[' + relType + '="' + relVal + '"]');
40915						idx  = what.index(this);
40916					}
40917
40918					options.index = idx;
40919
40920					// Stop an event from bubbling if everything is fine
40921					if (F.open(what, options) !== false) {
40922						e.preventDefault();
40923					}
40924				}
40925			};
40926
40927		options = options || {};
40928		index   = options.index || 0;
40929
40930		if (!selector || options.live === false) {
40931			that.unbind('click.fb-start').bind('click.fb-start', run);
40932
40933		} else {
40934			D.undelegate(selector, 'click.fb-start').delegate(selector + ":not('.fancybox-item, .fancybox-nav')", 'click.fb-start', run);
40935		}
40936
40937		this.filter('[data-fancybox-start=1]').trigger('click');
40938
40939		return this;
40940	};
40941
40942	// Tests that need a body at doc ready
40943	D.ready(function() {
40944		var w1, w2;
40945
40946		if ( $.scrollbarWidth === undefined ) {
40947			// http://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth
40948			$.scrollbarWidth = function() {
40949				var parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body'),
40950					child  = parent.children(),
40951					width  = child.innerWidth() - child.height( 99 ).innerWidth();
40952
40953				parent.remove();
40954
40955				return width;
40956			};
40957		}
40958
40959		if ( $.support.fixedPosition === undefined ) {
40960			$.support.fixedPosition = (function() {
40961				var elem  = $('<div style="position:fixed;top:20px;"></div>').appendTo('body'),
40962					fixed = ( elem[0].offsetTop === 20 || elem[0].offsetTop === 15 );
40963
40964				elem.remove();
40965
40966				return fixed;
40967			}());
40968		}
40969
40970		$.extend(F.defaults, {
40971			scrollbarWidth : $.scrollbarWidth(),
40972			fixed  : $.support.fixedPosition,
40973			parent : $('body')
40974		});
40975
40976		//Get real width of page scroll-bar
40977		w1 = $(window).width();
40978
40979		H.addClass('fancybox-lock-test');
40980
40981		w2 = $(window).width();
40982
40983		H.removeClass('fancybox-lock-test');
40984
40985		$("<style type='text/css'>.fancybox-margin{margin-right:" + (w2 - w1) + "px;}</style>").appendTo("head");
40986	});
40987
40988}(window, document, jQuery));
40989
40990/*!
40991 * Media helper for fancyBox
40992 * version: 1.0.6 (Fri, 14 Jun 2013)
40993 * @requires fancyBox v2.0 or later
40994 *
40995 * Usage:
40996 *     $(".fancybox").fancybox({
40997 *         helpers : {
40998 *             media: true
40999 *         }
41000 *     });
41001 *
41002 * Set custom URL parameters:
41003 *     $(".fancybox").fancybox({
41004 *         helpers : {
41005 *             media: {
41006 *                 youtube : {
41007 *                     params : {
41008 *                         autoplay : 0
41009 *                     }
41010 *                 }
41011 *             }
41012 *         }
41013 *     });
41014 *
41015 * Or:
41016 *     $(".fancybox").fancybox({,
41017 *         helpers : {
41018 *             media: true
41019 *         },
41020 *         youtube : {
41021 *             autoplay: 0
41022 *         }
41023 *     });
41024 *
41025 *  Supports:
41026 *
41027 *      Youtube
41028 *          http://www.youtube.com/watch?v=opj24KnzrWo
41029 *          http://www.youtube.com/embed/opj24KnzrWo
41030 *          http://youtu.be/opj24KnzrWo
41031 *			http://www.youtube-nocookie.com/embed/opj24KnzrWo
41032 *      Vimeo
41033 *          http://vimeo.com/40648169
41034 *          http://vimeo.com/channels/staffpicks/38843628
vendor: 4,290 bytes, lines 41035-41185
41035 *          http://vimeo.com/groups/surrealism/videos/36516384
41036 *          http://player.vimeo.com/video/45074303
41037 *      Metacafe
41038 *          http://www.metacafe.com/watch/7635964/dr_seuss_the_lorax_movie_trailer/
41039 *          http://www.metacafe.com/watch/7635964/
41040 *      Dailymotion
41041 *          http://www.dailymotion.com/video/xoytqh_dr-seuss-the-lorax-premiere_people
41042 *      Twitvid
41043 *          http://twitvid.com/QY7MD
41044 *      Twitpic
41045 *          http://twitpic.com/7p93st
41046 *      Instagram
41047 *          http://instagr.am/p/IejkuUGxQn/
41048 *          http://instagram.com/p/IejkuUGxQn/
41049 *      Google maps
41050 *          http://maps.google.com/maps?q=Eiffel+Tower,+Avenue+Gustave+Eiffel,+Paris,+France&t=h&z=17
41051 *          http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16
41052 *          http://maps.google.com/?ll=48.859463,2.292626&spn=0.000965,0.002642&t=m&z=19&layer=c&cbll=48.859524,2.292532&panoid=YJ0lq28OOy3VT2IqIuVY0g&cbp=12,151.58,,0,-15.56
41053 */
41054;(function ($) {
41055	"use strict";
41056
41057	//Shortcut for fancyBox object
41058	var F = $.fancybox,
41059		format = function( url, rez, params ) {
41060			params = params || '';
41061
41062			if ( $.type( params ) === "object" ) {
41063				params = $.param(params, true);
41064			}
41065
41066			$.each(rez, function(key, value) {
41067				url = url.replace( '$' + key, value || '' );
41068			});
41069
41070			if (params.length) {
41071				url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params;
41072			}
41073
41074			return url;
41075		};
41076
41077	//Add helper object
41078	F.helpers.media = {
41079		defaults : {
41080			youtube : {
41081				matcher : /(youtube\.com|youtu\.be|youtube-nocookie\.com)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i,
41082				params  : {
41083					autoplay    : 1,
41084					autohide    : 1,
41085					fs          : 1,
41086					rel         : 0,
41087					hd          : 1,
41088					wmode       : 'opaque',
41089					enablejsapi : 1,
41090                    			ps: 'docs',
41091                    			controls: 1
41092				},
41093				type : 'iframe',
41094				url  : '//www.youtube.com/embed/$3'
41095			},
41096			vimeo : {
41097				matcher : /(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/,
41098				params  : {
41099					autoplay      : 1,
41100					hd            : 1,
41101					show_title    : 1,
41102					show_byline   : 1,
41103					show_portrait : 0,
41104					fullscreen    : 1
41105				},
41106				type : 'iframe',
41107				url  : '//player.vimeo.com/video/$1'
41108			},
41109			metacafe : {
41110				matcher : /metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/,
41111				params  : {
41112					autoPlay : 'yes'
41113				},
41114				type : 'swf',
41115				url  : function( rez, params, obj ) {
41116					obj.swf.flashVars = 'playerVars=' + $.param( params, true );
41117
41118					return '//www.metacafe.com/fplayer/' + rez[1] + '/.swf';
41119				}
41120			},
41121			dailymotion : {
41122				matcher : /dailymotion.com\/video\/(.*)\/?(.*)/,
41123				params  : {
41124					additionalInfos : 0,
41125					autoStart : 1
41126				},
41127				type : 'swf',
41128				url  : '//www.dailymotion.com/swf/video/$1'
41129			},
41130			twitvid : {
41131				matcher : /twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i,
41132				params  : {
41133					autoplay : 0
41134				},
41135				type : 'iframe',
41136				url  : '//www.twitvid.com/embed.php?guid=$1'
41137			},
41138			twitpic : {
41139				matcher : /twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i,
41140				type : 'image',
41141				url  : '//twitpic.com/show/full/$1/'
41142			},
41143			instagram : {
41144				matcher : /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i,
41145				type : 'image',
41146				url  : '//$1/p/$2/media/?size=l'
41147			},
41148			google_maps : {
41149				matcher : /maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i,
41150				type : 'iframe',
41151				url  : function( rez ) {
41152					return '//maps.google.' + rez[1] + '/' + rez[3] + '' + rez[4] + '&output=' + (rez[4].indexOf('layer=c') > 0 ? 'svembed' : 'embed');
41153				}
41154			}
41155		},
41156
41157		beforeLoad : function(opts, obj) {
41158			var url   = obj.href || '',
41159				type  = false,
41160				what,
41161				item,
41162				rez,
41163				params;
41164
41165			for (what in opts) {
41166				if (opts.hasOwnProperty(what)) {
41167					item = opts[ what ];
41168					rez  = url.match( item.matcher );
41169
41170					if (rez) {
41171						type   = item.type;
41172						params = $.extend(true, {}, item.params, obj[ what ] || ($.isPlainObject(opts[ what ]) ? opts[ what ].params : null));
41173
41174						url = $.type( item.url ) === "function" ? item.url.call( this, rez, params, obj ) : format( item.url, rez, params );
41175
41176						break;
41177					}
41178				}
41179			}
41180
41181			if (type) {
41182				obj.href = url;
41183				obj.type = type;
41184
41185				obj.autoHeight = false;
41186			}
41187		}
41188	};
41189
41190}(jQuery));
41191
41192/*
41193 * Ajax Fetch content
41194 *
41195 * Use to either fetch & replace or fetch and append/preprend content.
41196 * EX:
41197 *
41198 * $('.link-class').on('click',function(e){
41199 *       e.preventDefault();
41200 *       window._fetch.replaceContent($(this).attr('href'), '.container-to-load-content','.content-to-load');
41201 *       window._fetch.appendContent ($(this).attr('href'), '.container-to-load-content','.content-to-load');
41202 *       window._fetch.prependContent($(this).attr('href'), '.container-to-load-content','.content-to-load');
41203 *  })
41204 */
41205
41206(function ($) {
41207
41208    // Create job object
41209    var _fetch = {
41210        'container': '',
41211        'callback': '',
41212        'content' : '',
41213        'results' : '',
41214        'url' : '',
41215        'ajax' : '',
41216
41217        // Function used to prepend content
41218        callbackContent: function(url, callback ){
41219            _fetch.callback = callback;
41220            _fetch.handleRequest( url, "body", "", 'callback' );
41221        },
41222        // Function used to replace content
41223        replaceContent: function(url, container, content  ){
41224            _fetch.handleRequest( url,container, content, 'html' );
41225        },
41226        // Function used to append content
41227        appendContent: function(url, container, content  ){
41228            _fetch.handleRequest( url, container, content, 'append' );
41229        },
41230        // Function used to prepend content
41231        prependContent: function(url, container, content ){
41232            _fetch.handleRequest(url, container, content, 'prepend' );
41233        },
41234        // Function takes results and handles them according to action (replace/append/prepend)
41235        handleContent: function(){
41236            if(_fetch.action === "callback" ){
41237                _fetch.callback( _fetch.results );
41238            }else{
41239                console.log('amending results');
41240                _fetch.container[_fetch.action]( _fetch.results.find(_fetch.content).html() );
41241            }
41242        }, //
41243        // Universal function for handling fetch requests. Given action by calling function
41244        handleRequest: function(url, container, content,  action){
41245            // Sets object variables when called
41246            _fetch.container = $(container);
41247            if(content.length > 1){
41248                _fetch.content = content;
41249            }else{
41250                _fetch.content = container;
41251            }
41252            _fetch.action = action;
41253            _fetch.url = url;
41254            // fetches page
41255            _fetch.fetchPage();
41256        },
41257        // Sets the url in the location bar to match the new content
41258        setURL: function (url) {
41259            history.pushState({}, '', url);
41260        },
41261        // Fetch results page
41262        fetchPage: function(){
41263            // Non ajax page reload
41264            _fetch.container.addClass('j-loading');
41265            _fetch.container.trigger('ajaxLoadBegin');
41266            // ajax request a page
41267            _fetch.ajax = jQuery.ajax({
41268                dataType: 'text',
41269                url: _fetch.url,
41270                success: function (rawhtml) {
41271                    // get results
41272                    _fetch.results = $(rawhtml);
41273                    _fetch.handleContent();
41274                    _fetch.container.removeClass('j-loading');
41275                    _fetch.container.trigger('ajaxLoadComplete');
41276                },
41277                error: function(){
41278                    _fetch.container.trigger('ajaxLoadFail');
41279                }
41280            });
41281        }
41282    };
41283    // Attach Toolbox to window //
41284    window._fetch = _fetch;
41285})(jQuery); // Fully reference jQuery after this point.
41286
41287
41288
41289
41290
41291/*
41292 * Mobile Search Vue Object
41293 *
41294 */
41295 (function ($) {
41296   var client = algoliasearch(
41297     "17RXKSIL5W",
41298     "bcea4cae315f4081a0dcfe758170481e"
41299   );
41300   var postIndex = client.initIndex("visual-economy");
41301
41302   // Create job object
41303   var _search = {
41304     setup: function () {
41305       vue = new Vue({
41306         el: "#v-attachment-search",
41307         data: {
41308           showResults: false,
41309           showFilters: false,
41310           sortBy: "recent",
41311           searchTerm: "",
41312           modalItem: {},
41313
41314           // extraIndexes: (LOCALIZED.extraIndexes) ? LOCALIZED.extraIndexes : false,
41315
41316           permalink: LOCALIZED.permalink,
41317
41318           currentFilters: [],
41319
41320           filterIssues: "",
41321           initialCategory: $("#initial_category").val(),
41322
41323           searchFilters: LOCALIZED.filterTerms,
41324           searchSuggestions: [],
41325           searchResults: [],
41326
41327           currentCount: 0,
41328           currentPage: 0,
41329           totalCount: 0,
41330           totalPages: 0,
41331         },
41332
41333         methods: {
41334           // Handle when the seach term is clicked
41335           searchClick: function (e) {
41336             console.log("vue fired");
41337             console.log(e);
41338             e.preventDefault();
41339             this.submitSearch();
41340           },
41341
41342           triggerModal: function () {
41343             // $.fancybox.defaults.maxHeight = 800;
41344             // $.fancybox.defaults.maxWidth = 1600;
41345             $.fancybox.defaults.autoSize = false;
41346             $.fancybox.defaults.fitToView = true;
41347             $.fancybox.defaults.height = 'auto';
41348             $.fancybox.defaults.aspectRation = true;
41349             $.fancybox.defaults.margin = [25, 50, 25, 50];
41350             setTimeout(function(){
41351               $.fancybox([{ href: "#vueAttachmentModal" }]);
41352             }, 200);
41353           },
41354           // Load More Posts
41355           loadMorePosts: function () {
41356             this.currentPage++;
41357             this.submitSearch(true);
41358           },
41359
41360           // Submit the Search
41361           submitSearch: function (keepPageVariableSet) {
41362             if (!keepPageVariableSet) {
41363               this.currentPage = 0;
41364             }
41365
41366             var filterQuery = "";
41367
41368             var join = "";
41369
41370             if (this.initialCategory) {
41371               if (this.filterIssues) {
41372                 filterQuery += "( category:'" + this.filterIssues+"'";
41373               } else {
41374                 filterQuery += "( category:'" + this.initialCategory +"'";
41375               }
41376               join = ") AND ";
41377             } else {
41378               if (this.filterIssues) {
41379                 filterQuery +=
41380                   join +"( category:'" + this.filterIssues+"'";
41381                 join = ") AND ";
41382               }
41383             }
41384
41385             var startingDate = $("#starting-year").val();
41386             var endingDate = $("#ending-year").val();
41387
41388               if (!startingDate) {
41389                 startingDate = "1970";
41390               }
41391               if (!endingDate) {
41392                 endingDate = new Date().getFullYear();
41393               }
41394
41395               startingDate =
41396                 new Date(
41397                   "January 1, " + startingDate
41398                 ).getTime() / 1000;
41399               endingDate =
41400                 new Date(
41401                   "December 31, " + endingDate
41402                 ).getTime() / 1000;
41403
41404               filterQuery +=
41405                 join +
41406                 "timestamp:" +
41407                 startingDate +
41408                 " TO " +
41409                 endingDate;
41410               join = " AND ";
41411
41412             if (this.extraIndexes) {
41413               queryArgs = [];
41414               queryArgs.push({
41415                 query: vue.searchTerm.toLowerCase(),
41416                 indexName: postIndex.indexName,
41417                 params: {
41418                   filters: filterQuery,
41419                   hitsPerPage: 9,
41420                 },
41421                 page: vue.currentPage,
41422               });
41423
41424               this.extraIndexes.forEach(function (extraIndex) {
41425                 queryArgs.push({
41426                   query: vue.searchTerm.toLowerCase(),
41427                   indexName: extraIndex.index_name,
41428                   params: {
41429                     filters: filterQuery,
41430                     hitsPerPage: 9,
41431                   },
41432                   page: vue.currentPage,
41433                 });
41434               });
41435               console.log(queryArgs);
41436               client.search(queryArgs, function (err, data) {
41437                 var results = data.results[0];
41438                 console.log(data);
41439                 vue.handleSearchResults(results[0]);
41440               });
41441             } else {
41442               // reverted
41443               queryArgs = {
41444                 query: vue.searchTerm.toLowerCase(),
41445                 filters: filterQuery,
41446                 hitsPerPage: 9,
41447                 page: vue.currentPage,
41448               };
41449               console.log(queryArgs);
41450               postIndex.search(queryArgs, function (err, hits) {
41451                 if (err) throw err;
41452                 console.log(hits);
41453                 vue.handleSearchResults(hits);
41454               });
41455             }
41456           },
41457
41458           // Process the search results
41459           handleSearchResults: function (results) {
41460             this.showResults = true;
41461             this.showFilters = false;
41462
41463             if (results.nbHits > 9) {
41464               this.currentCount =
41465                 (results.page + 1) * results.hitsPerPage;
41466               // Make sure our count isn't higher than the total (applies to last page)
41467               if (this.currentCount > results.nbHits) {
41468                 this.currentCount = results.nbHits;
41469               }
41470             } else {
41471               this.currentCount = results.nbHits;
41472             }
41473             this.totalCount = results.nbHits;
41474             this.totalPages = results.nbPages;
41475
41476             if (results.page == 0) {
41477               this.searchResults = results.hits;
41478             } else {
41479               this.searchResults = this.searchResults.concat(
41480                 results.hits
41481               );
41482             }
41483             $(".fancybox").fancybox({
41484               openEffect: "none",
41485               closeEffect: "none",
41486               helpers: {
41487                 media: {},
41488               },
41489             });
41490           },
41491
41492           getFirstSentence: function (text) {
41493             // Split text up into sentences (punctuation ends up at the start of the next sentence)
41494             var sentences = text.split(/(?=\.|!|\?)/g);
41495             var firstSentence = "";
41496             // Loop through and put the puncuation at the ends of the sentences
41497             for (var i = 0; i < sentences.length - 1; i++) {
41498               sentences[i] += sentences[i + 1].charAt(0);
41499               sentences[i + 1] = sentences[i + 1].substr(1);
41500             }
41501             // Loop through
41502             for (i = 0; i < sentences.length; i++) {
41503               // set current Sentence
41504               firstSentence += sentences[i];
41505               // Only add the first sentence unless it is too short, then add another
41506               if (firstSentence.length > 50) {
41507                 break;
41508               }
41509             }
41510             return firstSentence;
41511           },
41512
41513           // Toggle the filter menu
41514           toggleMenu: function (event) {
41515             var target = $(event.currentTarget).parent();
41516             target
41517               .toggleClass("active")
41518               .siblings(".active")
41519               .removeClass("active")
41520               .find(".gta-mobile-search--filter--sub")
41521               .slideUp();
41522             if (target.hasClass("active")) {
41523               target
41524                 .find(".gta-mobile-search--filter--sub")
41525                 .slideDown();
41526             } else {
41527               target
41528                 .find(".gta-mobile-search--filter--sub")
41529                 .slideUp();
41530             }
41531           },
41532
41533           // Searches the query-suggestion index and populates them
41534           updateQuerySuggestions: function () {
41535             var vue = this;
41536             this.showResults = false;
41537             vue.searchSuggestions = [];
41538
41539             querySuggestionIndex.search(
41540               {
41541                 query: vue.searchTerm.toLowerCase(),
41542                 hitsPerPage: 9,
41543                 attributesToRetrieve: ["title"],
41544               },
41545               function (err, hits) {
41546                 if (err) throw err;
41547                 hits.hits.forEach(function (index) {
41548                   vue.searchSuggestions.push(index.title);
41549                 });
41550               }
41551             );
41552           },
41553         },
41554         mounted: function () {
41555           setTimeout(function () {
41556             vue.submitSearch();
41557           }, 75);
41558         }
41559       });
41560     },
41561   };
41562   window._search = _search;
41563
41564 })(jQuery); // Fully reference jQuery after this point.
41565
41566 function getQueryParam(param) {
41567    var urlParams = new URLSearchParams(window.location.search);
41568    return urlParams.get(param);
41569}
41570
41571var _site_search = {
41572    setup: function () {
41573        var algoliaClient = algoliasearch("17RXKSIL5W", "bcea4cae315f4081a0dcfe758170481e");
41574        var postIndex = algoliaClient.initIndex("search");
41575
41576        var vue = new Vue({
41577            el: ".search-wrapper",
41578            data: {
41579                showResults: false,
41580                sortBy: "recent",
41581                searchTerm: getQueryParam('s') || "",
41582                searchResults: [],
41583
41584                permalink: LOCALIZED.permalink,
41585
41586                currentCount: 0,
41587                currentPage: 0,
41588                totalCount: 0,
41589                totalPages: 0,
41590                isPopState: false, // Flag to determine if the search is from popstate
41591            },
41592
41593            methods: {
41594                searchClick: function (e) {
41595                    console.log("vue fired");
41596                    console.log(e);
41597                    e.preventDefault();
41598                    this.isPopState = false;
41599                    this.submitSearch();
41600                },
41601                submitSearch: function (keepPageVariableSet) {
41602                    if (!keepPageVariableSet) {
41603                        this.currentPage = 0;
41604                    }
41605
41606                    if (!this.isPopState) {
41607                        // Update the URL with the current search term
41608                        const newUrl = new URL(window.location.href);
41609                        newUrl.searchParams.set('s', this.searchTerm);
41610                        history.pushState({ searchTerm: this.searchTerm }, '', newUrl);
41611                    }
41612
41613                    var filterQuery = "";
41614
41615                    var join = "";
41616
41617                    // reverted
41618                    queryArgs = {
41619                        query: vue.searchTerm.toLowerCase(),
41620                        filters: filterQuery,
41621                        hitsPerPage: 9,
41622                        page: vue.currentPage,
41623                    };
41624                    console.log(queryArgs);
41625                    postIndex.search(queryArgs, function (err, hits) {
41626                        if (err) throw err;
41627                        console.log(hits);
41628                        vue.handleSearchResults(hits);
41629                    });
41630                },
41631                handleSearchResults: function (results) {
41632                    this.showResults = true;
41633                    this.showFilters = false;
41634                    console.log(results);
41635                    if (results.nbHits > 9) {
41636                        this.currentCount =
41637                            (results.page + 1) * results.hitsPerPage;
41638                        // Make sure our count isn't higher than the total (applies to last page)
41639                        if (this.currentCount > results.nbHits) {
41640                            this.currentCount = results.nbHits;
41641                        }
41642                    } else {
41643                        this.currentCount = results.nbHits;
41644                    }
41645                    this.totalCount = results.nbHits;
41646                    this.totalPages = results.nbPages;
41647
41648                    if (results.page == 0) {
41649                        this.searchResults = results.hits;
41650                    } else {
41651                        this.searchResults = this.searchResults.concat(
41652                            results.hits
41653                        );
41654                    }
41655                },
41656                handlePopState: function (event) {
41657                    if (event.state && event.state.searchTerm !== undefined) {
41658                        this.isPopState = true;
41659                        this.searchTerm = event.state.searchTerm;
41660                        this.submitSearch(true);
41661                    }
41662                },
41663            },
41664            mounted() {
41665                if (this.searchTerm) {
41666                    this.$nextTick(() => {
41667                        // Ensure the DOM has been updated
41668                        let submitButton = document.querySelector('.submit-search');
41669                        if (submitButton) {
41670                            submitButton.click(); // Programmatically trigger a click event
41671                        }
41672                    });
41673                }
41674
41675                // Listen for the popstate event to handle browser navigation
41676                window.addEventListener('popstate', this.handlePopState);
41677            },
41678        });
41679    },
41680};
41681
41682/* ========================================================================
41683 * DOM-based Routing
41684 * Based on http://goo.gl/EUTi53 by Paul Irish
41685 *
41686 * Only fires on body classes that match. If a body class contains a dash,
41687 * replace the dash with an underscore when adding it to the object below.
41688 *
41689 * .noConflict()
41690 * The routing is enclosed within an anonymous function so that you can
41691 * always reference jQuery with $, even when in .noConflict() mode.
41692 * ======================================================================== */
41693
41694(function ($) {
41695	// Use this variable to set up the common and page specific functions. If you
41696	// rename this variable, you will also need to rename the namespace below.
41697	var Sage = {
41698		// All pages
41699		common: {
41700			init: function () {
41701
41702				if ($('body').hasClass('search-results')) {
41703					window._site_search.setup();
41704				}
41705
41706				if ($('body').hasClass('page-template-attachments-landing')) {
41707					window._search.setup();
41708				}
41709				// JavaScript to be fired on all pages
41710				$(".burger-trigger, .mobile-nav-offclick").click(function (e) {
41711					e.preventDefault();
41712					// console.log('fired');
41713					$(".burger-trigger").toggleClass("open");
41714					$(".mobile-nav-container").toggleClass("open");
41715					$(".mobile-nav-offclick").toggleClass("open");
41716					$("body").toggleClass("custom-overflow");
41717				});
41718
41719				$("#page").on("click", ".e-faq--single--question", function () {
41720					$(this).parent(".e-faq--single").toggleClass("active");
41721					$(this).siblings(".e-faq--single--answer").slideToggle();
41722				});
41723				$("#page").on("click", ".schema-faq-section", function () {
41724					$(this).toggleClass("active");
41725					$(this).children(".schema-faq-answer").slideToggle();
41726				});
41727				$(".slider").slick();
41728				$(".j-carousel").slick({
41729					dots: false,
41730					arrows: true,
41731					nextArrow: '<i class="fa fa-arrow-right slick-next"></i>',
41732					prevArrow: '<i class="fa fa-arrow-left slick-prev"></i>',
41733					adaptiveHeight: true,
41734				});
41735
41736				$(".fancybox").fancybox({
41737					openEffect: "none",
41738					closeEffect: "none",
41739					helpers: {
41740						media: {},
41741					},
41742				});
41743				// scrollama event handlers
41744				function handleStepEnter(response) {
41745					// response = { element, direction, index }
41746					var nav_el = "." + $(response.element).data("nav-class");
41747					if (response.direction == "down") {
41748						$(nav_el)
41749							.addClass("active")
41750							.siblings()
41751							.removeClass("active");
41752					}
41753					if (response.index != 0 && response.direction == "up") {
41754						$(nav_el)
41755							.removeClass("active")
41756							.prev()
41757							.addClass("active");
41758					}
41759					if (response.index == 0 && response.direction == "up") {
41760						$(nav_el).removeClass("active");
41761					}
41762					// add to color to current step
41763					// response.element.classList.add("is-active");
41764				}
41765				if ($(".gutenblock--section-header").length > 0) {
41766					var $sections = [];
41767					$(".gutenblock--section-header").each(function (e) {
41768						var $that = $(this);
41769						var $nav_title = $that.data("section-nav-title");
41770
41771						$sections.push({
41772							title: $nav_title,
41773							id: $that.attr("ID"),
41774						});
41775					});
41776					var $side_nav =
41777						"<div id='gutenberg-section-nav' class='section-nav'><span class='nav-title'>View Page Navigation</span><ul>";
41778
41779					$.each($sections, function (index, value) {
41780						$side_nav +=
41781							'<li class="e-section-nav related-' +
41782							value.id +
41783							'"><span></span><a class="j-section-nav--link" href="#' +
41784							value.id +
41785							'">' +
41786							value.title +
41787							"</a></li>";
41788					});
41789					$side_nav += "</ul></div>";
41790
41791					$("#longform-page").append($side_nav);
41792
41793					$(".j-section-nav--link").on("click", function (e) {
41794						e.preventDefault();
41795						$("html, body").animate(
41796							{ scrollTop: $($(this).attr("href")).offset().top },
41797							500
41798						);
41799						$("#gutenberg-section-nav ul").removeClass("revealed");
41800						$(this)
41801							.parent()
41802							.addClass("active")
41803							.siblings()
41804							.removeClass("active");
41805					});
41806					var long_form_nav = $("#gutenberg-section-nav");
41807					$(".nav-title").click(function (e) {
41808						$("#gutenberg-section-nav ul").toggleClass("revealed");
41809					});
41810					var scroller = scrollama();
41811					scroller
41812						.setup({
41813							step: ".gta-section-title",
41814							// debug: true,
41815							offset: 0.1,
41816						})
41817						.onStepEnter(handleStepEnter);
41818				}
41819				var sidebar = $(".e-share");
41820				checkWindowWidth(jQuery(window).width());
41821				jQuery(window).resize(function () {
41822					checkWindowWidth(jQuery(window).width());
41823				});
41824				function checkWindowWidth(window_width) {
41825					if (window_width < 950) {
41826						sidebar.trigger("sticky_kit:detach");
41827					} else {
41828						make_sticky();
41829					}
41830					if (typeof long_form_nav !== "undefined") {
41831						console.log("long form start");
41832						if (window_width < 768) {
41833							long_form_nav.trigger("sticky_kit:detach");
41834						} else {
41835							long_form_nav.stick_in_parent({
41836								offset_top: 50,
41837							});
41838						}
41839					}
41840				}
41841
41842				function make_sticky() {
41843					sidebar.stick_in_parent({
41844						offset_top: 50,
41845					});
41846				}
41847
41848				$("#page").on("click", ".j-share-expand", function () {
41849					$(this).parent().toggleClass("open");
41850				}); //
41851				$("#page").on("click", ".j-topic-count--toggle", function () {
41852					$(this).parent().toggleClass("open");
41853				}); //
41854
41855				// LOAD MORE
41856				$(".j-loadmore").on(
41857					"click",
41858					".j-loadmore--button",
41859					function (e) {
41860						// Setup _this variable and prevent default behaviour
41861						var _this = $(this);
41862						e.preventDefault();
41863
41864						// Exit if in progress class is added
41865						if (_this.hasClass("in-progress")) return;
41866
41867						// Add in progress class to prevent multiple clicks
41868						_this.addClass("in-progress");
41869
41870						// Get the container element
41871						var container = _this.parents(".j-loadmore");
41872
41873						// Get a list of classes for the object to use to find it in the results
41874						var containerClasses = "." + container.attr("class");
41875						containerClasses = containerClasses
41876							.split(" ")
41877							.join(".");
41878
41879						// Get the page URL to fetch
41880						var url = $(this).attr("href");
41881
41882						// Fetch the URL and replace/append the content
41883						window._fetch.callbackContent(url, function (result) {
41884							// Get results object
41885							var results = $(result);
41886							// Remove in progress class
41887							_this.removeClass("in-progress");
41888							// Add the posts from the results to the posts on the page
41889							container
41890								.find(".j-loadmore--posts")
41891								.append(
41892									results
41893										.find(containerClasses)
41894										.find(".j-loadmore--posts")
41895										.html()
41896								);
41897							// Replace the pagination on the page with the pagination on the fetched page
41898							container
41899								.find(".j-loadmore--pagination")
41900								.html(
41901									results
41902										.find(containerClasses)
41903										.find(".j-loadmore--pagination")
41904										.html()
41905								);
41906
41907							$(".fancybox").fancybox({
41908								openEffect: "none",
41909								closeEffect: "none",
41910								helpers: {
41911									media: {},
41912								},
41913							});
41914						});
41915					}
41916				);
41917
41918				$(".j-slide-content").on(
41919					"click",
41920					".j-slide-content--toggle",
41921					function () {
41922						var _this = $(this);
41923						var container = _this
41924							.parents(".j-slide-content")
41925							.toggleClass("j-slide-content__open");
41926						container
41927							.find(".j-slide-content--container")
41928							.slideToggle();
41929					}
41930				);
41931
41932				//MEDIA MENTIONS CHECKBOX SUBMIT
41933				$(".mm-filter--checkbox").on("change", function (e) {
41934					var otherCheckbox = null;
41935
41936					if (e.currentTarget.id === "mm-filter-opinion") {
41937						otherCheckbox = $("#mm-filter-mention")[0];
41938					} else {
41939						otherCheckbox = $("#mm-filter-opinion")[0];
41940					}
41941
41942					if (
41943						otherCheckbox.checked === false &&
41944						e.currentTarget.checked === false
41945					) {
41946						otherCheckbox.checked = true;
41947						e.currentTarget.checked = true;
41948					}
41949
41950					var _this = $(this);
41951
41952					_this.parents(".e-media-mentions-search--form").submit();
41953				});
41954
41955				//SEARCH AJAX
41956				$(".e-search-form--form").on("submit", function (e) {
41957					var _this = $(this);
41958					if (_this.hasClass("in-progress")) return;
41959					_this.addClass("in-progress");
41960
41961					var url = _this.attr("action") + "?" + _this.serialize();
41962					e.preventDefault();
41963
41964					var container = _this
41965						.parents(".e-search-form")
41966						.find(".j-loadmore");
41967					var containerClasses = "." + container.attr("class");
41968
41969					containerClasses = containerClasses.split(" ").join(".");
41970
41971					window._fetch.callbackContent(url, function (result) {
41972						var results = $(result);
41973						_this.removeClass("in-progress");
41974						window._fetch.setURL(url);
41975						container
41976							.find(".j-loadmore--posts")
41977							.html(
41978								results
41979									.find(containerClasses)
41980									.find(".j-loadmore--posts")
41981									.html()
41982							);
41983						container
41984							.find(".j-loadmore--pagination")
41985							.html(
41986								results
41987									.find(containerClasses)
41988									.find(".j-loadmore--pagination")
41989									.html()
41990							);
41991
41992						$(".fancybox").fancybox({
41993							openEffect: "none",
41994							closeEffect: "none",
41995							helpers: {
41996								media: {},
41997							},
41998						});
41999					});
42000				});
42001				$(".j-filter-issues--clear").on("click", function (e) {
42002					var _this = $(this);
42003					e.preventDefault();
42004					var form = $(".e-search-form--form-wrapper > form");
42005					form.find("#keyword").val('');
42006					form.find("#issues").val('');
42007					form.find("#grant-category").val('');
42008
42009					if (typeof queryArgs !== 'undefined') {
42010						queryArgs.query = "";
42011						vue.searchTerm = "";
42012						vue.filterIssues = "";
42013					};
42014
42015					form.find("#starting-year")
42016						.val(uiSliderMin)
42017						.trigger("change");
42018					form.find("#ending-year")
42019						.val(uiSliderMax)
42020						.trigger("change");
42021
42022					$("#ui-slider-min").html(uiSliderMin);
42023					$("#ui-slider-max").html(uiSliderMax);
42024
42025					var $sr = form.find("#slider-range");
42026
42027					$sr.slider("values", 0, uiSliderMin);
42028					$sr.slider("values", 1, uiSliderMax);
42029
42030					setup_handles();
42031
42032					form.find("input.button[value='filter']").trigger("click");
42033					//_search.setup();
42034				});
42035
42036				// JS PDF BUTTON
42037
42038				$("#page").on("click", ".j-pdf", function (e) {
42039					e.preventDefault();
42040					var _this = $(this);
42041					//var target = document.getElementById(_this.attr('href'));
42042					var filename = _this.data("filename");
42043					if (filename.length < 1) {
42044						filename = "Equitable Growth";
42045					}
42046					var element = $(_this.attr("href")).get(0);
42047					downloadSection(element, filename);
42048				});
42049
42050				$(function () {
42051					if ($("#slider-range").length) {
42052						$("#slider-range").slider({
42053							range: true,
42054							min: uiSliderMin,
42055							max: uiSliderMax,
42056							values: [uiSliderCurrentMin, uiSliderCurrentMax],
42057							slide: function (event, ui) {
42058								var delay = function () {
42059									var handleID = ui.handle.id;
42060									var target = $("#" + handleID);
42061									var label =
42062										handleID == "ui-slider-handle--0"
42063											? "#ui-slider-min"
42064											: "#ui-slider-max";
42065									var input =
42066										handleID == "ui-slider-handle--0"
42067											? "#starting-year"
42068											: "#ending-year";
42069									$(input).val(ui.value).trigger("change");
42070									$(label).html(ui.value);
42071									$(label).position({
42072										my: "center bottom",
42073										at: "center top",
42074										of: target,
42075									});
42076								};
42077								// wait for the ui.handle to set its position
42078								setTimeout(delay, 5);
42079							},
42080							create: function (event, ui) {
42081								$("#starting-year")
42082									.val(uiSliderCurrentMin)
42083									.trigger("change");
42084								$("#ending-year")
42085									.val(uiSliderCurrentMax)
42086									.trigger("change");
42087
42088								$("#ui-slider-min").html(uiSliderCurrentMin);
42089								$("#ui-slider-max").html(uiSliderCurrentMax);
42090								var handles = $(".ui-slider-handle");
42091								var counter = 0;
42092								for (
42093									counter = 0;
42094									counter < handles.length;
42095									counter++
42096								) {
42097									handles[counter].id =
42098										"ui-slider-handle--" + counter;
42099								}
42100							},
42101						});
42102					}
42103				});
42104
42105				function downloadAllSections(sections, filename) {
42106					var width = sections.width();
42107					var height = sections.height();
42108					var options = {
42109						margin: [20, 5, 20, 5],
42110						filename: "Equitable Growth - " + filename + ".pdf",
42111						jsPDF: {
42112							unit: "pt",
42113							format: [width, height],
42114							orientation: "portrait",
42115						},
42116					};
42117					var pdf = new jsPDF(options.jsPDF);
42118					// var elem = jQuery('<div class="eq-pdf-download-message"><h2>PDF Generation In Progress</h2></div>').appendTo('body');
42119					var totalPages = sections.length;
42120					var currentPages = 0;
42121
42122					sections.each(function (index) {
42123						var section = $(this);
42124						section.addClass("s-pdf");
42125						var pageImage = html2pdf()
42126							.from(this)
42127							.set(options)
42128							.outputImg()
42129							.then(function (worker) {
42130								pdf.addPage();
42131								pdf.addImage(
42132									pageImage.src,
42133									"jpeg",
42134									options.margin[0],
42135									options.margin[1],
42136									section.width(),
42137									section.height()
42138								);
42139								section.removeClass("s-pdf");
42140								currentPages++;
42141								if (currentPages >= totalPages) {
42142									pdf.save(
42143										"Equitable Growth - " +
42144											filename +
42145											".pdf"
42146									);
42147									// elem.detach();
42148								}
42149							});
42150					});
42151				}
42152
42153				function downloadSection(element, filename) {
42154					// var pdf = new jsPDF('p', 'pt', 'letter');
42155
42156					// if( $(element).attr('id') === "longform-page"){
42157					//     downloadAllSections($(element).find('.e-longform--section'), filename );
42158					//     return;
42159					// }
42160
42161					$(element).addClass("s-pdf");
42162					var width = $(element).width();
42163					var height = $(element).height();
42164					// html2pdf(element, {
42165					//     margin: [50, 4, 16, 50],
42166					//     filename: 'Equitable Growth - ' + filename + '.pdf',
42167					//     jsPDF: {unit: 'pt', format: [height, width], orientation: 'portrait'}
42168					// });
42169
42170					html2pdf()
42171						.from(element)
42172						.set({
42173							margin: [50, 5, 50, 5],
42174							filename: "Equitable Growth - " + filename + ".pdf",
42175							html2canvas: { dpi: 96, letterRendering: true },
42176							// image:        { type: 'jpeg', quality: 0.98 },
42177							jsPDF: {
42178								unit: "pt",
42179								format: [height, width],
42180								orientation: "portrait",
42181							},
42182						})
42183						.save("Equitable Growth - " + filename + ".pdf")
42184						.thenExternal(function () {
42185							// $(element).removeClass('s-pdf');
42186						});
42187					$(element).removeClass("s-pdf");
42188					$(element).find(".e-longform-meta--section-list").show();
42189				}
42190				// Longform Section by Section
42191				var longformSections = $(".j-longform-sections");
42192				longformSections.on(
42193					"click",
42194					".j-longform-sections--toggle",
42195					function () {
42196						longformSections.toggleClass(
42197							"j-longform-sections--open"
42198						);
42199					}
42200				);
42201				longformSections.on(
42202					"click",
42203					".j-longform-sections--option",
42204					function () {
42205						// var link = $(this).data('link');
42206						// if($(link).length > 0){
42207						//     // Scroll the page to the target.
42208						//     $('html, body').animate({
42209						//         scrollTop: $(link).offset().top
42210						//     }, 1000);
42211						// }
42212						longformSections
42213							.find(".j-longform-sections--current")
42214							.html($(this).html());
42215					}
42216				);
42217				// start auto download
42218
42219				if (
42220					$(".e-longform--section").find(".j-pdf-auto-download")
42221						.length > 0
42222				) {
42223					var _this = $(".j-pdf-auto-download");
42224					//var target = document.getElementById(_this.attr('href'));
42225					var filename = _this.data("filename");
42226					if (filename.length < 1) {
42227						filename = "Equitable Growth";
42228					}
42229					var element = $(_this.attr("href")).get(0);
42230					downloadSection(element, filename);
42231				}
42232
42233				// Create job object
42234				var _socialPopup = {
42235					window: "",
42236					popups: "",
42237
42238					watcher: function () {},
42239					updateSocialPopups: function () {
42240						_socialPopup.window = $(window);
42241						_socialPopup.popups = $(".j-share-expand");
42242						_socialPopup.popups.each(function () {
42243							var element = $(this);
42244							_socialPopup.updateSocialPopupDistances(
42245								element.parent()
42246							);
42247						});
42248					},
42249					updateSocialPopupDistances: function (element) {
42250						element.removeClass("near-right");
42251						element.addClass(
42252							_socialPopup.getSocialPopupDistanceClass(element)
42253						);
42254					},
42255					getSocialPopupDistanceClass: function (element) {
42256						var class_name = "size-ok";
42257						if (_socialPopup.getDistanceFromRight(element) < 100) {
42258							class_name = "near-right";
42259						}
42260						return class_name;
42261					},
42262					getDistanceFromRight: function (element) {
42263						return (
42264							_socialPopup.window.width() -
42265							(element.offset().left + element.width())
42266						);
42267					},
42268				};
42269				$(window).on("resize", function () {
42270					_socialPopup.updateSocialPopups();
42271				});
42272				_socialPopup.updateSocialPopups();
42273
42274				//updateSocialPopups();
42275				//$(window).on('resize', updateSocialPopups());
42276				//function updateSocialPopups() {
42277				//    var popups = $('.j-share-expand');
42278				//    popups.each(function () {
42279				//        var element = $(this);
42280				//        updateSocialPopupDistances(element);
42281				//    });
42282				//
42283				//}
42284				//
42285				//function updateSocialPopupDistances(element) {
42286				//    element.removeClass('near-right');
42287				//    element.addClass(getSocialPopupDistanceClass(element));
42288				//}
42289				//
42290				//function getSocialPopupDistanceClass(element) {
42291				//    var class_name = "size-ok";
42292				//    ;
42293				//    console.log(getDistanceFromRight(element));
42294				//    if (getDistanceFromRight(element) < 100) {
42295				//        class_name = "near-right distance--" + getDistanceFromRight(element);
42296				//    }
42297				//    return class_name;
42298				//}
42299				//
42300				//function getDistanceFromRight(element) {
42301				//
42302				//    console.log("windowWidth: " + window.width());
42303				//    console.log("element.offset(): " + element.offset());
42304				//    console.log("element.width(): " + element.width());
42305				//
42306				//
42307				//    return $(window).width() - (element.offset().left + element.width());
42308				//}
42309			},
42310			finalize: function () {
42311				// JavaScript to be fired on all pages, after page specific JS is fired
42312			},
42313		},
42314
42315		// About us page, note the change from about-us to about_us.
42316		page_template_long_form: {
42317			init: function () {},
42318		},
42319		// About us page, note the change from about-us to about_us.
42320		single_report: {
42321			init: function () {},
42322		},
42323	};
42324
42325	// The routing fires all common scripts, followed by the page specific scripts.
42326	// Add additional events for more control over timing e.g. a finalize event
42327	var UTIL = {
42328		fire: function (func, funcname, args) {
42329			var fire;
42330			var namespace = Sage;
42331			funcname = funcname === undefined ? "init" : funcname;
42332			fire = func !== "";
42333			fire = fire && namespace[func];
42334			fire = fire && typeof namespace[func][funcname] === "function";
42335
42336			if (fire) {
42337				namespace[func][funcname](args);
42338			}
42339		},
42340		loadEvents: function () {
42341			// Fire common init JS
42342			UTIL.fire("common");
42343
42344			// Fire page-specific init JS, and then finalize JS
42345			$.each(
42346				document.body.className.replace(/-/g, "_").split(/\s+/),
42347				function (i, classnm) {
42348					UTIL.fire(classnm);
42349					UTIL.fire(classnm, "finalize");
42350				}
42351			);
42352
42353			// Fire common finalize JS
42354			UTIL.fire("common", "finalize");
42355		},
42356	};
42357
42358	// Load Events
42359	$(document).ready(UTIL.loadEvents);
42360
42361	var setup_handles = function () {
42362		var delay = function () {
42363			var handles = $(".ui-slider-handle");
42364			var counter = 0;
42365			var label = "";
42366			for (counter = 0; counter < handles.length; counter++) {
42367				handles[counter].id = "ui-slider-handle--" + counter;
42368				label = counter == 0 ? "#ui-slider-min" : "#ui-slider-max";
42369				$(label).position({
42370					my: "center bottom",
42371					at: "center top",
42372					of: handles[counter],
42373				});
42374			}
42375		};
42376		setTimeout(delay, 10);
42377	};
42378
42379	$(function () {
42380		setup_handles();
42381	});
42382
42383	$(window).scroll(setup_handles);
42384})(jQuery); // Fully reference jQuery after this point.
42385
42386//# sourceMappingURL=main.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.